From f27c73b46935b3a4a9ee8cbf0f0d298543e6c720 Mon Sep 17 00:00:00 2001 From: Alex Newman Date: Fri, 7 Nov 2025 20:28:12 -0500 Subject: [PATCH] Fix project filter synchronization issues in viewer UI (#70) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Enhance session and summary handling - Update SQL query in SessionStore to exclude null or empty projects. - Add 'investigated' field to Summary interface for better tracking. - Modify App component to handle pagination more efficiently based on current filters. - Update SummaryCard to display the 'investigated' field if present. - Refactor usePagination hook to reset pagination state when filters change. - Adjust mergeAndDeduplicateByProject function to ensure it only merges unfiltered data. * refactor: address PR feedback - remove redundancies and fix dependency cycles Fixes based on PR #70 review feedback: Required: - Fixed useEffect dependency cycle in App.tsx (removed handleLoadMore from deps) Recommended: - Removed redundant filter detection from App.tsx (usePagination handles this) - Removed redundant stateRef update effect from usePagination.ts - Simplified mergeAndDeduplicateByProject by removing defensive validation - Removed unused imports (useRef, useEffect) All changes follow CLAUDE.md principles: DRY, fail-fast, no defensive programming. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude * fix: Reset paginated data arrays when filter changes Critical fix for data mixing bug identified in PR review follow-up. Problem: When filter changes, usePagination correctly resets its offset to 0, but the paginated state arrays (observations, summaries, prompts) were NOT being reset. This caused data from different projects to mix together because setState appends to the existing array. Example: - User views Project A: [A1, A2, A3] - User switches to Project B - API fetches [B1, B2, B3] - setState does: [...prev, ...new] = [A1, A2, A3, B1, B2, B3] ❌ Solution: Added a separate useEffect that resets all three paginated arrays when currentFilter changes. This happens BEFORE handleLoadMore fetches new data, ensuring clean state for the new filter. Files changed: - src/ui/viewer/App.tsx: Added useEffect to reset arrays on filter change - plugin/ui/viewer-bundle.js: Built UI bundle Testing: 1. Select Project A, verify data loads 2. Switch to Project B 3. Verify ONLY Project B data is shown (no mixing) 4. Switch back to "All Projects" 5. Verify all data appears correctly 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude * refactor: Combine filter change useEffect hooks for guaranteed order Merged two separate useEffect hooks into one to: 1. Guarantee execution order (reset THEN load) 2. Reduce complexity (one hook instead of two) 3. Make intent clearer with single comment Before: - useEffect #1: handleLoadMore() on filter change - useEffect #2: Reset arrays on filter change - React could run these in any order After: - Single useEffect: Reset arrays THEN handleLoadMore() - Execution order is now guaranteed Files changed: - src/ui/viewer/App.tsx: Combined useEffect hooks - plugin/ui/viewer-bundle.js: Built UI bundle 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --------- Co-authored-by: Claude --- plugin/scripts/cleanup-hook.js | 9 ++-- plugin/scripts/context-hook.js | 1 + plugin/scripts/new-hook.js | 3 +- plugin/scripts/save-hook.js | 61 ++++++++++++------------ plugin/scripts/search-server.mjs | 23 ++++----- plugin/scripts/summary-hook.js | 1 + plugin/scripts/worker-service.cjs | 1 + plugin/ui/viewer-bundle.js | 10 ++-- src/services/sqlite/SessionStore.ts | 1 + src/services/worker-types.ts | 1 + src/ui/viewer/App.tsx | 51 +++++++++++--------- src/ui/viewer/components/SummaryCard.tsx | 3 ++ src/ui/viewer/hooks/usePagination.ts | 54 ++++++++++----------- src/ui/viewer/types.ts | 1 + src/ui/viewer/utils/data.ts | 22 ++++----- 15 files changed, 128 insertions(+), 114 deletions(-) diff --git a/plugin/scripts/cleanup-hook.js b/plugin/scripts/cleanup-hook.js index b508ca2e..31409a99 100755 --- a/plugin/scripts/cleanup-hook.js +++ b/plugin/scripts/cleanup-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env node import{stdin as I}from"process";import w from"better-sqlite3";import{join as E,dirname as k,basename as W}from"path";import{homedir as O}from"os";import{existsSync as K,mkdirSync as x}from"fs";import{fileURLToPath as U}from"url";function M(){return typeof __dirname<"u"?__dirname:k(U(import.meta.url))}var q=M(),l=process.env.CLAUDE_MEM_DATA_DIR||E(O(),".claude-mem"),R=process.env.CLAUDE_CONFIG_DIR||E(O(),".claude"),J=E(l,"archives"),Q=E(l,"logs"),z=E(l,"trash"),Z=E(l,"backups"),ee=E(l,"settings.json"),f=E(l,"claude-mem.db"),se=E(l,"vector-db"),te=E(R,"settings.json"),re=E(R,"commands"),ne=E(R,"CLAUDE.md");function L(c){x(c,{recursive:!0})}var h=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(h||{}),N=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=h[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,s){return`obs-${e}-${s}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.level===0?`${e.message} ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Object.keys(e);return s.length===0?"{}":s.length<=3?JSON.stringify(e):`{${s.length} keys: ${s.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,s){if(!s)return e;try{let t=typeof s=="string"?JSON.parse(s):s;if(e==="Bash"&&t.command){let r=t.command.length>50?t.command.substring(0,50)+"...":t.command;return`${e}(${r})`}if(e==="Read"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Edit"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Write"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}return e}catch{return e}}log(e,s,t,r,n){if(e0&&(T=` {${Object.entries(a).map(([y,D])=>`${y}=${D}`).join(", ")}}`)}let g=`[${o}] [${i}] [${d}] ${_}${t}${T}${m}`;e===3?console.error(g):console.log(g)}debug(e,s,t,r){this.log(0,e,s,t,r)}info(e,s,t,r){this.log(1,e,s,t,r)}warn(e,s,t,r){this.log(2,e,s,t,r)}error(e,s,t,r){this.log(3,e,s,t,r)}dataIn(e,s,t,r){this.info(e,`\u2192 ${s}`,t,r)}dataOut(e,s,t,r){this.info(e,`\u2190 ${s}`,t,r)}success(e,s,t,r){this.info(e,`\u2713 ${s}`,t,r)}failure(e,s,t,r){this.error(e,`\u2717 ${s}`,t,r)}timing(e,s,t,r){this.info(e,`\u23F1 ${s}`,r,{duration:`${t}ms`})}},A=new N;var S=class{db;constructor(){L(l),this.db=new w(f),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` +`+JSON.stringify(n,null,2):m=" "+this.formatData(n));let T="";if(r){let{sessionId:u,sdkSessionId:b,correlationId:p,...a}=r;Object.keys(a).length>0&&(T=` {${Object.entries(a).map(([y,D])=>`${y}=${D}`).join(", ")}}`)}let S=`[${o}] [${i}] [${d}] ${_}${t}${T}${m}`;e===3?console.error(S):console.log(S)}debug(e,s,t,r){this.log(0,e,s,t,r)}info(e,s,t,r){this.log(1,e,s,t,r)}warn(e,s,t,r){this.log(2,e,s,t,r)}error(e,s,t,r){this.log(3,e,s,t,r)}dataIn(e,s,t,r){this.info(e,`\u2192 ${s}`,t,r)}dataOut(e,s,t,r){this.info(e,`\u2190 ${s}`,t,r)}success(e,s,t,r){this.info(e,`\u2713 ${s}`,t,r)}failure(e,s,t,r){this.error(e,`\u2717 ${s}`,t,r)}timing(e,s,t,r){this.info(e,`\u23F1 ${s}`,r,{duration:`${t}ms`})}},A=new N;var g=class{db;constructor(){L(l),this.db=new w(f),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` CREATE TABLE IF NOT EXISTS schema_versions ( id INTEGER PRIMARY KEY, version INTEGER UNIQUE NOT NULL, @@ -216,6 +216,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(t=>t.project)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` SELECT * FROM ( @@ -390,11 +391,11 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje FROM session_summaries WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o} ORDER BY created_at_epoch ASC - `,g=` + `,S=` SELECT up.*, s.project, s.sdk_session_id FROM user_prompts up JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${o.replace("project","s.project")} ORDER BY up.created_at_epoch ASC - `;try{let u=this.db.prepare(m).all(d,_,...i),b=this.db.prepare(T).all(d,_,...i),p=this.db.prepare(g).all(d,_,...i);return{observations:u,sessions:b.map(a=>({id:a.id,sdk_session_id:a.sdk_session_id,project:a.project,request:a.request,completed:a.completed,next_steps:a.next_steps,created_at:a.created_at,created_at_epoch:a.created_at_epoch})),prompts:p.map(a=>({id:a.id,claude_session_id:a.claude_session_id,project:a.project,prompt:a.prompt_text,created_at:a.created_at,created_at_epoch:a.created_at_epoch}))}}catch(u){return console.error("[SessionStore] Error querying timeline records:",u.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};import X from"path";import{homedir as F}from"os";import{existsSync as B,readFileSync as j}from"fs";function C(){try{let c=X.join(F(),".claude-mem","settings.json");if(B(c)){let e=JSON.parse(j(c,"utf-8")),s=parseInt(e.env?.CLAUDE_MEM_WORKER_PORT,10);if(!isNaN(s))return s}}catch{}return parseInt(process.env.CLAUDE_MEM_WORKER_PORT||"37777",10)}async function v(c){console.error("[claude-mem cleanup] Hook fired",{input:c?{session_id:c.session_id,cwd:c.cwd,reason:c.reason}:null}),c||(console.log("No input provided - this script is designed to run as a Claude Code SessionEnd hook"),console.log(` -Expected input format:`),console.log(JSON.stringify({session_id:"string",cwd:"string",transcript_path:"string",hook_event_name:"SessionEnd",reason:"exit"},null,2)),process.exit(0));let{session_id:e,reason:s}=c;console.error("[claude-mem cleanup] Searching for active SDK session",{session_id:e,reason:s});let t=new S,r=t.findActiveSDKSession(e);r||(console.error("[claude-mem cleanup] No active SDK session found",{session_id:e}),t.close(),console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)),console.error("[claude-mem cleanup] Active SDK session found",{session_id:r.id,sdk_session_id:r.sdk_session_id,project:r.project,worker_port:r.worker_port}),t.markSessionCompleted(r.id),console.error("[claude-mem cleanup] Session marked as completed in database"),t.close();try{let n=r.worker_port||C();await fetch(`http://127.0.0.1:${n}/sessions/${r.id}/complete`,{method:"POST",signal:AbortSignal.timeout(1e3)}),console.error("[claude-mem cleanup] Worker notified to stop processing indicator")}catch(n){console.error("[claude-mem cleanup] Failed to notify worker (non-critical):",n)}console.error("[claude-mem cleanup] Cleanup completed successfully"),console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(I.isTTY)v(void 0);else{let c="";I.on("data",e=>c+=e),I.on("end",async()=>{let e=c?JSON.parse(c):void 0;await v(e)})} + `;try{let u=this.db.prepare(m).all(d,_,...i),b=this.db.prepare(T).all(d,_,...i),p=this.db.prepare(S).all(d,_,...i);return{observations:u,sessions:b.map(a=>({id:a.id,sdk_session_id:a.sdk_session_id,project:a.project,request:a.request,completed:a.completed,next_steps:a.next_steps,created_at:a.created_at,created_at_epoch:a.created_at_epoch})),prompts:p.map(a=>({id:a.id,claude_session_id:a.claude_session_id,project:a.project,prompt:a.prompt_text,created_at:a.created_at,created_at_epoch:a.created_at_epoch}))}}catch(u){return console.error("[SessionStore] Error querying timeline records:",u.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};import X from"path";import{homedir as F}from"os";import{existsSync as B,readFileSync as j}from"fs";function C(){try{let c=X.join(F(),".claude-mem","settings.json");if(B(c)){let e=JSON.parse(j(c,"utf-8")),s=parseInt(e.env?.CLAUDE_MEM_WORKER_PORT,10);if(!isNaN(s))return s}}catch{}return parseInt(process.env.CLAUDE_MEM_WORKER_PORT||"37777",10)}async function v(c){console.error("[claude-mem cleanup] Hook fired",{input:c?{session_id:c.session_id,cwd:c.cwd,reason:c.reason}:null}),c||(console.log("No input provided - this script is designed to run as a Claude Code SessionEnd hook"),console.log(` +Expected input format:`),console.log(JSON.stringify({session_id:"string",cwd:"string",transcript_path:"string",hook_event_name:"SessionEnd",reason:"exit"},null,2)),process.exit(0));let{session_id:e,reason:s}=c;console.error("[claude-mem cleanup] Searching for active SDK session",{session_id:e,reason:s});let t=new g,r=t.findActiveSDKSession(e);r||(console.error("[claude-mem cleanup] No active SDK session found",{session_id:e}),t.close(),console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)),console.error("[claude-mem cleanup] Active SDK session found",{session_id:r.id,sdk_session_id:r.sdk_session_id,project:r.project,worker_port:r.worker_port}),t.markSessionCompleted(r.id),console.error("[claude-mem cleanup] Session marked as completed in database"),t.close();try{let n=r.worker_port||C();await fetch(`http://127.0.0.1:${n}/sessions/${r.id}/complete`,{method:"POST",signal:AbortSignal.timeout(1e3)}),console.error("[claude-mem cleanup] Worker notified to stop processing indicator")}catch(n){console.error("[claude-mem cleanup] Failed to notify worker (non-critical):",n)}console.error("[claude-mem cleanup] Cleanup completed successfully"),console.log('{"continue": true, "suppressOutput": true}'),process.exit(0)}if(I.isTTY)v(void 0);else{let c="";I.on("data",e=>c+=e),I.on("end",async()=>{let e=c?JSON.parse(c):void 0;await v(e)})} diff --git a/plugin/scripts/context-hook.js b/plugin/scripts/context-hook.js index 9383a988..8ef00ebb 100755 --- a/plugin/scripts/context-hook.js +++ b/plugin/scripts/context-hook.js @@ -216,6 +216,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(t=>t.project)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` SELECT * FROM ( diff --git a/plugin/scripts/new-hook.js b/plugin/scripts/new-hook.js index 23421acb..fe3132ca 100755 --- a/plugin/scripts/new-hook.js +++ b/plugin/scripts/new-hook.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -import z from"path";import{stdin as U}from"process";import j from"better-sqlite3";import{join as u,dirname as X,basename as te}from"path";import{homedir as L}from"os";import{existsSync as ie,mkdirSync as F}from"fs";import{fileURLToPath as P}from"url";function H(){return typeof __dirname<"u"?__dirname:X(P(import.meta.url))}var B=H(),m=process.env.CLAUDE_MEM_DATA_DIR||u(L(),".claude-mem"),R=process.env.CLAUDE_CONFIG_DIR||u(L(),".claude"),pe=u(m,"archives"),de=u(m,"logs"),ce=u(m,"trash"),_e=u(m,"backups"),ue=u(m,"settings.json"),A=u(m,"claude-mem.db"),Ee=u(m,"vector-db"),me=u(R,"settings.json"),le=u(R,"commands"),Te=u(R,"CLAUDE.md");function C(a){F(a,{recursive:!0})}function v(){return u(B,"..","..")}var h=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(h||{}),N=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=h[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,s){return`obs-${e}-${s}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.level===0?`${e.message} +import z from"path";import{stdin as U}from"process";import j from"better-sqlite3";import{join as u,dirname as X,basename as te}from"path";import{homedir as L}from"os";import{existsSync as ie,mkdirSync as F}from"fs";import{fileURLToPath as H}from"url";function P(){return typeof __dirname<"u"?__dirname:X(H(import.meta.url))}var B=P(),m=process.env.CLAUDE_MEM_DATA_DIR||u(L(),".claude-mem"),R=process.env.CLAUDE_CONFIG_DIR||u(L(),".claude"),pe=u(m,"archives"),de=u(m,"logs"),ce=u(m,"trash"),_e=u(m,"backups"),ue=u(m,"settings.json"),A=u(m,"claude-mem.db"),Ee=u(m,"vector-db"),me=u(R,"settings.json"),le=u(R,"commands"),Te=u(R,"CLAUDE.md");function C(a){F(a,{recursive:!0})}function v(){return u(B,"..","..")}var h=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(h||{}),N=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=h[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,s){return`obs-${e}-${s}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.level===0?`${e.message} ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Object.keys(e);return s.length===0?"{}":s.length<=3?JSON.stringify(e):`{${s.length} keys: ${s.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,s){if(!s)return e;try{let t=typeof s=="string"?JSON.parse(s):s;if(e==="Bash"&&t.command){let r=t.command.length>50?t.command.substring(0,50)+"...":t.command;return`${e}(${r})`}if(e==="Read"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Edit"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Write"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}return e}catch{return e}}log(e,s,t,r,n){if(e0&&(T=` {${Object.entries(p).map(([M,w])=>`${M}=${w}`).join(", ")}}`)}let S=`[${o}] [${i}] [${d}] ${c}${t}${T}${E}`;e===3?console.error(S):console.log(S)}debug(e,s,t,r){this.log(0,e,s,t,r)}info(e,s,t,r){this.log(1,e,s,t,r)}warn(e,s,t,r){this.log(2,e,s,t,r)}error(e,s,t,r){this.log(3,e,s,t,r)}dataIn(e,s,t,r){this.info(e,`\u2192 ${s}`,t,r)}dataOut(e,s,t,r){this.info(e,`\u2190 ${s}`,t,r)}success(e,s,t,r){this.info(e,`\u2713 ${s}`,t,r)}failure(e,s,t,r){this.error(e,`\u2717 ${s}`,t,r)}timing(e,s,t,r){this.info(e,`\u23F1 ${s}`,r,{duration:`${t}ms`})}},y=new N;var g=class{db;constructor(){C(m),this.db=new j(A),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` CREATE TABLE IF NOT EXISTS schema_versions ( @@ -216,6 +216,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(t=>t.project)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` SELECT * FROM ( diff --git a/plugin/scripts/save-hook.js b/plugin/scripts/save-hook.js index 2fb6d502..7ae5b04a 100755 --- a/plugin/scripts/save-hook.js +++ b/plugin/scripts/save-hook.js @@ -1,7 +1,7 @@ #!/usr/bin/env node -import{stdin as U}from"process";import j from"better-sqlite3";import{join as E,dirname as F,basename as te}from"path";import{homedir as C}from"os";import{existsSync as ie,mkdirSync as X}from"fs";import{fileURLToPath as H}from"url";function P(){return typeof __dirname<"u"?__dirname:F(H(import.meta.url))}var B=P(),l=process.env.CLAUDE_MEM_DATA_DIR||E(C(),".claude-mem"),h=process.env.CLAUDE_CONFIG_DIR||E(C(),".claude"),de=E(l,"archives"),pe=E(l,"logs"),ce=E(l,"trash"),_e=E(l,"backups"),ue=E(l,"settings.json"),v=E(l,"claude-mem.db"),Ee=E(l,"vector-db"),me=E(h,"settings.json"),le=E(h,"commands"),Te=E(h,"CLAUDE.md");function y(a){X(a,{recursive:!0})}function D(){return E(B,"..","..")}var N=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(N||{}),O=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=N[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,s){return`obs-${e}-${s}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.level===0?`${e.message} -${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Object.keys(e);return s.length===0?"{}":s.length<=3?JSON.stringify(e):`{${s.length} keys: ${s.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,s){if(!s)return e;try{let t=typeof s=="string"?JSON.parse(s):s;if(e==="Bash"&&t.command){let r=t.command.length>50?t.command.substring(0,50)+"...":t.command;return`${e}(${r})`}if(e==="Read"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Edit"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Write"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}return e}catch{return e}}log(e,s,t,r,n){if(e0&&(m=` {${Object.entries(d).map(([M,w])=>`${M}=${w}`).join(", ")}}`)}let g=`[${o}] [${i}] [${p}] ${u}${t}${m}${c}`;e===3?console.error(g):console.log(g)}debug(e,s,t,r){this.log(0,e,s,t,r)}info(e,s,t,r){this.log(1,e,s,t,r)}warn(e,s,t,r){this.log(2,e,s,t,r)}error(e,s,t,r){this.log(3,e,s,t,r)}dataIn(e,s,t,r){this.info(e,`\u2192 ${s}`,t,r)}dataOut(e,s,t,r){this.info(e,`\u2190 ${s}`,t,r)}success(e,s,t,r){this.info(e,`\u2713 ${s}`,t,r)}failure(e,s,t,r){this.error(e,`\u2717 ${s}`,t,r)}timing(e,s,t,r){this.info(e,`\u23F1 ${s}`,r,{duration:`${t}ms`})}},b=new O;var R=class{db;constructor(){y(l),this.db=new j(v),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` +import{stdin as U}from"process";import j from"better-sqlite3";import{join as E,dirname as F,basename as te}from"path";import{homedir as C}from"os";import{existsSync as ie,mkdirSync as X}from"fs";import{fileURLToPath as H}from"url";function P(){return typeof __dirname<"u"?__dirname:F(H(import.meta.url))}var B=P(),l=process.env.CLAUDE_MEM_DATA_DIR||E(C(),".claude-mem"),h=process.env.CLAUDE_CONFIG_DIR||E(C(),".claude"),de=E(l,"archives"),pe=E(l,"logs"),ce=E(l,"trash"),_e=E(l,"backups"),ue=E(l,"settings.json"),v=E(l,"claude-mem.db"),Ee=E(l,"vector-db"),me=E(h,"settings.json"),le=E(h,"commands"),Te=E(h,"CLAUDE.md");function y(a){X(a,{recursive:!0})}function D(){return E(B,"..","..")}var N=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(N||{}),O=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=N[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,s){return`obs-${e}-${s}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.level===0?`${e.message} +${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Object.keys(e);return s.length===0?"{}":s.length<=3?JSON.stringify(e):`{${s.length} keys: ${s.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,s){if(!s)return e;try{let t=typeof s=="string"?JSON.parse(s):s;if(e==="Bash"&&t.command){let r=t.command.length>50?t.command.substring(0,50)+"...":t.command;return`${e}(${r})`}if(e==="Read"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Edit"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}if(e==="Write"&&t.file_path){let r=t.file_path.split("/").pop()||t.file_path;return`${e}(${r})`}return e}catch{return e}}log(e,s,t,r,o){if(e0&&(m=` {${Object.entries(d).map(([M,w])=>`${M}=${w}`).join(", ")}}`)}let g=`[${n}] [${i}] [${p}] ${u}${t}${m}${c}`;e===3?console.error(g):console.log(g)}debug(e,s,t,r){this.log(0,e,s,t,r)}info(e,s,t,r){this.log(1,e,s,t,r)}warn(e,s,t,r){this.log(2,e,s,t,r)}error(e,s,t,r){this.log(3,e,s,t,r)}dataIn(e,s,t,r){this.info(e,`\u2192 ${s}`,t,r)}dataOut(e,s,t,r){this.info(e,`\u2190 ${s}`,t,r)}success(e,s,t,r){this.info(e,`\u2713 ${s}`,t,r)}failure(e,s,t,r){this.error(e,`\u2717 ${s}`,t,r)}timing(e,s,t,r){this.info(e,`\u23F1 ${s}`,r,{duration:`${t}ms`})}},b=new O;var R=class{db;constructor(){y(l),this.db=new j(v),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable()}initializeSchema(){try{this.db.exec(` CREATE TABLE IF NOT EXISTS schema_versions ( id INTEGER PRIMARY KEY, version INTEGER UNIQUE NOT NULL, @@ -216,6 +216,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(t=>t.project)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` SELECT * FROM ( @@ -243,12 +244,12 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje SELECT * FROM observations WHERE id = ? - `).get(e)||null}getObservationsByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:r}=s,n=t==="date_asc"?"ASC":"DESC",o=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` + `).get(e)||null}getObservationsByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:r}=s,o=t==="date_asc"?"ASC":"DESC",n=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` SELECT * FROM observations WHERE id IN (${i}) - ORDER BY created_at_epoch ${n} - ${o} + ORDER BY created_at_epoch ${o} + ${n} `).all(...e)}getSummaryForSession(e){return this.db.prepare(` SELECT request, investigated, learned, completed, next_steps, @@ -261,7 +262,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje SELECT files_read, files_modified FROM observations WHERE sdk_session_id = ? - `).all(e),r=new Set,n=new Set;for(let o of t){if(o.files_read)try{let i=JSON.parse(o.files_read);Array.isArray(i)&&i.forEach(p=>r.add(p))}catch{}if(o.files_modified)try{let i=JSON.parse(o.files_modified);Array.isArray(i)&&i.forEach(p=>n.add(p))}catch{}}return{filesRead:Array.from(r),filesModified:Array.from(n)}}getSessionById(e){return this.db.prepare(` + `).all(e),r=new Set,o=new Set;for(let n of t){if(n.files_read)try{let i=JSON.parse(n.files_read);Array.isArray(i)&&i.forEach(p=>r.add(p))}catch{}if(n.files_modified)try{let i=JSON.parse(n.files_modified);Array.isArray(i)&&i.forEach(p=>o.add(p))}catch{}}return{filesRead:Array.from(r),filesModified:Array.from(o)}}getSessionById(e){return this.db.prepare(` SELECT id, claude_session_id, sdk_session_id, project, user_prompt FROM sdk_sessions WHERE id = ? @@ -288,11 +289,11 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje SELECT prompt_counter FROM sdk_sessions WHERE id = ? `).get(e)?.prompt_counter||1}getPromptCounter(e){return this.db.prepare(` SELECT prompt_counter FROM sdk_sessions WHERE id = ? - `).get(e)?.prompt_counter||0}createSDKSession(e,s,t){let r=new Date,n=r.getTime(),i=this.db.prepare(` + `).get(e)?.prompt_counter||0}createSDKSession(e,s,t){let r=new Date,o=r.getTime(),i=this.db.prepare(` INSERT OR IGNORE INTO sdk_sessions (claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, status) VALUES (?, ?, ?, ?, ?, ?, 'active') - `).run(e,e,s,t,r.toISOString(),n);return i.lastInsertRowid===0||i.changes===0?this.db.prepare(` + `).run(e,e,s,t,r.toISOString(),o);return i.lastInsertRowid===0||i.changes===0?this.db.prepare(` SELECT id FROM sdk_sessions WHERE claude_session_id = ? LIMIT 1 `).get(e).id:i.lastInsertRowid}updateSDKSessionId(e,s){return this.db.prepare(` UPDATE sdk_sessions @@ -307,33 +308,33 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje FROM sdk_sessions WHERE id = ? LIMIT 1 - `).get(e)?.worker_port||null}saveUserPrompt(e,s,t){let r=new Date,n=r.getTime();return this.db.prepare(` + `).get(e)?.worker_port||null}saveUserPrompt(e,s,t){let r=new Date,o=r.getTime();return this.db.prepare(` INSERT INTO user_prompts (claude_session_id, prompt_number, prompt_text, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?) - `).run(e,s,t,r.toISOString(),n).lastInsertRowid}storeObservation(e,s,t,r){let n=new Date,o=n.getTime();this.db.prepare(` + `).run(e,s,t,r.toISOString(),o).lastInsertRowid}storeObservation(e,s,t,r){let o=new Date,n=o.getTime();this.db.prepare(` SELECT id FROM sdk_sessions WHERE sdk_session_id = ? `).get(e)||(this.db.prepare(` INSERT INTO sdk_sessions (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) VALUES (?, ?, ?, ?, ?, 'active') - `).run(e,e,s,n.toISOString(),o),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let c=this.db.prepare(` + `).run(e,e,s,o.toISOString(),n),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let c=this.db.prepare(` INSERT INTO observations (sdk_session_id, project, type, title, subtitle, facts, narrative, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e,s,t.type,t.title,t.subtitle,JSON.stringify(t.facts),t.narrative,JSON.stringify(t.concepts),JSON.stringify(t.files_read),JSON.stringify(t.files_modified),r||null,n.toISOString(),o);return{id:Number(c.lastInsertRowid),createdAtEpoch:o}}storeSummary(e,s,t,r){let n=new Date,o=n.getTime();this.db.prepare(` + `).run(e,s,t.type,t.title,t.subtitle,JSON.stringify(t.facts),t.narrative,JSON.stringify(t.concepts),JSON.stringify(t.files_read),JSON.stringify(t.files_modified),r||null,o.toISOString(),n);return{id:Number(c.lastInsertRowid),createdAtEpoch:n}}storeSummary(e,s,t,r){let o=new Date,n=o.getTime();this.db.prepare(` SELECT id FROM sdk_sessions WHERE sdk_session_id = ? `).get(e)||(this.db.prepare(` INSERT INTO sdk_sessions (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) VALUES (?, ?, ?, ?, ?, 'active') - `).run(e,e,s,n.toISOString(),o),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let c=this.db.prepare(` + `).run(e,e,s,o.toISOString(),n),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let c=this.db.prepare(` INSERT INTO session_summaries (sdk_session_id, project, request, investigated, learned, completed, next_steps, notes, prompt_number, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e,s,t.request,t.investigated,t.learned,t.completed,t.next_steps,t.notes,r||null,n.toISOString(),o);return{id:Number(c.lastInsertRowid),createdAtEpoch:o}}markSessionCompleted(e){let s=new Date,t=s.getTime();this.db.prepare(` + `).run(e,s,t.request,t.investigated,t.learned,t.completed,t.next_steps,t.notes,r||null,o.toISOString(),n);return{id:Number(c.lastInsertRowid),createdAtEpoch:n}}markSessionCompleted(e){let s=new Date,t=s.getTime();this.db.prepare(` UPDATE sdk_sessions SET status = 'completed', completed_at = ?, completed_at_epoch = ? WHERE id = ? @@ -341,12 +342,12 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje UPDATE sdk_sessions SET status = 'failed', completed_at = ?, completed_at_epoch = ? WHERE id = ? - `).run(s.toISOString(),t,e)}getSessionSummariesByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:r}=s,n=t==="date_asc"?"ASC":"DESC",o=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` + `).run(s.toISOString(),t,e)}getSessionSummariesByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:r}=s,o=t==="date_asc"?"ASC":"DESC",n=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` SELECT * FROM session_summaries WHERE id IN (${i}) - ORDER BY created_at_epoch ${n} - ${o} - `).all(...e)}getUserPromptsByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:r}=s,n=t==="date_asc"?"ASC":"DESC",o=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` + ORDER BY created_at_epoch ${o} + ${n} + `).all(...e)}getUserPromptsByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:r}=s,o=t==="date_asc"?"ASC":"DESC",n=r?`LIMIT ${r}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(` SELECT up.*, s.project, @@ -354,46 +355,46 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje FROM user_prompts up JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id WHERE up.id IN (${i}) - ORDER BY up.created_at_epoch ${n} - ${o} - `).all(...e)}getTimelineAroundTimestamp(e,s=10,t=10,r){return this.getTimelineAroundObservation(null,e,s,t,r)}getTimelineAroundObservation(e,s,t=10,r=10,n){let o=n?"AND project = ?":"",i=n?[n]:[],p,u;if(e!==null){let T=` + ORDER BY up.created_at_epoch ${o} + ${n} + `).all(...e)}getTimelineAroundTimestamp(e,s=10,t=10,r){return this.getTimelineAroundObservation(null,e,s,t,r)}getTimelineAroundObservation(e,s,t=10,r=10,o){let n=o?"AND project = ?":"",i=o?[o]:[],p,u;if(e!==null){let T=` SELECT id, created_at_epoch FROM observations - WHERE id <= ? ${o} + WHERE id <= ? ${n} ORDER BY id DESC LIMIT ? `,S=` SELECT id, created_at_epoch FROM observations - WHERE id >= ? ${o} + WHERE id >= ? ${n} ORDER BY id ASC LIMIT ? `;try{let _=this.db.prepare(T).all(e,...i,t+1),d=this.db.prepare(S).all(e,...i,r+1);if(_.length===0&&d.length===0)return{observations:[],sessions:[],prompts:[]};p=_.length>0?_[_.length-1].created_at_epoch:s,u=d.length>0?d[d.length-1].created_at_epoch:s}catch(_){return console.error("[SessionStore] Error getting boundary observations:",_.message),{observations:[],sessions:[],prompts:[]}}}else{let T=` SELECT created_at_epoch FROM observations - WHERE created_at_epoch <= ? ${o} + WHERE created_at_epoch <= ? ${n} ORDER BY created_at_epoch DESC LIMIT ? `,S=` SELECT created_at_epoch FROM observations - WHERE created_at_epoch >= ? ${o} + WHERE created_at_epoch >= ? ${n} ORDER BY created_at_epoch ASC LIMIT ? `;try{let _=this.db.prepare(T).all(s,...i,t),d=this.db.prepare(S).all(s,...i,r+1);if(_.length===0&&d.length===0)return{observations:[],sessions:[],prompts:[]};p=_.length>0?_[_.length-1].created_at_epoch:s,u=d.length>0?d[d.length-1].created_at_epoch:s}catch(_){return console.error("[SessionStore] Error getting boundary timestamps:",_.message),{observations:[],sessions:[],prompts:[]}}}let c=` SELECT * FROM observations - WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o} + WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${n} ORDER BY created_at_epoch ASC `,m=` SELECT * FROM session_summaries - WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o} + WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${n} ORDER BY created_at_epoch ASC `,g=` SELECT up.*, s.project, s.sdk_session_id FROM user_prompts up JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id - WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${o.replace("project","s.project")} + WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${n.replace("project","s.project")} ORDER BY up.created_at_epoch ASC - `;try{let T=this.db.prepare(c).all(p,u,...i),S=this.db.prepare(m).all(p,u,...i),_=this.db.prepare(g).all(p,u,...i);return{observations:T,sessions:S.map(d=>({id:d.id,sdk_session_id:d.sdk_session_id,project:d.project,request:d.request,completed:d.completed,next_steps:d.next_steps,created_at:d.created_at,created_at_epoch:d.created_at_epoch})),prompts:_.map(d=>({id:d.id,claude_session_id:d.claude_session_id,project:d.project,prompt:d.prompt_text,created_at:d.created_at,created_at_epoch:d.created_at_epoch}))}}catch(T){return console.error("[SessionStore] Error querying timeline records:",T.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};function $(a,e,s){return a==="PreCompact"?e?{continue:!0,suppressOutput:!0}:{continue:!1,stopReason:s.reason||"Pre-compact operation failed",suppressOutput:!0}:a==="SessionStart"?e&&s.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:s.context}}:{continue:!0,suppressOutput:!0}:a==="UserPromptSubmit"||a==="PostToolUse"?{continue:!0,suppressOutput:!0}:a==="Stop"?{continue:!0,suppressOutput:!0}:{continue:e,suppressOutput:!0,...s.reason&&!e?{stopReason:s.reason}:{}}}function f(a,e,s={}){let t=$(a,e,s);return JSON.stringify(t)}import I from"path";import{homedir as W}from"os";import{existsSync as G,readFileSync as Y}from"fs";import{execSync as K}from"child_process";var V=100,q=100,J=1e4;function L(){try{let a=I.join(W(),".claude-mem","settings.json");if(G(a)){let e=JSON.parse(Y(a,"utf-8")),s=parseInt(e.env?.CLAUDE_MEM_WORKER_PORT,10);if(!isNaN(s))return s}}catch{}return parseInt(process.env.CLAUDE_MEM_WORKER_PORT||"37777",10)}async function k(){try{let a=L();return(await fetch(`http://127.0.0.1:${a}/health`,{signal:AbortSignal.timeout(V)})).ok}catch{return!1}}async function Q(){let a=Date.now();for(;Date.now()-asetTimeout(e,q))}return!1}async function x(){if(await k())return;let a=D(),e=I.join(a,"node_modules",".bin","pm2"),s=I.join(a,"ecosystem.config.cjs");if(K(`"${e}" restart "${s}"`,{cwd:a,stdio:"pipe"}),!await Q())throw new Error("Worker failed to become healthy after restart")}var z=new Set(["ListMcpResourcesTool"]);async function Z(a){if(!a)throw new Error("saveHook requires input");let{session_id:e,tool_name:s,tool_input:t,tool_response:r}=a;if(z.has(s)){console.log(f("PostToolUse",!0));return}await x();let n=new R,o=n.createSDKSession(e,"",""),i=n.getPromptCounter(o);n.close();let p=b.formatTool(s,t),u=L();b.dataIn("HOOK",`PostToolUse: ${p}`,{sessionId:o,workerPort:u});try{let c=await fetch(`http://127.0.0.1:${u}/sessions/${o}/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool_name:s,tool_input:t!==void 0?JSON.stringify(t):"{}",tool_response:r!==void 0?JSON.stringify(r):"{}",prompt_number:i}),signal:AbortSignal.timeout(2e3)});if(!c.ok){let m=await c.text();throw b.failure("HOOK","Failed to send observation",{sessionId:o,status:c.status},m),new Error(`Failed to send observation to worker: ${c.status} ${m}`)}b.debug("HOOK","Observation sent successfully",{sessionId:o,toolName:s})}catch(c){throw c.cause?.code==="ECONNREFUSED"||c.name==="TimeoutError"||c.message.includes("fetch failed")?new Error("There's a problem with the worker. If you just updated, type `pm2 restart claude-mem-worker` in your terminal to continue"):c}console.log(f("PostToolUse",!0))}var A="";U.on("data",a=>A+=a);U.on("end",async()=>{let a=A?JSON.parse(A):void 0;await Z(a)}); + `;try{let T=this.db.prepare(c).all(p,u,...i),S=this.db.prepare(m).all(p,u,...i),_=this.db.prepare(g).all(p,u,...i);return{observations:T,sessions:S.map(d=>({id:d.id,sdk_session_id:d.sdk_session_id,project:d.project,request:d.request,completed:d.completed,next_steps:d.next_steps,created_at:d.created_at,created_at_epoch:d.created_at_epoch})),prompts:_.map(d=>({id:d.id,claude_session_id:d.claude_session_id,project:d.project,prompt:d.prompt_text,created_at:d.created_at,created_at_epoch:d.created_at_epoch}))}}catch(T){return console.error("[SessionStore] Error querying timeline records:",T.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};function $(a,e,s){return a==="PreCompact"?e?{continue:!0,suppressOutput:!0}:{continue:!1,stopReason:s.reason||"Pre-compact operation failed",suppressOutput:!0}:a==="SessionStart"?e&&s.context?{continue:!0,suppressOutput:!0,hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:s.context}}:{continue:!0,suppressOutput:!0}:a==="UserPromptSubmit"||a==="PostToolUse"?{continue:!0,suppressOutput:!0}:a==="Stop"?{continue:!0,suppressOutput:!0}:{continue:e,suppressOutput:!0,...s.reason&&!e?{stopReason:s.reason}:{}}}function f(a,e,s={}){let t=$(a,e,s);return JSON.stringify(t)}import I from"path";import{homedir as W}from"os";import{existsSync as G,readFileSync as Y}from"fs";import{execSync as K}from"child_process";var V=100,q=100,J=1e4;function L(){try{let a=I.join(W(),".claude-mem","settings.json");if(G(a)){let e=JSON.parse(Y(a,"utf-8")),s=parseInt(e.env?.CLAUDE_MEM_WORKER_PORT,10);if(!isNaN(s))return s}}catch{}return parseInt(process.env.CLAUDE_MEM_WORKER_PORT||"37777",10)}async function k(){try{let a=L();return(await fetch(`http://127.0.0.1:${a}/health`,{signal:AbortSignal.timeout(V)})).ok}catch{return!1}}async function Q(){let a=Date.now();for(;Date.now()-asetTimeout(e,q))}return!1}async function x(){if(await k())return;let a=D(),e=I.join(a,"node_modules",".bin","pm2"),s=I.join(a,"ecosystem.config.cjs");if(K(`"${e}" restart "${s}"`,{cwd:a,stdio:"pipe"}),!await Q())throw new Error("Worker failed to become healthy after restart")}var z=new Set(["ListMcpResourcesTool"]);async function Z(a){if(!a)throw new Error("saveHook requires input");let{session_id:e,tool_name:s,tool_input:t,tool_response:r}=a;if(z.has(s)){console.log(f("PostToolUse",!0));return}await x();let o=new R,n=o.createSDKSession(e,"",""),i=o.getPromptCounter(n);o.close();let p=b.formatTool(s,t),u=L();b.dataIn("HOOK",`PostToolUse: ${p}`,{sessionId:n,workerPort:u});try{let c=await fetch(`http://127.0.0.1:${u}/sessions/${n}/observations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool_name:s,tool_input:t!==void 0?JSON.stringify(t):"{}",tool_response:r!==void 0?JSON.stringify(r):"{}",prompt_number:i}),signal:AbortSignal.timeout(2e3)});if(!c.ok){let m=await c.text();throw b.failure("HOOK","Failed to send observation",{sessionId:n,status:c.status},m),new Error(`Failed to send observation to worker: ${c.status} ${m}`)}b.debug("HOOK","Observation sent successfully",{sessionId:n,toolName:s})}catch(c){throw c.cause?.code==="ECONNREFUSED"||c.name==="TimeoutError"||c.message.includes("fetch failed")?new Error("There's a problem with the worker. If you just updated, type `pm2 restart claude-mem-worker` in your terminal to continue"):c}console.log(f("PostToolUse",!0))}var A="";U.on("data",a=>A+=a);U.on("end",async()=>{let a=A?JSON.parse(A):void 0;await Z(a)}); diff --git a/plugin/scripts/search-server.mjs b/plugin/scripts/search-server.mjs index a3aeedc6..65813732 100755 --- a/plugin/scripts/search-server.mjs +++ b/plugin/scripts/search-server.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -import{Server as he}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as _e}from"@modelcontextprotocol/sdk/server/stdio.js";import{Client as fe}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Ee}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolRequestSchema as be,ListToolsRequestSchema as ge}from"@modelcontextprotocol/sdk/types.js";import{z as i}from"zod";import{zodToJsonSchema as Te}from"zod-to-json-schema";import{basename as Se}from"path";import pe from"better-sqlite3";import{join as L,dirname as ce,basename as xe}from"path";import{homedir as ee}from"os";import{existsSync as De,mkdirSync as de}from"fs";import{fileURLToPath as le}from"url";function ue(){return typeof __dirname<"u"?__dirname:ce(le(import.meta.url))}var $e=ue(),w=process.env.CLAUDE_MEM_DATA_DIR||L(ee(),".claude-mem"),V=process.env.CLAUDE_CONFIG_DIR||L(ee(),".claude"),ke=L(w,"archives"),Fe=L(w,"logs"),Me=L(w,"trash"),Ue=L(w,"backups"),je=L(w,"settings.json"),X=L(w,"claude-mem.db"),te=L(w,"vector-db"),Be=L(V,"settings.json"),Xe=L(V,"commands"),Pe=L(V,"CLAUDE.md");function P(c){de(c,{recursive:!0})}var G=class{db;constructor(e){e||(P(w),e=X),this.db=new pe(e),this.db.pragma("journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(r=>r.name==="observations_fts"||r.name==="session_summaries_fts"))return;console.error("[SessionSearch] Creating FTS5 tables..."),this.db.exec(` +import{Server as he}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as _e}from"@modelcontextprotocol/sdk/server/stdio.js";import{Client as fe}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Ee}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolRequestSchema as be,ListToolsRequestSchema as ge}from"@modelcontextprotocol/sdk/types.js";import{z as i}from"zod";import{zodToJsonSchema as Te}from"zod-to-json-schema";import{basename as Se}from"path";import pe from"better-sqlite3";import{join as L,dirname as ce,basename as xe}from"path";import{homedir as ee}from"os";import{existsSync as De,mkdirSync as de}from"fs";import{fileURLToPath as le}from"url";function ue(){return typeof __dirname<"u"?__dirname:ce(le(import.meta.url))}var $e=ue(),w=process.env.CLAUDE_MEM_DATA_DIR||L(ee(),".claude-mem"),V=process.env.CLAUDE_CONFIG_DIR||L(ee(),".claude"),ke=L(w,"archives"),Fe=L(w,"logs"),Ue=L(w,"trash"),Me=L(w,"backups"),je=L(w,"settings.json"),X=L(w,"claude-mem.db"),te=L(w,"vector-db"),Be=L(V,"settings.json"),Xe=L(V,"commands"),Pe=L(V,"CLAUDE.md");function P(c){de(c,{recursive:!0})}var G=class{db;constructor(e){e||(P(w),e=X),this.db=new pe(e),this.db.pragma("journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(r=>r.name==="observations_fts"||r.name==="session_summaries_fts"))return;console.error("[SessionSearch] Creating FTS5 tables..."),this.db.exec(` CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( title, subtitle, @@ -352,6 +352,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(r=>r.project)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` SELECT * FROM ( @@ -532,7 +533,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${o.replace("project","s.project")} ORDER BY up.created_at_epoch ASC - `;try{let f=this.db.prepare(p).all(d,l,...a),h=this.db.prepare(u).all(d,l,...a),b=this.db.prepare(m).all(d,l,...a);return{observations:f,sessions:h.map(_=>({id:_.id,sdk_session_id:_.sdk_session_id,project:_.project,request:_.request,completed:_.completed,next_steps:_.next_steps,created_at:_.created_at,created_at_epoch:_.created_at_epoch})),prompts:b.map(_=>({id:_.id,claude_session_id:_.claude_session_id,project:_.project,prompt:_.prompt_text,created_at:_.created_at,created_at_epoch:_.created_at_epoch}))}}catch(f){return console.error("[SessionStore] Error querying timeline records:",f.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};var $,N,k=null,ye="cm__claude-mem";try{$=new G,N=new H}catch(c){console.error("[search-server] Failed to initialize search:",c.message),process.exit(1)}async function U(c,e,s){if(!k)throw new Error("Chroma client not initialized");let t=(await k.callTool({name:"chroma_query_documents",arguments:{collection_name:ye,query_texts:[c],n_results:e,include:["documents","metadatas","distances"],where:s}})).content[0]?.text||"",n;try{n=JSON.parse(t)}catch(p){return console.error("[search-server] Failed to parse Chroma response as JSON:",p),{ids:[],distances:[],metadatas:[]}}let o=[],a=n.ids?.[0]||[];for(let p of a){let u=p.match(/obs_(\d+)_/),m=p.match(/summary_(\d+)_/),f=p.match(/prompt_(\d+)/),h=null;u?h=parseInt(u[1],10):m?h=parseInt(m[1],10):f&&(h=parseInt(f[1],10)),h!==null&&!o.includes(h)&&o.push(h)}let d=n.distances?.[0]||[],l=n.metadatas?.[0]||[];return{ids:o,distances:d,metadatas:l}}function j(){return` + `;try{let f=this.db.prepare(p).all(d,l,...a),h=this.db.prepare(u).all(d,l,...a),b=this.db.prepare(m).all(d,l,...a);return{observations:f,sessions:h.map(_=>({id:_.id,sdk_session_id:_.sdk_session_id,project:_.project,request:_.request,completed:_.completed,next_steps:_.next_steps,created_at:_.created_at,created_at_epoch:_.created_at_epoch})),prompts:b.map(_=>({id:_.id,claude_session_id:_.claude_session_id,project:_.project,prompt:_.prompt_text,created_at:_.created_at,created_at_epoch:_.created_at_epoch}))}}catch(f){return console.error("[SessionStore] Error querying timeline records:",f.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};var $,N,k=null,ye="cm__claude-mem";try{$=new G,N=new H}catch(c){console.error("[search-server] Failed to initialize search:",c.message),process.exit(1)}async function M(c,e,s){if(!k)throw new Error("Chroma client not initialized");let t=(await k.callTool({name:"chroma_query_documents",arguments:{collection_name:ye,query_texts:[c],n_results:e,include:["documents","metadatas","distances"],where:s}})).content[0]?.text||"",n;try{n=JSON.parse(t)}catch(p){return console.error("[search-server] Failed to parse Chroma response as JSON:",p),{ids:[],distances:[],metadatas:[]}}let o=[],a=n.ids?.[0]||[];for(let p of a){let u=p.match(/obs_(\d+)_/),m=p.match(/summary_(\d+)_/),f=p.match(/prompt_(\d+)/),h=null;u?h=parseInt(u[1],10):m?h=parseInt(m[1],10):f&&(h=parseInt(f[1],10)),h!==null&&!o.includes(h)&&o.push(h)}let d=n.distances?.[0]||[],l=n.metadatas?.[0]||[];return{ids:o,distances:d,metadatas:l}}function j(){return` --- \u{1F4A1} Search Strategy: ALWAYS search with index format FIRST to get an overview and identify relevant results. @@ -556,7 +557,7 @@ Other tips: `)}function Re(c,e){let s=new Date(c.created_at_epoch).toLocaleString();return`${e+1}. "${c.prompt_text}" Date: ${s} | Prompt #${c.prompt_number} Source: claude-mem://user-prompt/${c.id}`}function ve(c){let e=[];e.push(`## User Prompt #${c.prompt_number}`),e.push(`*Source: claude-mem://user-prompt/${c.id}*`),e.push(""),e.push(c.prompt_text),e.push(""),e.push("---");let s=new Date(c.created_at_epoch).toLocaleString();return e.push(`Date: ${s}`),e.join(` -`)}var Oe=i.object({project:i.string().optional().describe("Filter by project name"),type:i.union([i.enum(["decision","bugfix","feature","refactor","discovery","change"]),i.array(i.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe("Filter by observation type"),concepts:i.union([i.string(),i.array(i.string())]).optional().describe("Filter by concept tags"),files:i.union([i.string(),i.array(i.string())]).optional().describe("Filter by file paths (partial match)"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional().describe("Start date (ISO string or epoch)"),end:i.union([i.string(),i.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),oe=[{name:"search_observations",description:'Search observations using full-text search across titles, narratives, facts, and concepts. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),...Oe.shape}),handler:async c=>{try{let{query:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using hybrid semantic search (Chroma + SQLite)");let o=await U(e,100);if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let a=Date.now()-7776e6,d=o.ids.filter((l,p)=>{let u=o.metadatas[p];return u&&u.created_at_epoch>a});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=r.limit||20;t=N.getObservationsByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} observations from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=$.searchObservations(e,r)),t.length===0)return{content:[{type:"text",text:`No observations found matching "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} observation(s) matching "${e}": +`)}var Oe=i.object({project:i.string().optional().describe("Filter by project name"),type:i.union([i.enum(["decision","bugfix","feature","refactor","discovery","change"]),i.array(i.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe("Filter by observation type"),concepts:i.union([i.string(),i.array(i.string())]).optional().describe("Filter by concept tags"),files:i.union([i.string(),i.array(i.string())]).optional().describe("Filter by file paths (partial match)"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional().describe("Start date (ISO string or epoch)"),end:i.union([i.string(),i.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),oe=[{name:"search_observations",description:'Search observations using full-text search across titles, narratives, facts, and concepts. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),...Oe.shape}),handler:async c=>{try{let{query:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using hybrid semantic search (Chroma + SQLite)");let o=await M(e,100);if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let a=Date.now()-7776e6,d=o.ids.filter((l,p)=>{let u=o.metadatas[p];return u&&u.created_at_epoch>a});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=r.limit||20;t=N.getObservationsByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} observations from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=$.searchObservations(e,r)),t.length===0)return{content:[{type:"text",text:`No observations found matching "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} observation(s) matching "${e}": `,a=t.map((d,l)=>q(d,l));n=o+a.join(` @@ -564,7 +565,7 @@ Other tips: --- -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"search_sessions",description:'Search session summaries using full-text search across requests, completions, learnings, and notes. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{query:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using hybrid semantic search for sessions");let o=await U(e,100,{doc_type:"session_summary"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let a=Date.now()-7776e6,d=o.ids.filter((l,p)=>{let u=o.metadatas[p];return u&&u.created_at_epoch>a});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=r.limit||20;t=N.getSessionSummariesByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} sessions from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=$.searchSessions(e,r)),t.length===0)return{content:[{type:"text",text:`No sessions found matching "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} session(s) matching "${e}": +`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"search_sessions",description:'Search session summaries using full-text search across requests, completions, learnings, and notes. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{query:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using hybrid semantic search for sessions");let o=await M(e,100,{doc_type:"session_summary"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let a=Date.now()-7776e6,d=o.ids.filter((l,p)=>{let u=o.metadatas[p];return u&&u.created_at_epoch>a});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=r.limit||20;t=N.getSessionSummariesByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} sessions from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=$.searchSessions(e,r)),t.length===0)return{content:[{type:"text",text:`No sessions found matching "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} session(s) matching "${e}": `,a=t.map((d,l)=>re(d,l));n=o+a.join(` @@ -572,7 +573,7 @@ Other tips: --- -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_concept",description:'Find observations tagged with a specific concept. Available concepts: "discovery", "problem-solution", "what-changed", "how-it-works", "pattern", "gotcha", "change". IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({concept:i.string().describe("Concept tag to search for. Available: discovery, problem-solution, what-changed, how-it-works, pattern, gotcha, change"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{concept:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using metadata-first + semantic ranking for concept search");let o=$.findByConcept(e,r);if(console.error(`[search-server] Found ${o.length} observations with concept "${e}"`),o.length>0){let a=o.map(p=>p.id),d=await U(e,Math.min(a.length,100)),l=[];for(let p of d.ids)a.includes(p)&&!l.includes(p)&&l.push(p);console.error(`[search-server] Chroma ranked ${l.length} results by semantic relevance`),l.length>0&&(t=N.getObservationsByIds(l,{limit:r.limit||20}),t.sort((p,u)=>l.indexOf(p.id)-l.indexOf(u.id)))}}catch(o){console.error("[search-server] Chroma ranking failed, using SQLite order:",o.message)}if(t.length===0&&(console.error("[search-server] Using SQLite-only concept search"),t=$.findByConcept(e,r)),t.length===0)return{content:[{type:"text",text:`No observations found with concept "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} observation(s) with concept "${e}": +`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_concept",description:'Find observations tagged with a specific concept. Available concepts: "discovery", "problem-solution", "what-changed", "how-it-works", "pattern", "gotcha", "change". IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({concept:i.string().describe("Concept tag to search for. Available: discovery, problem-solution, what-changed, how-it-works, pattern, gotcha, change"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{concept:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using metadata-first + semantic ranking for concept search");let o=$.findByConcept(e,r);if(console.error(`[search-server] Found ${o.length} observations with concept "${e}"`),o.length>0){let a=o.map(p=>p.id),d=await M(e,Math.min(a.length,100)),l=[];for(let p of d.ids)a.includes(p)&&!l.includes(p)&&l.push(p);console.error(`[search-server] Chroma ranked ${l.length} results by semantic relevance`),l.length>0&&(t=N.getObservationsByIds(l,{limit:r.limit||20}),t.sort((p,u)=>l.indexOf(p.id)-l.indexOf(u.id)))}}catch(o){console.error("[search-server] Chroma ranking failed, using SQLite order:",o.message)}if(t.length===0&&(console.error("[search-server] Using SQLite-only concept search"),t=$.findByConcept(e,r)),t.length===0)return{content:[{type:"text",text:`No observations found with concept "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} observation(s) with concept "${e}": `,a=t.map((d,l)=>q(d,l));n=o+a.join(` @@ -580,7 +581,7 @@ Other tips: --- -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_file",description:'Find observations and sessions that reference a specific file path. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({filePath:i.string().describe("File path to search for (supports partial matching)"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{filePath:e,format:s="index",...r}=c,t=[],n=[];if(k)try{console.error("[search-server] Using metadata-first + semantic ranking for file search");let d=$.findByFile(e,r);if(console.error(`[search-server] Found ${d.observations.length} observations, ${d.sessions.length} sessions for file "${e}"`),n=d.sessions,d.observations.length>0){let l=d.observations.map(m=>m.id),p=await U(e,Math.min(l.length,100)),u=[];for(let m of p.ids)l.includes(m)&&!u.includes(m)&&u.push(m);console.error(`[search-server] Chroma ranked ${u.length} observations by semantic relevance`),u.length>0&&(t=N.getObservationsByIds(u,{limit:r.limit||20}),t.sort((m,f)=>u.indexOf(m.id)-u.indexOf(f.id)))}}catch(d){console.error("[search-server] Chroma ranking failed, using SQLite order:",d.message)}if(t.length===0&&n.length===0){console.error("[search-server] Using SQLite-only file search");let d=$.findByFile(e,r);t=d.observations,n=d.sessions}let o=t.length+n.length;if(o===0)return{content:[{type:"text",text:`No results found for file "${e}"`}]};let a;if(s==="index"){let d=`Found ${o} result(s) for file "${e}": +`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_file",description:'Find observations and sessions that reference a specific file path. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({filePath:i.string().describe("File path to search for (supports partial matching)"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{filePath:e,format:s="index",...r}=c,t=[],n=[];if(k)try{console.error("[search-server] Using metadata-first + semantic ranking for file search");let d=$.findByFile(e,r);if(console.error(`[search-server] Found ${d.observations.length} observations, ${d.sessions.length} sessions for file "${e}"`),n=d.sessions,d.observations.length>0){let l=d.observations.map(m=>m.id),p=await M(e,Math.min(l.length,100)),u=[];for(let m of p.ids)l.includes(m)&&!u.includes(m)&&u.push(m);console.error(`[search-server] Chroma ranked ${u.length} observations by semantic relevance`),u.length>0&&(t=N.getObservationsByIds(u,{limit:r.limit||20}),t.sort((m,f)=>u.indexOf(m.id)-u.indexOf(f.id)))}}catch(d){console.error("[search-server] Chroma ranking failed, using SQLite order:",d.message)}if(t.length===0&&n.length===0){console.error("[search-server] Using SQLite-only file search");let d=$.findByFile(e,r);t=d.observations,n=d.sessions}let o=t.length+n.length;if(o===0)return{content:[{type:"text",text:`No results found for file "${e}"`}]};let a;if(s==="index"){let d=`Found ${o} result(s) for file "${e}": `,l=[];t.forEach((p,u)=>{l.push(q(p,u))}),n.forEach((p,u)=>{l.push(re(p,u+t.length))}),a=d+l.join(` @@ -588,7 +589,7 @@ Other tips: --- -`)}return{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_type",description:'Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({type:i.union([i.enum(["decision","bugfix","feature","refactor","discovery","change"]),i.array(i.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).describe("Observation type(s) to filter by"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{type:e,format:s="index",...r}=c,t=Array.isArray(e)?e.join(", "):e,n=[];if(k)try{console.error("[search-server] Using metadata-first + semantic ranking for type search");let a=$.findByType(e,r);if(console.error(`[search-server] Found ${a.length} observations with type "${t}"`),a.length>0){let d=a.map(u=>u.id),l=await U(t,Math.min(d.length,100)),p=[];for(let u of l.ids)d.includes(u)&&!p.includes(u)&&p.push(u);console.error(`[search-server] Chroma ranked ${p.length} results by semantic relevance`),p.length>0&&(n=N.getObservationsByIds(p,{limit:r.limit||20}),n.sort((u,m)=>p.indexOf(u.id)-p.indexOf(m.id)))}}catch(a){console.error("[search-server] Chroma ranking failed, using SQLite order:",a.message)}if(n.length===0&&(console.error("[search-server] Using SQLite-only type search"),n=$.findByType(e,r)),n.length===0)return{content:[{type:"text",text:`No observations found with type "${t}"`}]};let o;if(s==="index"){let a=`Found ${n.length} observation(s) with type "${t}": +`)}return{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_type",description:'Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({type:i.union([i.enum(["decision","bugfix","feature","refactor","discovery","change"]),i.array(i.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).describe("Observation type(s) to filter by"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{type:e,format:s="index",...r}=c,t=Array.isArray(e)?e.join(", "):e,n=[];if(k)try{console.error("[search-server] Using metadata-first + semantic ranking for type search");let a=$.findByType(e,r);if(console.error(`[search-server] Found ${a.length} observations with type "${t}"`),a.length>0){let d=a.map(u=>u.id),l=await M(t,Math.min(d.length,100)),p=[];for(let u of l.ids)d.includes(u)&&!p.includes(u)&&p.push(u);console.error(`[search-server] Chroma ranked ${p.length} results by semantic relevance`),p.length>0&&(n=N.getObservationsByIds(p,{limit:r.limit||20}),n.sort((u,m)=>p.indexOf(u.id)-p.indexOf(m.id)))}}catch(a){console.error("[search-server] Chroma ranking failed, using SQLite order:",a.message)}if(n.length===0&&(console.error("[search-server] Using SQLite-only type search"),n=$.findByType(e,r)),n.length===0)return{content:[{type:"text",text:`No observations found with type "${t}"`}]};let o;if(s==="index"){let a=`Found ${n.length} observation(s) with type "${t}": `,d=n.map((l,p)=>q(l,p));o=a+d.join(` @@ -599,7 +600,7 @@ Other tips: `);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_recent_context",description:"Get recent session context including summaries and observations for a project",inputSchema:i.object({project:i.string().optional().describe("Project name (defaults to current working directory basename)"),limit:i.number().min(1).max(10).default(3).describe("Number of recent sessions to retrieve")}),handler:async c=>{try{let e=c.project||Se(process.cwd()),s=c.limit||3,r=N.getRecentSessionsWithStatus(e,s);if(r.length===0)return{content:[{type:"text",text:`# Recent Session Context No previous sessions found for project "${e}".`}]};let t=[];t.push("# Recent Session Context"),t.push(""),t.push(`Showing last ${r.length} session(s) for **${e}**:`),t.push("");for(let n of r)if(n.sdk_session_id){if(t.push("---"),t.push(""),n.has_summary){let o=N.getSummaryForSession(n.sdk_session_id);if(o){let a=o.prompt_number?` (Prompt #${o.prompt_number})`:"";if(t.push(`**Summary${a}**`),t.push(""),o.request&&t.push(`**Request:** ${o.request}`),o.completed&&t.push(`**Completed:** ${o.completed}`),o.learned&&t.push(`**Learned:** ${o.learned}`),o.next_steps&&t.push(`**Next Steps:** ${o.next_steps}`),o.files_read)try{let l=JSON.parse(o.files_read);Array.isArray(l)&&l.length>0&&t.push(`**Files Read:** ${l.join(", ")}`)}catch{o.files_read.trim()&&t.push(`**Files Read:** ${o.files_read}`)}if(o.files_edited)try{let l=JSON.parse(o.files_edited);Array.isArray(l)&&l.length>0&&t.push(`**Files Edited:** ${l.join(", ")}`)}catch{o.files_edited.trim()&&t.push(`**Files Edited:** ${o.files_edited}`)}let d=new Date(o.created_at).toLocaleString();t.push(`**Date:** ${d}`)}}else if(n.status==="active"){t.push("**In Progress**"),t.push(""),n.user_prompt&&t.push(`**Request:** ${n.user_prompt}`);let o=N.getObservationsForSession(n.sdk_session_id);if(o.length>0){t.push(""),t.push(`**Observations (${o.length}):**`);for(let d of o)t.push(`- ${d.title}`)}else t.push(""),t.push("*No observations yet*");t.push(""),t.push("**Status:** Active - summary pending");let a=new Date(n.started_at).toLocaleString();t.push(`**Date:** ${a}`)}else{t.push(`**${n.status.charAt(0).toUpperCase()+n.status.slice(1)}**`),t.push(""),n.user_prompt&&t.push(`**Request:** ${n.user_prompt}`),t.push(""),t.push(`**Status:** ${n.status} - no summary available`);let o=new Date(n.started_at).toLocaleString();t.push(`**Date:** ${o}`)}t.push("")}return{content:[{type:"text",text:t.join(` -`)}]}}catch(e){return{content:[{type:"text",text:`Failed to get recent context: ${e.message}`}],isError:!0}}}},{name:"search_user_prompts",description:'Search raw user prompts with full-text search. Use this to find what the user actually said/requested across all sessions. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for truncated prompts/dates (default, RECOMMENDED for initial search), "full" for complete prompt text (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{query:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using hybrid semantic search for user prompts");let o=await U(e,100,{doc_type:"user_prompt"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let a=Date.now()-7776e6,d=o.ids.filter((l,p)=>{let u=o.metadatas[p];return u&&u.created_at_epoch>a});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=r.limit||20;t=N.getUserPromptsByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} user prompts from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=$.searchUserPrompts(e,r)),t.length===0)return{content:[{type:"text",text:`No user prompts found matching "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} user prompt(s) matching "${e}": +`)}]}}catch(e){return{content:[{type:"text",text:`Failed to get recent context: ${e.message}`}],isError:!0}}}},{name:"search_user_prompts",description:'Search raw user prompts with full-text search. Use this to find what the user actually said/requested across all sessions. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:i.object({query:i.string().describe("Search query for FTS5 full-text search"),format:i.enum(["index","full"]).default("index").describe('Output format: "index" for truncated prompts/dates (default, RECOMMENDED for initial search), "full" for complete prompt text (use only after reviewing index results)'),project:i.string().optional().describe("Filter by project name"),dateRange:i.object({start:i.union([i.string(),i.number()]).optional(),end:i.union([i.string(),i.number()]).optional()}).optional().describe("Filter by date range"),limit:i.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:i.number().min(0).default(0).describe("Number of results to skip"),orderBy:i.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async c=>{try{let{query:e,format:s="index",...r}=c,t=[];if(k)try{console.error("[search-server] Using hybrid semantic search for user prompts");let o=await M(e,100,{doc_type:"user_prompt"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let a=Date.now()-7776e6,d=o.ids.filter((l,p)=>{let u=o.metadatas[p];return u&&u.created_at_epoch>a});if(console.error(`[search-server] ${d.length} results within 90-day window`),d.length>0){let l=r.limit||20;t=N.getUserPromptsByIds(d,{orderBy:"date_desc",limit:l}),console.error(`[search-server] Hydrated ${t.length} user prompts from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed, falling back to FTS5:",o.message)}if(t.length===0&&(console.error("[search-server] Using FTS5 keyword search"),t=$.searchUserPrompts(e,r)),t.length===0)return{content:[{type:"text",text:`No user prompts found matching "${e}"`}]};let n;if(s==="index"){let o=`Found ${t.length} user prompt(s) matching "${e}": `,a=t.map((d,l)=>Re(d,l));n=o+a.join(` @@ -607,7 +608,7 @@ No previous sessions found for project "${e}".`}]};let t=[];t.push("# Recent Ses --- -`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_context_timeline",description:'Get a unified timeline of context (observations, sessions, and prompts) around a specific point in time. All record types are interleaved chronologically. Useful for understanding "what was happening when X occurred". Returns depth_before records before anchor + anchor + depth_after records after (total: depth_before + 1 + depth_after mixed records).',inputSchema:i.object({anchor:i.union([i.number().describe("Observation ID to center timeline around"),i.string().describe("Session ID (format: S123) or ISO timestamp to center timeline around")]).describe('Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp'),depth_before:i.number().min(0).max(50).default(10).describe("Number of records to retrieve before anchor, not including anchor (default: 10)"),depth_after:i.number().min(0).max(50).default(10).describe("Number of records to retrieve after anchor, not including anchor (default: 10)"),project:i.string().optional().describe("Filter by project name")}),handler:async c=>{try{let f=function(g){return new Date(g).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},h=function(g){return new Date(g).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},b=function(g){return new Date(g).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},_=function(g){return g?Math.ceil(g.length/4):0};var e=f,s=h,r=b,t=_;let{anchor:n,depth_before:o=10,depth_after:a=10,project:d}=c,l,p=n,u;if(typeof n=="number"){let g=N.getObservationById(n);if(!g)return{content:[{type:"text",text:`Observation #${n} not found`}],isError:!0};l=g.created_at_epoch,u=N.getTimelineAroundObservation(n,l,o,a,d)}else if(typeof n=="string")if(n.startsWith("S")||n.startsWith("#S")){let g=n.replace(/^#?S/,""),I=parseInt(g,10),S=N.getSessionSummariesByIds([I]);if(S.length===0)return{content:[{type:"text",text:`Session #${I} not found`}],isError:!0};l=S[0].created_at_epoch,p=`S${I}`,u=N.getTimelineAroundTimestamp(l,o,a,d)}else{let g=new Date(n);if(isNaN(g.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${n}`}],isError:!0};l=g.getTime(),u=N.getTimelineAroundTimestamp(l,o,a,d)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let m=[...u.observations.map(g=>({type:"observation",data:g,epoch:g.created_at_epoch})),...u.sessions.map(g=>({type:"session",data:g,epoch:g.created_at_epoch})),...u.prompts.map(g=>({type:"prompt",data:g,epoch:g.created_at_epoch}))];if(m.sort((g,I)=>g.epoch-I.epoch),m.length===0)return{content:[{type:"text",text:`No context found around ${new Date(l).toLocaleString()} (${o} records before, ${a} records after)`}]};let E=[];E.push(`# Timeline around anchor: ${p}`),E.push(`**Window:** ${o} records before \u2192 ${a} records after | **Items:** ${m.length} (${u.observations.length} obs, ${u.sessions.length} sessions, ${u.prompts.length} prompts)`),E.push(""),E.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),E.push("");let x=new Map;for(let g of m){let I=f(g.epoch);x.has(I)||x.set(I,[]),x.get(I).push(g)}let T=Array.from(x.entries()).sort((g,I)=>{let S=new Date(g[0]).getTime(),O=new Date(I[0]).getTime();return S-O});for(let[g,I]of T){E.push(`### ${g}`),E.push("");let S=null,O="",C=!1;for(let v of I){let F=typeof p=="number"&&v.type==="observation"&&v.data.id===p||typeof p=="string"&&p.startsWith("S")&&v.type==="session"&&`S${v.data.id}`===p;if(v.type==="session"){C&&(E.push(""),C=!1,S=null,O="");let y=v.data,M=y.request||"Session summary",R=`claude-mem://session-summary/${y.id}`,A=F?" \u2190 **ANCHOR**":"";E.push(`**\u{1F3AF} #S${y.id}** ${M} (${b(v.epoch)}) [\u2192](${R})${A}`),E.push("")}else if(v.type==="prompt"){C&&(E.push(""),C=!1,S=null,O="");let y=v.data,M=y.prompt.length>100?y.prompt.substring(0,100)+"...":y.prompt;E.push(`**\u{1F4AC} User Prompt #${y.prompt_number}** (${b(v.epoch)})`),E.push(`> ${M}`),E.push("")}else if(v.type==="observation"){let y=v.data,M="General";M!==S&&(C&&E.push(""),E.push(`**${M}**`),E.push("| ID | Time | T | Title | Tokens |"),E.push("|----|------|---|-------|--------|"),S=M,C=!0,O="");let R="\u2022";switch(y.type){case"bugfix":R="\u{1F534}";break;case"feature":R="\u{1F7E3}";break;case"refactor":R="\u{1F504}";break;case"change":R="\u2705";break;case"discovery":R="\u{1F535}";break;case"decision":R="\u{1F9E0}";break}let A=h(v.epoch),D=y.title||"Untitled",B=_(y.narrative),Y=A!==O?A:"\u2033";O=A;let Z=F?" \u2190 **ANCHOR**":"";E.push(`| #${y.id} | ${Y} | ${R} | ${D}${Z} | ~${B} |`)}}C&&E.push("")}return{content:[{type:"text",text:E.join(` -`)}]}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}},{name:"get_timeline_by_query",description:'Search for observations using natural language and get timeline context around the best match. Two modes: "auto" (default) automatically uses top result as timeline anchor; "interactive" returns top matches for you to choose from. This combines search + timeline into a single operation for faster context discovery.',inputSchema:i.object({query:i.string().describe("Natural language search query to find relevant observations"),mode:i.enum(["auto","interactive"]).default("auto").describe("auto: Automatically use top search result as timeline anchor. interactive: Show top N search results for manual anchor selection."),depth_before:i.number().min(0).max(50).default(10).describe("Number of timeline records before anchor (default: 10)"),depth_after:i.number().min(0).max(50).default(10).describe("Number of timeline records after anchor (default: 10)"),limit:i.number().min(1).max(20).default(5).describe("For interactive mode: number of top search results to display (default: 5)"),project:i.string().optional().describe("Filter by project name")}),handler:async c=>{try{let{query:n,mode:o="auto",depth_before:a=10,depth_after:d=10,limit:l=5,project:p}=c,u=[];if(k)try{console.error("[search-server] Using hybrid semantic search for timeline query");let m=await U(n,100);if(console.error(`[search-server] Chroma returned ${m.ids.length} semantic matches`),m.ids.length>0){let f=Date.now()-7776e6,h=m.ids.filter((b,_)=>{let E=m.metadatas[_];return E&&E.created_at_epoch>f});console.error(`[search-server] ${h.length} results within 90-day window`),h.length>0&&(u=N.getObservationsByIds(h,{orderBy:"date_desc",limit:o==="auto"?1:l}),console.error(`[search-server] Hydrated ${u.length} observations from SQLite`))}}catch(m){console.error("[search-server] Chroma query failed, falling back to FTS5:",m.message)}if(u.length===0&&(console.error("[search-server] Using FTS5 keyword search"),u=$.searchObservations(n,{orderBy:"relevance",limit:o==="auto"?1:l,project:p})),u.length===0)return{content:[{type:"text",text:`No observations found matching "${n}". Try a different search query.`}]};if(o==="interactive"){let m=[];m.push("# Timeline Anchor Search Results"),m.push(""),m.push(`Found ${u.length} observation(s) matching "${n}"`),m.push(""),m.push("To get timeline context around any of these observations, use the `get_context_timeline` tool with the observation ID as the anchor."),m.push(""),m.push(`**Top ${u.length} matches:**`),m.push("");for(let f=0;f({type:"observation",data:S,epoch:S.created_at_epoch})),...f.sessions.map(S=>({type:"session",data:S,epoch:S.created_at_epoch})),...f.prompts.map(S=>({type:"prompt",data:S,epoch:S.created_at_epoch}))];if(h.sort((S,O)=>S.epoch-O.epoch),h.length===0)return{content:[{type:"text",text:`Found observation #${m.id} matching "${n}", but no timeline context available (${a} records before, ${d} records after).`}]};let T=[];T.push(`# Timeline for query: "${n}"`),T.push(`**Anchor:** Observation #${m.id} - ${m.title||"Untitled"}`),T.push(`**Window:** ${a} records before \u2192 ${d} records after | **Items:** ${h.length} (${f.observations.length} obs, ${f.sessions.length} sessions, ${f.prompts.length} prompts)`),T.push(""),T.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),T.push("");let g=new Map;for(let S of h){let O=b(S.epoch);g.has(O)||g.set(O,[]),g.get(O).push(S)}let I=Array.from(g.entries()).sort((S,O)=>{let C=new Date(S[0]).getTime(),v=new Date(O[0]).getTime();return C-v});for(let[S,O]of I){T.push(`### ${S}`),T.push("");let C=null,v="",F=!1;for(let y of O){let M=y.type==="observation"&&y.data.id===m.id;if(y.type==="session"){F&&(T.push(""),F=!1,C=null,v="");let R=y.data,A=R.request||"Session summary",D=`claude-mem://session-summary/${R.id}`;T.push(`**\u{1F3AF} #S${R.id}** ${A} (${E(y.epoch)}) [\u2192](${D})`),T.push("")}else if(y.type==="prompt"){F&&(T.push(""),F=!1,C=null,v="");let R=y.data,A=R.prompt.length>100?R.prompt.substring(0,100)+"...":R.prompt;T.push(`**\u{1F4AC} User Prompt #${R.prompt_number}** (${E(y.epoch)})`),T.push(`> ${A}`),T.push("")}else if(y.type==="observation"){let R=y.data,A="General";A!==C&&(F&&T.push(""),T.push(`**${A}**`),T.push("| ID | Time | T | Title | Tokens |"),T.push("|----|------|---|-------|--------|"),C=A,F=!0,v="");let D="\u2022";switch(R.type){case"bugfix":D="\u{1F534}";break;case"feature":D="\u{1F7E3}";break;case"refactor":D="\u{1F504}";break;case"change":D="\u2705";break;case"discovery":D="\u{1F535}";break;case"decision":D="\u{1F9E0}";break}let B=_(y.epoch),z=R.title||"Untitled",Y=x(R.narrative),ie=B!==v?B:"\u2033";v=B;let ae=M?" \u2190 **ANCHOR**":"";T.push(`| #${R.id} | ${ie} | ${D} | ${z}${ae} | ~${Y} |`)}}F&&T.push("")}return{content:[{type:"text",text:T.join(` +`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_context_timeline",description:'Get a unified timeline of context (observations, sessions, and prompts) around a specific point in time. All record types are interleaved chronologically. Useful for understanding "what was happening when X occurred". Returns depth_before records before anchor + anchor + depth_after records after (total: depth_before + 1 + depth_after mixed records).',inputSchema:i.object({anchor:i.union([i.number().describe("Observation ID to center timeline around"),i.string().describe("Session ID (format: S123) or ISO timestamp to center timeline around")]).describe('Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp'),depth_before:i.number().min(0).max(50).default(10).describe("Number of records to retrieve before anchor, not including anchor (default: 10)"),depth_after:i.number().min(0).max(50).default(10).describe("Number of records to retrieve after anchor, not including anchor (default: 10)"),project:i.string().optional().describe("Filter by project name")}),handler:async c=>{try{let f=function(g){return new Date(g).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},h=function(g){return new Date(g).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},b=function(g){return new Date(g).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},_=function(g){return g?Math.ceil(g.length/4):0};var e=f,s=h,r=b,t=_;let{anchor:n,depth_before:o=10,depth_after:a=10,project:d}=c,l,p=n,u;if(typeof n=="number"){let g=N.getObservationById(n);if(!g)return{content:[{type:"text",text:`Observation #${n} not found`}],isError:!0};l=g.created_at_epoch,u=N.getTimelineAroundObservation(n,l,o,a,d)}else if(typeof n=="string")if(n.startsWith("S")||n.startsWith("#S")){let g=n.replace(/^#?S/,""),I=parseInt(g,10),S=N.getSessionSummariesByIds([I]);if(S.length===0)return{content:[{type:"text",text:`Session #${I} not found`}],isError:!0};l=S[0].created_at_epoch,p=`S${I}`,u=N.getTimelineAroundTimestamp(l,o,a,d)}else{let g=new Date(n);if(isNaN(g.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${n}`}],isError:!0};l=g.getTime(),u=N.getTimelineAroundTimestamp(l,o,a,d)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let m=[...u.observations.map(g=>({type:"observation",data:g,epoch:g.created_at_epoch})),...u.sessions.map(g=>({type:"session",data:g,epoch:g.created_at_epoch})),...u.prompts.map(g=>({type:"prompt",data:g,epoch:g.created_at_epoch}))];if(m.sort((g,I)=>g.epoch-I.epoch),m.length===0)return{content:[{type:"text",text:`No context found around ${new Date(l).toLocaleString()} (${o} records before, ${a} records after)`}]};let E=[];E.push(`# Timeline around anchor: ${p}`),E.push(`**Window:** ${o} records before \u2192 ${a} records after | **Items:** ${m.length} (${u.observations.length} obs, ${u.sessions.length} sessions, ${u.prompts.length} prompts)`),E.push(""),E.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),E.push("");let x=new Map;for(let g of m){let I=f(g.epoch);x.has(I)||x.set(I,[]),x.get(I).push(g)}let T=Array.from(x.entries()).sort((g,I)=>{let S=new Date(g[0]).getTime(),O=new Date(I[0]).getTime();return S-O});for(let[g,I]of T){E.push(`### ${g}`),E.push("");let S=null,O="",C=!1;for(let v of I){let F=typeof p=="number"&&v.type==="observation"&&v.data.id===p||typeof p=="string"&&p.startsWith("S")&&v.type==="session"&&`S${v.data.id}`===p;if(v.type==="session"){C&&(E.push(""),C=!1,S=null,O="");let y=v.data,U=y.request||"Session summary",R=`claude-mem://session-summary/${y.id}`,A=F?" \u2190 **ANCHOR**":"";E.push(`**\u{1F3AF} #S${y.id}** ${U} (${b(v.epoch)}) [\u2192](${R})${A}`),E.push("")}else if(v.type==="prompt"){C&&(E.push(""),C=!1,S=null,O="");let y=v.data,U=y.prompt.length>100?y.prompt.substring(0,100)+"...":y.prompt;E.push(`**\u{1F4AC} User Prompt #${y.prompt_number}** (${b(v.epoch)})`),E.push(`> ${U}`),E.push("")}else if(v.type==="observation"){let y=v.data,U="General";U!==S&&(C&&E.push(""),E.push(`**${U}**`),E.push("| ID | Time | T | Title | Tokens |"),E.push("|----|------|---|-------|--------|"),S=U,C=!0,O="");let R="\u2022";switch(y.type){case"bugfix":R="\u{1F534}";break;case"feature":R="\u{1F7E3}";break;case"refactor":R="\u{1F504}";break;case"change":R="\u2705";break;case"discovery":R="\u{1F535}";break;case"decision":R="\u{1F9E0}";break}let A=h(v.epoch),D=y.title||"Untitled",B=_(y.narrative),Y=A!==O?A:"\u2033";O=A;let Z=F?" \u2190 **ANCHOR**":"";E.push(`| #${y.id} | ${Y} | ${R} | ${D}${Z} | ~${B} |`)}}C&&E.push("")}return{content:[{type:"text",text:E.join(` +`)}]}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}},{name:"get_timeline_by_query",description:'Search for observations using natural language and get timeline context around the best match. Two modes: "auto" (default) automatically uses top result as timeline anchor; "interactive" returns top matches for you to choose from. This combines search + timeline into a single operation for faster context discovery.',inputSchema:i.object({query:i.string().describe("Natural language search query to find relevant observations"),mode:i.enum(["auto","interactive"]).default("auto").describe("auto: Automatically use top search result as timeline anchor. interactive: Show top N search results for manual anchor selection."),depth_before:i.number().min(0).max(50).default(10).describe("Number of timeline records before anchor (default: 10)"),depth_after:i.number().min(0).max(50).default(10).describe("Number of timeline records after anchor (default: 10)"),limit:i.number().min(1).max(20).default(5).describe("For interactive mode: number of top search results to display (default: 5)"),project:i.string().optional().describe("Filter by project name")}),handler:async c=>{try{let{query:n,mode:o="auto",depth_before:a=10,depth_after:d=10,limit:l=5,project:p}=c,u=[];if(k)try{console.error("[search-server] Using hybrid semantic search for timeline query");let m=await M(n,100);if(console.error(`[search-server] Chroma returned ${m.ids.length} semantic matches`),m.ids.length>0){let f=Date.now()-7776e6,h=m.ids.filter((b,_)=>{let E=m.metadatas[_];return E&&E.created_at_epoch>f});console.error(`[search-server] ${h.length} results within 90-day window`),h.length>0&&(u=N.getObservationsByIds(h,{orderBy:"date_desc",limit:o==="auto"?1:l}),console.error(`[search-server] Hydrated ${u.length} observations from SQLite`))}}catch(m){console.error("[search-server] Chroma query failed, falling back to FTS5:",m.message)}if(u.length===0&&(console.error("[search-server] Using FTS5 keyword search"),u=$.searchObservations(n,{orderBy:"relevance",limit:o==="auto"?1:l,project:p})),u.length===0)return{content:[{type:"text",text:`No observations found matching "${n}". Try a different search query.`}]};if(o==="interactive"){let m=[];m.push("# Timeline Anchor Search Results"),m.push(""),m.push(`Found ${u.length} observation(s) matching "${n}"`),m.push(""),m.push("To get timeline context around any of these observations, use the `get_context_timeline` tool with the observation ID as the anchor."),m.push(""),m.push(`**Top ${u.length} matches:**`),m.push("");for(let f=0;f({type:"observation",data:S,epoch:S.created_at_epoch})),...f.sessions.map(S=>({type:"session",data:S,epoch:S.created_at_epoch})),...f.prompts.map(S=>({type:"prompt",data:S,epoch:S.created_at_epoch}))];if(h.sort((S,O)=>S.epoch-O.epoch),h.length===0)return{content:[{type:"text",text:`Found observation #${m.id} matching "${n}", but no timeline context available (${a} records before, ${d} records after).`}]};let T=[];T.push(`# Timeline for query: "${n}"`),T.push(`**Anchor:** Observation #${m.id} - ${m.title||"Untitled"}`),T.push(`**Window:** ${a} records before \u2192 ${d} records after | **Items:** ${h.length} (${f.observations.length} obs, ${f.sessions.length} sessions, ${f.prompts.length} prompts)`),T.push(""),T.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),T.push("");let g=new Map;for(let S of h){let O=b(S.epoch);g.has(O)||g.set(O,[]),g.get(O).push(S)}let I=Array.from(g.entries()).sort((S,O)=>{let C=new Date(S[0]).getTime(),v=new Date(O[0]).getTime();return C-v});for(let[S,O]of I){T.push(`### ${S}`),T.push("");let C=null,v="",F=!1;for(let y of O){let U=y.type==="observation"&&y.data.id===m.id;if(y.type==="session"){F&&(T.push(""),F=!1,C=null,v="");let R=y.data,A=R.request||"Session summary",D=`claude-mem://session-summary/${R.id}`;T.push(`**\u{1F3AF} #S${R.id}** ${A} (${E(y.epoch)}) [\u2192](${D})`),T.push("")}else if(y.type==="prompt"){F&&(T.push(""),F=!1,C=null,v="");let R=y.data,A=R.prompt.length>100?R.prompt.substring(0,100)+"...":R.prompt;T.push(`**\u{1F4AC} User Prompt #${R.prompt_number}** (${E(y.epoch)})`),T.push(`> ${A}`),T.push("")}else if(y.type==="observation"){let R=y.data,A="General";A!==C&&(F&&T.push(""),T.push(`**${A}**`),T.push("| ID | Time | T | Title | Tokens |"),T.push("|----|------|---|-------|--------|"),C=A,F=!0,v="");let D="\u2022";switch(R.type){case"bugfix":D="\u{1F534}";break;case"feature":D="\u{1F7E3}";break;case"refactor":D="\u{1F504}";break;case"change":D="\u2705";break;case"discovery":D="\u{1F535}";break;case"decision":D="\u{1F9E0}";break}let B=_(y.epoch),z=R.title||"Untitled",Y=x(R.narrative),ie=B!==v?B:"\u2033";v=B;let ae=U?" \u2190 **ANCHOR**":"";T.push(`| #${R.id} | ${ie} | ${D} | ${z}${ae} | ~${Y} |`)}}F&&T.push("")}return{content:[{type:"text",text:T.join(` `)}]}}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}}],Q=new he({name:"claude-mem-search",version:"1.0.0"},{capabilities:{tools:{}}});Q.setRequestHandler(ge,async()=>({tools:oe.map(c=>({name:c.name,description:c.description,inputSchema:Te(c.inputSchema)}))}));Q.setRequestHandler(be,async c=>{let e=oe.find(s=>s.name===c.params.name);if(!e)throw new Error(`Unknown tool: ${c.params.name}`);try{return await e.handler(c.params.arguments||{})}catch(s){return{content:[{type:"text",text:`Tool execution failed: ${s.message}`}],isError:!0}}});async function Ie(){let c=new _e;await Q.connect(c),console.error("[search-server] Claude-mem search server started"),setTimeout(async()=>{try{console.error("[search-server] Initializing Chroma client...");let e=new Ee({command:"uvx",args:["chroma-mcp","--client-type","persistent","--data-dir",te],stderr:"ignore"}),s=new fe({name:"claude-mem-search-chroma-client",version:"1.0.0"},{capabilities:{}});await s.connect(e),k=s,console.error("[search-server] Chroma client connected successfully")}catch(e){console.error("[search-server] Failed to initialize Chroma client:",e.message),console.error("[search-server] Falling back to FTS5-only search"),k=null}},0)}Ie().catch(c=>{console.error("[search-server] Fatal error:",c),process.exit(1)}); diff --git a/plugin/scripts/summary-hook.js b/plugin/scripts/summary-hook.js index 069936ae..2e5b09cb 100755 --- a/plugin/scripts/summary-hook.js +++ b/plugin/scripts/summary-hook.js @@ -216,6 +216,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(t=>t.project)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` SELECT * FROM ( diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index cfd6a958..2714fd3d 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -266,6 +266,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let a=Obje `).all(e)}getAllProjects(){return this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `).all().map(t=>t.project)}getRecentSessionsWithStatus(e,a=3){return this.db.prepare(` SELECT * FROM ( diff --git a/plugin/ui/viewer-bundle.js b/plugin/ui/viewer-bundle.js index 17f4870d..5a13fb5e 100644 --- a/plugin/ui/viewer-bundle.js +++ b/plugin/ui/viewer-bundle.js @@ -1,13 +1,13 @@ -"use strict";(()=>{var If=Object.create;var Tu=Object.defineProperty;var Af=Object.getOwnPropertyDescriptor;var Uf=Object.getOwnPropertyNames;var Ff=Object.getPrototypeOf,jf=Object.prototype.hasOwnProperty;var be=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Vf=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of Uf(t))!jf.call(e,l)&&l!==n&&Tu(e,l,{get:()=>t[l],enumerable:!(r=Af(t,l))||r.enumerable});return e};var L=(e,t,n)=>(n=e!=null?If(Ff(e)):{},Vf(t||!e||!e.__esModule?Tu(n,"default",{value:e,enumerable:!0}):n,e));var ju=be(T=>{"use strict";var zn=Symbol.for("react.element"),Bf=Symbol.for("react.portal"),Hf=Symbol.for("react.fragment"),Wf=Symbol.for("react.strict_mode"),$f=Symbol.for("react.profiler"),Qf=Symbol.for("react.provider"),Kf=Symbol.for("react.context"),Gf=Symbol.for("react.forward_ref"),Xf=Symbol.for("react.suspense"),Yf=Symbol.for("react.memo"),Zf=Symbol.for("react.lazy"),Pu=Symbol.iterator;function Jf(e){return e===null||typeof e!="object"?null:(e=Pu&&e[Pu]||e["@@iterator"],typeof e=="function"?e:null)}var Mu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ru=Object.assign,zu={};function Zt(e,t,n){this.props=e,this.context=t,this.refs=zu,this.updater=n||Mu}Zt.prototype.isReactComponent={};Zt.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Zt.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Du(){}Du.prototype=Zt.prototype;function no(e,t,n){this.props=e,this.context=t,this.refs=zu,this.updater=n||Mu}var ro=no.prototype=new Du;ro.constructor=no;Ru(ro,Zt.prototype);ro.isPureReactComponent=!0;var Lu=Array.isArray,Iu=Object.prototype.hasOwnProperty,lo={current:null},Au={key:!0,ref:!0,__self:!0,__source:!0};function Uu(e,t,n){var r,l={},o=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(o=""+t.key),t)Iu.call(t,r)&&!Au.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1{"use strict";Vu.exports=ju()});var Zu=be(D=>{"use strict";function ao(e,t){var n=e.length;e.push(t);e:for(;0>>1,l=e[r];if(0>>1;rOr(u,n))sOr(a,u)?(e[r]=a,e[s]=n,r=s):(e[r]=u,e[i]=n,r=i);else if(sOr(a,n))e[r]=a,e[s]=n,r=s;else break e}}return t}function Or(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}typeof performance=="object"&&typeof performance.now=="function"?(Bu=performance,D.unstable_now=function(){return Bu.now()}):(io=Date,Hu=io.now(),D.unstable_now=function(){return io.now()-Hu});var Bu,io,Hu,Ke=[],ft=[],nd=1,Ne=null,ne=3,zr=!1,zt=!1,In=!1,Qu=typeof setTimeout=="function"?setTimeout:null,Ku=typeof clearTimeout=="function"?clearTimeout:null,Wu=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function co(e){for(var t=Ae(ft);t!==null;){if(t.callback===null)Rr(ft);else if(t.startTime<=e)Rr(ft),t.sortIndex=t.expirationTime,ao(Ke,t);else break;t=Ae(ft)}}function fo(e){if(In=!1,co(e),!zt)if(Ae(Ke)!==null)zt=!0,mo(po);else{var t=Ae(ft);t!==null&&vo(fo,t.startTime-e)}}function po(e,t){zt=!1,In&&(In=!1,Ku(An),An=-1),zr=!0;var n=ne;try{for(co(t),Ne=Ae(Ke);Ne!==null&&(!(Ne.expirationTime>t)||e&&!Yu());){var r=Ne.callback;if(typeof r=="function"){Ne.callback=null,ne=Ne.priorityLevel;var l=r(Ne.expirationTime<=t);t=D.unstable_now(),typeof l=="function"?Ne.callback=l:Ne===Ae(Ke)&&Rr(Ke),co(t)}else Rr(Ke);Ne=Ae(Ke)}if(Ne!==null)var o=!0;else{var i=Ae(ft);i!==null&&vo(fo,i.startTime-t),o=!1}return o}finally{Ne=null,ne=n,zr=!1}}var Dr=!1,Mr=null,An=-1,Gu=5,Xu=-1;function Yu(){return!(D.unstable_now()-Xue||125r?(e.sortIndex=n,ao(ft,e),Ae(Ke)===null&&e===Ae(ft)&&(In?(Ku(An),An=-1):In=!0,vo(fo,n-r))):(e.sortIndex=l,ao(Ke,e),zt||zr||(zt=!0,mo(po))),e};D.unstable_shouldYield=Yu;D.unstable_wrapCallback=function(e){var t=ne;return function(){var n=ne;ne=t;try{return e.apply(this,arguments)}finally{ne=n}}}});var qu=be((hm,Ju)=>{"use strict";Ju.exports=Zu()});var nf=be(_e=>{"use strict";var rd=de(),ke=qu();function h(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Fo=Object.prototype.hasOwnProperty,ld=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,bu={},es={};function od(e){return Fo.call(es,e)?!0:Fo.call(bu,e)?!1:ld.test(e)?es[e]=!0:(bu[e]=!0,!1)}function id(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ud(e,t,n,r){if(t===null||typeof t>"u"||id(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function fe(e,t,n,r,l,o,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=i}var te={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){te[e]=new fe(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];te[t]=new fe(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){te[e]=new fe(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){te[e]=new fe(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){te[e]=new fe(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){te[e]=new fe(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){te[e]=new fe(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){te[e]=new fe(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){te[e]=new fe(e,5,!1,e.toLowerCase(),null,!1,!1)});var Oi=/[\-:]([a-z])/g;function Mi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Oi,Mi);te[t]=new fe(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Oi,Mi);te[t]=new fe(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Oi,Mi);te[t]=new fe(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){te[e]=new fe(e,1,!1,e.toLowerCase(),null,!1,!1)});te.xlinkHref=new fe("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){te[e]=new fe(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ri(e,t,n,r){var l=te.hasOwnProperty(t)?te[t]:null;(l!==null?l.type!==0:r||!(2{var Df=Object.create;var Tu=Object.defineProperty;var Af=Object.getOwnPropertyDescriptor;var Uf=Object.getOwnPropertyNames;var Ff=Object.getPrototypeOf,jf=Object.prototype.hasOwnProperty;var qe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Vf=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of Uf(t))!jf.call(e,l)&&l!==n&&Tu(e,l,{get:()=>t[l],enumerable:!(r=Af(t,l))||r.enumerable});return e};var L=(e,t,n)=>(n=e!=null?Df(Ff(e)):{},Vf(t||!e||!e.__esModule?Tu(n,"default",{value:e,enumerable:!0}):n,e));var ju=qe(T=>{"use strict";var zn=Symbol.for("react.element"),Bf=Symbol.for("react.portal"),Hf=Symbol.for("react.fragment"),Wf=Symbol.for("react.strict_mode"),$f=Symbol.for("react.profiler"),Qf=Symbol.for("react.provider"),Kf=Symbol.for("react.context"),Gf=Symbol.for("react.forward_ref"),Xf=Symbol.for("react.suspense"),Yf=Symbol.for("react.memo"),Zf=Symbol.for("react.lazy"),Pu=Symbol.iterator;function Jf(e){return e===null||typeof e!="object"?null:(e=Pu&&e[Pu]||e["@@iterator"],typeof e=="function"?e:null)}var Mu={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ru=Object.assign,zu={};function Zt(e,t,n){this.props=e,this.context=t,this.refs=zu,this.updater=n||Mu}Zt.prototype.isReactComponent={};Zt.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Zt.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Iu(){}Iu.prototype=Zt.prototype;function no(e,t,n){this.props=e,this.context=t,this.refs=zu,this.updater=n||Mu}var ro=no.prototype=new Iu;ro.constructor=no;Ru(ro,Zt.prototype);ro.isPureReactComponent=!0;var Lu=Array.isArray,Du=Object.prototype.hasOwnProperty,lo={current:null},Au={key:!0,ref:!0,__self:!0,__source:!0};function Uu(e,t,n){var r,l={},o=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(o=""+t.key),t)Du.call(t,r)&&!Au.hasOwnProperty(r)&&(l[r]=t[r]);var u=arguments.length-2;if(u===1)l.children=n;else if(1{"use strict";Vu.exports=ju()});var Zu=qe(I=>{"use strict";function ao(e,t){var n=e.length;e.push(t);e:for(;0>>1,l=e[r];if(0>>1;rOr(u,n))sOr(a,u)?(e[r]=a,e[s]=n,r=s):(e[r]=u,e[i]=n,r=i);else if(sOr(a,n))e[r]=a,e[s]=n,r=s;else break e}}return t}function Or(e,t){var n=e.sortIndex-t.sortIndex;return n!==0?n:e.id-t.id}typeof performance=="object"&&typeof performance.now=="function"?(Bu=performance,I.unstable_now=function(){return Bu.now()}):(io=Date,Hu=io.now(),I.unstable_now=function(){return io.now()-Hu});var Bu,io,Hu,Qe=[],ct=[],nd=1,Ne=null,ne=3,zr=!1,zt=!1,Dn=!1,Qu=typeof setTimeout=="function"?setTimeout:null,Ku=typeof clearTimeout=="function"?clearTimeout:null,Wu=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function co(e){for(var t=De(ct);t!==null;){if(t.callback===null)Rr(ct);else if(t.startTime<=e)Rr(ct),t.sortIndex=t.expirationTime,ao(Qe,t);else break;t=De(ct)}}function fo(e){if(Dn=!1,co(e),!zt)if(De(Qe)!==null)zt=!0,mo(po);else{var t=De(ct);t!==null&&vo(fo,t.startTime-e)}}function po(e,t){zt=!1,Dn&&(Dn=!1,Ku(An),An=-1),zr=!0;var n=ne;try{for(co(t),Ne=De(Qe);Ne!==null&&(!(Ne.expirationTime>t)||e&&!Yu());){var r=Ne.callback;if(typeof r=="function"){Ne.callback=null,ne=Ne.priorityLevel;var l=r(Ne.expirationTime<=t);t=I.unstable_now(),typeof l=="function"?Ne.callback=l:Ne===De(Qe)&&Rr(Qe),co(t)}else Rr(Qe);Ne=De(Qe)}if(Ne!==null)var o=!0;else{var i=De(ct);i!==null&&vo(fo,i.startTime-t),o=!1}return o}finally{Ne=null,ne=n,zr=!1}}var Ir=!1,Mr=null,An=-1,Gu=5,Xu=-1;function Yu(){return!(I.unstable_now()-Xue||125r?(e.sortIndex=n,ao(ct,e),De(Qe)===null&&e===De(ct)&&(Dn?(Ku(An),An=-1):Dn=!0,vo(fo,n-r))):(e.sortIndex=l,ao(Qe,e),zt||zr||(zt=!0,mo(po))),e};I.unstable_shouldYield=Yu;I.unstable_wrapCallback=function(e){var t=ne;return function(){var n=ne;ne=t;try{return e.apply(this,arguments)}finally{ne=n}}}});var qu=qe((hm,Ju)=>{"use strict";Ju.exports=Zu()});var nf=qe(xe=>{"use strict";var rd=de(),Ee=qu();function h(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Fo=Object.prototype.hasOwnProperty,ld=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,bu={},es={};function od(e){return Fo.call(es,e)?!0:Fo.call(bu,e)?!1:ld.test(e)?es[e]=!0:(bu[e]=!0,!1)}function id(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ud(e,t,n,r){if(t===null||typeof t>"u"||id(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ce(e,t,n,r,l,o,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=i}var te={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){te[e]=new ce(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];te[t]=new ce(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){te[e]=new ce(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){te[e]=new ce(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){te[e]=new ce(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){te[e]=new ce(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){te[e]=new ce(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){te[e]=new ce(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){te[e]=new ce(e,5,!1,e.toLowerCase(),null,!1,!1)});var Oi=/[\-:]([a-z])/g;function Mi(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Oi,Mi);te[t]=new ce(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Oi,Mi);te[t]=new ce(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Oi,Mi);te[t]=new ce(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){te[e]=new ce(e,1,!1,e.toLowerCase(),null,!1,!1)});te.xlinkHref=new ce("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){te[e]=new ce(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ri(e,t,n,r){var l=te.hasOwnProperty(t)?te[t]:null;(l!==null?l.type!==0:r||!(2u||l[i]!==o[u]){var s=` -`+l[i].replace(" at new "," at ");return e.displayName&&s.includes("")&&(s=s.replace("",e.displayName)),s}while(1<=i&&0<=u);break}}}finally{go=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Qn(e):""}function sd(e){switch(e.tag){case 5:return Qn(e.type);case 16:return Qn("Lazy");case 13:return Qn("Suspense");case 19:return Qn("SuspenseList");case 0:case 2:case 15:return e=yo(e.type,!1),e;case 11:return e=yo(e.type.render,!1),e;case 1:return e=yo(e.type,!0),e;default:return""}}function Ho(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case en:return"Fragment";case bt:return"Portal";case jo:return"Profiler";case zi:return"StrictMode";case Vo:return"Suspense";case Bo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ua:return(e.displayName||"Context")+".Consumer";case ia:return(e._context.displayName||"Context")+".Provider";case Di:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ii:return t=e.displayName||null,t!==null?t:Ho(e.type)||"Memo";case pt:t=e._payload,e=e._init;try{return Ho(e(t))}catch{}}return null}function ad(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ho(t);case 8:return t===zi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Tt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function aa(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function cd(e){var t=aa(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ar(e){e._valueTracker||(e._valueTracker=cd(e))}function ca(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=aa(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function cl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Wo(e,t){var n=t.checked;return H({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function ns(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Tt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function fa(e,t){t=t.checked,t!=null&&Ri(e,"checked",t,!1)}function $o(e,t){fa(e,t);var n=Tt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Qo(e,t.type,n):t.hasOwnProperty("defaultValue")&&Qo(e,t.type,Tt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function rs(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Qo(e,t,n){(t!=="number"||cl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Kn=Array.isArray;function dn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Ur.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function or(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Yn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},fd=["Webkit","ms","Moz","O"];Object.keys(Yn).forEach(function(e){fd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Yn[t]=Yn[e]})});function va(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Yn.hasOwnProperty(e)&&Yn[e]?(""+t).trim():t+"px"}function ha(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=va(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var dd=H({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Xo(e,t){if(t){if(dd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(h(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(h(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(h(61))}if(t.style!=null&&typeof t.style!="object")throw Error(h(62))}}function Yo(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Zo=null;function Ai(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Jo=null,pn=null,mn=null;function is(e){if(e=_r(e)){if(typeof Jo!="function")throw Error(h(280));var t=e.stateNode;t&&(t=Fl(t),Jo(e.stateNode,e.type,t))}}function ga(e){pn?mn?mn.push(e):mn=[e]:pn=e}function ya(){if(pn){var e=pn,t=mn;if(mn=pn=null,is(e),t)for(e=0;e>>=0,e===0?32:31-(_d(e)/xd|0)|0}var Fr=64,jr=4194304;function Gn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ml(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,o=e.pingedLanes,i=n&268435455;if(i!==0){var u=i&~l;u!==0?r=Gn(u):(o&=i,o!==0&&(r=Gn(o)))}else i=n&~l,i!==0?r=Gn(i):o!==0&&(r=Gn(o));if(r===0)return 0;if(t!==0&&t!==r&&(t&l)===0&&(l=r&-r,o=t&-t,l>=o||l===16&&(o&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function kr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Be(t),e[t]=n}function Pd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Jn),vs=" ",hs=!1;function Fa(e,t){switch(e){case"keyup":return np.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ja(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var tn=!1;function lp(e,t){switch(e){case"compositionend":return ja(t);case"keypress":return t.which!==32?null:(hs=!0,vs);case"textInput":return e=t.data,e===vs&&hs?null:e;default:return null}}function op(e,t){if(tn)return e==="compositionend"||!$i&&Fa(e,t)?(e=Aa(),tl=Bi=gt=null,tn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ss(n)}}function Wa(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Wa(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function $a(){for(var e=window,t=cl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=cl(e.document)}return t}function Qi(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function mp(e){var t=$a(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Wa(n.ownerDocument.documentElement,n)){if(r!==null&&Qi(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=r.end===void 0?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=ws(n,o);var i=ws(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,nn=null,ri=null,bn=null,li=!1;function ks(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;li||nn==null||nn!==cl(r)||(r=nn,"selectionStart"in r&&Qi(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),bn&&fr(bn,r)||(bn=r,r=gl(ri,"onSelect"),0on||(e.current=ci[on],ci[on]=null,on--)}function I(e,t){on++,ci[on]=e.current,e.current=t}var Pt={},ie=Ot(Pt),ve=Ot(!1),Bt=Pt;function Sn(e,t){var n=e.type.contextTypes;if(!n)return Pt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},o;for(o in n)l[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function he(e){return e=e.childContextTypes,e!=null}function Sl(){U(ve),U(ie)}function Os(e,t,n){if(ie.current!==Pt)throw Error(h(168));I(ie,t),I(ve,n)}function ba(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(h(108,ad(e)||"Unknown",l));return H({},n,r)}function wl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Pt,Bt=ie.current,I(ie,e),I(ve,ve.current),!0}function Ms(e,t,n){var r=e.stateNode;if(!r)throw Error(h(169));n?(e=ba(e,t,Bt),r.__reactInternalMemoizedMergedChildContext=e,U(ve),U(ie),I(ie,e)):U(ve),I(ve,n)}var tt=null,jl=!1,Lo=!1;function ec(e){tt===null?tt=[e]:tt.push(e)}function xp(e){jl=!0,ec(e)}function Mt(){if(!Lo&&tt!==null){Lo=!0;var e=0,t=R;try{var n=tt;for(R=1;e>=i,l-=i,nt=1<<32-Be(t)+l|n<x?(K=C,C=null):K=C.sibling;var P=v(f,C,d[x],g);if(P===null){C===null&&(C=K);break}e&&C&&P.alternate===null&&t(f,C),c=o(P,c,x),N===null?_=P:N.sibling=P,N=P,C=K}if(x===d.length)return n(f,C),j&&Dt(f,x),_;if(C===null){for(;xx?(K=C,C=null):K=C.sibling;var Qe=v(f,C,P.value,g);if(Qe===null){C===null&&(C=K);break}e&&C&&Qe.alternate===null&&t(f,C),c=o(Qe,c,x),N===null?_=Qe:N.sibling=Qe,N=Qe,C=K}if(P.done)return n(f,C),j&&Dt(f,x),_;if(C===null){for(;!P.done;x++,P=d.next())P=m(f,P.value,g),P!==null&&(c=o(P,c,x),N===null?_=P:N.sibling=P,N=P);return j&&Dt(f,x),_}for(C=r(f,C);!P.done;x++,P=d.next())P=y(C,f,x,P.value,g),P!==null&&(e&&P.alternate!==null&&C.delete(P.key===null?x:P.key),c=o(P,c,x),N===null?_=P:N.sibling=P,N=P);return e&&C.forEach(function(Nr){return t(f,Nr)}),j&&Dt(f,x),_}function z(f,c,d,g){if(typeof d=="object"&&d!==null&&d.type===en&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case Ir:e:{for(var _=d.key,N=c;N!==null;){if(N.key===_){if(_=d.type,_===en){if(N.tag===7){n(f,N.sibling),c=l(N,d.props.children),c.return=f,f=c;break e}}else if(N.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===pt&&Ds(_)===N.type){n(f,N.sibling),c=l(N,d.props),c.ref=Bn(f,N,d),c.return=f,f=c;break e}n(f,N);break}else t(f,N);N=N.sibling}d.type===en?(c=Vt(d.props.children,f.mode,g,d.key),c.return=f,f=c):(g=al(d.type,d.key,d.props,null,f.mode,g),g.ref=Bn(f,c,d),g.return=f,f=g)}return i(f);case bt:e:{for(N=d.key;c!==null;){if(c.key===N)if(c.tag===4&&c.stateNode.containerInfo===d.containerInfo&&c.stateNode.implementation===d.implementation){n(f,c.sibling),c=l(c,d.children||[]),c.return=f,f=c;break e}else{n(f,c);break}else t(f,c);c=c.sibling}c=Uo(d,f.mode,g),c.return=f,f=c}return i(f);case pt:return N=d._init,z(f,c,N(d._payload),g)}if(Kn(d))return w(f,c,d,g);if(Un(d))return S(f,c,d,g);Zr(f,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,c!==null&&c.tag===6?(n(f,c.sibling),c=l(c,d),c.return=f,f=c):(n(f,c),c=Ao(d,f.mode,g),c.return=f,f=c),i(f)):n(f,c)}return z}var kn=lc(!0),oc=lc(!1),_l=Ot(null),xl=null,an=null,Yi=null;function Zi(){Yi=an=xl=null}function Ji(e){var t=_l.current;U(_l),e._currentValue=t}function pi(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function hn(e,t){xl=e,Yi=an=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(me=!0),e.firstContext=null)}function Me(e){var t=e._currentValue;if(Yi!==e)if(e={context:e,memoizedValue:t,next:null},an===null){if(xl===null)throw Error(h(308));an=e,xl.dependencies={lanes:0,firstContext:e}}else an=an.next=e;return t}var Ut=null;function qi(e){Ut===null?Ut=[e]:Ut.push(e)}function ic(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,qi(t)):(n.next=l.next,l.next=n),t.interleaved=n,ut(e,r)}function ut(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var mt=!1;function bi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function uc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function _t(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(M&2)!==0){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,ut(e,n)}return l=r.interleaved,l===null?(t.next=t,qi(r)):(t.next=l.next,l.next=t),r.interleaved=t,ut(e,n)}function rl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Fi(e,n)}}function Is(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?l=o=i:o=o.next=i,n=n.next}while(n!==null);o===null?l=o=t:o=o.next=t}else l=o=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Cl(e,t,n,r){var l=e.updateQueue;mt=!1;var o=l.firstBaseUpdate,i=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var s=u,a=s.next;s.next=null,i===null?o=a:i.next=a,i=s;var p=e.alternate;p!==null&&(p=p.updateQueue,u=p.lastBaseUpdate,u!==i&&(u===null?p.firstBaseUpdate=a:u.next=a,p.lastBaseUpdate=s))}if(o!==null){var m=l.baseState;i=0,p=a=s=null,u=o;do{var v=u.lane,y=u.eventTime;if((r&v)===v){p!==null&&(p=p.next={eventTime:y,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var w=e,S=u;switch(v=t,y=n,S.tag){case 1:if(w=S.payload,typeof w=="function"){m=w.call(y,m,v);break e}m=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=S.payload,v=typeof w=="function"?w.call(y,m,v):w,v==null)break e;m=H({},m,v);break e;case 2:mt=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,v=l.effects,v===null?l.effects=[u]:v.push(u))}else y={eventTime:y,lane:v,tag:u.tag,payload:u.payload,callback:u.callback,next:null},p===null?(a=p=y,s=m):p=p.next=y,i|=v;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;v=u,u=v.next,v.next=null,l.lastBaseUpdate=v,l.shared.pending=null}}while(!0);if(p===null&&(s=m),l.baseState=s,l.firstBaseUpdate=a,l.lastBaseUpdate=p,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else o===null&&(l.shared.lanes=0);$t|=i,e.lanes=i,e.memoizedState=m}}function As(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Mo.transition;Mo.transition={};try{e(!1),t()}finally{R=n,Mo.transition=r}}function xc(){return Re().memoizedState}function Pp(e,t,n){var r=Ct(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Cc(e))Nc(t,n);else if(n=ic(e,t,n,r),n!==null){var l=ce();He(n,e,r,l),Tc(n,t,r)}}function Lp(e,t,n){var r=Ct(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Cc(e))Nc(t,l);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var i=t.lastRenderedState,u=o(i,n);if(l.hasEagerState=!0,l.eagerState=u,We(u,i)){var s=t.interleaved;s===null?(l.next=l,qi(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=ic(e,t,l,r),n!==null&&(l=ce(),He(n,e,r,l),Tc(n,t,r))}}function Cc(e){var t=e.alternate;return e===B||t!==null&&t===B}function Nc(e,t){er=Tl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tc(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Fi(e,n)}}var Pl={readContext:Me,useCallback:re,useContext:re,useEffect:re,useImperativeHandle:re,useInsertionEffect:re,useLayoutEffect:re,useMemo:re,useReducer:re,useRef:re,useState:re,useDebugValue:re,useDeferredValue:re,useTransition:re,useMutableSource:re,useSyncExternalStore:re,useId:re,unstable_isNewReconciler:!1},Op={readContext:Me,useCallback:function(e,t){return Xe().memoizedState=[e,t===void 0?null:t],e},useContext:Me,useEffect:Fs,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ol(4194308,4,Sc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ol(4194308,4,e,t)},useInsertionEffect:function(e,t){return ol(4,2,e,t)},useMemo:function(e,t){var n=Xe();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Xe();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Pp.bind(null,B,e),[r.memoizedState,e]},useRef:function(e){var t=Xe();return e={current:e},t.memoizedState=e},useState:Us,useDebugValue:uu,useDeferredValue:function(e){return Xe().memoizedState=e},useTransition:function(){var e=Us(!1),t=e[0];return e=Tp.bind(null,e[1]),Xe().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=B,l=Xe();if(j){if(n===void 0)throw Error(h(407));n=n()}else{if(n=t(),q===null)throw Error(h(349));(Wt&30)!==0||fc(r,t,n)}l.memoizedState=n;var o={value:n,getSnapshot:t};return l.queue=o,Fs(pc.bind(null,r,o,e),[e]),r.flags|=2048,Sr(9,dc.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=Xe(),t=q.identifierPrefix;if(j){var n=rt,r=nt;n=(r&~(1<<32-Be(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=gr++,0")&&(s=s.replace("",e.displayName)),s}while(1<=i&&0<=u);break}}}finally{go=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?Qn(e):""}function sd(e){switch(e.tag){case 5:return Qn(e.type);case 16:return Qn("Lazy");case 13:return Qn("Suspense");case 19:return Qn("SuspenseList");case 0:case 2:case 15:return e=yo(e.type,!1),e;case 11:return e=yo(e.type.render,!1),e;case 1:return e=yo(e.type,!0),e;default:return""}}function Ho(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case en:return"Fragment";case bt:return"Portal";case jo:return"Profiler";case zi:return"StrictMode";case Vo:return"Suspense";case Bo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ua:return(e.displayName||"Context")+".Consumer";case ia:return(e._context.displayName||"Context")+".Provider";case Ii:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Di:return t=e.displayName||null,t!==null?t:Ho(e.type)||"Memo";case dt:t=e._payload,e=e._init;try{return Ho(e(t))}catch{}}return null}function ad(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ho(t);case 8:return t===zi?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Nt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function aa(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function cd(e){var t=aa(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ar(e){e._valueTracker||(e._valueTracker=cd(e))}function ca(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=aa(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function cl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Wo(e,t){var n=t.checked;return H({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function ns(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Nt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function fa(e,t){t=t.checked,t!=null&&Ri(e,"checked",t,!1)}function $o(e,t){fa(e,t);var n=Nt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Qo(e,t.type,n):t.hasOwnProperty("defaultValue")&&Qo(e,t.type,Nt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function rs(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Qo(e,t,n){(t!=="number"||cl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var Kn=Array.isArray;function dn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Ur.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function or(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Yn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},fd=["Webkit","ms","Moz","O"];Object.keys(Yn).forEach(function(e){fd.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Yn[t]=Yn[e]})});function va(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Yn.hasOwnProperty(e)&&Yn[e]?(""+t).trim():t+"px"}function ha(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=va(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var dd=H({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Xo(e,t){if(t){if(dd[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(h(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(h(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(h(61))}if(t.style!=null&&typeof t.style!="object")throw Error(h(62))}}function Yo(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Zo=null;function Ai(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Jo=null,pn=null,mn=null;function is(e){if(e=_r(e)){if(typeof Jo!="function")throw Error(h(280));var t=e.stateNode;t&&(t=Fl(t),Jo(e.stateNode,e.type,t))}}function ga(e){pn?mn?mn.push(e):mn=[e]:pn=e}function ya(){if(pn){var e=pn,t=mn;if(mn=pn=null,is(e),t)for(e=0;e>>=0,e===0?32:31-(_d(e)/xd|0)|0}var Fr=64,jr=4194304;function Gn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ml(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,o=e.pingedLanes,i=n&268435455;if(i!==0){var u=i&~l;u!==0?r=Gn(u):(o&=i,o!==0&&(r=Gn(o)))}else i=n&~l,i!==0?r=Gn(i):o!==0&&(r=Gn(o));if(r===0)return 0;if(t!==0&&t!==r&&(t&l)===0&&(l=r&-r,o=t&-t,l>=o||l===16&&(o&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function kr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ve(t),e[t]=n}function Pd(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Jn),vs=" ",hs=!1;function Fa(e,t){switch(e){case"keyup":return np.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ja(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var tn=!1;function lp(e,t){switch(e){case"compositionend":return ja(t);case"keypress":return t.which!==32?null:(hs=!0,vs);case"textInput":return e=t.data,e===vs&&hs?null:e;default:return null}}function op(e,t){if(tn)return e==="compositionend"||!$i&&Fa(e,t)?(e=Aa(),tl=Bi=ht=null,tn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ss(n)}}function Wa(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Wa(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function $a(){for(var e=window,t=cl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=cl(e.document)}return t}function Qi(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function mp(e){var t=$a(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Wa(n.ownerDocument.documentElement,n)){if(r!==null&&Qi(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,o=Math.min(r.start,l);r=r.end===void 0?o:Math.min(r.end,l),!e.extend&&o>r&&(l=r,r=o,o=l),l=ws(n,o);var i=ws(n,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,nn=null,ri=null,bn=null,li=!1;function ks(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;li||nn==null||nn!==cl(r)||(r=nn,"selectionStart"in r&&Qi(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),bn&&fr(bn,r)||(bn=r,r=gl(ri,"onSelect"),0on||(e.current=ci[on],ci[on]=null,on--)}function D(e,t){on++,ci[on]=e.current,e.current=t}var Tt={},ie=Lt(Tt),ve=Lt(!1),Bt=Tt;function Sn(e,t){var n=e.type.contextTypes;if(!n)return Tt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},o;for(o in n)l[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function he(e){return e=e.childContextTypes,e!=null}function Sl(){U(ve),U(ie)}function Os(e,t,n){if(ie.current!==Tt)throw Error(h(168));D(ie,t),D(ve,n)}function ba(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(h(108,ad(e)||"Unknown",l));return H({},n,r)}function wl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Tt,Bt=ie.current,D(ie,e),D(ve,ve.current),!0}function Ms(e,t,n){var r=e.stateNode;if(!r)throw Error(h(169));n?(e=ba(e,t,Bt),r.__reactInternalMemoizedMergedChildContext=e,U(ve),U(ie),D(ie,e)):U(ve),D(ve,n)}var et=null,jl=!1,Lo=!1;function ec(e){et===null?et=[e]:et.push(e)}function xp(e){jl=!0,ec(e)}function Ot(){if(!Lo&&et!==null){Lo=!0;var e=0,t=R;try{var n=et;for(R=1;e>=i,l-=i,tt=1<<32-Ve(t)+l|n<x?(K=C,C=null):K=C.sibling;var P=v(f,C,d[x],g);if(P===null){C===null&&(C=K);break}e&&C&&P.alternate===null&&t(f,C),c=o(P,c,x),N===null?_=P:N.sibling=P,N=P,C=K}if(x===d.length)return n(f,C),j&&It(f,x),_;if(C===null){for(;xx?(K=C,C=null):K=C.sibling;var $e=v(f,C,P.value,g);if($e===null){C===null&&(C=K);break}e&&C&&$e.alternate===null&&t(f,C),c=o($e,c,x),N===null?_=$e:N.sibling=$e,N=$e,C=K}if(P.done)return n(f,C),j&&It(f,x),_;if(C===null){for(;!P.done;x++,P=d.next())P=m(f,P.value,g),P!==null&&(c=o(P,c,x),N===null?_=P:N.sibling=P,N=P);return j&&It(f,x),_}for(C=r(f,C);!P.done;x++,P=d.next())P=y(C,f,x,P.value,g),P!==null&&(e&&P.alternate!==null&&C.delete(P.key===null?x:P.key),c=o(P,c,x),N===null?_=P:N.sibling=P,N=P);return e&&C.forEach(function(Nr){return t(f,Nr)}),j&&It(f,x),_}function z(f,c,d,g){if(typeof d=="object"&&d!==null&&d.type===en&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case Dr:e:{for(var _=d.key,N=c;N!==null;){if(N.key===_){if(_=d.type,_===en){if(N.tag===7){n(f,N.sibling),c=l(N,d.props.children),c.return=f,f=c;break e}}else if(N.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===dt&&Is(_)===N.type){n(f,N.sibling),c=l(N,d.props),c.ref=Bn(f,N,d),c.return=f,f=c;break e}n(f,N);break}else t(f,N);N=N.sibling}d.type===en?(c=Vt(d.props.children,f.mode,g,d.key),c.return=f,f=c):(g=al(d.type,d.key,d.props,null,f.mode,g),g.ref=Bn(f,c,d),g.return=f,f=g)}return i(f);case bt:e:{for(N=d.key;c!==null;){if(c.key===N)if(c.tag===4&&c.stateNode.containerInfo===d.containerInfo&&c.stateNode.implementation===d.implementation){n(f,c.sibling),c=l(c,d.children||[]),c.return=f,f=c;break e}else{n(f,c);break}else t(f,c);c=c.sibling}c=Uo(d,f.mode,g),c.return=f,f=c}return i(f);case dt:return N=d._init,z(f,c,N(d._payload),g)}if(Kn(d))return w(f,c,d,g);if(Un(d))return S(f,c,d,g);Zr(f,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,c!==null&&c.tag===6?(n(f,c.sibling),c=l(c,d),c.return=f,f=c):(n(f,c),c=Ao(d,f.mode,g),c.return=f,f=c),i(f)):n(f,c)}return z}var kn=lc(!0),oc=lc(!1),_l=Lt(null),xl=null,an=null,Yi=null;function Zi(){Yi=an=xl=null}function Ji(e){var t=_l.current;U(_l),e._currentValue=t}function pi(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function hn(e,t){xl=e,Yi=an=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(me=!0),e.firstContext=null)}function Me(e){var t=e._currentValue;if(Yi!==e)if(e={context:e,memoizedValue:t,next:null},an===null){if(xl===null)throw Error(h(308));an=e,xl.dependencies={lanes:0,firstContext:e}}else an=an.next=e;return t}var Ut=null;function qi(e){Ut===null?Ut=[e]:Ut.push(e)}function ic(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,qi(t)):(n.next=l.next,l.next=n),t.interleaved=n,it(e,r)}function it(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var pt=!1;function bi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function uc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function rt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Et(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(M&2)!==0){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,it(e,n)}return l=r.interleaved,l===null?(t.next=t,qi(r)):(t.next=l.next,l.next=t),r.interleaved=t,it(e,n)}function rl(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Fi(e,n)}}function Ds(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?l=o=i:o=o.next=i,n=n.next}while(n!==null);o===null?l=o=t:o=o.next=t}else l=o=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Cl(e,t,n,r){var l=e.updateQueue;pt=!1;var o=l.firstBaseUpdate,i=l.lastBaseUpdate,u=l.shared.pending;if(u!==null){l.shared.pending=null;var s=u,a=s.next;s.next=null,i===null?o=a:i.next=a,i=s;var p=e.alternate;p!==null&&(p=p.updateQueue,u=p.lastBaseUpdate,u!==i&&(u===null?p.firstBaseUpdate=a:u.next=a,p.lastBaseUpdate=s))}if(o!==null){var m=l.baseState;i=0,p=a=s=null,u=o;do{var v=u.lane,y=u.eventTime;if((r&v)===v){p!==null&&(p=p.next={eventTime:y,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var w=e,S=u;switch(v=t,y=n,S.tag){case 1:if(w=S.payload,typeof w=="function"){m=w.call(y,m,v);break e}m=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=S.payload,v=typeof w=="function"?w.call(y,m,v):w,v==null)break e;m=H({},m,v);break e;case 2:pt=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,v=l.effects,v===null?l.effects=[u]:v.push(u))}else y={eventTime:y,lane:v,tag:u.tag,payload:u.payload,callback:u.callback,next:null},p===null?(a=p=y,s=m):p=p.next=y,i|=v;if(u=u.next,u===null){if(u=l.shared.pending,u===null)break;v=u,u=v.next,v.next=null,l.lastBaseUpdate=v,l.shared.pending=null}}while(!0);if(p===null&&(s=m),l.baseState=s,l.firstBaseUpdate=a,l.lastBaseUpdate=p,t=l.shared.interleaved,t!==null){l=t;do i|=l.lane,l=l.next;while(l!==t)}else o===null&&(l.shared.lanes=0);$t|=i,e.lanes=i,e.memoizedState=m}}function As(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Mo.transition;Mo.transition={};try{e(!1),t()}finally{R=n,Mo.transition=r}}function xc(){return Re().memoizedState}function Pp(e,t,n){var r=xt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Cc(e))Nc(t,n);else if(n=ic(e,t,n,r),n!==null){var l=ae();Be(n,e,r,l),Tc(n,t,r)}}function Lp(e,t,n){var r=xt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Cc(e))Nc(t,l);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var i=t.lastRenderedState,u=o(i,n);if(l.hasEagerState=!0,l.eagerState=u,He(u,i)){var s=t.interleaved;s===null?(l.next=l,qi(t)):(l.next=s.next,s.next=l),t.interleaved=l;return}}catch{}finally{}n=ic(e,t,l,r),n!==null&&(l=ae(),Be(n,e,r,l),Tc(n,t,r))}}function Cc(e){var t=e.alternate;return e===B||t!==null&&t===B}function Nc(e,t){er=Tl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tc(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Fi(e,n)}}var Pl={readContext:Me,useCallback:re,useContext:re,useEffect:re,useImperativeHandle:re,useInsertionEffect:re,useLayoutEffect:re,useMemo:re,useReducer:re,useRef:re,useState:re,useDebugValue:re,useDeferredValue:re,useTransition:re,useMutableSource:re,useSyncExternalStore:re,useId:re,unstable_isNewReconciler:!1},Op={readContext:Me,useCallback:function(e,t){return Ge().memoizedState=[e,t===void 0?null:t],e},useContext:Me,useEffect:Fs,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,ol(4194308,4,Sc.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ol(4194308,4,e,t)},useInsertionEffect:function(e,t){return ol(4,2,e,t)},useMemo:function(e,t){var n=Ge();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ge();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Pp.bind(null,B,e),[r.memoizedState,e]},useRef:function(e){var t=Ge();return e={current:e},t.memoizedState=e},useState:Us,useDebugValue:uu,useDeferredValue:function(e){return Ge().memoizedState=e},useTransition:function(){var e=Us(!1),t=e[0];return e=Tp.bind(null,e[1]),Ge().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=B,l=Ge();if(j){if(n===void 0)throw Error(h(407));n=n()}else{if(n=t(),q===null)throw Error(h(349));(Wt&30)!==0||fc(r,t,n)}l.memoizedState=n;var o={value:n,getSnapshot:t};return l.queue=o,Fs(pc.bind(null,r,o,e),[e]),r.flags|=2048,Sr(9,dc.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=Ge(),t=q.identifierPrefix;if(j){var n=nt,r=tt;n=(r&~(1<<32-Ve(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=gr++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[Ye]=t,e[mr]=r,Uc(e,t,!1,!1),t.stateNode=e;e:{switch(i=Yo(n,r),n){case"dialog":A("cancel",e),A("close",e),l=r;break;case"iframe":case"object":case"embed":A("load",e),l=r;break;case"video":case"audio":for(l=0;lxn&&(t.flags|=128,r=!0,Hn(o,!1),t.lanes=4194304)}else{if(!r)if(e=Nl(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Hn(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!j)return le(t),null}else 2*Q()-o.renderingStartTime>xn&&n!==1073741824&&(t.flags|=128,r=!0,Hn(o,!1),t.lanes=4194304);o.isBackwards?(i.sibling=t.child,t.child=i):(n=o.last,n!==null?n.sibling=i:t.child=i,o.last=i)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Q(),t.sibling=null,n=V.current,I(V,r?n&1|2:n&1),t):(le(t),null);case 22:case 23:return pu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(ye&1073741824)!==0&&(le(t),t.subtreeFlags&6&&(t.flags|=8192)):le(t),null;case 24:return null;case 25:return null}throw Error(h(156,t.tag))}function Fp(e,t){switch(Gi(t),t.tag){case 1:return he(t.type)&&Sl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return En(),U(ve),U(ie),nu(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return tu(t),null;case 13:if(U(V),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(h(340));wn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return U(V),null;case 4:return En(),null;case 10:return Ji(t.type._context),null;case 22:case 23:return pu(),null;case 24:return null;default:return null}}var qr=!1,oe=!1,jp=typeof WeakSet=="function"?WeakSet:Set,k=null;function cn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){$(e,t,r)}else n.current=null}function Ei(e,t,n){try{n()}catch(r){$(e,t,r)}}var Ys=!1;function Vp(e,t){if(oi=vl,e=$a(),Qi(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var i=0,u=-1,s=-1,a=0,p=0,m=e,v=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(u=i+l),m!==o||r!==0&&m.nodeType!==3||(s=i+r),m.nodeType===3&&(i+=m.nodeValue.length),(y=m.firstChild)!==null;)v=m,m=y;for(;;){if(m===e)break t;if(v===n&&++a===l&&(u=i),v===o&&++p===r&&(s=i),(y=m.nextSibling)!==null)break;m=v,v=m.parentNode}m=y}n=u===-1||s===-1?null:{start:u,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(ii={focusedElem:e,selectionRange:n},vl=!1,k=t;k!==null;)if(t=k,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,k=e;else for(;k!==null;){t=k;try{var w=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var S=w.memoizedProps,z=w.memoizedState,f=t.stateNode,c=f.getSnapshotBeforeUpdate(t.elementType===t.type?S:Fe(t.type,S),z);f.__reactInternalSnapshotBeforeUpdate=c}break;case 3:var d=t.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(h(163))}}catch(g){$(t,t.return,g)}if(e=t.sibling,e!==null){e.return=t.return,k=e;break}k=t.return}return w=Ys,Ys=!1,w}function tr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var o=l.destroy;l.destroy=void 0,o!==void 0&&Ei(t,n,o)}l=l.next}while(l!==r)}}function Hl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function _i(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Vc(e){var t=e.alternate;t!==null&&(e.alternate=null,Vc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Ye],delete t[mr],delete t[ai],delete t[Ep],delete t[_p])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Bc(e){return e.tag===5||e.tag===3||e.tag===4}function Zs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Bc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function xi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=yl));else if(r!==4&&(e=e.child,e!==null))for(xi(e,t,n),e=e.sibling;e!==null;)xi(e,t,n),e=e.sibling}function Ci(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ci(e,t,n),e=e.sibling;e!==null;)Ci(e,t,n),e=e.sibling}var b=null,je=!1;function dt(e,t,n){for(n=n.child;n!==null;)Hc(e,t,n),n=n.sibling}function Hc(e,t,n){if(Ze&&typeof Ze.onCommitFiberUnmount=="function")try{Ze.onCommitFiberUnmount(Dl,n)}catch{}switch(n.tag){case 5:oe||cn(n,t);case 6:var r=b,l=je;b=null,dt(e,t,n),b=r,je=l,b!==null&&(je?(e=b,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):b.removeChild(n.stateNode));break;case 18:b!==null&&(je?(e=b,n=n.stateNode,e.nodeType===8?Po(e.parentNode,n):e.nodeType===1&&Po(e,n),ar(e)):Po(b,n.stateNode));break;case 4:r=b,l=je,b=n.stateNode.containerInfo,je=!0,dt(e,t,n),b=r,je=l;break;case 0:case 11:case 14:case 15:if(!oe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var o=l,i=o.destroy;o=o.tag,i!==void 0&&((o&2)!==0||(o&4)!==0)&&Ei(n,t,i),l=l.next}while(l!==r)}dt(e,t,n);break;case 1:if(!oe&&(cn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){$(n,t,u)}dt(e,t,n);break;case 21:dt(e,t,n);break;case 22:n.mode&1?(oe=(r=oe)||n.memoizedState!==null,dt(e,t,n),oe=r):dt(e,t,n);break;default:dt(e,t,n)}}function Js(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new jp),t.forEach(function(r){var l=Yp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Ue(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=i),r&=~o}if(r=l,r=Q()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Hp(r/1960))-r,10e?16:e,yt===null)var r=!1;else{if(e=yt,yt=null,Ml=0,(M&6)!==0)throw Error(h(331));var l=M;for(M|=4,k=e.current;k!==null;){var o=k,i=o.child;if((k.flags&16)!==0){var u=o.deletions;if(u!==null){for(var s=0;sQ()-fu?jt(e,0):cu|=n),ge(e,t)}function Zc(e,t){t===0&&((e.mode&1)===0?t=1:(t=jr,jr<<=1,(jr&130023424)===0&&(jr=4194304)));var n=ce();e=ut(e,t),e!==null&&(kr(e,t,n),ge(e,n))}function Xp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zc(e,n)}function Yp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(h(314))}r!==null&&r.delete(t),Zc(e,n)}var Jc;Jc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ve.current)me=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return me=!1,Ap(e,t,n);me=(e.flags&131072)!==0}else me=!1,j&&(t.flags&1048576)!==0&&tc(t,El,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;il(e,t),e=t.pendingProps;var l=Sn(t,ie.current);hn(t,n),l=lu(null,t,r,e,l,n);var o=ou();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,he(r)?(o=!0,wl(t)):o=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,bi(t),l.updater=Bl,t.stateNode=l,l._reactInternals=t,vi(t,r,e,n),t=yi(null,t,r,!0,o,n)):(t.tag=0,j&&o&&Ki(t),ae(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(il(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Jp(r),e=Fe(r,e),l){case 0:t=gi(null,t,r,e,n);break e;case 1:t=Ks(null,t,r,e,n);break e;case 11:t=$s(null,t,r,e,n);break e;case 14:t=Qs(null,t,r,Fe(r.type,e),n);break e}throw Error(h(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Fe(r,l),gi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Fe(r,l),Ks(e,t,r,l,n);case 3:e:{if(Dc(t),e===null)throw Error(h(387));r=t.pendingProps,o=t.memoizedState,l=o.element,uc(e,t),Cl(t,r,null,n);var i=t.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){l=_n(Error(h(423)),t),t=Gs(e,t,r,n,l);break e}else if(r!==l){l=_n(Error(h(424)),t),t=Gs(e,t,r,n,l);break e}else for(Se=Et(t.stateNode.containerInfo.firstChild),we=t,j=!0,Ve=null,n=oc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(wn(),r===l){t=st(e,t,n);break e}ae(e,t,r,n)}t=t.child}return t;case 5:return sc(t),e===null&&di(t),r=t.type,l=t.pendingProps,o=e!==null?e.memoizedProps:null,i=l.children,ui(r,l)?i=null:o!==null&&ui(r,o)&&(t.flags|=32),zc(e,t),ae(e,t,i,n),t.child;case 6:return e===null&&di(t),null;case 13:return Ic(e,t,n);case 4:return eu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=kn(t,null,r,n):ae(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Fe(r,l),$s(e,t,r,l,n);case 7:return ae(e,t,t.pendingProps,n),t.child;case 8:return ae(e,t,t.pendingProps.children,n),t.child;case 12:return ae(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,o=t.memoizedProps,i=l.value,I(_l,r._currentValue),r._currentValue=i,o!==null)if(We(o.value,i)){if(o.children===l.children&&!ve.current){t=st(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var u=o.dependencies;if(u!==null){i=o.child;for(var s=u.firstContext;s!==null;){if(s.context===r){if(o.tag===1){s=lt(-1,n&-n),s.tag=2;var a=o.updateQueue;if(a!==null){a=a.shared;var p=a.pending;p===null?s.next=s:(s.next=p.next,p.next=s),a.pending=s}}o.lanes|=n,s=o.alternate,s!==null&&(s.lanes|=n),pi(o.return,n,t),u.lanes|=n;break}s=s.next}}else if(o.tag===10)i=o.type===t.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(h(341));i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),pi(i,n,t),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===t){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}ae(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,hn(t,n),l=Me(l),r=r(l),t.flags|=1,ae(e,t,r,n),t.child;case 14:return r=t.type,l=Fe(r,t.pendingProps),l=Fe(r.type,l),Qs(e,t,r,l,n);case 15:return Mc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Fe(r,l),il(e,t),t.tag=1,he(r)?(e=!0,wl(t)):e=!1,hn(t,n),Pc(t,r,l),vi(t,r,l,n),yi(null,t,r,!0,e,n);case 19:return Ac(e,t,n);case 22:return Rc(e,t,n)}throw Error(h(156,t.tag))};function qc(e,t){return Ca(e,t)}function Zp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Le(e,t,n,r){return new Zp(e,t,n,r)}function vu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Jp(e){if(typeof e=="function")return vu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Di)return 11;if(e===Ii)return 14}return 2}function Nt(e,t){var n=e.alternate;return n===null?(n=Le(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function al(e,t,n,r,l,o){var i=2;if(r=e,typeof e=="function")vu(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case en:return Vt(n.children,l,o,t);case zi:i=8,l|=8;break;case jo:return e=Le(12,n,t,l|2),e.elementType=jo,e.lanes=o,e;case Vo:return e=Le(13,n,t,l),e.elementType=Vo,e.lanes=o,e;case Bo:return e=Le(19,n,t,l),e.elementType=Bo,e.lanes=o,e;case sa:return $l(n,l,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ia:i=10;break e;case ua:i=9;break e;case Di:i=11;break e;case Ii:i=14;break e;case pt:i=16,r=null;break e}throw Error(h(130,e==null?e:typeof e,""))}return t=Le(i,n,t,l),t.elementType=e,t.type=r,t.lanes=o,t}function Vt(e,t,n,r){return e=Le(7,e,r,t),e.lanes=n,e}function $l(e,t,n,r){return e=Le(22,e,r,t),e.elementType=sa,e.lanes=n,e.stateNode={isHidden:!1},e}function Ao(e,t,n){return e=Le(6,e,null,t),e.lanes=n,e}function Uo(e,t,n){return t=Le(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function qp(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=wo(0),this.expirationTimes=wo(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=wo(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function hu(e,t,n,r,l,o,i,u,s){return e=new qp(e,t,n,u,s),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Le(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},bi(o),e}function bp(e,t,n){var r=3{"use strict";function rf(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(rf)}catch(e){console.error(e)}}rf(),lf.exports=nf()});var sf=be(wu=>{"use strict";var uf=of();wu.createRoot=uf.createRoot,wu.hydrateRoot=uf.hydrateRoot;var Sm});var cf=be(Yl=>{"use strict";var lm=de(),om=Symbol.for("react.element"),im=Symbol.for("react.fragment"),um=Object.prototype.hasOwnProperty,sm=lm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,am={key:!0,ref:!0,__self:!0,__source:!0};function af(e,t,n){var r,l={},o=null,i=null;n!==void 0&&(o=""+n),t.key!==void 0&&(o=""+t.key),t.ref!==void 0&&(i=t.ref);for(r in t)um.call(t,r)&&!am.hasOwnProperty(r)&&(l[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)l[r]===void 0&&(l[r]=t[r]);return{$$typeof:om,type:e,key:o,ref:i,props:l,_owner:sm.current}}Yl.Fragment=im;Yl.jsx=af;Yl.jsxs=af});var W=be((Em,ff)=>{"use strict";ff.exports=cf()});var zf=L(sf(),1);var ue=L(de(),1);var Z=L(W(),1);function df({preference:e,onThemeChange:t}){let n=()=>{let o=["system","light","dark"],u=(o.indexOf(e)+1)%o.length;t(o[u])},r=()=>{switch(e){case"light":return(0,Z.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,Z.jsx)("circle",{cx:"12",cy:"12",r:"5"}),(0,Z.jsx)("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),(0,Z.jsx)("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),(0,Z.jsx)("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),(0,Z.jsx)("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),(0,Z.jsx)("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),(0,Z.jsx)("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),(0,Z.jsx)("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),(0,Z.jsx)("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]});case"dark":return(0,Z.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,Z.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})});case"system":default:return(0,Z.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,Z.jsx)("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),(0,Z.jsx)("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),(0,Z.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}},l=()=>{switch(e){case"light":return"Theme: Light (click for Dark)";case"dark":return"Theme: Dark (click for System)";case"system":default:return"Theme: System (click for Light)"}};return(0,Z.jsx)("button",{className:"theme-toggle-btn",onClick:n,title:l(),"aria-label":l(),children:r()})}var F=L(W(),1);function pf({isConnected:e,projects:t,currentFilter:n,onFilterChange:r,onSettingsToggle:l,sidebarOpen:o,isProcessing:i,themePreference:u,onThemeChange:s}){return(0,F.jsxs)("div",{className:"header",children:[(0,F.jsxs)("h1",{children:[(0,F.jsx)("img",{src:"claude-mem-logomark.webp",alt:"",className:`logomark ${i?"spinning":""}`}),(0,F.jsx)("span",{className:"logo-text",children:"claude-mem"})]}),(0,F.jsxs)("div",{className:"status",children:[(0,F.jsx)("a",{href:"https://docs.claude-mem.ai",target:"_blank",rel:"noopener noreferrer",title:"Documentation",style:{display:"block",padding:"8px 4px 8px 8px",color:"#a0a0a0",transition:"color 0.2s",lineHeight:0},onMouseEnter:a=>a.currentTarget.style.color="#606060",onMouseLeave:a=>a.currentTarget.style.color="#a0a0a0",children:(0,F.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,F.jsx)("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),(0,F.jsx)("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"})]})}),(0,F.jsx)("a",{href:"https://github.com/thedotmack/claude-mem/",target:"_blank",rel:"noopener noreferrer",title:"GitHub",style:{display:"block",padding:"8px 4px",color:"#a0a0a0",transition:"color 0.2s",lineHeight:0},onMouseEnter:a=>a.currentTarget.style.color="#606060",onMouseLeave:a=>a.currentTarget.style.color="#a0a0a0",children:(0,F.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:(0,F.jsx)("path",{d:"M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"})})}),(0,F.jsx)("a",{href:"https://x.com/Claude_Memory",target:"_blank",rel:"noopener noreferrer",title:"X (Twitter)",style:{display:"block",padding:"8px 8px 8px 4px",color:"#a0a0a0",transition:"color 0.2s",lineHeight:0},onMouseEnter:a=>a.currentTarget.style.color="#606060",onMouseLeave:a=>a.currentTarget.style.color="#a0a0a0",children:(0,F.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:(0,F.jsx)("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})})}),(0,F.jsxs)("select",{value:n,onChange:a=>r(a.target.value),children:[(0,F.jsx)("option",{value:"",children:"All Projects"}),t.map(a=>(0,F.jsx)("option",{value:a,children:a},a))]}),(0,F.jsx)(df,{preference:u,onThemeChange:s}),(0,F.jsx)("button",{className:`settings-btn ${o?"active":""}`,onClick:l,title:"Settings",children:(0,F.jsxs)("svg",{className:"settings-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,F.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),(0,F.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})]})}var ct=L(de(),1);var ku=L(de(),1);function Tn(e){return new Date(e).toLocaleString()}function mf(e){if(!e)return"-";let t=Math.floor(e/3600),n=Math.floor(e%3600/60);return`${t}h ${n}m`}function vf(e){return e?e<1024?e+" B":e<1024*1024?(e/1024).toFixed(1)+" KB":(e/(1024*1024)).toFixed(1)+" MB":"-"}var O=L(W(),1);function hf(e){let t=["/Scripts/","/src/","/plugin/","/docs/"];for(let l of t){let o=e.indexOf(l);if(o!==-1)return e.substring(o+1)}let n=e.indexOf("claude-mem/");if(n!==-1)return e.substring(n+11);let r=e.split("/");return r.length>3?r.slice(-3).join("/"):e}function gf({observation:e}){let[t,n]=(0,ku.useState)(!1),[r,l]=(0,ku.useState)(!1),o=Tn(e.created_at_epoch),i=e.facts?JSON.parse(e.facts):[],u=e.concepts?JSON.parse(e.concepts):[],s=e.files_read?JSON.parse(e.files_read).map(hf):[],a=e.files_modified?JSON.parse(e.files_modified).map(hf):[],p=i.length>0||u.length>0||s.length>0||a.length>0;return(0,O.jsxs)("div",{className:"card",children:[(0,O.jsxs)("div",{className:"card-header",children:[(0,O.jsxs)("div",{className:"card-header-left",children:[(0,O.jsx)("span",{className:`card-type type-${e.type}`,children:e.type}),(0,O.jsx)("span",{className:"card-project",children:e.project})]}),(0,O.jsxs)("div",{className:"view-mode-toggles",children:[p&&(0,O.jsxs)("button",{className:`view-mode-toggle ${t?"active":""}`,onClick:()=>{n(!t),t||l(!1)},children:[(0,O.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,O.jsx)("polyline",{points:"9 11 12 14 22 4"}),(0,O.jsx)("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]}),(0,O.jsx)("span",{children:"facts"})]}),e.narrative&&(0,O.jsxs)("button",{className:`view-mode-toggle ${r?"active":""}`,onClick:()=>{l(!r),r||n(!1)},children:[(0,O.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,O.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,O.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,O.jsx)("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),(0,O.jsx)("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),(0,O.jsx)("span",{children:"narrative"})]})]})]}),(0,O.jsx)("div",{className:"card-title",children:e.title||"Untitled"}),(0,O.jsxs)("div",{className:"view-mode-content",children:[!t&&!r&&e.subtitle&&(0,O.jsx)("div",{className:"card-subtitle",children:e.subtitle}),t&&i.length>0&&(0,O.jsx)("ul",{className:"facts-list",children:i.map((m,v)=>(0,O.jsx)("li",{children:m},v))}),r&&e.narrative&&(0,O.jsx)("div",{className:"narrative",children:e.narrative})]}),(0,O.jsxs)("div",{className:"card-meta",children:[(0,O.jsxs)("span",{className:"meta-date",children:["#",e.id," \u2022 ",o]}),t&&(u.length>0||s.length>0||a.length>0)&&(0,O.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",alignItems:"center"},children:[u.map((m,v)=>(0,O.jsx)("span",{style:{padding:"2px 8px",background:"var(--color-type-badge-bg)",color:"var(--color-type-badge-text)",borderRadius:"3px",fontWeight:"500",fontSize:"10px"},children:m},v)),s.length>0&&(0,O.jsxs)("span",{className:"meta-files",children:[(0,O.jsx)("span",{className:"file-label",children:"read:"})," ",s.join(", ")]}),a.length>0&&(0,O.jsxs)("span",{className:"meta-files",children:[(0,O.jsx)("span",{className:"file-label",children:"modified:"})," ",a.join(", ")]})]})]})]})}var xe=L(W(),1);function yf({summary:e}){let t=Tn(e.created_at_epoch);return(0,xe.jsxs)("div",{className:"card summary-card",children:[(0,xe.jsx)("div",{className:"card-header",children:(0,xe.jsxs)("div",{className:"card-header-left",children:[(0,xe.jsx)("span",{className:"card-type",children:"SUMMARY"}),(0,xe.jsx)("span",{className:"card-project",children:e.project})]})}),e.request&&(0,xe.jsxs)("div",{className:"card-title",children:["Request: ",e.request]}),e.learned&&(0,xe.jsxs)("div",{className:"card-subtitle",children:["Learned: ",e.learned]}),e.completed&&(0,xe.jsxs)("div",{className:"card-subtitle",children:["Completed: ",e.completed]}),e.next_steps&&(0,xe.jsxs)("div",{className:"card-subtitle",children:["Next: ",e.next_steps]}),(0,xe.jsx)("div",{className:"card-meta",children:(0,xe.jsxs)("span",{className:"meta-date",children:["#",e.id," \u2022 ",t]})})]})}var qe=L(W(),1);function Sf({prompt:e}){let t=Tn(e.created_at_epoch);return(0,qe.jsxs)("div",{className:"card prompt-card",children:[(0,qe.jsx)("div",{className:"card-header",children:(0,qe.jsxs)("div",{className:"card-header-left",children:[(0,qe.jsx)("span",{className:"card-type",children:"Prompt"}),(0,qe.jsx)("span",{className:"card-project",children:e.project})]})}),(0,qe.jsx)("div",{className:"card-content",children:e.prompt_text}),(0,qe.jsx)("div",{className:"card-meta",children:(0,qe.jsxs)("span",{className:"meta-date",children:["#",e.id," \u2022 ",t]})})]})}var Jl=L(de(),1),Zl=L(W(),1);function wf({targetRef:e}){let[t,n]=(0,Jl.useState)(!1);(0,Jl.useEffect)(()=>{let l=()=>{let i=e.current;i&&n(i.scrollTop>300)},o=e.current;if(o)return o.addEventListener("scroll",l),()=>o.removeEventListener("scroll",l)},[]);let r=()=>{let l=e.current;l&&l.scrollTo({top:0,behavior:"smooth"})};return t?(0,Zl.jsx)("button",{onClick:r,className:"scroll-to-top","aria-label":"Scroll to top",children:(0,Zl.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,Zl.jsx)("polyline",{points:"18 15 12 9 6 15"})})}):null}var Cr={PAGINATION_PAGE_SIZE:50,LOAD_MORE_THRESHOLD:.1};var Ce=L(W(),1);function kf({observations:e,summaries:t,prompts:n,onLoadMore:r,isLoading:l,hasMore:o}){let i=(0,ct.useRef)(null),u=(0,ct.useRef)(null),s=(0,ct.useRef)(r);(0,ct.useEffect)(()=>{s.current=r},[r]),(0,ct.useEffect)(()=>{let p=i.current;if(!p)return;let m=new IntersectionObserver(v=>{v[0].isIntersecting&&o&&!l&&s.current?.()},{threshold:Cr.LOAD_MORE_THRESHOLD});return m.observe(p),()=>{p&&m.unobserve(p),m.disconnect()}},[o,l]);let a=(0,ct.useMemo)(()=>[...e.map(m=>({...m,itemType:"observation"})),...t.map(m=>({...m,itemType:"summary"})),...n.map(m=>({...m,itemType:"prompt"}))].sort((m,v)=>v.created_at_epoch-m.created_at_epoch),[e,t,n]);return(0,Ce.jsxs)("div",{className:"feed",ref:u,children:[(0,Ce.jsx)(wf,{targetRef:u}),(0,Ce.jsxs)("div",{className:"feed-content",children:[a.map(p=>{let m=`${p.itemType}-${p.id}`;return p.itemType==="observation"?(0,Ce.jsx)(gf,{observation:p},m):p.itemType==="summary"?(0,Ce.jsx)(yf,{summary:p},m):(0,Ce.jsx)(Sf,{prompt:p},m)}),a.length===0&&!l&&(0,Ce.jsx)("div",{style:{textAlign:"center",padding:"40px",color:"#8b949e"},children:"No items to display"}),l&&(0,Ce.jsxs)("div",{style:{textAlign:"center",padding:"20px",color:"#8b949e"},children:[(0,Ce.jsx)("div",{className:"spinner",style:{display:"inline-block",marginRight:"10px"}}),"Loading more..."]}),o&&!l&&a.length>0&&(0,Ce.jsx)("div",{ref:i,style:{height:"20px",margin:"10px 0"}}),!o&&a.length>0&&(0,Ce.jsx)("div",{style:{textAlign:"center",padding:"20px",color:"#8b949e",fontSize:"14px"},children:"No more items to load"})]})]})}var Pn=L(de(),1);var ze={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777"};var E=L(W(),1);function Ef({isOpen:e,settings:t,stats:n,isSaving:r,saveStatus:l,isConnected:o,onSave:i,onClose:u}){let[s,a]=(0,Pn.useState)(t.CLAUDE_MEM_MODEL||ze.CLAUDE_MEM_MODEL),[p,m]=(0,Pn.useState)(t.CLAUDE_MEM_CONTEXT_OBSERVATIONS||ze.CLAUDE_MEM_CONTEXT_OBSERVATIONS),[v,y]=(0,Pn.useState)(t.CLAUDE_MEM_WORKER_PORT||ze.CLAUDE_MEM_WORKER_PORT);return(0,Pn.useEffect)(()=>{a(t.CLAUDE_MEM_MODEL||ze.CLAUDE_MEM_MODEL),m(t.CLAUDE_MEM_CONTEXT_OBSERVATIONS||ze.CLAUDE_MEM_CONTEXT_OBSERVATIONS),y(t.CLAUDE_MEM_WORKER_PORT||ze.CLAUDE_MEM_WORKER_PORT)},[t]),(0,E.jsxs)("div",{className:`sidebar ${e?"open":""}`,children:[(0,E.jsxs)("div",{className:"sidebar-header",children:[(0,E.jsx)("h1",{children:"Settings"}),(0,E.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[(0,E.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[(0,E.jsx)("span",{className:`status-dot ${o?"connected":""}`}),(0,E.jsx)("span",{style:{fontSize:"11px",opacity:.5,fontWeight:300},children:o?"Connected":"Disconnected"})]}),(0,E.jsx)("button",{onClick:()=>{i({CLAUDE_MEM_MODEL:s,CLAUDE_MEM_CONTEXT_OBSERVATIONS:p,CLAUDE_MEM_WORKER_PORT:v})},disabled:r,children:r?"Saving...":"Save"}),(0,E.jsx)("button",{onClick:u,title:"Close settings",style:{background:"transparent",border:"1px solid #404040",padding:"8px",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center"},children:(0,E.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,E.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,E.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),(0,E.jsxs)("div",{className:"stats-scroll",children:[(0,E.jsxs)("div",{className:"settings-section",children:[(0,E.jsx)("h3",{children:"Environment Variables"}),(0,E.jsxs)("div",{className:"form-group",children:[(0,E.jsx)("label",{htmlFor:"model",children:"CLAUDE_MEM_MODEL"}),(0,E.jsx)("div",{className:"setting-description",children:"Model used for AI compression of tool observations. Haiku is fast and cheap, Sonnet offers better quality, Opus is most capable but expensive."}),(0,E.jsxs)("select",{id:"model",value:s,onChange:S=>a(S.target.value),children:[(0,E.jsx)("option",{value:"claude-haiku-4-5",children:"claude-haiku-4-5"}),(0,E.jsx)("option",{value:"claude-sonnet-4-5",children:"claude-sonnet-4-5"}),(0,E.jsx)("option",{value:"claude-opus-4",children:"claude-opus-4"})]})]}),(0,E.jsxs)("div",{className:"form-group",children:[(0,E.jsx)("label",{htmlFor:"contextObs",children:"CLAUDE_MEM_CONTEXT_OBSERVATIONS"}),(0,E.jsx)("div",{className:"setting-description",children:"Number of recent observations to inject at session start. Higher values provide more context but increase token usage. Default: 50"}),(0,E.jsx)("input",{type:"number",id:"contextObs",min:"1",max:"200",value:p,onChange:S=>m(S.target.value)})]}),(0,E.jsxs)("div",{className:"form-group",children:[(0,E.jsx)("label",{htmlFor:"workerPort",children:"CLAUDE_MEM_WORKER_PORT"}),(0,E.jsx)("div",{className:"setting-description",children:"Port number for the background worker service. Change only if port 37777 conflicts with another service."}),(0,E.jsx)("input",{type:"number",id:"workerPort",min:"1024",max:"65535",value:v,onChange:S=>y(S.target.value)})]}),l&&(0,E.jsx)("div",{className:"save-status",children:l})]}),(0,E.jsxs)("div",{className:"settings-section",children:[(0,E.jsx)("h3",{children:"Worker Stats"}),(0,E.jsxs)("div",{className:"stats-grid",children:[(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Version"}),(0,E.jsx)("div",{className:"stat-value",children:n.worker?.version||"-"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Uptime"}),(0,E.jsx)("div",{className:"stat-value",children:mf(n.worker?.uptime)})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Active Sessions"}),(0,E.jsx)("div",{className:"stat-value",children:n.worker?.activeSessions||"0"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"SSE Clients"}),(0,E.jsx)("div",{className:"stat-value",children:n.worker?.sseClients||"0"})]})]})]}),(0,E.jsxs)("div",{className:"settings-section",children:[(0,E.jsx)("h3",{children:"Database Stats"}),(0,E.jsxs)("div",{className:"stats-grid",children:[(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"DB Size"}),(0,E.jsx)("div",{className:"stat-value",children:vf(n.database?.size)})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Observations"}),(0,E.jsx)("div",{className:"stat-value",children:n.database?.observations||"0"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Sessions"}),(0,E.jsx)("div",{className:"stat-value",children:n.database?.sessions||"0"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Summaries"}),(0,E.jsx)("div",{className:"stat-value",children:n.database?.summaries||"0"})]})]})]})]})]})}var De=L(de(),1);var $e={OBSERVATIONS:"/api/observations",SUMMARIES:"/api/summaries",PROMPTS:"/api/prompts",SETTINGS:"/api/settings",STATS:"/api/stats",PROCESSING_STATUS:"/api/processing-status",STREAM:"/stream"};var Ln={SSE_RECONNECT_DELAY_MS:3e3,STATS_REFRESH_INTERVAL_MS:1e4,SAVE_STATUS_DISPLAY_DURATION_MS:3e3};function _f(){let[e,t]=(0,De.useState)([]),[n,r]=(0,De.useState)([]),[l,o]=(0,De.useState)([]),[i,u]=(0,De.useState)([]),[s,a]=(0,De.useState)(!1),[p,m]=(0,De.useState)(!1),v=(0,De.useRef)(null),y=(0,De.useRef)();return(0,De.useEffect)(()=>{let w=()=>{v.current&&v.current.close();let S=new EventSource($e.STREAM);v.current=S,S.onopen=()=>{console.log("[SSE] Connected"),a(!0),y.current&&clearTimeout(y.current)},S.onerror=z=>{console.error("[SSE] Connection error:",z),a(!1),S.close(),y.current=setTimeout(()=>{y.current=void 0,console.log("[SSE] Attempting to reconnect..."),w()},Ln.SSE_RECONNECT_DELAY_MS)},S.onmessage=z=>{try{let f=JSON.parse(z.data);switch(f.type){case"initial_load":console.log("[SSE] Initial load:",{projects:f.projects?.length||0}),u(f.projects||[]);break;case"new_observation":f.observation&&(console.log("[SSE] New observation:",f.observation.id),t(c=>[f.observation,...c]));break;case"new_summary":if(f.summary){let c=f.summary;console.log("[SSE] New summary:",c.id),r(d=>[c,...d])}break;case"new_prompt":if(f.prompt){let c=f.prompt;console.log("[SSE] New prompt:",c.id),o(d=>[c,...d])}break;case"processing_status":typeof f.isProcessing=="boolean"&&(console.log("[SSE] Processing status:",f.isProcessing),m(f.isProcessing));break}}catch(f){console.error("[SSE] Failed to parse message:",f)}}};return w(),()=>{v.current&&v.current.close(),y.current&&clearTimeout(y.current)}},[]),{observations:e,summaries:n,prompts:l,projects:i,isProcessing:p,isConnected:s}}var On=L(de(),1);function xf(){let[e,t]=(0,On.useState)(ze),[n,r]=(0,On.useState)(!1),[l,o]=(0,On.useState)("");return(0,On.useEffect)(()=>{fetch($e.SETTINGS).then(u=>u.json()).then(u=>{t({CLAUDE_MEM_MODEL:u.CLAUDE_MEM_MODEL||ze.CLAUDE_MEM_MODEL,CLAUDE_MEM_CONTEXT_OBSERVATIONS:u.CLAUDE_MEM_CONTEXT_OBSERVATIONS||ze.CLAUDE_MEM_CONTEXT_OBSERVATIONS,CLAUDE_MEM_WORKER_PORT:u.CLAUDE_MEM_WORKER_PORT||ze.CLAUDE_MEM_WORKER_PORT})}).catch(u=>{console.error("Failed to load settings:",u)})},[]),{settings:e,saveSettings:async u=>{r(!0),o("Saving...");try{let a=await(await fetch($e.SETTINGS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})).json();a.success?(t(u),o("\u2713 Saved"),setTimeout(()=>o(""),Ln.SAVE_STATUS_DISPLAY_DURATION_MS)):o(`\u2717 Error: ${a.error}`)}catch(s){o(`\u2717 Error: ${s instanceof Error?s.message:"Unknown error"}`)}finally{r(!1)}},isSaving:n,saveStatus:l}}var ql=L(de(),1);function Cf(){let[e,t]=(0,ql.useState)({});return(0,ql.useEffect)(()=>{let n=async()=>{try{let o=await(await fetch($e.STATS)).json();t(o)}catch(l){console.error("Failed to load stats:",l)}};n();let r=setInterval(n,Ln.STATS_REFRESH_INTERVAL_MS);return()=>clearInterval(r)},[]),{stats:e}}var Ie=L(de(),1);function Eu(e,t,n){let[r,l]=(0,Ie.useState)({isLoading:!1,hasMore:!0}),[o,i]=(0,Ie.useState)(0),u=(0,Ie.useRef)(r),s=(0,Ie.useRef)(o);(0,Ie.useEffect)(()=>{u.current=r},[r]),(0,Ie.useEffect)(()=>{s.current=o},[o]),(0,Ie.useEffect)(()=>{i(0),l({isLoading:!1,hasMore:!0})},[n]);let a=(0,Ie.useCallback)(async()=>{if(u.current.isLoading||!u.current.hasMore)return[];l(p=>({...p,isLoading:!0}));try{let p=new URLSearchParams({offset:s.current.toString(),limit:Cr.PAGINATION_PAGE_SIZE.toString()});n&&p.append("project",n);let m=await fetch(`${e}?${p}`);if(!m.ok)throw new Error(`Failed to load ${t}: ${m.statusText}`);let v=await m.json();return l(y=>({...y,isLoading:!1,hasMore:v.hasMore})),i(y=>y+Cr.PAGINATION_PAGE_SIZE),v.items}catch(p){return console.error(`Failed to load ${t}:`,p),l(m=>({...m,isLoading:!1})),[]}},[n,e,t]);return{...r,loadMore:a}}function Nf(e){let t=Eu($e.OBSERVATIONS,"observations",e),n=Eu($e.SUMMARIES,"summaries",e),r=Eu($e.PROMPTS,"prompts",e);return{observations:t,summaries:n,prompts:r}}var Mn=L(de(),1),Lf="claude-mem-theme";function cm(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Tf(){try{let e=localStorage.getItem(Lf);if(e==="system"||e==="light"||e==="dark")return e}catch(e){console.warn("Failed to read theme preference from localStorage:",e)}return"system"}function Pf(e){return e==="system"?cm():e}function Of(){let[e,t]=(0,Mn.useState)(Tf),[n,r]=(0,Mn.useState)(()=>Pf(Tf()));return(0,Mn.useEffect)(()=>{let o=Pf(e);r(o),document.documentElement.setAttribute("data-theme",o)},[e]),(0,Mn.useEffect)(()=>{if(e!=="system")return;let o=window.matchMedia("(prefers-color-scheme: dark)"),i=u=>{let s=u.matches?"dark":"light";r(s),document.documentElement.setAttribute("data-theme",s)};return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]),{preference:e,resolvedTheme:n,setThemePreference:o=>{try{localStorage.setItem(Lf,o),t(o)}catch(i){console.warn("Failed to save theme preference to localStorage:",i),t(o)}}}}function bl(e,t,n){let r=n?e.filter(o=>o.project===n):e,l=new Set;return[...r,...t].filter(o=>l.has(o.id)?!1:(l.add(o.id),!0))}var Xt=L(W(),1);function Mf(){let[e,t]=(0,ue.useState)(""),[n,r]=(0,ue.useState)(!1),[l,o]=(0,ue.useState)([]),[i,u]=(0,ue.useState)([]),[s,a]=(0,ue.useState)([]),{observations:p,summaries:m,prompts:v,projects:y,isProcessing:w,isConnected:S}=_f(),{settings:z,saveSettings:f,isSaving:c,saveStatus:d}=xf(),{stats:g}=Cf(),{preference:_,resolvedTheme:N,setThemePreference:C}=Of(),x=Nf(e);(0,ue.useEffect)(()=>{o([]),u([]),a([])},[e]);let K=(0,ue.useMemo)(()=>bl(p,l,e),[p,l,e]),P=(0,ue.useMemo)(()=>bl(m,i,e),[m,i,e]),Qe=(0,ue.useMemo)(()=>bl(v,s,e),[v,s,e]),Nr=(0,ue.useCallback)(()=>{r(Yt=>!Yt)},[]),xu=(0,ue.useCallback)(async()=>{try{let[Yt,Cu,Nu]=await Promise.all([x.observations.loadMore(),x.summaries.loadMore(),x.prompts.loadMore()]);Yt.length>0&&o(Rn=>[...Rn,...Yt]),Cu.length>0&&u(Rn=>[...Rn,...Cu]),Nu.length>0&&a(Rn=>[...Rn,...Nu])}catch(Yt){console.error("Failed to load more data:",Yt)}},[x.observations,x.summaries,x.prompts]);return(0,ue.useEffect)(()=>{xu()},[e]),(0,Xt.jsxs)("div",{className:"container",children:[(0,Xt.jsxs)("div",{className:"main-col",children:[(0,Xt.jsx)(pf,{isConnected:S,projects:y,currentFilter:e,onFilterChange:t,onSettingsToggle:Nr,sidebarOpen:n,isProcessing:w,themePreference:_,onThemeChange:C}),(0,Xt.jsx)(kf,{observations:K,summaries:P,prompts:Qe,onLoadMore:xu,isLoading:x.observations.isLoading||x.summaries.isLoading||x.prompts.isLoading,hasMore:x.observations.hasMore||x.summaries.hasMore||x.prompts.hasMore})]}),(0,Xt.jsx)(Ef,{isOpen:n,settings:z,stats:g,isSaving:c,saveStatus:d,isConnected:S,onSave:f,onClose:Nr})]})}var Rf=L(de(),1),Rt=L(W(),1),eo=class extends Rf.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary] Caught error:",t,n),this.setState({error:t,errorInfo:n})}render(){return this.state.hasError?(0,Rt.jsxs)("div",{style:{padding:"20px",color:"#ff6b6b",backgroundColor:"#1a1a1a",minHeight:"100vh"},children:[(0,Rt.jsx)("h1",{style:{fontSize:"24px",marginBottom:"10px"},children:"Something went wrong"}),(0,Rt.jsx)("p",{style:{marginBottom:"10px",color:"#8b949e"},children:"The application encountered an error. Please refresh the page to try again."}),this.state.error&&(0,Rt.jsxs)("details",{style:{marginTop:"20px",color:"#8b949e"},children:[(0,Rt.jsx)("summary",{style:{cursor:"pointer",marginBottom:"10px"},children:"Error details"}),(0,Rt.jsxs)("pre",{style:{backgroundColor:"#0d1117",padding:"10px",borderRadius:"6px",overflow:"auto"},children:[this.state.error.toString(),this.state.errorInfo&&` +`+o.stack}return{value:e,source:t,stack:l,digest:null}}function Io(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function hi(e,t){try{console.error(t.value)}catch(n){setTimeout(function(){throw n})}}var zp=typeof WeakMap=="function"?WeakMap:Map;function Lc(e,t,n){n=rt(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){Ol||(Ol=!0,Ni=r),hi(e,t)},n}function Oc(e,t,n){n=rt(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){hi(e,t)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(n.callback=function(){hi(e,t),typeof r!="function"&&(_t===null?_t=new Set([this]):_t.add(this));var i=t.stack;this.componentDidCatch(t.value,{componentStack:i!==null?i:""})}),n}function Bs(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new zp;var l=new Set;r.set(t,l)}else l=r.get(t),l===void 0&&(l=new Set,r.set(t,l));l.has(n)||(l.add(n),e=Gp.bind(null,e,t,n),t.then(e,e))}function Hs(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t!==null?t.dehydrated!==null:!0),t)return e;e=e.return}while(e!==null);return null}function Ws(e,t,n,r,l){return(e.mode&1)===0?(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=rt(-1,1),t.tag=2,Et(n,t,1))),n.lanes|=1),e):(e.flags|=65536,e.lanes=l,e)}var Ip=st.ReactCurrentOwner,me=!1;function se(e,t,n,r){t.child=e===null?oc(t,null,n,r):kn(t,e.child,n,r)}function $s(e,t,n,r,l){n=n.render;var o=t.ref;return hn(t,l),r=lu(e,t,n,r,o,l),n=ou(),e!==null&&!me?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,ut(e,t,l)):(j&&n&&Ki(t),t.flags|=1,se(e,t,r,l),t.child)}function Qs(e,t,n,r,l){if(e===null){var o=n.type;return typeof o=="function"&&!vu(o)&&o.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=o,Mc(e,t,o,r,l)):(e=al(n.type,null,r,t,t.mode,l),e.ref=t.ref,e.return=t,t.child=e)}if(o=e.child,(e.lanes&l)===0){var i=o.memoizedProps;if(n=n.compare,n=n!==null?n:fr,n(i,r)&&e.ref===t.ref)return ut(e,t,l)}return t.flags|=1,e=Ct(o,r),e.ref=t.ref,e.return=t,t.child=e}function Mc(e,t,n,r,l){if(e!==null){var o=e.memoizedProps;if(fr(o,r)&&e.ref===t.ref)if(me=!1,t.pendingProps=r=o,(e.lanes&l)!==0)(e.flags&131072)!==0&&(me=!0);else return t.lanes=e.lanes,ut(e,t,l)}return gi(e,t,n,r,l)}function Rc(e,t,n){var r=t.pendingProps,l=r.children,o=e!==null?e.memoizedState:null;if(r.mode==="hidden")if((t.mode&1)===0)t.memoizedState={baseLanes:0,cachePool:null,transitions:null},D(fn,Se),Se|=n;else{if((n&1073741824)===0)return e=o!==null?o.baseLanes|n:n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,D(fn,Se),Se|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=o!==null?o.baseLanes:n,D(fn,Se),Se|=r}else o!==null?(r=o.baseLanes|n,t.memoizedState=null):r=n,D(fn,Se),Se|=r;return se(e,t,l,n),t.child}function zc(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function gi(e,t,n,r,l){var o=he(n)?Bt:ie.current;return o=Sn(t,o),hn(t,l),n=lu(e,t,n,r,o,l),r=ou(),e!==null&&!me?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~l,ut(e,t,l)):(j&&r&&Ki(t),t.flags|=1,se(e,t,n,l),t.child)}function Ks(e,t,n,r,l){if(he(n)){var o=!0;wl(t)}else o=!1;if(hn(t,l),t.stateNode===null)il(e,t),Pc(t,n,r),vi(t,n,r,l),r=!0;else if(e===null){var i=t.stateNode,u=t.memoizedProps;i.props=u;var s=i.context,a=n.contextType;typeof a=="object"&&a!==null?a=Me(a):(a=he(n)?Bt:ie.current,a=Sn(t,a));var p=n.getDerivedStateFromProps,m=typeof p=="function"||typeof i.getSnapshotBeforeUpdate=="function";m||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(u!==r||s!==a)&&Vs(t,i,r,a),pt=!1;var v=t.memoizedState;i.state=v,Cl(t,r,i,l),s=t.memoizedState,u!==r||v!==s||ve.current||pt?(typeof p=="function"&&(mi(t,n,p,r),s=t.memoizedState),(u=pt||js(t,n,u,r,v,s,a))?(m||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(t.flags|=4194308)):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=s),i.props=r,i.state=s,i.context=a,r=u):(typeof i.componentDidMount=="function"&&(t.flags|=4194308),r=!1)}else{i=t.stateNode,uc(e,t),u=t.memoizedProps,a=t.type===t.elementType?u:Ue(t.type,u),i.props=a,m=t.pendingProps,v=i.context,s=n.contextType,typeof s=="object"&&s!==null?s=Me(s):(s=he(n)?Bt:ie.current,s=Sn(t,s));var y=n.getDerivedStateFromProps;(p=typeof y=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(u!==m||v!==s)&&Vs(t,i,r,s),pt=!1,v=t.memoizedState,i.state=v,Cl(t,r,i,l);var w=t.memoizedState;u!==m||v!==w||ve.current||pt?(typeof y=="function"&&(mi(t,n,y,r),w=t.memoizedState),(a=pt||js(t,n,a,r,v,w,s)||!1)?(p||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,w,s),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,w,s)),typeof i.componentDidUpdate=="function"&&(t.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof i.componentDidUpdate!="function"||u===e.memoizedProps&&v===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&v===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=w),i.props=r,i.state=w,i.context=s,r=a):(typeof i.componentDidUpdate!="function"||u===e.memoizedProps&&v===e.memoizedState||(t.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||u===e.memoizedProps&&v===e.memoizedState||(t.flags|=1024),r=!1)}return yi(e,t,n,r,o,l)}function yi(e,t,n,r,l,o){zc(e,t);var i=(t.flags&128)!==0;if(!r&&!i)return l&&Ms(t,n,!1),ut(e,t,o);r=t.stateNode,Ip.current=t;var u=i&&typeof n.getDerivedStateFromError!="function"?null:r.render();return t.flags|=1,e!==null&&i?(t.child=kn(t,e.child,null,o),t.child=kn(t,null,u,o)):se(e,t,u,o),t.memoizedState=r.state,l&&Ms(t,n,!0),t.child}function Ic(e){var t=e.stateNode;t.pendingContext?Os(e,t.pendingContext,t.pendingContext!==t.context):t.context&&Os(e,t.context,!1),eu(e,t.containerInfo)}function Gs(e,t,n,r,l){return wn(),Xi(l),t.flags|=256,se(e,t,n,r),t.child}var Si={dehydrated:null,treeContext:null,retryLane:0};function wi(e){return{baseLanes:e,cachePool:null,transitions:null}}function Dc(e,t,n){var r=t.pendingProps,l=V.current,o=!1,i=(t.flags&128)!==0,u;if((u=i)||(u=e!==null&&e.memoizedState===null?!1:(l&2)!==0),u?(o=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(l|=1),D(V,l&1),e===null)return di(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?((t.mode&1)===0?t.lanes=1:e.data==="$!"?t.lanes=8:t.lanes=1073741824,null):(i=r.children,e=r.fallback,o?(r=t.mode,o=t.child,i={mode:"hidden",children:i},(r&1)===0&&o!==null?(o.childLanes=0,o.pendingProps=i):o=$l(i,r,0,null),e=Vt(e,r,n,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=wi(n),t.memoizedState=Si,e):su(t,i));if(l=e.memoizedState,l!==null&&(u=l.dehydrated,u!==null))return Dp(e,t,i,r,u,l,n);if(o){o=r.fallback,i=t.mode,l=e.child,u=l.sibling;var s={mode:"hidden",children:r.children};return(i&1)===0&&t.child!==l?(r=t.child,r.childLanes=0,r.pendingProps=s,t.deletions=null):(r=Ct(l,s),r.subtreeFlags=l.subtreeFlags&14680064),u!==null?o=Ct(u,o):(o=Vt(o,i,n,null),o.flags|=2),o.return=t,r.return=t,r.sibling=o,t.child=r,r=o,o=t.child,i=e.child.memoizedState,i=i===null?wi(n):{baseLanes:i.baseLanes|n,cachePool:null,transitions:i.transitions},o.memoizedState=i,o.childLanes=e.childLanes&~n,t.memoizedState=Si,r}return o=e.child,e=o.sibling,r=Ct(o,{mode:"visible",children:r.children}),(t.mode&1)===0&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function su(e,t){return t=$l({mode:"visible",children:t},e.mode,0,null),t.return=e,e.child=t}function Jr(e,t,n,r){return r!==null&&Xi(r),kn(t,e.child,null,n),e=su(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Dp(e,t,n,r,l,o,i){if(n)return t.flags&256?(t.flags&=-257,r=Io(Error(h(422))),Jr(e,t,i,r)):t.memoizedState!==null?(t.child=e.child,t.flags|=128,null):(o=r.fallback,l=t.mode,r=$l({mode:"visible",children:r.children},l,0,null),o=Vt(o,l,i,null),o.flags|=2,r.return=t,o.return=t,r.sibling=o,t.child=r,(t.mode&1)!==0&&kn(t,e.child,null,i),t.child.memoizedState=wi(i),t.memoizedState=Si,o);if((t.mode&1)===0)return Jr(e,t,i,null);if(l.data==="$!"){if(r=l.nextSibling&&l.nextSibling.dataset,r)var u=r.dgst;return r=u,o=Error(h(419)),r=Io(o,r,void 0),Jr(e,t,i,r)}if(u=(i&e.childLanes)!==0,me||u){if(r=q,r!==null){switch(i&-i){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}l=(l&(r.suspendedLanes|i))!==0?0:l,l!==0&&l!==o.retryLane&&(o.retryLane=l,it(e,l),Be(r,e,l,-1))}return mu(),r=Io(Error(h(421))),Jr(e,t,i,r)}return l.data==="$?"?(t.flags|=128,t.child=e.child,t=Xp.bind(null,e),l._reactRetry=t,null):(e=o.treeContext,we=kt(l.nextSibling),ke=t,j=!0,je=null,e!==null&&(Te[Pe++]=tt,Te[Pe++]=nt,Te[Pe++]=Ht,tt=e.id,nt=e.overflow,Ht=t),t=su(t,r.children),t.flags|=4096,t)}function Xs(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),pi(e.return,t,n)}function Do(e,t,n,r,l){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=l)}function Ac(e,t,n){var r=t.pendingProps,l=r.revealOrder,o=r.tail;if(se(e,t,r.children,n),r=V.current,(r&2)!==0)r=r&1|2,t.flags|=128;else{if(e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Xs(e,n,t);else if(e.tag===19)Xs(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(D(V,r),(t.mode&1)===0)t.memoizedState=null;else switch(l){case"forwards":for(n=t.child,l=null;n!==null;)e=n.alternate,e!==null&&Nl(e)===null&&(l=n),n=n.sibling;n=l,n===null?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),Do(t,!1,l,n,o);break;case"backwards":for(n=null,l=t.child,t.child=null;l!==null;){if(e=l.alternate,e!==null&&Nl(e)===null){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}Do(t,!0,n,null,o);break;case"together":Do(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function il(e,t){(t.mode&1)===0&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function ut(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),$t|=t.lanes,(n&t.childLanes)===0)return null;if(e!==null&&t.child!==e.child)throw Error(h(153));if(t.child!==null){for(e=t.child,n=Ct(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=Ct(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function Ap(e,t,n){switch(t.tag){case 3:Ic(t),wn();break;case 5:sc(t);break;case 1:he(t.type)&&wl(t);break;case 4:eu(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,l=t.memoizedProps.value;D(_l,r._currentValue),r._currentValue=l;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated!==null?(D(V,V.current&1),t.flags|=128,null):(n&t.child.childLanes)!==0?Dc(e,t,n):(D(V,V.current&1),e=ut(e,t,n),e!==null?e.sibling:null);D(V,V.current&1);break;case 19:if(r=(n&t.childLanes)!==0,(e.flags&128)!==0){if(r)return Ac(e,t,n);t.flags|=128}if(l=t.memoizedState,l!==null&&(l.rendering=null,l.tail=null,l.lastEffect=null),D(V,V.current),r)break;return null;case 22:case 23:return t.lanes=0,Rc(e,t,n)}return ut(e,t,n)}var Uc,ki,Fc,jc;Uc=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};ki=function(){};Fc=function(e,t,n,r){var l=e.memoizedProps;if(l!==r){e=t.stateNode,Ft(Ze.current);var o=null;switch(n){case"input":l=Wo(e,l),r=Wo(e,r),o=[];break;case"select":l=H({},l,{value:void 0}),r=H({},r,{value:void 0}),o=[];break;case"textarea":l=Ko(e,l),r=Ko(e,r),o=[];break;default:typeof l.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=yl)}Xo(n,r);var i;n=null;for(a in l)if(!r.hasOwnProperty(a)&&l.hasOwnProperty(a)&&l[a]!=null)if(a==="style"){var u=l[a];for(i in u)u.hasOwnProperty(i)&&(n||(n={}),n[i]="")}else a!=="dangerouslySetInnerHTML"&&a!=="children"&&a!=="suppressContentEditableWarning"&&a!=="suppressHydrationWarning"&&a!=="autoFocus"&&(lr.hasOwnProperty(a)?o||(o=[]):(o=o||[]).push(a,null));for(a in r){var s=r[a];if(u=l?.[a],r.hasOwnProperty(a)&&s!==u&&(s!=null||u!=null))if(a==="style")if(u){for(i in u)!u.hasOwnProperty(i)||s&&s.hasOwnProperty(i)||(n||(n={}),n[i]="");for(i in s)s.hasOwnProperty(i)&&u[i]!==s[i]&&(n||(n={}),n[i]=s[i])}else n||(o||(o=[]),o.push(a,n)),n=s;else a==="dangerouslySetInnerHTML"?(s=s?s.__html:void 0,u=u?u.__html:void 0,s!=null&&u!==s&&(o=o||[]).push(a,s)):a==="children"?typeof s!="string"&&typeof s!="number"||(o=o||[]).push(a,""+s):a!=="suppressContentEditableWarning"&&a!=="suppressHydrationWarning"&&(lr.hasOwnProperty(a)?(s!=null&&a==="onScroll"&&A("scroll",e),o||u===s||(o=[])):(o=o||[]).push(a,s))}n&&(o=o||[]).push("style",n);var a=o;(t.updateQueue=a)&&(t.flags|=4)}};jc=function(e,t,n,r){n!==r&&(t.flags|=4)};function Hn(e,t){if(!j)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function le(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags&14680064,r|=l.flags&14680064,l.return=e,l=l.sibling;else for(l=e.child;l!==null;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function Up(e,t,n){var r=t.pendingProps;switch(Gi(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return le(t),null;case 1:return he(t.type)&&Sl(),le(t),null;case 3:return r=t.stateNode,En(),U(ve),U(ie),nu(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(Yr(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,je!==null&&(Li(je),je=null))),ki(e,t),le(t),null;case 5:tu(t);var l=Ft(hr.current);if(n=t.type,e!==null&&t.stateNode!=null)Fc(e,t,n,r,l),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(h(166));return le(t),null}if(e=Ft(Ze.current),Yr(t)){r=t.stateNode,n=t.type;var o=t.memoizedProps;switch(r[Xe]=t,r[mr]=o,e=(t.mode&1)!==0,n){case"dialog":A("cancel",r),A("close",r);break;case"iframe":case"object":case"embed":A("load",r);break;case"video":case"audio":for(l=0;l<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[Xe]=t,e[mr]=r,Uc(e,t,!1,!1),t.stateNode=e;e:{switch(i=Yo(n,r),n){case"dialog":A("cancel",e),A("close",e),l=r;break;case"iframe":case"object":case"embed":A("load",e),l=r;break;case"video":case"audio":for(l=0;lxn&&(t.flags|=128,r=!0,Hn(o,!1),t.lanes=4194304)}else{if(!r)if(e=Nl(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Hn(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!j)return le(t),null}else 2*Q()-o.renderingStartTime>xn&&n!==1073741824&&(t.flags|=128,r=!0,Hn(o,!1),t.lanes=4194304);o.isBackwards?(i.sibling=t.child,t.child=i):(n=o.last,n!==null?n.sibling=i:t.child=i,o.last=i)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Q(),t.sibling=null,n=V.current,D(V,r?n&1|2:n&1),t):(le(t),null);case 22:case 23:return pu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(Se&1073741824)!==0&&(le(t),t.subtreeFlags&6&&(t.flags|=8192)):le(t),null;case 24:return null;case 25:return null}throw Error(h(156,t.tag))}function Fp(e,t){switch(Gi(t),t.tag){case 1:return he(t.type)&&Sl(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return En(),U(ve),U(ie),nu(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return tu(t),null;case 13:if(U(V),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(h(340));wn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return U(V),null;case 4:return En(),null;case 10:return Ji(t.type._context),null;case 22:case 23:return pu(),null;case 24:return null;default:return null}}var qr=!1,oe=!1,jp=typeof WeakSet=="function"?WeakSet:Set,k=null;function cn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){$(e,t,r)}else n.current=null}function Ei(e,t,n){try{n()}catch(r){$(e,t,r)}}var Ys=!1;function Vp(e,t){if(oi=vl,e=$a(),Qi(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var i=0,u=-1,s=-1,a=0,p=0,m=e,v=null;t:for(;;){for(var y;m!==n||l!==0&&m.nodeType!==3||(u=i+l),m!==o||r!==0&&m.nodeType!==3||(s=i+r),m.nodeType===3&&(i+=m.nodeValue.length),(y=m.firstChild)!==null;)v=m,m=y;for(;;){if(m===e)break t;if(v===n&&++a===l&&(u=i),v===o&&++p===r&&(s=i),(y=m.nextSibling)!==null)break;m=v,v=m.parentNode}m=y}n=u===-1||s===-1?null:{start:u,end:s}}else n=null}n=n||{start:0,end:0}}else n=null;for(ii={focusedElem:e,selectionRange:n},vl=!1,k=t;k!==null;)if(t=k,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,k=e;else for(;k!==null;){t=k;try{var w=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var S=w.memoizedProps,z=w.memoizedState,f=t.stateNode,c=f.getSnapshotBeforeUpdate(t.elementType===t.type?S:Ue(t.type,S),z);f.__reactInternalSnapshotBeforeUpdate=c}break;case 3:var d=t.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(h(163))}}catch(g){$(t,t.return,g)}if(e=t.sibling,e!==null){e.return=t.return,k=e;break}k=t.return}return w=Ys,Ys=!1,w}function tr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var o=l.destroy;l.destroy=void 0,o!==void 0&&Ei(t,n,o)}l=l.next}while(l!==r)}}function Hl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function _i(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Vc(e){var t=e.alternate;t!==null&&(e.alternate=null,Vc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Xe],delete t[mr],delete t[ai],delete t[Ep],delete t[_p])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Bc(e){return e.tag===5||e.tag===3||e.tag===4}function Zs(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Bc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function xi(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=yl));else if(r!==4&&(e=e.child,e!==null))for(xi(e,t,n),e=e.sibling;e!==null;)xi(e,t,n),e=e.sibling}function Ci(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ci(e,t,n),e=e.sibling;e!==null;)Ci(e,t,n),e=e.sibling}var b=null,Fe=!1;function ft(e,t,n){for(n=n.child;n!==null;)Hc(e,t,n),n=n.sibling}function Hc(e,t,n){if(Ye&&typeof Ye.onCommitFiberUnmount=="function")try{Ye.onCommitFiberUnmount(Il,n)}catch{}switch(n.tag){case 5:oe||cn(n,t);case 6:var r=b,l=Fe;b=null,ft(e,t,n),b=r,Fe=l,b!==null&&(Fe?(e=b,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):b.removeChild(n.stateNode));break;case 18:b!==null&&(Fe?(e=b,n=n.stateNode,e.nodeType===8?Po(e.parentNode,n):e.nodeType===1&&Po(e,n),ar(e)):Po(b,n.stateNode));break;case 4:r=b,l=Fe,b=n.stateNode.containerInfo,Fe=!0,ft(e,t,n),b=r,Fe=l;break;case 0:case 11:case 14:case 15:if(!oe&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var o=l,i=o.destroy;o=o.tag,i!==void 0&&((o&2)!==0||(o&4)!==0)&&Ei(n,t,i),l=l.next}while(l!==r)}ft(e,t,n);break;case 1:if(!oe&&(cn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(u){$(n,t,u)}ft(e,t,n);break;case 21:ft(e,t,n);break;case 22:n.mode&1?(oe=(r=oe)||n.memoizedState!==null,ft(e,t,n),oe=r):ft(e,t,n);break;default:ft(e,t,n)}}function Js(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new jp),t.forEach(function(r){var l=Yp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Ae(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=i),r&=~o}if(r=l,r=Q()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Hp(r/1960))-r,10e?16:e,gt===null)var r=!1;else{if(e=gt,gt=null,Ml=0,(M&6)!==0)throw Error(h(331));var l=M;for(M|=4,k=e.current;k!==null;){var o=k,i=o.child;if((k.flags&16)!==0){var u=o.deletions;if(u!==null){for(var s=0;sQ()-fu?jt(e,0):cu|=n),ge(e,t)}function Zc(e,t){t===0&&((e.mode&1)===0?t=1:(t=jr,jr<<=1,(jr&130023424)===0&&(jr=4194304)));var n=ae();e=it(e,t),e!==null&&(kr(e,t,n),ge(e,n))}function Xp(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zc(e,n)}function Yp(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(h(314))}r!==null&&r.delete(t),Zc(e,n)}var Jc;Jc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ve.current)me=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return me=!1,Ap(e,t,n);me=(e.flags&131072)!==0}else me=!1,j&&(t.flags&1048576)!==0&&tc(t,El,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;il(e,t),e=t.pendingProps;var l=Sn(t,ie.current);hn(t,n),l=lu(null,t,r,e,l,n);var o=ou();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,he(r)?(o=!0,wl(t)):o=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,bi(t),l.updater=Bl,t.stateNode=l,l._reactInternals=t,vi(t,r,e,n),t=yi(null,t,r,!0,o,n)):(t.tag=0,j&&o&&Ki(t),se(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(il(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=Jp(r),e=Ue(r,e),l){case 0:t=gi(null,t,r,e,n);break e;case 1:t=Ks(null,t,r,e,n);break e;case 11:t=$s(null,t,r,e,n);break e;case 14:t=Qs(null,t,r,Ue(r.type,e),n);break e}throw Error(h(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ue(r,l),gi(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ue(r,l),Ks(e,t,r,l,n);case 3:e:{if(Ic(t),e===null)throw Error(h(387));r=t.pendingProps,o=t.memoizedState,l=o.element,uc(e,t),Cl(t,r,null,n);var i=t.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){l=_n(Error(h(423)),t),t=Gs(e,t,r,n,l);break e}else if(r!==l){l=_n(Error(h(424)),t),t=Gs(e,t,r,n,l);break e}else for(we=kt(t.stateNode.containerInfo.firstChild),ke=t,j=!0,je=null,n=oc(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(wn(),r===l){t=ut(e,t,n);break e}se(e,t,r,n)}t=t.child}return t;case 5:return sc(t),e===null&&di(t),r=t.type,l=t.pendingProps,o=e!==null?e.memoizedProps:null,i=l.children,ui(r,l)?i=null:o!==null&&ui(r,o)&&(t.flags|=32),zc(e,t),se(e,t,i,n),t.child;case 6:return e===null&&di(t),null;case 13:return Dc(e,t,n);case 4:return eu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=kn(t,null,r,n):se(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ue(r,l),$s(e,t,r,l,n);case 7:return se(e,t,t.pendingProps,n),t.child;case 8:return se(e,t,t.pendingProps.children,n),t.child;case 12:return se(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,o=t.memoizedProps,i=l.value,D(_l,r._currentValue),r._currentValue=i,o!==null)if(He(o.value,i)){if(o.children===l.children&&!ve.current){t=ut(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var u=o.dependencies;if(u!==null){i=o.child;for(var s=u.firstContext;s!==null;){if(s.context===r){if(o.tag===1){s=rt(-1,n&-n),s.tag=2;var a=o.updateQueue;if(a!==null){a=a.shared;var p=a.pending;p===null?s.next=s:(s.next=p.next,p.next=s),a.pending=s}}o.lanes|=n,s=o.alternate,s!==null&&(s.lanes|=n),pi(o.return,n,t),u.lanes|=n;break}s=s.next}}else if(o.tag===10)i=o.type===t.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(h(341));i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),pi(i,n,t),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===t){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}se(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,hn(t,n),l=Me(l),r=r(l),t.flags|=1,se(e,t,r,n),t.child;case 14:return r=t.type,l=Ue(r,t.pendingProps),l=Ue(r.type,l),Qs(e,t,r,l,n);case 15:return Mc(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ue(r,l),il(e,t),t.tag=1,he(r)?(e=!0,wl(t)):e=!1,hn(t,n),Pc(t,r,l),vi(t,r,l,n),yi(null,t,r,!0,e,n);case 19:return Ac(e,t,n);case 22:return Rc(e,t,n)}throw Error(h(156,t.tag))};function qc(e,t){return Ca(e,t)}function Zp(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Le(e,t,n,r){return new Zp(e,t,n,r)}function vu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Jp(e){if(typeof e=="function")return vu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Ii)return 11;if(e===Di)return 14}return 2}function Ct(e,t){var n=e.alternate;return n===null?(n=Le(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function al(e,t,n,r,l,o){var i=2;if(r=e,typeof e=="function")vu(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case en:return Vt(n.children,l,o,t);case zi:i=8,l|=8;break;case jo:return e=Le(12,n,t,l|2),e.elementType=jo,e.lanes=o,e;case Vo:return e=Le(13,n,t,l),e.elementType=Vo,e.lanes=o,e;case Bo:return e=Le(19,n,t,l),e.elementType=Bo,e.lanes=o,e;case sa:return $l(n,l,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ia:i=10;break e;case ua:i=9;break e;case Ii:i=11;break e;case Di:i=14;break e;case dt:i=16,r=null;break e}throw Error(h(130,e==null?e:typeof e,""))}return t=Le(i,n,t,l),t.elementType=e,t.type=r,t.lanes=o,t}function Vt(e,t,n,r){return e=Le(7,e,r,t),e.lanes=n,e}function $l(e,t,n,r){return e=Le(22,e,r,t),e.elementType=sa,e.lanes=n,e.stateNode={isHidden:!1},e}function Ao(e,t,n){return e=Le(6,e,null,t),e.lanes=n,e}function Uo(e,t,n){return t=Le(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function qp(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=wo(0),this.expirationTimes=wo(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=wo(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function hu(e,t,n,r,l,o,i,u,s){return e=new qp(e,t,n,u,s),t===1?(t=1,o===!0&&(t|=8)):t=0,o=Le(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},bi(o),e}function bp(e,t,n){var r=3{"use strict";function rf(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(rf)}catch(e){console.error(e)}}rf(),lf.exports=nf()});var sf=qe(wu=>{"use strict";var uf=of();wu.createRoot=uf.createRoot,wu.hydrateRoot=uf.hydrateRoot;var Sm});var cf=qe(Yl=>{"use strict";var lm=de(),om=Symbol.for("react.element"),im=Symbol.for("react.fragment"),um=Object.prototype.hasOwnProperty,sm=lm.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,am={key:!0,ref:!0,__self:!0,__source:!0};function af(e,t,n){var r,l={},o=null,i=null;n!==void 0&&(o=""+n),t.key!==void 0&&(o=""+t.key),t.ref!==void 0&&(i=t.ref);for(r in t)um.call(t,r)&&!am.hasOwnProperty(r)&&(l[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps,t)l[r]===void 0&&(l[r]=t[r]);return{$$typeof:om,type:e,key:o,ref:i,props:l,_owner:sm.current}}Yl.Fragment=im;Yl.jsx=af;Yl.jsxs=af});var W=qe((Em,ff)=>{"use strict";ff.exports=cf()});var zf=L(sf(),1);var fe=L(de(),1);var Z=L(W(),1);function df({preference:e,onThemeChange:t}){let n=()=>{let o=["system","light","dark"],u=(o.indexOf(e)+1)%o.length;t(o[u])},r=()=>{switch(e){case"light":return(0,Z.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,Z.jsx)("circle",{cx:"12",cy:"12",r:"5"}),(0,Z.jsx)("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),(0,Z.jsx)("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),(0,Z.jsx)("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),(0,Z.jsx)("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),(0,Z.jsx)("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),(0,Z.jsx)("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),(0,Z.jsx)("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),(0,Z.jsx)("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]});case"dark":return(0,Z.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,Z.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})});case"system":default:return(0,Z.jsxs)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,Z.jsx)("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),(0,Z.jsx)("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),(0,Z.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}},l=()=>{switch(e){case"light":return"Theme: Light (click for Dark)";case"dark":return"Theme: Dark (click for System)";case"system":default:return"Theme: System (click for Light)"}};return(0,Z.jsx)("button",{className:"theme-toggle-btn",onClick:n,title:l(),"aria-label":l(),children:r()})}var F=L(W(),1);function pf({isConnected:e,projects:t,currentFilter:n,onFilterChange:r,onSettingsToggle:l,sidebarOpen:o,isProcessing:i,themePreference:u,onThemeChange:s}){return(0,F.jsxs)("div",{className:"header",children:[(0,F.jsxs)("h1",{children:[(0,F.jsx)("img",{src:"claude-mem-logomark.webp",alt:"",className:`logomark ${i?"spinning":""}`}),(0,F.jsx)("span",{className:"logo-text",children:"claude-mem"})]}),(0,F.jsxs)("div",{className:"status",children:[(0,F.jsx)("a",{href:"https://docs.claude-mem.ai",target:"_blank",rel:"noopener noreferrer",title:"Documentation",style:{display:"block",padding:"8px 4px 8px 8px",color:"#a0a0a0",transition:"color 0.2s",lineHeight:0},onMouseEnter:a=>a.currentTarget.style.color="#606060",onMouseLeave:a=>a.currentTarget.style.color="#a0a0a0",children:(0,F.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,F.jsx)("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),(0,F.jsx)("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"})]})}),(0,F.jsx)("a",{href:"https://github.com/thedotmack/claude-mem/",target:"_blank",rel:"noopener noreferrer",title:"GitHub",style:{display:"block",padding:"8px 4px",color:"#a0a0a0",transition:"color 0.2s",lineHeight:0},onMouseEnter:a=>a.currentTarget.style.color="#606060",onMouseLeave:a=>a.currentTarget.style.color="#a0a0a0",children:(0,F.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:(0,F.jsx)("path",{d:"M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"})})}),(0,F.jsx)("a",{href:"https://x.com/Claude_Memory",target:"_blank",rel:"noopener noreferrer",title:"X (Twitter)",style:{display:"block",padding:"8px 8px 8px 4px",color:"#a0a0a0",transition:"color 0.2s",lineHeight:0},onMouseEnter:a=>a.currentTarget.style.color="#606060",onMouseLeave:a=>a.currentTarget.style.color="#a0a0a0",children:(0,F.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:(0,F.jsx)("path",{d:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"})})}),(0,F.jsxs)("select",{value:n,onChange:a=>r(a.target.value),children:[(0,F.jsx)("option",{value:"",children:"All Projects"}),t.map(a=>(0,F.jsx)("option",{value:a,children:a},a))]}),(0,F.jsx)(df,{preference:u,onThemeChange:s}),(0,F.jsx)("button",{className:`settings-btn ${o?"active":""}`,onClick:l,title:"Settings",children:(0,F.jsxs)("svg",{className:"settings-icon",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,F.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),(0,F.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})]})}var at=L(de(),1);var ku=L(de(),1);function Tn(e){return new Date(e).toLocaleString()}function mf(e){if(!e)return"-";let t=Math.floor(e/3600),n=Math.floor(e%3600/60);return`${t}h ${n}m`}function vf(e){return e?e<1024?e+" B":e<1024*1024?(e/1024).toFixed(1)+" KB":(e/(1024*1024)).toFixed(1)+" MB":"-"}var O=L(W(),1);function hf(e){let t=["/Scripts/","/src/","/plugin/","/docs/"];for(let l of t){let o=e.indexOf(l);if(o!==-1)return e.substring(o+1)}let n=e.indexOf("claude-mem/");if(n!==-1)return e.substring(n+11);let r=e.split("/");return r.length>3?r.slice(-3).join("/"):e}function gf({observation:e}){let[t,n]=(0,ku.useState)(!1),[r,l]=(0,ku.useState)(!1),o=Tn(e.created_at_epoch),i=e.facts?JSON.parse(e.facts):[],u=e.concepts?JSON.parse(e.concepts):[],s=e.files_read?JSON.parse(e.files_read).map(hf):[],a=e.files_modified?JSON.parse(e.files_modified).map(hf):[],p=i.length>0||u.length>0||s.length>0||a.length>0;return(0,O.jsxs)("div",{className:"card",children:[(0,O.jsxs)("div",{className:"card-header",children:[(0,O.jsxs)("div",{className:"card-header-left",children:[(0,O.jsx)("span",{className:`card-type type-${e.type}`,children:e.type}),(0,O.jsx)("span",{className:"card-project",children:e.project})]}),(0,O.jsxs)("div",{className:"view-mode-toggles",children:[p&&(0,O.jsxs)("button",{className:`view-mode-toggle ${t?"active":""}`,onClick:()=>{n(!t),t||l(!1)},children:[(0,O.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,O.jsx)("polyline",{points:"9 11 12 14 22 4"}),(0,O.jsx)("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]}),(0,O.jsx)("span",{children:"facts"})]}),e.narrative&&(0,O.jsxs)("button",{className:`view-mode-toggle ${r?"active":""}`,onClick:()=>{l(!r),r||n(!1)},children:[(0,O.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,O.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,O.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,O.jsx)("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),(0,O.jsx)("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),(0,O.jsx)("span",{children:"narrative"})]})]})]}),(0,O.jsx)("div",{className:"card-title",children:e.title||"Untitled"}),(0,O.jsxs)("div",{className:"view-mode-content",children:[!t&&!r&&e.subtitle&&(0,O.jsx)("div",{className:"card-subtitle",children:e.subtitle}),t&&i.length>0&&(0,O.jsx)("ul",{className:"facts-list",children:i.map((m,v)=>(0,O.jsx)("li",{children:m},v))}),r&&e.narrative&&(0,O.jsx)("div",{className:"narrative",children:e.narrative})]}),(0,O.jsxs)("div",{className:"card-meta",children:[(0,O.jsxs)("span",{className:"meta-date",children:["#",e.id," \u2022 ",o]}),t&&(u.length>0||s.length>0||a.length>0)&&(0,O.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",alignItems:"center"},children:[u.map((m,v)=>(0,O.jsx)("span",{style:{padding:"2px 8px",background:"var(--color-type-badge-bg)",color:"var(--color-type-badge-text)",borderRadius:"3px",fontWeight:"500",fontSize:"10px"},children:m},v)),s.length>0&&(0,O.jsxs)("span",{className:"meta-files",children:[(0,O.jsx)("span",{className:"file-label",children:"read:"})," ",s.join(", ")]}),a.length>0&&(0,O.jsxs)("span",{className:"meta-files",children:[(0,O.jsx)("span",{className:"file-label",children:"modified:"})," ",a.join(", ")]})]})]})]})}var ye=L(W(),1);function yf({summary:e}){let t=Tn(e.created_at_epoch);return(0,ye.jsxs)("div",{className:"card summary-card",children:[(0,ye.jsx)("div",{className:"card-header",children:(0,ye.jsxs)("div",{className:"card-header-left",children:[(0,ye.jsx)("span",{className:"card-type",children:"SUMMARY"}),(0,ye.jsx)("span",{className:"card-project",children:e.project})]})}),e.request&&(0,ye.jsxs)("div",{className:"card-title",children:["Request: ",e.request]}),e.investigated&&(0,ye.jsxs)("div",{className:"card-subtitle",children:["Investigated: ",e.investigated]}),e.learned&&(0,ye.jsxs)("div",{className:"card-subtitle",children:["Learned: ",e.learned]}),e.completed&&(0,ye.jsxs)("div",{className:"card-subtitle",children:["Completed: ",e.completed]}),e.next_steps&&(0,ye.jsxs)("div",{className:"card-subtitle",children:["Next: ",e.next_steps]}),(0,ye.jsx)("div",{className:"card-meta",children:(0,ye.jsxs)("span",{className:"meta-date",children:["#",e.id," \u2022 ",t]})})]})}var Je=L(W(),1);function Sf({prompt:e}){let t=Tn(e.created_at_epoch);return(0,Je.jsxs)("div",{className:"card prompt-card",children:[(0,Je.jsx)("div",{className:"card-header",children:(0,Je.jsxs)("div",{className:"card-header-left",children:[(0,Je.jsx)("span",{className:"card-type",children:"Prompt"}),(0,Je.jsx)("span",{className:"card-project",children:e.project})]})}),(0,Je.jsx)("div",{className:"card-content",children:e.prompt_text}),(0,Je.jsx)("div",{className:"card-meta",children:(0,Je.jsxs)("span",{className:"meta-date",children:["#",e.id," \u2022 ",t]})})]})}var Jl=L(de(),1),Zl=L(W(),1);function wf({targetRef:e}){let[t,n]=(0,Jl.useState)(!1);(0,Jl.useEffect)(()=>{let l=()=>{let i=e.current;i&&n(i.scrollTop>300)},o=e.current;if(o)return o.addEventListener("scroll",l),()=>o.removeEventListener("scroll",l)},[]);let r=()=>{let l=e.current;l&&l.scrollTo({top:0,behavior:"smooth"})};return t?(0,Zl.jsx)("button",{onClick:r,className:"scroll-to-top","aria-label":"Scroll to top",children:(0,Zl.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,Zl.jsx)("polyline",{points:"18 15 12 9 6 15"})})}):null}var Cr={PAGINATION_PAGE_SIZE:50,LOAD_MORE_THRESHOLD:.1};var Ce=L(W(),1);function kf({observations:e,summaries:t,prompts:n,onLoadMore:r,isLoading:l,hasMore:o}){let i=(0,at.useRef)(null),u=(0,at.useRef)(null),s=(0,at.useRef)(r);(0,at.useEffect)(()=>{s.current=r},[r]),(0,at.useEffect)(()=>{let p=i.current;if(!p)return;let m=new IntersectionObserver(v=>{v[0].isIntersecting&&o&&!l&&s.current?.()},{threshold:Cr.LOAD_MORE_THRESHOLD});return m.observe(p),()=>{p&&m.unobserve(p),m.disconnect()}},[o,l]);let a=(0,at.useMemo)(()=>[...e.map(m=>({...m,itemType:"observation"})),...t.map(m=>({...m,itemType:"summary"})),...n.map(m=>({...m,itemType:"prompt"}))].sort((m,v)=>v.created_at_epoch-m.created_at_epoch),[e,t,n]);return(0,Ce.jsxs)("div",{className:"feed",ref:u,children:[(0,Ce.jsx)(wf,{targetRef:u}),(0,Ce.jsxs)("div",{className:"feed-content",children:[a.map(p=>{let m=`${p.itemType}-${p.id}`;return p.itemType==="observation"?(0,Ce.jsx)(gf,{observation:p},m):p.itemType==="summary"?(0,Ce.jsx)(yf,{summary:p},m):(0,Ce.jsx)(Sf,{prompt:p},m)}),a.length===0&&!l&&(0,Ce.jsx)("div",{style:{textAlign:"center",padding:"40px",color:"#8b949e"},children:"No items to display"}),l&&(0,Ce.jsxs)("div",{style:{textAlign:"center",padding:"20px",color:"#8b949e"},children:[(0,Ce.jsx)("div",{className:"spinner",style:{display:"inline-block",marginRight:"10px"}}),"Loading more..."]}),o&&!l&&a.length>0&&(0,Ce.jsx)("div",{ref:i,style:{height:"20px",margin:"10px 0"}}),!o&&a.length>0&&(0,Ce.jsx)("div",{style:{textAlign:"center",padding:"20px",color:"#8b949e",fontSize:"14px"},children:"No more items to load"})]})]})}var Pn=L(de(),1);var ze={CLAUDE_MEM_MODEL:"claude-haiku-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777"};var E=L(W(),1);function Ef({isOpen:e,settings:t,stats:n,isSaving:r,saveStatus:l,isConnected:o,onSave:i,onClose:u}){let[s,a]=(0,Pn.useState)(t.CLAUDE_MEM_MODEL||ze.CLAUDE_MEM_MODEL),[p,m]=(0,Pn.useState)(t.CLAUDE_MEM_CONTEXT_OBSERVATIONS||ze.CLAUDE_MEM_CONTEXT_OBSERVATIONS),[v,y]=(0,Pn.useState)(t.CLAUDE_MEM_WORKER_PORT||ze.CLAUDE_MEM_WORKER_PORT);return(0,Pn.useEffect)(()=>{a(t.CLAUDE_MEM_MODEL||ze.CLAUDE_MEM_MODEL),m(t.CLAUDE_MEM_CONTEXT_OBSERVATIONS||ze.CLAUDE_MEM_CONTEXT_OBSERVATIONS),y(t.CLAUDE_MEM_WORKER_PORT||ze.CLAUDE_MEM_WORKER_PORT)},[t]),(0,E.jsxs)("div",{className:`sidebar ${e?"open":""}`,children:[(0,E.jsxs)("div",{className:"sidebar-header",children:[(0,E.jsx)("h1",{children:"Settings"}),(0,E.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"center"},children:[(0,E.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[(0,E.jsx)("span",{className:`status-dot ${o?"connected":""}`}),(0,E.jsx)("span",{style:{fontSize:"11px",opacity:.5,fontWeight:300},children:o?"Connected":"Disconnected"})]}),(0,E.jsx)("button",{onClick:()=>{i({CLAUDE_MEM_MODEL:s,CLAUDE_MEM_CONTEXT_OBSERVATIONS:p,CLAUDE_MEM_WORKER_PORT:v})},disabled:r,children:r?"Saving...":"Save"}),(0,E.jsx)("button",{onClick:u,title:"Close settings",style:{background:"transparent",border:"1px solid #404040",padding:"8px",width:"36px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center"},children:(0,E.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,E.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,E.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),(0,E.jsxs)("div",{className:"stats-scroll",children:[(0,E.jsxs)("div",{className:"settings-section",children:[(0,E.jsx)("h3",{children:"Environment Variables"}),(0,E.jsxs)("div",{className:"form-group",children:[(0,E.jsx)("label",{htmlFor:"model",children:"CLAUDE_MEM_MODEL"}),(0,E.jsx)("div",{className:"setting-description",children:"Model used for AI compression of tool observations. Haiku is fast and cheap, Sonnet offers better quality, Opus is most capable but expensive."}),(0,E.jsxs)("select",{id:"model",value:s,onChange:S=>a(S.target.value),children:[(0,E.jsx)("option",{value:"claude-haiku-4-5",children:"claude-haiku-4-5"}),(0,E.jsx)("option",{value:"claude-sonnet-4-5",children:"claude-sonnet-4-5"}),(0,E.jsx)("option",{value:"claude-opus-4",children:"claude-opus-4"})]})]}),(0,E.jsxs)("div",{className:"form-group",children:[(0,E.jsx)("label",{htmlFor:"contextObs",children:"CLAUDE_MEM_CONTEXT_OBSERVATIONS"}),(0,E.jsx)("div",{className:"setting-description",children:"Number of recent observations to inject at session start. Higher values provide more context but increase token usage. Default: 50"}),(0,E.jsx)("input",{type:"number",id:"contextObs",min:"1",max:"200",value:p,onChange:S=>m(S.target.value)})]}),(0,E.jsxs)("div",{className:"form-group",children:[(0,E.jsx)("label",{htmlFor:"workerPort",children:"CLAUDE_MEM_WORKER_PORT"}),(0,E.jsx)("div",{className:"setting-description",children:"Port number for the background worker service. Change only if port 37777 conflicts with another service."}),(0,E.jsx)("input",{type:"number",id:"workerPort",min:"1024",max:"65535",value:v,onChange:S=>y(S.target.value)})]}),l&&(0,E.jsx)("div",{className:"save-status",children:l})]}),(0,E.jsxs)("div",{className:"settings-section",children:[(0,E.jsx)("h3",{children:"Worker Stats"}),(0,E.jsxs)("div",{className:"stats-grid",children:[(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Version"}),(0,E.jsx)("div",{className:"stat-value",children:n.worker?.version||"-"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Uptime"}),(0,E.jsx)("div",{className:"stat-value",children:mf(n.worker?.uptime)})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Active Sessions"}),(0,E.jsx)("div",{className:"stat-value",children:n.worker?.activeSessions||"0"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"SSE Clients"}),(0,E.jsx)("div",{className:"stat-value",children:n.worker?.sseClients||"0"})]})]})]}),(0,E.jsxs)("div",{className:"settings-section",children:[(0,E.jsx)("h3",{children:"Database Stats"}),(0,E.jsxs)("div",{className:"stats-grid",children:[(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"DB Size"}),(0,E.jsx)("div",{className:"stat-value",children:vf(n.database?.size)})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Observations"}),(0,E.jsx)("div",{className:"stat-value",children:n.database?.observations||"0"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Sessions"}),(0,E.jsx)("div",{className:"stat-value",children:n.database?.sessions||"0"})]}),(0,E.jsxs)("div",{className:"stat",children:[(0,E.jsx)("div",{className:"stat-label",children:"Summaries"}),(0,E.jsx)("div",{className:"stat-value",children:n.database?.summaries||"0"})]})]})]})]})]})}var Ie=L(de(),1);var We={OBSERVATIONS:"/api/observations",SUMMARIES:"/api/summaries",PROMPTS:"/api/prompts",SETTINGS:"/api/settings",STATS:"/api/stats",PROCESSING_STATUS:"/api/processing-status",STREAM:"/stream"};var Ln={SSE_RECONNECT_DELAY_MS:3e3,STATS_REFRESH_INTERVAL_MS:1e4,SAVE_STATUS_DISPLAY_DURATION_MS:3e3};function _f(){let[e,t]=(0,Ie.useState)([]),[n,r]=(0,Ie.useState)([]),[l,o]=(0,Ie.useState)([]),[i,u]=(0,Ie.useState)([]),[s,a]=(0,Ie.useState)(!1),[p,m]=(0,Ie.useState)(!1),v=(0,Ie.useRef)(null),y=(0,Ie.useRef)();return(0,Ie.useEffect)(()=>{let w=()=>{v.current&&v.current.close();let S=new EventSource(We.STREAM);v.current=S,S.onopen=()=>{console.log("[SSE] Connected"),a(!0),y.current&&clearTimeout(y.current)},S.onerror=z=>{console.error("[SSE] Connection error:",z),a(!1),S.close(),y.current=setTimeout(()=>{y.current=void 0,console.log("[SSE] Attempting to reconnect..."),w()},Ln.SSE_RECONNECT_DELAY_MS)},S.onmessage=z=>{try{let f=JSON.parse(z.data);switch(f.type){case"initial_load":console.log("[SSE] Initial load:",{projects:f.projects?.length||0}),u(f.projects||[]);break;case"new_observation":f.observation&&(console.log("[SSE] New observation:",f.observation.id),t(c=>[f.observation,...c]));break;case"new_summary":if(f.summary){let c=f.summary;console.log("[SSE] New summary:",c.id),r(d=>[c,...d])}break;case"new_prompt":if(f.prompt){let c=f.prompt;console.log("[SSE] New prompt:",c.id),o(d=>[c,...d])}break;case"processing_status":typeof f.isProcessing=="boolean"&&(console.log("[SSE] Processing status:",f.isProcessing),m(f.isProcessing));break}}catch(f){console.error("[SSE] Failed to parse message:",f)}}};return w(),()=>{v.current&&v.current.close(),y.current&&clearTimeout(y.current)}},[]),{observations:e,summaries:n,prompts:l,projects:i,isProcessing:p,isConnected:s}}var On=L(de(),1);function xf(){let[e,t]=(0,On.useState)(ze),[n,r]=(0,On.useState)(!1),[l,o]=(0,On.useState)("");return(0,On.useEffect)(()=>{fetch(We.SETTINGS).then(u=>u.json()).then(u=>{t({CLAUDE_MEM_MODEL:u.CLAUDE_MEM_MODEL||ze.CLAUDE_MEM_MODEL,CLAUDE_MEM_CONTEXT_OBSERVATIONS:u.CLAUDE_MEM_CONTEXT_OBSERVATIONS||ze.CLAUDE_MEM_CONTEXT_OBSERVATIONS,CLAUDE_MEM_WORKER_PORT:u.CLAUDE_MEM_WORKER_PORT||ze.CLAUDE_MEM_WORKER_PORT})}).catch(u=>{console.error("Failed to load settings:",u)})},[]),{settings:e,saveSettings:async u=>{r(!0),o("Saving...");try{let a=await(await fetch(We.SETTINGS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})).json();a.success?(t(u),o("\u2713 Saved"),setTimeout(()=>o(""),Ln.SAVE_STATUS_DISPLAY_DURATION_MS)):o(`\u2717 Error: ${a.error}`)}catch(s){o(`\u2717 Error: ${s instanceof Error?s.message:"Unknown error"}`)}finally{r(!1)}},isSaving:n,saveStatus:l}}var ql=L(de(),1);function Cf(){let[e,t]=(0,ql.useState)({});return(0,ql.useEffect)(()=>{let n=async()=>{try{let o=await(await fetch(We.STATS)).json();t(o)}catch(l){console.error("Failed to load stats:",l)}};n();let r=setInterval(n,Ln.STATS_REFRESH_INTERVAL_MS);return()=>clearInterval(r)},[]),{stats:e}}var Mt=L(de(),1);function Eu(e,t,n){let[r,l]=(0,Mt.useState)({isLoading:!1,hasMore:!0}),o=(0,Mt.useRef)(0),i=(0,Mt.useRef)(n),u=(0,Mt.useRef)(r),s=(0,Mt.useCallback)(async()=>{let a=i.current!==n;if(a){o.current=0,i.current=n;let p={isLoading:!1,hasMore:!0};l(p),u.current=p}if(!a&&(u.current.isLoading||!u.current.hasMore))return[];l(p=>({...p,isLoading:!0}));try{let p=new URLSearchParams({offset:o.current.toString(),limit:Cr.PAGINATION_PAGE_SIZE.toString()});n&&p.append("project",n);let m=await fetch(`${e}?${p}`);if(!m.ok)throw new Error(`Failed to load ${t}: ${m.statusText}`);let v=await m.json();return l(y=>({...y,isLoading:!1,hasMore:v.hasMore})),o.current+=Cr.PAGINATION_PAGE_SIZE,v.items}catch(p){return console.error(`Failed to load ${t}:`,p),l(m=>({...m,isLoading:!1})),[]}},[n,e,t]);return{...r,loadMore:s}}function Nf(e){let t=Eu(We.OBSERVATIONS,"observations",e),n=Eu(We.SUMMARIES,"summaries",e),r=Eu(We.PROMPTS,"prompts",e);return{observations:t,summaries:n,prompts:r}}var Mn=L(de(),1),Lf="claude-mem-theme";function cm(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Tf(){try{let e=localStorage.getItem(Lf);if(e==="system"||e==="light"||e==="dark")return e}catch(e){console.warn("Failed to read theme preference from localStorage:",e)}return"system"}function Pf(e){return e==="system"?cm():e}function Of(){let[e,t]=(0,Mn.useState)(Tf),[n,r]=(0,Mn.useState)(()=>Pf(Tf()));return(0,Mn.useEffect)(()=>{let o=Pf(e);r(o),document.documentElement.setAttribute("data-theme",o)},[e]),(0,Mn.useEffect)(()=>{if(e!=="system")return;let o=window.matchMedia("(prefers-color-scheme: dark)"),i=u=>{let s=u.matches?"dark":"light";r(s),document.documentElement.setAttribute("data-theme",s)};return o.addEventListener("change",i),()=>o.removeEventListener("change",i)},[e]),{preference:e,resolvedTheme:n,setThemePreference:o=>{try{localStorage.setItem(Lf,o),t(o)}catch(i){console.warn("Failed to save theme preference to localStorage:",i),t(o)}}}}function bl(e,t){let n=new Set;return[...e,...t].filter(r=>n.has(r.id)?!1:(n.add(r.id),!0))}var Xt=L(W(),1);function Mf(){let[e,t]=(0,fe.useState)(""),[n,r]=(0,fe.useState)(!1),[l,o]=(0,fe.useState)([]),[i,u]=(0,fe.useState)([]),[s,a]=(0,fe.useState)([]),{observations:p,summaries:m,prompts:v,projects:y,isProcessing:w,isConnected:S}=_f(),{settings:z,saveSettings:f,isSaving:c,saveStatus:d}=xf(),{stats:g}=Cf(),{preference:_,resolvedTheme:N,setThemePreference:C}=Of(),x=Nf(e),K=(0,fe.useMemo)(()=>e?l:bl(p,l),[p,l,e]),P=(0,fe.useMemo)(()=>e?i:bl(m,i),[m,i,e]),$e=(0,fe.useMemo)(()=>e?s:bl(v,s),[v,s,e]),Nr=(0,fe.useCallback)(()=>{r(Yt=>!Yt)},[]),xu=(0,fe.useCallback)(async()=>{try{let[Yt,Cu,Nu]=await Promise.all([x.observations.loadMore(),x.summaries.loadMore(),x.prompts.loadMore()]);Yt.length>0&&o(Rn=>[...Rn,...Yt]),Cu.length>0&&u(Rn=>[...Rn,...Cu]),Nu.length>0&&a(Rn=>[...Rn,...Nu])}catch(Yt){console.error("Failed to load more data:",Yt)}},[e,x.observations,x.summaries,x.prompts]);return(0,fe.useEffect)(()=>{o([]),u([]),a([]),xu()},[e]),(0,Xt.jsxs)("div",{className:"container",children:[(0,Xt.jsxs)("div",{className:"main-col",children:[(0,Xt.jsx)(pf,{isConnected:S,projects:y,currentFilter:e,onFilterChange:t,onSettingsToggle:Nr,sidebarOpen:n,isProcessing:w,themePreference:_,onThemeChange:C}),(0,Xt.jsx)(kf,{observations:K,summaries:P,prompts:$e,onLoadMore:xu,isLoading:x.observations.isLoading||x.summaries.isLoading||x.prompts.isLoading,hasMore:x.observations.hasMore||x.summaries.hasMore||x.prompts.hasMore})]}),(0,Xt.jsx)(Ef,{isOpen:n,settings:z,stats:g,isSaving:c,saveStatus:d,isConnected:S,onSave:f,onClose:Nr})]})}var Rf=L(de(),1),Rt=L(W(),1),eo=class extends Rf.Component{constructor(t){super(t),this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary] Caught error:",t,n),this.setState({error:t,errorInfo:n})}render(){return this.state.hasError?(0,Rt.jsxs)("div",{style:{padding:"20px",color:"#ff6b6b",backgroundColor:"#1a1a1a",minHeight:"100vh"},children:[(0,Rt.jsx)("h1",{style:{fontSize:"24px",marginBottom:"10px"},children:"Something went wrong"}),(0,Rt.jsx)("p",{style:{marginBottom:"10px",color:"#8b949e"},children:"The application encountered an error. Please refresh the page to try again."}),this.state.error&&(0,Rt.jsxs)("details",{style:{marginTop:"20px",color:"#8b949e"},children:[(0,Rt.jsx)("summary",{style:{cursor:"pointer",marginBottom:"10px"},children:"Error details"}),(0,Rt.jsxs)("pre",{style:{backgroundColor:"#0d1117",padding:"10px",borderRadius:"6px",overflow:"auto"},children:[this.state.error.toString(),this.state.errorInfo&&` -`+this.state.errorInfo.componentStack]})]})]}):this.props.children}};var _u=L(W(),1),Df=document.getElementById("root");if(!Df)throw new Error("Root element not found");var fm=(0,zf.createRoot)(Df);fm.render((0,_u.jsx)(eo,{children:(0,_u.jsx)(Mf,{})}));})(); +`+this.state.errorInfo.componentStack]})]})]}):this.props.children}};var _u=L(W(),1),If=document.getElementById("root");if(!If)throw new Error("Root element not found");var fm=(0,zf.createRoot)(If);fm.render((0,_u.jsx)(eo,{children:(0,_u.jsx)(Mf,{})}));})(); /*! Bundled license information: react/cjs/react.production.min.js: diff --git a/src/services/sqlite/SessionStore.ts b/src/services/sqlite/SessionStore.ts index eb1c5972..eb086723 100644 --- a/src/services/sqlite/SessionStore.ts +++ b/src/services/sqlite/SessionStore.ts @@ -656,6 +656,7 @@ export class SessionStore { const stmt = this.db.prepare(` SELECT DISTINCT project FROM sdk_sessions + WHERE project IS NOT NULL AND project != '' ORDER BY project ASC `); diff --git a/src/services/worker-types.ts b/src/services/worker-types.ts index 876a2de8..20fd1edd 100644 --- a/src/services/worker-types.ts +++ b/src/services/worker-types.ts @@ -102,6 +102,7 @@ export interface Summary { session_id: string; // claude_session_id (from JOIN) project: string; request: string | null; + investigated: string | null; learned: string | null; completed: string | null; next_steps: string | null; diff --git a/src/ui/viewer/App.tsx b/src/ui/viewer/App.tsx index 52c37f65..4a62b7a5 100644 --- a/src/ui/viewer/App.tsx +++ b/src/ui/viewer/App.tsx @@ -23,28 +23,30 @@ export function App() { const { preference, resolvedTheme, setThemePreference } = useTheme(); const pagination = usePagination(currentFilter); - // Reset paginated data when filter changes - useEffect(() => { - setPaginatedObservations([]); - setPaginatedSummaries([]); - setPaginatedPrompts([]); - }, [currentFilter]); + // When filtering by project: ONLY use paginated data (API-filtered) + // When showing all projects: merge SSE live data with paginated data + const allObservations = useMemo(() => { + if (currentFilter) { + // Project filter active: API handles filtering, ignore SSE items + return paginatedObservations; + } + // No filter: merge SSE + paginated, deduplicate by ID + return mergeAndDeduplicateByProject(observations, paginatedObservations); + }, [observations, paginatedObservations, currentFilter]); - // Merge real-time data with paginated data, removing duplicates and filtering by project - const allObservations = useMemo( - () => mergeAndDeduplicateByProject(observations, paginatedObservations, currentFilter), - [observations, paginatedObservations, currentFilter] - ); + const allSummaries = useMemo(() => { + if (currentFilter) { + return paginatedSummaries; + } + return mergeAndDeduplicateByProject(summaries, paginatedSummaries); + }, [summaries, paginatedSummaries, currentFilter]); - const allSummaries = useMemo( - () => mergeAndDeduplicateByProject(summaries, paginatedSummaries, currentFilter), - [summaries, paginatedSummaries, currentFilter] - ); - - const allPrompts = useMemo( - () => mergeAndDeduplicateByProject(prompts, paginatedPrompts, currentFilter), - [prompts, paginatedPrompts, currentFilter] - ); + const allPrompts = useMemo(() => { + if (currentFilter) { + return paginatedPrompts; + } + return mergeAndDeduplicateByProject(prompts, paginatedPrompts); + }, [prompts, paginatedPrompts, currentFilter]); // Toggle sidebar const toggleSidebar = useCallback(() => { @@ -72,13 +74,16 @@ export function App() { } catch (error) { console.error('Failed to load more data:', error); } - }, [pagination.observations, pagination.summaries, pagination.prompts]); + }, [currentFilter, pagination.observations, pagination.summaries, pagination.prompts]); - // Load first page only when filter changes + // Reset paginated data and load first page when filter changes useEffect(() => { + setPaginatedObservations([]); + setPaginatedSummaries([]); + setPaginatedPrompts([]); handleLoadMore(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [currentFilter]); // Only re-run when filter changes, not when handleLoadMore changes + }, [currentFilter]); return (
diff --git a/src/ui/viewer/components/SummaryCard.tsx b/src/ui/viewer/components/SummaryCard.tsx index 7b9bc9d5..77105430 100644 --- a/src/ui/viewer/components/SummaryCard.tsx +++ b/src/ui/viewer/components/SummaryCard.tsx @@ -20,6 +20,9 @@ export function SummaryCard({ summary }: SummaryCardProps) { {summary.request && (
Request: {summary.request}
)} + {summary.investigated && ( +
Investigated: {summary.investigated}
+ )} {summary.learned && (
Learned: {summary.learned}
)} diff --git a/src/ui/viewer/hooks/usePagination.ts b/src/ui/viewer/hooks/usePagination.ts index 55d63439..47723397 100644 --- a/src/ui/viewer/hooks/usePagination.ts +++ b/src/ui/viewer/hooks/usePagination.ts @@ -1,4 +1,4 @@ -import { useState, useEffect, useCallback, useRef } from 'react'; +import { useState, useCallback, useRef } from 'react'; import { Observation, Summary, UserPrompt } from '../types'; import { UI } from '../constants/ui'; import { API_ENDPOINTS } from '../constants/api'; @@ -19,42 +19,40 @@ function usePaginationFor(endpoint: string, dataType: DataType, currentFilter: s isLoading: false, hasMore: true }); - const [offset, setOffset] = useState(0); - // Use refs to avoid stale closures and prevent infinite loops + // Track offset and filter in refs to handle synchronous resets + const offsetRef = useRef(0); + const lastFilterRef = useRef(currentFilter); const stateRef = useRef(state); - const offsetRef = useRef(offset); - - useEffect(() => { - stateRef.current = state; - }, [state]); - - useEffect(() => { - offsetRef.current = offset; - }, [offset]); - - // Reset pagination when filter changes - useEffect(() => { - setOffset(0); - setState({ - isLoading: false, - hasMore: true - }); - }, [currentFilter]); /** * Load more items from the API + * Automatically resets offset to 0 if filter has changed */ const loadMore = useCallback(async (): Promise => { + // Check if filter changed - if so, reset pagination synchronously + const filterChanged = lastFilterRef.current !== currentFilter; + + if (filterChanged) { + offsetRef.current = 0; + lastFilterRef.current = currentFilter; + + // Reset state both in React state and ref synchronously + const newState = { isLoading: false, hasMore: true }; + setState(newState); + stateRef.current = newState; // Update ref immediately to avoid stale checks + } + // Prevent concurrent requests using ref (always current) - if (stateRef.current.isLoading || !stateRef.current.hasMore) { + // Skip this check if we just reset the filter - we want to load the first page + if (!filterChanged && (stateRef.current.isLoading || !stateRef.current.hasMore)) { return []; } setState(prev => ({ ...prev, isLoading: true })); try { - // Build query params using ref (always current) + // Build query params using current offset from ref const params = new URLSearchParams({ offset: offsetRef.current.toString(), limit: UI.PAGINATION_PAGE_SIZE.toString() @@ -71,7 +69,7 @@ function usePaginationFor(endpoint: string, dataType: DataType, currentFilter: s throw new Error(`Failed to load ${dataType}: ${response.statusText}`); } - const data = await response.json(); + const data = await response.json() as { items: DataItem[], hasMore: boolean }; setState(prev => ({ ...prev, @@ -79,14 +77,16 @@ function usePaginationFor(endpoint: string, dataType: DataType, currentFilter: s hasMore: data.hasMore })); - setOffset(prev => prev + UI.PAGINATION_PAGE_SIZE); - return data.items as DataItem[]; + // Increment offset after successful load + offsetRef.current += UI.PAGINATION_PAGE_SIZE; + + return data.items; } catch (error) { console.error(`Failed to load ${dataType}:`, error); setState(prev => ({ ...prev, isLoading: false })); return []; } - }, [currentFilter, endpoint, dataType]); // Only stable values - no state/offset deps + }, [currentFilter, endpoint, dataType]); return { ...state, diff --git a/src/ui/viewer/types.ts b/src/ui/viewer/types.ts index 56883cb7..c614a31d 100644 --- a/src/ui/viewer/types.ts +++ b/src/ui/viewer/types.ts @@ -21,6 +21,7 @@ export interface Summary { session_id: string; project: string; request?: string; + investigated?: string; learned?: string; completed?: string; next_steps?: string; diff --git a/src/ui/viewer/utils/data.ts b/src/ui/viewer/utils/data.ts index e2998964..5211a5c2 100644 --- a/src/ui/viewer/utils/data.ts +++ b/src/ui/viewer/utils/data.ts @@ -4,25 +4,21 @@ */ /** - * Merge real-time SSE items with paginated items, removing duplicates and filtering by project - * @param liveItems - Items from SSE stream - * @param paginatedItems - Items from pagination API (already filtered by project) - * @param projectFilter - Current project filter (empty string = all projects) + * Merge real-time SSE items with paginated items, removing duplicates by ID + * NOTE: This should ONLY be used when no project filter is active. + * When filtering, use ONLY paginated data (API-filtered). + * + * @param liveItems - Items from SSE stream (unfiltered) + * @param paginatedItems - Items from pagination API * @returns Merged and deduplicated array */ export function mergeAndDeduplicateByProject( liveItems: T[], - paginatedItems: T[], - projectFilter: string + paginatedItems: T[] ): T[] { - // Filter SSE items by current project (pagination is already filtered) - const filteredLive = projectFilter - ? liveItems.filter(item => item.project === projectFilter) - : liveItems; - - // Deduplicate using Set + // Deduplicate by ID const seen = new Set(); - return [...filteredLive, ...paginatedItems].filter(item => { + return [...liveItems, ...paginatedItems].filter(item => { if (seen.has(item.id)) return false; seen.add(item.id); return true;