@calmabacus/pi-web 1.1.5 → 1.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +11 -11
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +4 -4
- package/.next/required-server-files.js +5 -5
- package/.next/required-server-files.json +5 -5
- package/.next/server/app/_global-error/page.js +2 -2
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +4 -4
- package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
- package/.next/server/app/api/agent/[id]/bash-output/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/agent/[id]/events/route.js +1 -1
- package/.next/server/app/api/agent/[id]/events/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/agent/[id]/lease/route.js +1 -1
- package/.next/server/app/api/agent/[id]/lease/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/agent/[id]/route.js +1 -1
- package/.next/server/app/api/agent/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/agent/new/route.js +1 -1
- package/.next/server/app/api/agent/new/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/agent/running/route.js +1 -1
- package/.next/server/app/api/agent/running/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/api/app-update/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/api-key/[provider]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
- package/.next/server/app/api/auth/login/[provider]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
- package/.next/server/app/api/auth/logout/[provider]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/auth/providers/route.js +1 -1
- package/.next/server/app/api/auth/providers/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/cwd/browse/route.js +1 -1
- package/.next/server/app/api/cwd/browse/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/cwd/validate/route.js +1 -1
- package/.next/server/app/api/cwd/validate/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/default-cwd/route.js +1 -1
- package/.next/server/app/api/default-cwd/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/file-index/route.js +1 -1
- package/.next/server/app/api/file-index/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/files/[...path]/route.js +2 -2
- package/.next/server/app/api/files/[...path]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/git/diff/route.js +1 -1
- package/.next/server/app/api/git/diff/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/git/status/route.js +2 -2
- package/.next/server/app/api/git/status/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/home/route.js +1 -1
- package/.next/server/app/api/home/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/image-generation/route.js +1 -1
- package/.next/server/app/api/image-generation/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/image-generation/settings/connections/route.js +1 -1
- package/.next/server/app/api/image-generation/settings/connections/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/image-generation/settings/route.js +1 -1
- package/.next/server/app/api/image-generation/settings/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models/route.js +1 -1
- package/.next/server/app/api/models/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models-config/catalog/route.js +1 -1
- package/.next/server/app/api/models-config/catalog/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models-config/discover/route.js +1 -1
- package/.next/server/app/api/models-config/discover/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models-config/picker/route.js +1 -1
- package/.next/server/app/api/models-config/picker/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models-config/route.js +1 -1
- package/.next/server/app/api/models-config/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models-config/runtime/route.js +1 -1
- package/.next/server/app/api/models-config/runtime/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/models-config/test/route.js +1 -1
- package/.next/server/app/api/models-config/test/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/plugins/check/route.js +1 -1
- package/.next/server/app/api/plugins/check/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/plugins/route.js +1 -1
- package/.next/server/app/api/plugins/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/project-trust/route.js +1 -1
- package/.next/server/app/api/project-trust/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/projects/route.js +1 -1
- package/.next/server/app/api/projects/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/push/config/route.js +1 -1
- package/.next/server/app/api/push/config/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/push/subscribe/route.js +1 -1
- package/.next/server/app/api/push/subscribe/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/auto-name/route.js +2 -2
- package/.next/server/app/api/sessions/[id]/auto-name/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/context/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/export/route.js +2 -2
- package/.next/server/app/api/sessions/[id]/export/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/outline/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
- package/.next/server/app/api/sessions/[id]/state/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/route.js +1 -1
- package/.next/server/app/api/sessions/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/sessions/search/route.js +1 -1
- package/.next/server/app/api/sessions/search/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/skills/check/route.js +1 -1
- package/.next/server/app/api/skills/check/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/skills/install/route.js +1 -1
- package/.next/server/app/api/skills/install/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/skills/route.js +1 -1
- package/.next/server/app/api/skills/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/skills/search/route.js +1 -1
- package/.next/server/app/api/skills/search/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/skills/update/route.js +1 -1
- package/.next/server/app/api/skills/update/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/subagents/[id]/route.js +1 -1
- package/.next/server/app/api/subagents/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/subagents/profiles/route.js +1 -1
- package/.next/server/app/api/subagents/profiles/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/subagents/settings/route.js +1 -1
- package/.next/server/app/api/subagents/settings/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/terminal/[id]/events/route.js +2 -2
- package/.next/server/app/api/terminal/[id]/events/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/terminal/[id]/route.js +1 -1
- package/.next/server/app/api/terminal/[id]/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/terminal/route.js +1 -1
- package/.next/server/app/api/terminal/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/tools/settings/route.js +1 -1
- package/.next/server/app/api/tools/settings/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/web-auth/route.js +1 -1
- package/.next/server/app/api/web-auth/route_client-reference-manifest.js +1 -1
- package/.next/server/app/api/worktrees/route.js +1 -1
- package/.next/server/app/api/worktrees/route_client-reference-manifest.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +6 -6
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -6
- package/.next/server/app/index.segments/_full.segment.rsc +6 -6
- package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/login/page.js +2 -2
- package/.next/server/app/login/page.js.nft.json +1 -1
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +5 -5
- package/.next/server/app/login.segments/_full.segment.rsc +5 -5
- package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +5 -5
- package/.next/server/app/manifest.webmanifest/route.js +2 -2
- package/.next/server/app/manifest.webmanifest/route_client-reference-manifest.js +1 -1
- package/.next/server/app/page.js +20 -20
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +11 -11
- package/.next/server/chunks/2243.js +1 -1
- package/.next/server/chunks/2430.js +4 -4
- package/.next/server/chunks/2555.js +1 -0
- package/.next/server/chunks/3379.js +1 -1
- package/.next/server/chunks/6429.js +1 -1
- package/.next/server/instrumentation.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/middleware.js +2 -2
- package/.next/server/next-font-manifest.js +1 -1
- package/.next/server/next-font-manifest.json +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/1278-c513c5eacbbd1cad.js +1 -0
- package/.next/static/chunks/app/_not-found/page-20635dd42c478444.js +1 -0
- package/.next/static/chunks/app/{layout-7b931197cecbbd97.js → layout-d872269345a7e6fc.js} +1 -1
- package/.next/static/chunks/app/login/{page-9d52903f1c0a420e.js → page-d79a8deae913b439.js} +1 -1
- package/.next/static/chunks/app/page-9be4c7b688a47ef0.js +232 -0
- package/.next/static/chunks/{main-app-383718dbff9aa426.js → main-app-d6258fdb36a09040.js} +1 -1
- package/.next/static/chunks/next/dist/client/components/builtin/global-error-1fccd26caf053973.js +1 -0
- package/.next/static/css/{99591b721802b68b.css → 637f1d7332cae886.css} +1 -1
- package/.next/static/css/9e326ad64c41a025.css +1 -0
- package/.next/trace +41 -41
- package/.next/trace-build +1 -1
- package/.next/types/app/api/agent/[id]/bash-output/route.ts +1 -1
- package/.next/types/app/api/agent/[id]/events/route.ts +1 -1
- package/.next/types/app/api/agent/[id]/lease/route.ts +1 -1
- package/.next/types/app/api/agent/[id]/route.ts +1 -1
- package/.next/types/app/api/agent/new/route.ts +1 -1
- package/.next/types/app/api/agent/running/route.ts +1 -1
- package/.next/types/app/api/app-update/route.ts +1 -1
- package/.next/types/app/api/auth/api-key/[provider]/route.ts +1 -1
- package/.next/types/app/api/auth/login/[provider]/route.ts +1 -1
- package/.next/types/app/api/auth/logout/[provider]/route.ts +1 -1
- package/.next/types/app/api/auth/providers/route.ts +1 -1
- package/.next/types/app/api/cwd/browse/route.ts +1 -1
- package/.next/types/app/api/cwd/validate/route.ts +1 -1
- package/.next/types/app/api/default-cwd/route.ts +1 -1
- package/.next/types/app/api/file-index/route.ts +1 -1
- package/.next/types/app/api/files/[...path]/route.ts +1 -1
- package/.next/types/app/api/git/diff/route.ts +1 -1
- package/.next/types/app/api/git/status/route.ts +1 -1
- package/.next/types/app/api/home/route.ts +1 -1
- package/.next/types/app/api/image-generation/route.ts +1 -1
- package/.next/types/app/api/image-generation/settings/connections/route.ts +1 -1
- package/.next/types/app/api/image-generation/settings/route.ts +1 -1
- package/.next/types/app/api/models/route.ts +1 -1
- package/.next/types/app/api/models-config/catalog/route.ts +1 -1
- package/.next/types/app/api/models-config/discover/route.ts +1 -1
- package/.next/types/app/api/models-config/picker/route.ts +1 -1
- package/.next/types/app/api/models-config/route.ts +1 -1
- package/.next/types/app/api/models-config/runtime/route.ts +1 -1
- package/.next/types/app/api/models-config/test/route.ts +1 -1
- package/.next/types/app/api/plugins/check/route.ts +1 -1
- package/.next/types/app/api/plugins/route.ts +1 -1
- package/.next/types/app/api/project-trust/route.ts +1 -1
- package/.next/types/app/api/projects/route.ts +1 -1
- package/.next/types/app/api/push/config/route.ts +1 -1
- package/.next/types/app/api/push/subscribe/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/auto-name/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/context/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/entries/[entryId]/thinking/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/entries/[entryId]/tool-result-image/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/export/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/outline/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/route.ts +1 -1
- package/.next/types/app/api/sessions/[id]/state/route.ts +1 -1
- package/.next/types/app/api/sessions/route.ts +1 -1
- package/.next/types/app/api/sessions/search/route.ts +1 -1
- package/.next/types/app/api/skills/check/route.ts +1 -1
- package/.next/types/app/api/skills/install/route.ts +1 -1
- package/.next/types/app/api/skills/route.ts +1 -1
- package/.next/types/app/api/skills/search/route.ts +1 -1
- package/.next/types/app/api/skills/update/route.ts +1 -1
- package/.next/types/app/api/subagents/[id]/route.ts +1 -1
- package/.next/types/app/api/subagents/profiles/route.ts +1 -1
- package/.next/types/app/api/subagents/settings/route.ts +1 -1
- package/.next/types/app/api/terminal/[id]/events/route.ts +1 -1
- package/.next/types/app/api/terminal/[id]/route.ts +1 -1
- package/.next/types/app/api/terminal/route.ts +1 -1
- package/.next/types/app/api/tools/settings/route.ts +1 -1
- package/.next/types/app/api/web-auth/route.ts +1 -1
- package/.next/types/app/api/worktrees/route.ts +1 -1
- package/.next/types/app/layout.ts +1 -1
- package/.next/types/app/login/page.ts +1 -1
- package/.next/types/app/page.ts +1 -1
- package/package.json +1 -1
- package/.next/server/chunks/2269.js +0 -1
- package/.next/static/chunks/1278-c5108e95ba8af70e.js +0 -1
- package/.next/static/chunks/app/_not-found/page-c547ea4fd9b1457c.js +0 -1
- package/.next/static/chunks/app/page-1548543334d51dee.js +0 -232
- package/.next/static/chunks/next/dist/client/components/builtin/global-error-abddff9adf970d39.js +0 -1
- package/.next/static/css/42f1d7e7e39768de.css +0 -1
- /package/.next/static/{Prscx-ou4jvyQLamvK9J0 → yRhrvt0f-Y2K-w3kfFFuX}/_buildManifest.js +0 -0
- /package/.next/static/{Prscx-ou4jvyQLamvK9J0 → yRhrvt0f-Y2K-w3kfFFuX}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>h,sn:()=>u,xG:()=>o});let r="configured",i=[r,"none","read-only","default","full"];function o(e){if(e!==r)return"none"===e?[...s]:"read-only"===e?[...l]:"full"===e?[...d]:[...a]}let s=[],l=["read","grep","find","ls"],a=["read","bash","edit","write"],d=["bash","read","edit","write","grep","find","ls"],c=new Set([...d,"powershell"]);function u(e){return"string"==typeof e&&i.includes(e)}function h(e){return p(e.filter(e=>e.active).map(e=>e.name))}function p(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>c.has(e)).sort().join(",");return t===[...l].sort().join(",")?"read-only":t===[...a].sort().join(",")?"default":t===[...d].sort().join(",")?"full":"default"}},61795:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>at});var r=n(95155),i=n(12115),o=n(73321);function s(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,o=r.id,s=null;for(;;){if(n.has(o)){s=n.get(o)??null;break}if(i.has(o))break;i.add(o),e.push(o);let r=t.get(o);if(!r)break;if(r.relation?.kind!=="subagent"){s=r.id;break}o=r.relation.parentSessionId}for(let t of e)n.set(t,s)}return n}(e),n=new Map;for(let t of e)t.relation?.kind!=="subagent"&&n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(r.relation?.kind!=="subagent")continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}let l="pi-web:file-explorer:open";function a(){try{return window.localStorage}catch{return null}}function d(e,t=a()){if(t)try{t.setItem(l,String(e))}catch{}}let c=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function u(e){let t=e.match(c);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}function h(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1);return r>=55296&&r<=56319?n.slice(0,-1):n}function p(e){var t;return e.name?e.name:h((t=e.firstMessage)?h(u(t)??t,500):"",50)||e.id.slice(0,12)}function f(e){return e.projectKey??e.projectRoot??e.cwd}function g(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=f(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(([e,{root:t}])=>({key:e,root:t}))}function m(e,t){return e.filter(e=>f(e)===t)}let x="pi-sidebar-single-project",v="pi-sidebar-single-project-changed";function y(){return"true"===window.localStorage.getItem(x)}var b=n(2730),w=n(21278);function k(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function j(e){return k(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function S(e){let t=k(e).replace(/\/+$/,"");return t.split("/").pop()??t}function C(e){let t=k(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function E(e,t){if(!t)return e;let n=k(e),r=k(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function N(e,t){return`${k(e).replace(/\/$/,"")}/${t}`}var I=n(47650);async function M(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function T(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function L(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function R({onCancel:e,onSelect:t,initialPath:n,busy:o=!1,error:s}){let{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(n??""),[m,x]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await M(e),n=t.path??e??"/";u(n),p(t.parentPath??null),g(n),x(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),C(n||void 0)},[n,C]);let E=f.trim()!==c,N=!!c&&!E&&!o,$=!!h||/^[a-zA-Z]:[\\/]?$/.test(c);return a?(0,I.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||o||e()},onKeyDown:t=>{"Escape"!==t.key||o||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:o,title:l("i18n.close"),"aria-label":l("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:o?"default":"pointer",opacity:o?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(h??void 0),disabled:j||!$,title:l("directoryPicker.goToParent"),"aria-label":l("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:$?"pointer":"default",opacity:$?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:l("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(L,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):m.length>0?m.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(T,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noSubdirectories")}),(b||s)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??s})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:o,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:o?"default":"pointer",fontSize:13},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!N,title:l(E?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,opacity:N?1:.6,cursor:N?"pointer":"default"},children:l(o?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),a):null}function $({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon":`url(/icons/catppuccin/latte/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function W({size:e=14,open:t=!1}){return(0,r.jsx)($,{name:t?"_folder_open":"_folder",size:e})}function z({size:e=14}){return(0,r.jsx)($,{name:"_file",size:e})}let P={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function A(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)($,{name:i,size:t});let o=P[n.split(".").pop()??""];return o?(0,r.jsx)($,{name:o,size:t}):(0,r.jsx)(z,{size:t})}function D({open:e}){return(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:e?"rotate(90deg)":"none",transition:"transform 0.15s",display:"block",flexShrink:0},children:(0,r.jsx)("polyline",{points:"9 6 15 12 9 18"})})}async function H(e){let t=j(e),n=await fetch(`/api/files/${t}?type=list`);if(!n.ok){let e=`Failed to load files (HTTP ${n.status})`;try{let t=await n.json();t.error&&(e=t.error)}catch{}throw Error(e)}return((await n.json()).entries??[]).map(t=>({name:t.name,fullPath:N(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function B(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let F={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},O={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function U({status:e,t}){return(0,r.jsx)("span",{title:t(F[e.status]),"aria-label":t(F[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:O[e.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:e.code})}function _({size:e=11}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function q({onClick:e,title:t}){return(0,r.jsx)("button",{type:"button",onClick:e,title:t,"aria-label":t,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}function K({node:e,depth:t,cwd:n,onOpenFile:o,onAtMention:s,expandedPaths:l,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p}){let f=l.has(e.fullPath),g=c.has(e.fullPath),m=k(e.fullPath),x=u.get(m),v=e.isDir&&(void 0!==x||h.has(m)),[y,b]=(0,i.useState)(e.children??[]),[w,S]=(0,i.useState)(e.loaded??!1),[C,N]=(0,i.useState)(!1),[I,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(!1),R=(0,i.useCallback)(async(t=!1)=>{if(!w||t){N(!0),M(null);try{let t=await H(e.fullPath);b(t),S(!0)}catch(e){M(e instanceof Error?e.message:String(e))}finally{N(!1)}}},[w,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&f&&w&&R(!0)},[d]);let $=(0,i.useCallback)(()=>{if(e.isDir){let t=!f;a(e.fullPath,t)}else o(e.fullPath,e.name,{cwd:n})},[n,e.isDir,e.fullPath,e.name,f,o,a]);return(0,i.useEffect)(()=>{f&&!w&&R()},[R,w,f]),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:$,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:2,paddingLeft:2+14*t,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:T?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",display:"inline-flex"},children:(0,r.jsx)(D,{open:f})}),!e.isDir&&(0,r.jsx)("span",{style:{width:12,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",transform:"translateY(0.5px)"},children:e.isDir?(0,r.jsx)(W,{size:14,open:f}):A(e.name,14)}),(0,r.jsx)("span",{style:{fontSize:12,lineHeight:1,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),g&&(0,r.jsx)("span",{title:p("files.newlyUploaded"),"aria-label":p("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!T&&!e.isDir&&x&&(0,r.jsx)(U,{status:x,t:p}),!T&&v&&(0,r.jsx)("span",{title:p("files.containsChangedFiles"),"aria-label":p("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),C&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),s&&T&&(0,r.jsxs)("button",{onClick:t=>{t.stopPropagation(),s(E(e.fullPath,n),e.isDir,n)},title:p("files.insertPath"),style:{position:"absolute",right:e.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(_,{}),p("files.mention")]}),T&&!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${j(e.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:p("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),e.isDir&&f&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(K,{node:e,depth:t+1,cwd:n,onOpenFile:o,onAtMention:s,expandedPaths:l,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p},e.fullPath)),0===y.length&&w&&(0,r.jsx)("div",{style:{paddingLeft:2+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),I&&(0,r.jsx)("button",{type:"button",onClick:()=>void R(!0),title:I,style:{marginLeft:2+(t+1)*14,height:22,padding:0,border:0,background:"none",color:"#f87171",cursor:"pointer",fontSize:11},children:p("files.loadFailedRetry")})]})]})}function V({status:e,cwd:t,onOpenFile:n,t:o}){let[s,l]=(0,i.useState)(!1),a=S(e.filePath),d=E(e.filePath,t);return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,a,{modeHint:"diff",cwd:t}),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:s?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)(U,{status:e,t:o}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",opacity:.85,transform:"translateY(0.5px)"},children:A(a,13)}),(0,r.jsx)("span",{style:{fontSize:12,lineHeight:1,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:d})]})}let J=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:o,onAtMentions:s,onUploadBusyChange:l,changesCollapsed:a,onChangesCountChange:d,fileSearchOpen:c=!1,onFileSearchOpenChange:u},h){let{t:p}=(0,w.s)(),[f,g]=(0,i.useState)([]),[m,x]=(0,i.useState)(!0),[v,y]=(0,i.useState)(null),[b,S]=(0,i.useState)(new Set),[I,M]=(0,i.useState)(0),[T,L]=(0,i.useState)(new Set),[R,$]=(0,i.useState)([]),[W,z]=(0,i.useState)({additions:0,deletions:0}),[P,A]=(0,i.useState)(null),[D,F]=(0,i.useState)(null),[U,J]=(0,i.useState)("idle"),[Y,Z]=(0,i.useState)(0),[X,G]=(0,i.useState)(null),[Q,ee]=(0,i.useState)(null),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(""),[eo,es]=(0,i.useState)([]),[el,ea]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)(!1),[eu,eh]=(0,i.useState)(new Set),ep=(0,i.useRef)(null),ef=(0,i.useRef)(null),eg=(0,i.useRef)(null),em=(0,i.useRef)(null),ex=`${n??0}:${I}`,ev="idle"!==U,ey=er.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=er.trim();if(!t){es([]),ea(!1),ec(!1);return}let n=new AbortController;ea(!0),ec(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}&kind=file&version=${encodeURIComponent(ex)}`,{signal:n.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>es((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{n.signal.aborted||(es([]),ec(!0))}).finally(()=>{n.signal.aborted||ea(!1)})},150);return()=>{clearTimeout(r),n.abort()}},[e,c,ex,er]),(0,i.useEffect)(()=>{c&&ep.current?.focus()},[c]),(0,i.useEffect)(()=>{if(0===eo.length)return;let t=new Set;for(let n of eo){let r=n.split("/"),i="";for(let n=0;n<r.length-1;n++)i=i?`${i}/${r[n]}`:r[n],t.add(N(e,i))}eh(e=>{let n=!1,r=new Set(e);for(let e of t)r.has(e)||(r.add(e),n=!0);return n?r:e})},[e,eo]);let eb=(0,i.useMemo)(()=>{let t=n=>({name:n.name,fullPath:N(e,n.path),isDir:n.isDir,size:0,children:n.children.map(t),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,o="";for(let t=0;t<e.length;t++){o=o?`${o}/${e[t]}`:e[t];let r=n.get(o);r||(r={name:e[t],path:o,isDir:t<e.length-1,children:[]},n.set(o,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t})(eo).map(t)},[e,eo]),ew=(0,i.useMemo)(()=>new Map(R.map(e=>[k(e.filePath),e])),[R]),ek=(0,i.useMemo)(()=>{let t=new Set,n=k(e).replace(/\/$/,"");for(let e of R){let r=C(k(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=C(r);if(e===r)break;r=e}}return t},[e,R]),ej=(0,i.useCallback)((e,t)=>{S(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),eS=(0,i.useCallback)(t=>{let n=t.uploaded??[];ee({uploaded:n,skipped:t.skipped??[],errors:t.errors??[]}),n.length>0&&(L(new Set(n.map(t=>N(e,t)))),M(e=>e+1))},[e]),eC=(0,i.useCallback)(async(t,n)=>{en(null),G(null),Z(0),J("uploading");try{let{status:r,data:i}=await new Promise((r,i)=>{let o=new FormData;t.forEach(e=>o.append("files",e,e.name));let s=new XMLHttpRequest;s.open("POST",`/api/files/${j(e)}?type=upload&conflict=${n}`),s.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&Z(Math.round(e.loaded/e.total*100))},s.onerror=()=>i(Error("Network error while uploading files")),s.onabort=()=>i(Error("Upload cancelled")),s.onload=()=>{let e={};try{e=JSON.parse(s.responseText)}catch{s.responseText&&(e.error=s.responseText)}r({status:s.status,data:e})},s.send(o)});if(409===r&&i.conflicts?.length)return void en({files:t,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);Z(100),eS(i)}catch(e){G(e instanceof Error?e.message:String(e))}finally{J("idle")}},[eS,e]),eE=(0,i.useCallback)(async t=>{if(0!==t.length&&!ev){ee(null),L(new Set),en(null),G(null),Z(0),J("checking");try{let n=await fetch(`/api/files/${j(e)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:t.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void en({files:t,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await eC(t,"error")}catch(e){G(e instanceof Error?e.message:String(e))}finally{J("idle")}}},[e,eC,ev]),eN=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eE(t)},[eE]);(0,i.useImperativeHandle)(h,()=>({openUploadPicker(){ev||em.current?.click()}}),[ev]),(0,i.useEffect)(()=>{l?.(ev)},[l,ev]),(0,i.useEffect)(()=>()=>l?.(!1),[l]),(0,i.useEffect)(()=>{let t=ef.current!==e;ef.current=e,t&&(S(new Set),L(new Set),ee(null),en(null),G(null)),x(t),y(null);let n=!1;return H(e).then(e=>{n||g(e)}).catch(e=>{n||y(e instanceof Error?e.message:String(e))}).finally(()=>{n||x(!1)}),()=>{n=!0}},[e,n,I]),(0,i.useEffect)(()=>{let t=!1;return eg.current!==e&&(A(null),$([]),z({additions:0,deletions:0})),F(null),B(e).then(n=>{t||($(n.isGitRepository?n.files:[]),z(n.isGitRepository?{additions:n.additions,deletions:n.deletions}:{additions:0,deletions:0}),eg.current=e,A(e))}).catch(e=>{t||F(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e,n,I]),(0,i.useEffect)(()=>{d?.(P===e?R.length:0)},[e,R,P,d]);let eI=ev||null!==et||null!==X||null!==Q,eM=(0,i.useCallback)(()=>{Q&&0!==Q.uploaded.length&&s?.(Q.uploaded.map(t=>E(N(e,t),e)),e)},[e,s,Q]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:em,type:"file",multiple:!0,hidden:!0,onChange:eN}),eI&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ev&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===U?p("files.checking"):p("files.uploading",{progress:Y}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===U?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===U&&(0,r.jsxs)("span",{style:{fontSize:10},children:[Y,"%"]})]}),"uploading"===U&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${Y}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),et&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:p("files.conflictSummary",{count:et.conflicts.length,countSuffix:1===et.conflicts.length?"":"s",files:et.conflicts.join(", ")})}),et.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:p("files.cannotReplace",{files:et.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void eC(et.files,"overwrite"),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:p("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void eC(et.files,"skip"),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:p("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>en(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:p("files.cancel")})]})]}),X&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:X}),(0,r.jsx)(q,{onClick:()=>G(null),title:p("files.dismissError")})]}),Q&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[Q.uploaded.length>0&&(0,r.jsxs)("span",{title:`${Q.uploaded.length} uploaded`,"aria-label":`${Q.uploaded.length} uploaded`,style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:Q.uploaded.length})]}),Q.skipped.length>0&&(0,r.jsxs)("span",{title:`${Q.skipped.length} skipped`,"aria-label":`${Q.skipped.length} skipped`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:Q.skipped.length})]}),Q.errors.length>0&&(0,r.jsxs)("span",{title:`${Q.errors.length} failed`,"aria-label":`${Q.errors.length} failed`,style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:Q.errors.length})]})]}),Q.uploaded.length>0&&s&&(0,r.jsxs)("button",{type:"button",onClick:eM,title:1===Q.uploaded.length?p("files.addUploadedFile"):p("files.addAllUploadedFiles"),"aria-label":1===Q.uploaded.length?p("files.addUploadedFile"):p("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(_,{}),p("files.mention")]}),(0,r.jsx)(q,{onClick:()=>ee(null),title:p("files.dismissUploadResults")})]}),Q.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),c&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:ep,className:"file-search-input",value:er,onChange:e=>ei(e.target.value),onKeyDown:e=>{"Escape"===e.key&&u?.(!1)},placeholder:p("sidebar.searchFilesPlaceholder"),"aria-label":p("sidebar.searchFiles"),style:{width:"100%",boxSizing:"border-box",padding:"6px 24px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit",fontSize:12}}),er&&(0,r.jsx)("button",{type:"button",onClick:()=>ei(""),title:p("sidebar.clearSearch"),"aria-label":p("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),ey&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[el&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:p("sidebar.searchingFiles")}),!el&&ed&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:p("i18n.networkError")}),!el&&!ed&&0===eo.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:p("sidebar.noMatchingFiles")}),!el&&!ed&&eo.length>0&&(0,r.jsx)("div",{children:eb.map(n=>(0,r.jsx)(K,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:eu,onToggleExpanded:(e,t)=>{eh(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:T,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},`${er}:${n.fullPath}`))})]})]}),D&&(0,r.jsx)("div",{role:"alert",title:D,style:{padding:"6px 12px",fontSize:11,color:"#f87171"},children:p("files.gitStatusFailed")}),!a&&P===e&&R.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":p("files.changeStats",{count:R.length,additions:W.additions,deletions:W.deletions}),style:{display:"flex",alignItems:"center",gap:6,height:24,padding:"0 10px",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:p("files.changedCount",{count:R.length})}),(0,r.jsxs)("span",{style:{color:O.added,fontFamily:"var(--font-mono)"},children:["+",W.additions]}),(0,r.jsxs)("span",{style:{color:O.deleted,fontFamily:"var(--font-mono)"},children:["-",W.deletions]})]}),R.map(n=>(0,r.jsx)(V,{status:n,cwd:e,onOpenFile:t,t:p},n.filePath))]}),(a||P!==e||0===R.length)&&(!c||!ey)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[m?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:v}):f.map(n=>(0,r.jsx)(K,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:b,onToggleExpanded:ej,refreshToken:ex,highlightedPaths:T,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},n.fullPath)),!m&&!v&&0===f.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:p("files.noFiles")})]})]})});function Y({open:e,query:t,refreshKey:n,children:o,selectedSessionId:s,onSelectSession:l}){let{t:a,locale:d}=(0,w.s)(),[c,u]=(0,i.useState)({query:""}),h=t.trim(),p=c.query===h?c.response:void 0,f=c.query===h&&c.failed;return(0,i.useEffect)(()=>{if(!e||!h)return;let t=new AbortController;u({query:h});let n=setTimeout(async()=>{try{let e=await fetch(`/api/sessions/search?${new URLSearchParams({q:h})}`,{signal:t.signal});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await e.json();t.signal.aborted||u({query:h,response:n})}catch{t.signal.aborted||u({query:h,failed:!0})}},300);return()=>{clearTimeout(n),t.abort()}},[e,h,n]),e&&h?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!p&&!f,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:f?a("sidebar.sessionSearchFailed"):p?0===p.results.length?a("sidebar.sessionSearchEmpty"):a("sidebar.sessionSearchCount",{count:p.results.length}):a("sidebar.sessionSearching")}),p?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:a("sidebar.sessionSearchPartial")}),p?.results.map(({session:e,entryId:t,blockIndex:n,before:i,match:o,after:a})=>(0,r.jsxs)("button",{type:"button",onClick:()=>l(e,t,n),"aria-current":e.id===s?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${e.id===s?"bg-bg-selected":""}`,children:[(0,r.jsx)("span",{className:"block truncate text-xs font-medium text-text",children:e.name||e.firstMessage}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:e.cwd,children:e.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,b.fw)(e.modified,d)})]}),(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[i,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:o}),a]})]},e.id))]}):o}function Z({size:e=14,title:t,ariaLabel:n,className:i,style:o}){let s=e<=10?4:5;return(0,r.jsxs)("span",{className:`live-pulse-beacon${i?` ${i}`:""}`,title:t,"aria-label":n,style:{width:e,height:e,...o},children:[(0,r.jsx)("span",{className:"live-pulse-beacon-halo",style:{width:s,height:s},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"live-pulse-beacon-core",style:{width:s,height:s},"aria-hidden":"true"})]})}function X({size:e=14,strokeWidth:t=2,className:n,style:i}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:n,style:{flexShrink:0,...i},children:[(0,r.jsx)("rect",{x:"3",y:"7",width:"13",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 3h10a2 2 0 0 1 2 2v10"})]})}function G({onClick:e,title:t,disabled:n,skipHover:i,color:o,background:s="none",marginRight:l,ariaPressed:a,className:d,children:c}){return(0,r.jsx)("button",{onClick:e,disabled:n,title:t,"aria-label":t,"aria-pressed":a,className:d,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,marginRight:l,background:s,border:"none",color:o,cursor:n?"default":"pointer",borderRadius:4,flexShrink:0,opacity:n?.6:1,transition:"color 0.3s, background 0.3s"},onMouseEnter:e=>{n||i||(e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||i||(e.currentTarget.style.color=o,e.currentTarget.style.background=s)},children:c})}function Q({open:e}){return(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(D,{open:e})})}let ee="pi-web:unread-session-ids",et="pi-web:last-custom-cwd",en="pi-web:workspace-expansion";function er(){try{let e=window.localStorage.getItem(en);if(!e)return null;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):null}catch{return null}}function ei(){try{return window.localStorage.getItem(et)??""}catch{return""}}function eo(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function es({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function el({open:e,children:t,style:n}){let[o,s]=(0,i.useState)(e),[l,a]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),a(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>a(!0))})):(a(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),o)?(0,r.jsx)("div",{style:{...n,opacity:+!!l,transform:l?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}function ea({selectedSessionId:e,onSelectSession:t,onOpenSessionInNewTab:n,onPinSession:o,onNewSession:c,initialSessionId:u,skipInitialProjectSelection:h,refreshKey:p,onSessionDeleted:x,selectedCwd:b,onCwdChange:k,onOpenFile:j,onOpenTerminal:C,explorerRefreshKey:E,onExplorerRefresh:N,onAtMention:I,onAtMentions:M,onBackgroundTaskDone:T,onRunningSessionIdsChange:L,onSessionsChange:$,pinnedCwds:W,onTogglePinnedCwd:z,onHomeDirChange:P,onWorktreeInfoChange:A}){let D,H,B,{t:F}=(0,w.s)(),[O,U]=(0,i.useState)([]),[_,q]=(0,i.useState)(null),K=(0,i.useRef)(null),V=(0,i.useRef)(0),[X,ed]=(0,i.useState)(!0),[ec,eh]=(0,i.useState)(null),[ep,ef]=(0,i.useState)(null),[eg,em]=(0,i.useState)(""),[ex,ev]=(0,i.useState)(!1),[ey,eb]=(0,i.useState)(""),[ew,ek]=(0,i.useState)(!1),[ej,eS]=(0,i.useState)(ei),[eC,eE]=(0,i.useState)(null),[eN,eI]=(0,i.useState)(!1),[eM,eT]=(0,i.useState)(null),eL=(0,i.useRef)(null),[eR,e$]=(0,i.useState)(null),[eW,ez]=(0,i.useState)(!1),[eP,eA]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(""),[eB,eF]=(0,i.useState)(null),[eO,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(null),eJ=(0,i.useRef)(null),eY=(0,i.useRef)(null),[eZ,eX]=(0,i.useState)(!0),[eG,eQ]=(0,i.useState)(!0),[e0,e1]=(0,i.useState)(er),[e2,e4]=(0,i.useState)({}),[e8,e5]=(0,i.useState)(0),[e6,e3]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(""),ti=te&&!!tn.trim(),[to,ts]=(0,i.useState)(0),[tl,ta]=(0,i.useState)(!0),[td,tc]=(0,i.useState)(()=>new Set),[tu,th]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(ee);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),tp=(0,i.useRef)(new Set),tf=(0,i.useRef)(new Set),tg=(0,i.useRef)(new Set),tm=(0,i.useRef)(!1),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),[ty,tb]=(0,i.useState)(0),[tw,tk]=(0,i.useState)(0),[tj,tS]=(0,i.useState)(null),[tC,tE]=(0,i.useState)(null),[tN,tI]=(0,i.useState)(null),[tM,tT]=(0,i.useState)(null),[tL,tR]=(0,i.useState)(null),[t$,tW]=(0,i.useState)(null),tz=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(!1),tD=(0,i.useRef)(null),tH=(0,i.useCallback)(e=>{tE(null),tI(null);let t=e.currentTarget.scrollTop;null==tD.current&&(tD.current=requestAnimationFrame(()=>{tD.current=null,tk(t)}))},[]);(0,i.useEffect)(()=>{if(!tC&&!tN)return;let e=e=>{let t=e.target;t?.closest(".session-row-actions, .workspace-row-action")||(tE(null),tI(null))};return window.addEventListener("pointerdown",e,!0),()=>window.removeEventListener("pointerdown",e,!0)},[tC,tN]);let tB=(0,i.useCallback)((e,t)=>{if(t.target?.closest(".workspace-row-action"))return;let n=t.touches[0];tP.current={x:n.clientX,y:n.clientY},tA.current=!1,tz.current=setTimeout(()=>{tA.current=!0,tI(e),navigator.vibrate?.(15)},400)},[]),tF=(0,i.useCallback)(e=>{if(!tP.current||!tz.current)return;let t=e.touches[0];(Math.abs(t.clientX-tP.current.x)>10||Math.abs(t.clientY-tP.current.y)>10)&&(clearTimeout(tz.current),tz.current=null)},[]),tO=(0,i.useCallback)(()=>{tz.current&&clearTimeout(tz.current),tz.current=null,tP.current=null},[]);(0,i.useLayoutEffect)(()=>{let e=tv.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)tb(t.contentRect.height)});return t.observe(e),tb(e.clientHeight),tk(e.scrollTop),()=>t.disconnect()},[ti]);let tU=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++V.current;try{e&&ed(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(n!==V.current)return;K.current=i.sessionListVersion,q(i.sessionListVersion),U(i.sessions),tm.current||(tf.current=new Set(i.completionNotificationSuppressedSessionIds??[]),tc(new Set(i.runningSessionIds??[])));let o=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));th(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),eh(null)}catch(e){n===V.current&&eh(String(e))}finally{n===V.current&&ed(!1)}},[]),t_=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!t_.current;t_.current=!0,tU(e,!e)},[tU,p]),(0,i.useEffect)(()=>{eX(function(e=a()){if(!e)return!0;try{return"false"!==e.getItem(l)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===tu.size?window.localStorage.removeItem(ee):window.localStorage.setItem(ee,JSON.stringify([...tu]))}catch{}},[tu]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let o=new AbortController;n?.abort(),n=o;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:o.signal});if(!t.ok)return;let r=await t.json();if(e||n!==o)return;tm.current=!0,tf.current=new Set(r.completionNotificationSuppressedSessionIds??[]),tc(new Set(r.runningSessionIds??[])),r.sessionListVersion!==K.current&&await tU()}catch{}finally{n===o&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},o=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",o),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",o)}},[tU]),(0,i.useEffect)(()=>{L?.(td)},[L,td]),(0,i.useEffect)(()=>{$?.(O)},[O,$]),(0,i.useEffect)(()=>{let t=tp.current,n=[...t].filter(t=>!td.has(t)&&t!==e),r=new Set(O.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!tg.current.has(e)&&!r.has(e)),o=[...td].filter(e=>!t.has(e));(i.length>0||o.length>0)&&th(e=>{let t=new Set(e);return td.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let s=o.some(e=>!O.some(t=>t.id===e));(n.length>0||s)&&tU(!1,!0),i.length>0&&T?.(i),tp.current=td,tg.current=new Set([...td].filter(e=>tf.current.has(e)||r.has(e)))},[td,e,O,tU,T]),(0,i.useEffect)(()=>{e&&th(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==E&&e5(e=>e+1)},[E]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&em(e.home)}).catch(()=>{})},[]),(0,i.useEffect)(()=>{eg&&P?.(eg)},[eg,P]);let tq=(0,i.useRef)(!1),tK=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tV=(0,i.useCallback)(e=>{if(!e)return null;if(eM?.cwd===e)return tK(eM.root,eM.key);if(eR&&eR.forCwd===e||eR?.worktrees.some(t=>t.path===e))return tK(eR.projectRoot,eR.projectKey);let t=O.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tK(t.projectRoot??t.cwd,f(t)):tK(e,e)},[eM,eR,O,tK]),tJ=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tV(ep),t=tJ.current;(t?.cwd!==ep||t.key!==(e?.key??null))&&(tJ.current={cwd:ep,key:e?.key??null},k?.(ep,e?.root??null,e?.key??null))},[ep,k,tV]);let tY=(0,i.useRef)(null);(0,i.useEffect)(()=>{b&&b!==tY.current&&(tY.current=b,ef(b))},[b]);let[tZ,tX]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!ep){e$(null),eV(null);return}let e=!1;return eV(ep),fetch(`/api/worktrees?cwd=${encodeURIComponent(ep)}`).then(e=>e.json()).then(t=>{if(!e){if(eV(null),t.error||!t.projectRoot)return void e$(null);e$({forCwd:ep,projectRoot:t.projectRoot,projectKey:t.projectKey??t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,currentWorktreePath:t.currentWorktreePath??null,worktrees:t.worktrees??[]})}}).catch(()=>{e||(eV(null),e$(null))}),()=>{e=!0}},[ep,tZ,p]),(0,i.useEffect)(()=>{if(A){if(!eR?.isGit)return void A(null);A({forCwd:eR.forCwd,projectRoot:eR.projectRoot,currentWorktreePath:eR.currentWorktreePath,worktrees:eR.worktrees})}},[eR,A]),(0,i.useEffect)(()=>{if(0!==O.length&&!h&&null===ep){if(u&&!tq.current){tq.current=!0;let e=O.find(e=>e.id===u);if(e){ef(e.cwd),t(e,!0);return}}let e=g(O);e.length>0&&ef(e[0].root)}},[O,ep,u,h,t]);let tG=eR?eR.worktrees.find(e=>e.path===ep)??(eR.forCwd===ep&&eR.currentWorktreePath?eR.worktrees.find(e=>e.path===eR.currentWorktreePath):void 0)??eR.worktrees.find(e=>e.isMain):void 0,tQ=tG?.path??null,t0=(0,i.useCallback)(async e=>{let t=(e??ej).trim();if(t&&!eN){eI(!0),eE(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await e.json().catch(()=>({}));if(!e.ok||r.error||!r.cwd||!r.projectRoot||!r.projectKey)return void eE(r.error??`HTTP ${e.status}`);eT({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(et,n)}catch{}eS(r.cwd),W.includes(r.projectRoot)||z(r.projectRoot),e1(e=>new Set([...e??[],r.projectKey])),ef(r.cwd),ek(!1),ev(!1)}catch(e){eE(e instanceof Error?e.message:String(e))}finally{eI(!1)}}},[ej,eN,z,W]),t1=(0,i.useCallback)(()=>{ek(!0),eE(null),ev(!1)},[]),t2=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(W.includes(t.cwd)||z(t.cwd),e1(e=>new Set([...e??[],t.cwd])),ef(t.cwd),ek(!1),eE(null),ev(!1))}catch{}},[z,W]),t4=(0,i.useCallback)(async()=>{let e=eD.trim();if(e&&!eO&&eR){eU(!0),eF(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eR.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eF(n.error??`HTTP ${t.status}`);eA(!1),eH(""),ez(!1),e$(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),ef(n.path),tX(e=>e+1)}catch(e){eF(e instanceof Error?e.message:String(e))}finally{eU(!1)}}},[eD,eO,eR]),t8=(0,i.useCallback)(async(e,t)=>{if(eR&&!eO){eU(!0),eF(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eR.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eq(e);eF(r.error??`HTTP ${n.status}`);return}eq(null),tQ===e&&ef(eR.projectRoot),tX(e=>e+1)}catch(e){eF(e instanceof Error?e.message:String(e))}finally{eU(!1)}}},[eR,eO,tQ]);(0,i.useEffect)(()=>{let e=e=>{eL.current&&!eL.current.contains(e.target)&&ev(!1),eJ.current&&!eJ.current.contains(e.target)&&(ez(!1),eA(!1),eH(""),eF(null),eq(null),eb(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t5=(0,i.useCallback)((e,n,r)=>{U(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e1(t=>{let n=new Set(t??[]);return n.add(f(e)),n});let i=tV(ep)?.key;(function(e){let t=e.sessionCwd;if(!t)return!1;let n=e.selectedCwd;if(!n)return!0;if(t===n)return!1;if(e.sessionProjectKey&&e.selectedProjectKey&&e.sessionProjectKey!==e.selectedProjectKey)return!0;let r=e.worktrees;if(!r?.length)return!0;let i=e=>r.find(t=>t.path===e)?.path??null,o=i(t);return!!o&&o!==(i(n)??n)})({sessionCwd:e.cwd,selectedCwd:ep,sessionProjectKey:f(e),selectedProjectKey:i,worktrees:eR?.worktrees})&&ef(e.cwd),t(e,!1,n,r)},[t,tV,ep,eR]),t6=(0,i.useCallback)(e=>{let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;c?.(t,e)},[c]),[t3,t7]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=()=>t7(y());return e(),window.addEventListener(v,e),()=>window.removeEventListener(v,e)},[]);let t9=(0,i.useMemo)(()=>g(O),[O]),ne=!ep&&!X&&!ec&&0===t9.length,nt=(0,i.useMemo)(()=>tV(ep),[tV,ep]),nn=(0,i.useMemo)(()=>{let e=[],t=new Set,n=n=>{!n||t.has(n.key)||(t.add(n.key),e.push(n))};return W.forEach(e=>n(tV(e))),t9.forEach(n),n(nt),e},[W,tV,t9,nt]),nr=(0,i.useMemo)(()=>{let t;return e?t=nt?.key:1===nn.length&&(t=nn[0]?.key),new Set(t?[t]:[])},[nt?.key,e,nn]);(0,i.useEffect)(()=>{null===e0&&0!==nn.length&&e1(nr)},[nr,e0,nn.length]),(0,i.useEffect)(()=>{null!==e0&&function(e){try{window.localStorage.setItem(en,JSON.stringify([...e]))}catch{}}(e0)},[e0]);let ni=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=f(i);if(!e)continue;let o=r.get(e);o||(o={running:0,unread:0},r.set(e,o)),t.has(i.id)&&o.running++,n.has(i.id)&&o.unread++}return r})(O,td,tu),[O,td,tu]),no=(0,i.useMemo)(()=>{let e=0,t=0;for(let[n,r]of ni)n!==nt?.key&&(e+=r.running,t+=r.unread);return{running:e,unread:t}},[ni,nt?.key]),ns=(0,i.useCallback)(async e=>{tT(null),tW(null),tR(e.key);try{let t=await fetch("/api/projects",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key})}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);for(let t of W)tV(t)?.key===e.key&&z(t);for(let t of(nt?.key===e.key&&ef(nn.find(t=>t.key!==e.key)?.root??null),n.deletedSessionIds??[]))x?.(t);tU()}catch(e){tW(e instanceof Error?e.message:String(e))}finally{tR(null)}},[tU,x,z,W,tV,nt?.key,nn]),nl=!!(eR?.isGit&&eR.isTopLevel&&ep&&nt?.key===eR.projectKey),na=(0,i.useMemo)(()=>{let t=[],n=e0??nr;for(let r of t3?nn.filter(e=>e.key===(nt??nn[0])?.key):nn){let i=s(m(O,r.key));if(t.push({kind:"workspace",project:r,cwd:i[0]?.root.cwd??r.root}),t3||n.has(r.key)){let n=t3?1/0:e2[r.key]??6,o=i.slice(0,n),s=i.find(t=>t.root.id===e||t.subagents.some(t=>t.id===e));s&&!o.includes(s)&&(o=[...o.slice(0,Math.max(0,n-1)),s]),t.push(...o.map(e=>({kind:"session",family:e})));let l=i.length-o.length;l>0&&t.push({kind:"showMore",projectKey:r.key,remaining:l})}}return t},[O,nr,e0,nt,e,t3,nn,e2]),nd=function(e,t,n,r=-1){let i=Math.ceil((n||600)/28)+16,o=Math.max(0,Math.min(Math.floor(t/28)-8,e-i)),s=Math.min(e,o+i),l=Array.from({length:s-o},(e,t)=>o+t);return r>=0&&r<o&&l.unshift(r),r>=s&&r<e&&l.push(r),l}(na.length,tw,ty,na.findIndex(e=>"session"===e.kind&&e.family.root.id===tj)),nc=nl&&eR?(H=(D=eR.worktrees.length>=8)&&ey.trim()?eR.worktrees.filter(e=>(e.branch??eo(e.path,eg)).toLowerCase().includes(ey.trim().toLowerCase())):eR.worktrees,B=tG?tG.branch??eo(tG.path,eg):"…",(0,r.jsxs)("div",{ref:eJ,className:"workspace-worktree-switcher",style:{minWidth:0,flex:"0 1 auto"},children:[(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),ez(e=>!e),ev(!1)},onTouchStart:e=>e.stopPropagation(),title:tG?F("sidebar.switchWorktreeTitle",{path:tG.path}):F("sidebar.switchWorktree"),"aria-expanded":eW,"aria-haspopup":"listbox",style:{display:"flex",alignItems:"center",gap:4,height:22,maxWidth:96,minWidth:0,padding:"0 4px",background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:4,cursor:"pointer",fontSize:11,lineHeight:1,color:"var(--text-dim)",textAlign:"left",overflow:"hidden",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{eW||(e.currentTarget.style.background="none"),e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,fontSize:11,lineHeight:1},children:B})]}),(0,r.jsxs)(el,{open:eW,style:{position:"absolute",top:"calc(100% + 4px)",left:2,right:2,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[D&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px",borderBottom:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{className:"sidebar-dropdown-filter-input",value:ey,onChange:e=>eb(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eb(""),ez(!1))},placeholder:F("sidebar.filterWorktrees"),autoFocus:!0,style:{flex:1,minWidth:0,fontSize:12,fontFamily:"inherit",padding:"2px 0",border:"none",outline:"none",background:"transparent",color:"var(--text)"}}),ey&&(0,r.jsx)("button",{type:"button",onClick:()=>eb(""),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,padding:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},title:F("chat.clear"),children:(0,r.jsxs)("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[H.map(e=>{let t=e.path===tQ;return e_===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:F("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void t8(e.path,!0),disabled:eO,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:F("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eq(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:F("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{ef(e.path),ez(!1),eF(null),eb("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(es,{text:e.branch??eo(e.path,eg),style:{flex:1}}),e.isMain&&(e.branch??"").toLowerCase()!==F("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:F("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void t8(e.path,!1),disabled:eO,title:F("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:4,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),D&&0===H.length&&ey.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:F("sidebar.noMatchingWorktrees")})]}),eP?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eY,className:"sidebar-dropdown-filter-input",value:eD,onChange:e=>{eH(e.target.value),eF(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t4()),"Escape"===e.key&&(eA(!1),eH(""),eF(null))},placeholder:F("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void t4(),disabled:eO||!eD.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",fontSize:11,fontWeight:600,cursor:eO||!eD.trim()?"not-allowed":"pointer",opacity:eO||!eD.trim()?.65:1},children:eO?F("sidebar.creating"):F("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eA(!1),eH(""),eF(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:F("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eA(!0),eF(null),setTimeout(()=>eY.current?.focus(),0)},title:F("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:F("sidebar.newWorktree")})]}),eB&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eB})]})]})):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[ew&&(0,r.jsx)(R,{initialPath:ej,busy:eN,error:eC,onCancel:()=>{ek(!1),eE(null)},onSelect:e=>void t0(e)}),(0,r.jsxs)("div",{ref:eL,className:"sidebar-section-row",style:{position:"relative"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eQ(e=>!e),className:"sidebar-section-label",children:[(0,r.jsx)(Q,{open:eG}),(0,r.jsx)("span",{children:F("sidebar.projects")})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[t3&&(no.running>0||no.unread>0)&&(0,r.jsx)("span",{role:"status",title:F("sidebar.otherProjectActivity"),"aria-label":`${F("sidebar.otherProjectActivity")} (${no.running+no.unread})`,style:{display:"inline-flex",alignItems:"center"},children:no.running>0?(0,r.jsx)(Z,{size:11}):(0,r.jsx)("span",{style:{color:"#10b981",fontSize:10},children:no.unread})}),(0,r.jsx)(G,{onClick:()=>{ev(e=>!e),ez(!1)},title:F(t3?"sidebar.switchProject":"sidebar.addProject"),ariaPressed:ex,color:ex?"var(--accent)":"var(--text-dim)",background:ex?"var(--bg-selected)":"none",children:t3?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),(0,r.jsx)(G,{onClick:()=>{tt(e=>{let t=!e;return t&&eQ(!0),t}),ez(!1),ev(!1)},title:F("sidebar.toggleSessionSearch"),ariaPressed:te,color:te?"var(--accent)":"var(--text-dim)",background:te?"var(--bg-selected)":"none",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})})]}),(0,r.jsxs)(el,{open:ex,style:{position:"absolute",top:"calc(100% + 4px)",left:6,right:6,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[t3&&(0,r.jsx)("div",{style:{maxHeight:"min(50vh, 380px)",overflowY:"auto",borderBottom:"1px solid var(--border)"},children:nn.map(e=>{let t=e.key===nt?.key,n=W.includes(e.root),i=ni.get(e.key);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"true":void 0,onClick:()=>{ef(e.root),ev(!1)},title:e.root,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"7px 10px",background:"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)(es,{text:eo(e.root,eg),style:{flex:1}}),i?.running?(0,r.jsx)(Z,{size:11}):null,i?.unread?(0,r.jsx)("span",{style:{color:"#10b981",fontSize:10},children:i.unread}):null]}),O.some(t=>f(t)===e.key)&&(0,r.jsx)(G,{onClick:()=>{ev(!1),tT(e.key)},disabled:!!i?.running||tL===e.key,title:F(i?.running?"sidebar.deleteProjectSessionsRunning":"sidebar.deleteProjectSessions"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}),(0,r.jsx)(G,{onClick:()=>z(e.root),title:F(n?"sidebar.unpinDirectory":"sidebar.pinDirectory"),ariaPressed:n,color:n?"var(--text-muted)":"var(--text-dim)",marginRight:4,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:n?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]})})]},e.key)})}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t2()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderBottom:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:(0,r.jsx)("path",{d:"M1 3A1 1 0 0 1 2 2H4L5 3.5H8.5a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-.5.5h-7A.5.5 0 0 1 1 8V3Z"})}),(0,r.jsx)("span",{children:F("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t1()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:F("sidebar.customPath")})]})]})]}),te&&eG&&(0,r.jsx)("div",{style:{padding:"4px 8px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tn,maxLength:200,"aria-label":F("sidebar.searchSessions"),placeholder:F("sidebar.searchSessions"),onChange:e=>tr(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),tr(""))},className:"block h-[29px] w-full min-w-0 rounded-[4px] border border-border bg-bg px-[10px] text-xs text-text focus:outline-2 focus:outline-accent"})}),(()=>{let e=tM?nn.find(e=>e.key===tM):null;if(!e)return null;let t=S(e.root),n=m(O,e.key).length;return(0,r.jsxs)("div",{role:"alertdialog","aria-labelledby":"delete-project-title","aria-describedby":"delete-project-detail",onKeyDown:e=>{"Escape"===e.key&&tT(null)},style:{margin:"4px 8px 6px",padding:"8px 10px",flexShrink:0,border:"1px solid rgba(239,68,68,0.4)",borderRadius:4,background:"rgba(239,68,68,0.06)",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{id:"delete-project-title",style:{fontWeight:600,color:"#ef4444",overflowWrap:"anywhere"},children:F("sidebar.deleteProjectSessionsConfirm",{name:t,count:n})}),(0,r.jsx)("div",{id:"delete-project-detail",style:{marginTop:4,color:"var(--text-muted)"},children:F("sidebar.deleteProjectSessionsDetail",{name:t,count:n})}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:6,marginTop:8},children:[(0,r.jsx)("button",{type:"button",autoFocus:!0,onClick:()=>tT(null),style:{height:24,padding:"0 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:F("sidebar.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ns(e),style:{height:24,padding:"0 10px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:F("sidebar.deleteProjectSessionsAction",{count:n})})]})]})})(),(0,r.jsx)(Y,{open:te&&eG,query:tn,refreshKey:_,selectedSessionId:e,onSelectSession:t5,children:eG&&(0,r.jsxs)("div",{ref:tv,onScroll:tH,style:{flex:eZ&&(b||ep)?"1 1 0":"1 1 auto",overflowY:"auto",padding:"0",minHeight:80},children:[ec&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:ec}),t$&&(0,r.jsx)("div",{role:"alert",onClick:()=>tW(null),style:{padding:"6px 14px",color:"#f87171",fontSize:12,cursor:"pointer"},children:F("sidebar.deleteProjectSessionsFailed",{error:t$})}),!X&&!ec&&!ne&&0===nn.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:F("sidebar.noSessions")}),na.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:28*na.length},children:nd.map(t=>{let i=na[t];if("workspace"===i.kind){let e=(e0??nr).has(i.project.key),n=i.project.key===nt?.key,o=ni.get(i.project.key),s=n&&ep?ep:i.cwd,l=W.includes(i.project.root),a=tN===i.project.key,c=tM===i.project.key;return(0,r.jsxs)("div",{className:`workspace-list-row${a?" is-actions-revealed":""}`,"data-active":n?"true":"false","data-pending-delete":c?"true":void 0,onTouchStart:e=>tB(i.project.key,e),onTouchMove:tF,onTouchEnd:tO,onTouchCancel:tO,onContextMenu:e=>{tA.current&&(e.preventDefault(),e.stopPropagation())},style:{position:"absolute",top:28*t,left:4,right:4,height:28,display:"flex",alignItems:"center",WebkitTouchCallout:"none",userSelect:"none"},children:[(0,r.jsxs)("button",{type:"button","aria-current":n?"page":void 0,"aria-expanded":t3?ex:e,onMouseDown:t3?e=>e.stopPropagation():void 0,onClick:()=>{if(tA.current){tA.current=!1;return}if(t3){ev(e=>!e),ez(!1);return}e&&e4(e=>{if(!(i.project.key in e))return e;let t={...e};return delete t[i.project.key],t}),e1(e=>{let t=new Set(e??nr);return t.has(i.project.key)?t.delete(i.project.key):t.add(i.project.key),t})},title:i.project.root,style:{display:"flex",alignItems:"center",gap:4,flex:1,minWidth:0,height:"100%",padding:"0 4px 0 0",border:"none",background:"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12,fontWeight:500},children:[(0,r.jsx)(Q,{open:t3?ex:e}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:S(i.project.root)}),o?.running?(0,r.jsx)("span",{role:"status","aria-label":`${F("sidebar.agentRunning")} (${o.running})`,children:(0,r.jsx)(Z,{size:11})}):null,o?.unread?(0,r.jsx)("span",{"aria-label":`${F("sidebar.newSessionActivity")} (${o.unread})`,style:{color:"#10b981",fontSize:10},children:o.unread}):null]}),n?nc:null,(0,r.jsxs)("span",{className:"workspace-row-action",children:[(0,r.jsx)(G,{onClick:()=>{tI(null),tT(i.project.key)},disabled:!!o?.running||tL===i.project.key,title:F(o?.running?"sidebar.deleteProjectSessionsRunning":"sidebar.deleteProjectSessions"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}),(0,r.jsx)(G,{onClick:()=>{tI(null),ef(s),eX(!0),d(!0)},title:F("sidebar.openProjectExplorer",{path:s}),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M4 5h4"}),(0,r.jsx)("path",{d:"M10 5h10"}),(0,r.jsx)("path",{d:"M4 12h4"}),(0,r.jsx)("path",{d:"M10 12h10"}),(0,r.jsx)("path",{d:"M4 19h4"}),(0,r.jsx)("path",{d:"M10 19h10"})]})}),(0,r.jsx)(G,{onClick:()=>{tI(null),z(i.project.root)},title:F(l?"sidebar.unpinDirectory":"sidebar.pinDirectory"),ariaPressed:l,color:l?"var(--text-muted)":"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:l?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]})}),(0,r.jsx)(G,{onClick:()=>{tA.current=!1,tI(null),ef(s),e1(e=>new Set([...e??nr,i.project.key])),t6(s)},title:F("sidebar.newSessionTitle",{path:s}),color:"var(--text-dim)",className:"workspace-new-session",marginRight:6,children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]},`workspace:${i.project.key}`)}if("showMore"===i.kind)return(0,r.jsxs)("button",{type:"button",className:"workspace-show-more-button","aria-label":F("sidebar.showMoreSessionsLabel",{count:i.remaining}),onClick:()=>e4(e=>({...e,[i.projectKey]:(e[i.projectKey]??6)+Math.min(20,i.remaining)})),style:{position:"absolute",top:28*t,left:4,right:4,height:28},children:[(0,r.jsx)("span",{children:F("sidebar.showMoreSessions")}),(0,r.jsx)("span",{className:"workspace-show-more-count",children:i.remaining})]},`more:${i.projectKey}`);let s=i.family,l=[s.root,...s.subagents],a=s.latestModified===s.root.modified?s.root:{...s.root,modified:s.latestModified};return(0,r.jsx)("div",{onFocus:()=>tS(s.root.id),onBlur:()=>tS(null),style:{position:"absolute",top:28*t,left:4,right:4},children:(0,r.jsx)(eu,{session:a,indent:14,isSelected:l.some(t=>t.id===e),isRunning:l.some(e=>td.has(e.id)),isUnread:l.some(e=>tu.has(e.id)),isActionsRevealed:tC===s.root.id,onRevealActions:()=>tE(s.root.id),onDismissActions:()=>tE(e=>e===s.root.id?null:e),onClick:()=>{tE(null),t5(s.root)},onRenamed:tU,onOpenInNewTab:n?()=>{tE(null),n(s.root)}:void 0,onPin:o?()=>{tE(null),o(s.root)}:void 0,onDeleted:e=>{tE(null),x?.(e),tU()}})},s.root.id)})})]})}),(b||ep)&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:eZ?"1 1 0":"0 0 auto",minHeight:0,overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"sidebar-section-row",children:[(0,r.jsxs)("button",{onClick:()=>eX(e=>{let t=!e;return d(t),t}),className:"sidebar-section-label",children:[(0,r.jsx)(Q,{open:eZ}),(0,r.jsx)("span",{children:F("files.explorer")})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[C&&(0,r.jsx)(G,{onClick:()=>C(ep??b),title:F("terminal.open"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),eZ&&to>0&&(0,r.jsx)(G,{onClick:()=>ta(e=>!e),title:F("sidebar.changedFiles",{count:to}),ariaPressed:!tl,color:tl?"var(--text-dim)":"var(--accent)",background:tl?"none":"var(--bg-selected)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6"}),(0,r.jsx)("path",{d:"M15 12h6"})]})}),eZ&&(0,r.jsx)(G,{onClick:()=>{e9(e=>!e)},title:F("sidebar.searchFiles"),ariaPressed:e7,color:e7?"var(--accent)":"var(--text-dim)",background:e7?"var(--bg-selected)":"none",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}),eZ&&(0,r.jsx)(G,{onClick:()=>tx.current?.openUploadPicker(),disabled:e6,title:F("sidebar.uploadFilesTitle"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}),(0,r.jsx)(G,{onClick:()=>{N?N():e5(e=>e+1)},title:F("sidebar.refreshExplorer"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]}),eZ&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(J,{ref:tx,cwd:ep??b,onOpenFile:j??(()=>{}),refreshKey:e8,onAtMention:I,onAtMentions:M,onUploadBusyChange:e3,changesCollapsed:tl,onChangesCountChange:ts,fileSearchOpen:e7,onFileSearchOpenChange:e9})})]})]})}function ed(){let{t:e}=(0,w.s)();return(0,r.jsx)(Z,{size:14,title:e("sidebar.agentRunning"),ariaLabel:e("sidebar.agentRunning")})}function ec(){let{t:e}=(0,w.s)();return(0,r.jsx)("span",{title:e("sidebar.newSessionActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"5",fill:"#10b981"}),(0,r.jsx)("path",{d:"M3.6 6.2l1.6 1.6 3.2-3.4",stroke:"#ffffff",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})}function eu({session:e,isSelected:t,isRunning:n,isUnread:o,isActionsRevealed:s=!1,onRevealActions:l,onDismissActions:a,onClick:d,onRenamed:c,onOpenInNewTab:h,onPin:f,onDeleted:g,indent:m=0,depth:x=0,hasChildren:v=!1,collapsed:y=!1,onToggleCollapse:k}){let{locale:j,t:S}=(0,w.s)(),[C,E]=(0,i.useState)(!1),[N,I]=(0,i.useState)(!1),[M,T]=(0,i.useState)(""),[L,R]=(0,i.useState)(!1),[$,W]=(0,i.useState)(!1),z=(0,i.useRef)(null),P=(0,i.useRef)(null),A=(0,i.useRef)(null),D=(0,i.useRef)(!1),H=(0,i.useCallback)(t=>{if(L||N||e.transient)return;let n=t.touches[0];A.current={x:n.clientX,y:n.clientY},D.current=!1,P.current=setTimeout(()=>{D.current=!0,window.getSelection()?.removeAllRanges();try{navigator.vibrate?.(15)}catch{}l?.()},400)},[L,l,N,e.transient]),B=(0,i.useCallback)(e=>{if(!A.current||!P.current)return;let t=e.touches[0],n=Math.abs(t.clientX-A.current.x),r=Math.abs(t.clientY-A.current.y);(n>10||r>10)&&(clearTimeout(P.current),P.current=null)},[]),F=(0,i.useCallback)(()=>{P.current&&(clearTimeout(P.current),P.current=null)},[]);(0,i.useEffect)(()=>{if(N){let e=requestAnimationFrame(()=>z.current?.select());return()=>cancelAnimationFrame(e)}},[N]);let O=u(e.firstMessage)??e.firstMessage,U=p(e),_=(0,i.useCallback)(t=>{t?.stopPropagation(),e.transient||(T(p(e)),I(!0))},[e]),q=(0,i.useCallback)(async()=>{let t=M.trim();if(I(!1),M!==U&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[M,e.id,e.name,c,U]),K=(0,i.useCallback)(async()=>{if(!e.transient){R(!1),W(!0);try{let t=await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"});if(!t.ok)throw Error(`HTTP ${t.status}`);g?.(e.id)}catch{W(!1)}}},[e.id,e.transient,g]),V=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?K():R(!0)},[K]),J=(0,i.useCallback)(e=>{e.stopPropagation(),K()},[K]),Y=(0,i.useCallback)(e=>{e.stopPropagation(),R(!1)},[]),Z=(0,i.useCallback)(t=>{if(D.current||s){t.preventDefault(),t.stopPropagation();return}(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[s,c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`session-list-row${s?" is-actions-revealed":""}`,onClick:e=>{if(D.current){D.current=!1,e.preventDefault(),e.stopPropagation();return}s?a?.():L||N||d()},onDoubleClick:()=>{L||N||s||e.transient||f?.()},onTouchStart:H,onTouchMove:B,onTouchEnd:F,onTouchCancel:F,onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1!==e.button||!h||L||N||(e.preventDefault(),e.stopPropagation(),h())},onContextMenu:L||N?void 0:Z,onMouseEnter:()=>E(!0),onMouseLeave:()=>{E(!1)},style:{height:28,position:"relative",display:"flex",alignItems:"center",paddingLeft:10+m+14*x,paddingRight:8,cursor:L||N?"default":"pointer",background:L?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":C?"var(--bg-hover)":"transparent",borderLeft:L?"2px solid #ef4444":"2px solid transparent",borderRadius:4,transition:"background 0.1s",opacity:$?.5:1,gap:6,overflow:"hidden",userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none"},children:L?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S("sidebar.deleteSession",{title:U.slice(0,22)+(U.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:J,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:24,padding:"0 8px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),S("sidebar.delete")]}),(0,r.jsx)("button",{onClick:Y,style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:S("sidebar.cancel")})]})]}):N?(0,r.jsx)("input",{ref:z,value:M,onChange:e=>T(e.target.value),onBlur:q,onKeyDown:e=>{"Enter"===e.key&&q(),"Escape"===e.key&&I(!1)},autoFocus:!0,className:"session-rename-input",style:{flex:1,minWidth:0,fontSize:13,fontWeight:t?500:400,fontFamily:"inherit",lineHeight:1.4,padding:"1px 6px",border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg)",color:"var(--text)",height:24,boxSizing:"border-box"}}):(0,r.jsxs)(r.Fragment,{children:[x>0&&(0,r.jsx)(X,{size:11,strokeWidth:2,style:{color:"var(--accent)"}}),(0,r.jsx)("button",{type:"button","aria-current":t?"page":void 0,style:{flex:1,minWidth:0,padding:0,border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0,fontSize:13,fontWeight:t?500:400,lineHeight:1.4,color:"var(--text)"},title:e.name||O||e.id,children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:U})})}),e.isWorktree&&e.branch&&(0,r.jsxs)("span",{title:`Worktree: ${e.branch}
|
|
2
|
+
${e.cwd}`,style:{display:"flex",alignItems:"center",gap:3,maxWidth:82,color:"var(--text-dim)",flexShrink:1,fontSize:10,fontFamily:"var(--font-mono)",lineHeight:1},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e.branch})]}),v&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),k?.()},title:S(y?"sidebar.expandSubagents":"sidebar.collapseSubagents"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:y?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("div",{className:"session-row-meta",style:{display:"flex",alignItems:"center",justifyContent:"flex-end",flexShrink:0,color:"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:n?(0,r.jsx)(ed,{}):o?(0,r.jsx)(ec,{}):(0,r.jsx)("span",{title:e.modified,children:(0,b.wA)(e.modified,j)})}),!e.transient&&(0,r.jsxs)("div",{className:"session-row-actions",style:{display:"flex",alignItems:"center",gap:2,position:"absolute",right:6,top:0,height:"100%",background:t?"var(--bg-selected)":C?"var(--bg-hover)":"var(--bg-panel)",paddingLeft:4,borderRadius:4},children:[h&&(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),a?.(),h()},title:S("chatTabs.openInNewTab",{defaultValue:"在新标签页打开"}),"aria-label":S("chatTabs.openInNewTab",{defaultValue:"在新标签页打开"}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=t?"var(--bg-hover)":"var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),(0,r.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),f&&(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),a?.(),f()},onDoubleClick:e=>e.stopPropagation(),title:S("chatTabs.pinTab",{defaultValue:"固定标签"}),"aria-label":S("chatTabs.pinTab",{defaultValue:"固定标签"}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=t?"var(--bg-hover)":"var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]})}),(0,r.jsx)("button",{onClick:e=>{a?.(),_(e)},title:S("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=t?"var(--bg-hover)":"var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:e=>{a?.(),V(e)},title:S("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.12)",e.currentTarget.style.color="#ef4444"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}function eh({src:e,alt:t="",children:n,className:o,style:s}){let{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(!1),c=(0,i.useRef)(null),u=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!a)return;let e=u.current;if(!e)return;let t=c.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),h.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[a]);let p=()=>{u.current?.open&&u.current.close(),d(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:c,type:"button",className:o,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...s},onClick:()=>d(!0),"aria-label":l("chat.previewImage"),"aria-haspopup":"dialog","aria-expanded":a,title:l("chat.previewImage"),children:n}),a&&(0,r.jsxs)("dialog",{ref:u,className:"image-preview-dialog","aria-label":l("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),p()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),p())},onClick:e=>{e.target===e.currentTarget&&p()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:e,alt:t}),(0,r.jsx)("button",{ref:h,type:"button",className:"image-preview-close",onClick:p,"aria-label":l("chat.close"),title:l("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}let ep="pi-image-result",ef=[{model:"gpt-image-2.5-flare",label:"Flare"},{model:"gpt-image-2.5-sunburst",label:"Sunburst"},{model:"grok-imagine-image-2.0",label:"Grok"}],eg=["1:1","16:9","9:16","4:3","3:4","3:2","2:3"];function em(e,t){let n=Math.abs(e),r=Math.abs(t);for(;r;){let e=n%r;n=r,r=e}return`${e/n}:${t/n}`}let ex=/@"([^"]+)"|@([^\s"]+)/g,ev=/\.(?:png|jpe?g|webp)$/i;function ey(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eb(e){if(!ey(e)||![ep,"pi-web:image"].includes(e.type)||1!==e.version)return null;let t=e.type===ep;return!("string"!=typeof e.path||!e.path||t&&(!e.path.startsWith(".pi/generated-images/")||e.path.split(/[\\/]/).includes("..")))&&"string"==typeof e.mimeType&&e.mimeType.startsWith("image/")&&"string"==typeof e.prompt&&e.prompt&&"string"==typeof e.connection&&e.connection&&(void 0===e.label||"string"==typeof e.label&&e.label)&&"string"==typeof e.model&&e.model&&"number"==typeof e.width&&Number.isSafeInteger(e.width)&&!(e.width<=0)&&"number"==typeof e.height&&Number.isSafeInteger(e.height)&&!(e.height<=0)&&(void 0===e.size||"string"==typeof e.size)&&(void 0===e.resolution||"string"==typeof e.resolution)&&(void 0===e.quality||"string"==typeof e.quality)&&(void 0===e.source||"string"==typeof e.source)?{...e,type:ep}:null}function ew(e,t,n){if("generate_image"!==e)return null;let r=eb(n);return r?r.source?"edit":"generate":ey(t)&&!0===t.new_image?"generate":ey(t)&&("string"==typeof t.target&&t.target||!0===t.use_last_attachment)?"edit":null}function ek(e,t){return`/api/files/${j(e)}?type=${t}`}function ej(e,t){return e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:t?N(t,e):e}function eS({path:e,cwd:t,onRemove:n}){let{t:i}=(0,w.s)(),o=ek(ej(e,t),"read");return(0,r.jsxs)("span",{className:"relative inline-block shrink-0 overflow-hidden rounded-md border border-border align-middle",style:{width:56,height:56},children:[(0,r.jsx)("img",{src:o,alt:"",className:"block h-full w-full object-cover"}),n?(0,r.jsx)("button",{type:"button",onClick:n,className:"absolute right-0.5 top-0.5 flex h-4 w-4 items-center justify-center rounded-full border-0 bg-black/55 text-white","aria-label":i("i18n.close"),children:(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}):null]})}function eC(e,t){return{aspectRatio:`${e} / ${t}`,width:`min(100%, calc(28rem * ${e/t}))`}}function eE({value:e,cwd:t,onEdit:n,onMention:o,showPrompt:s=!1,createdAt:l}){let a,d,c,u,{t:h,locale:p}=(0,w.s)(),f=eb(e),[g,m]=(0,i.useState)(!1);if(!f)return null;let x=ej(f.path,t),v=ek(x,"read"),y=(c=[(a=function(e,t){if(e<=0||t<=0)return em(e,t);let n=e/t,r=eg[0],i=1/0;for(let e of eg){let[t,o]=e.split(":").map(Number),s=Math.abs(n-t/o)/(t/o);s<i&&(r=e,i=s)}return i<=.03?r:em(e,t)}(f.width,f.height),d=`${f.width}\u00d7${f.height}`,a===`${f.width}:${f.height}`?d:`${a}(${d})`)],f.resolution&&c.push(f.resolution.toUpperCase()),(u="low"===f.quality?h("image.qualityLow"):"medium"===f.quality?h("image.qualityMedium"):"high"===f.quality?h("image.qualityHigh"):"auto"===f.quality?h("image.qualityAuto"):f.quality)&&c.push(u),c.join(" \xb7 ")),b=[f.label?f.label:f.model.includes("sunburst")?"Sunburst":f.model.includes("flare")?"Flare":f.model.includes("grok-imagine")?"Grok":f.model.includes("flash-image")?"Banana 2":f.model,l?function(e,t){let n=new Date(e),r=new Date,i=n.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit",hour12:!1});if(n.getFullYear()===r.getFullYear()&&n.getMonth()===r.getMonth()&&n.getDate()===r.getDate())return i;let o=n.toLocaleDateString(t,{month:"short",day:"numeric",year:n.getFullYear()!==r.getFullYear()?"numeric":void 0});return`${o} ${i}`}(l,p):void 0].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("article",{className:"mb-3 mt-2 w-fit max-w-full",children:[(0,r.jsxs)("div",{className:"relative max-w-full overflow-hidden rounded-[10px] border border-border/80 bg-bg-panel",style:eC(f.width,f.height),children:[g?(0,r.jsx)("div",{className:"flex h-full min-h-28 items-center justify-center px-4 text-xs text-text-muted",children:h("chat.imagePreviewUnavailable")}):(0,r.jsx)(eh,{src:v,alt:f.prompt,className:"block h-full w-full",children:(0,r.jsx)("img",{src:v,alt:f.prompt,loading:"lazy",onError:()=>m(!0),className:"block h-full w-full object-cover"})}),(0,r.jsx)("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex justify-end p-2",children:(0,r.jsxs)("div",{className:"pointer-events-auto flex items-center rounded-full bg-black/50 p-0.5 text-white backdrop-blur-sm",children:[n?(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),n(f)},title:h("image.edit"),className:"h-7 rounded-full px-2.5 text-[11px] font-medium tracking-wide text-white/95 hover:bg-white/15",children:h("image.edit")}):null,n?(0,r.jsx)("span",{className:"mx-0.5 h-3 w-px bg-white/25","aria-hidden":"true"}):null,o?(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),o(f.path)},title:h("image.quote"),"aria-label":h("image.quote"),className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-white/95 hover:bg-white/15",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9 17 4 12l5-5"}),(0,r.jsx)("path",{d:"M20 18v-2a4 4 0 0 0-4-4H4"})]})}):null,(0,r.jsx)("a",{href:ek(x,"download"),download:!0,title:h("i18n.downloadFile"),"aria-label":h("i18n.downloadFile"),onClick:e=>e.stopPropagation(),className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-white/95 hover:bg-white/15",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m7 10 5 5 5-5M12 15V3"})]})})]})})]}),s&&f.prompt?(0,r.jsx)("p",{className:"mt-1.5 line-clamp-3 text-[12px] leading-snug text-text-muted",title:f.prompt,children:f.prompt}):null,y||b?(0,r.jsxs)("div",{className:`${s&&f.prompt?"mt-1":"mt-1.5"} max-w-full text-[11px] leading-snug tracking-wide text-text-muted`,title:f.model,children:[y,y&&b?" \xb7 ":null,b]}):null]})}function eN({prompt:e,size:t,width:n,height:i,previewUrl:o}){let{t:s}=(0,w.s)(),{w:l,h:a}=function(e,t){if(e&&"auto"!==e){let t=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(e.trim());if(t)return{w:Number(t[1]),h:Number(t[2])};let n=/^(\d+)x(\d+)$/.exec(e.trim());if(n)return{w:Number(n[1]),h:Number(n[2])}}return t?.width&&t.height?{w:t.width,h:t.height}:{w:1,h:1}}(t,{width:n,height:i});return(0,r.jsxs)("article",{className:"mb-3 mt-2 w-fit max-w-full",children:[(0,r.jsxs)("div",{role:"status","aria-label":s("image.generating"),className:"relative max-w-full overflow-hidden rounded-[10px] border border-border/80 bg-bg-panel",style:eC(l,a),children:[o?(0,r.jsx)("img",{src:o,alt:"",className:"absolute inset-0 h-full w-full object-cover opacity-35"}):null,(0,r.jsx)("div",{className:"image-pending-sheen","aria-hidden":"true"})]}),e?(0,r.jsx)("p",{className:"mt-1.5 line-clamp-3 text-[12px] leading-snug text-text-muted",children:e}):null]})}let eI=["off","minimal","low","medium","high","xhigh","max"],eM=RegExp(`:(${eI.join("|")})$`),eT=new Map;function eL(e){return`pi-chat-draft:${encodeURIComponent(e)}`}function eR(){try{return window.sessionStorage}catch{return null}}function e$(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function eW(e){return!e.value&&0===e.images.length}function ez(e){let t=eT.get(e)??function(e){try{let t=eR()?.getItem(eL(e));if(!t)return null;let n=JSON.parse(t);if("string"!=typeof n.value||!Array.isArray(n.images)||!n.images.every(e=>"string"==typeof e?.data&&"string"==typeof e?.mimeType))return null;return e$(n)}catch{return null}}(e);return t&&!eT.has(e)&&eT.set(e,t),t?e$(t):null}function eP(e,t){if(eW(t))return eA(e),!0;let n=e$(t);eT.set(e,n);let r=eR();if(!r)return!1;try{return r.setItem(eL(e),JSON.stringify(n)),!0}catch{return r.removeItem(eL(e)),!1}}function eA(e){eT.delete(e);try{eR()?.removeItem(eL(e))}catch{}}function eD(e,t){return e.trim()?t.trim()?`${e}
|
|
3
|
+
|
|
4
|
+
${t}`:e:t}function eH(e){return{data:e.data,mimeType:e.mimeType}}function eB(e,t,n,r){return{value:eD(e,n),images:[...t??[],...r].map(eH)}}function eF(e,t,n){if(e===t)return n?e$(n):ez(t);let r=ez(e),i=n&&!eW(n)?e$(n):r??(n?e$(n):null),o=ez(t);if(eA(e),!i)return o;let s=o?eB(o.value,o.images,i.value,i.images):i;return eP(t,s),e$(s)}function eO(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function eU(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function e_(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function eq(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function eK({active:e,size:t=14,className:n,style:i}){return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:n,style:{flexShrink:0,color:e?"var(--accent)":"currentColor",display:"block",...i},children:[(0,r.jsx)("path",{d:"M9.5 4a3.5 3.5 0 0 0-3.5 3.5c0 .34.05.67.14.98A4 4 0 0 0 4 12c0 1.9 1.3 3.5 3.1 3.9A3.5 3.5 0 0 0 10.5 19h1"}),(0,r.jsx)("path",{d:"M14.5 4a3.5 3.5 0 0 1 3.5 3.5c0 .34-.05.67-.14.98A4 4 0 0 1 20 12c0 1.9-1.3 3.5-3.1 3.9A3.5 3.5 0 0 1 13.5 19h-1"}),(0,r.jsx)("path",{d:"M12 4v16"})]})}let eV="(max-width: 640px)",eJ=e=>(function(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)})(eV,e),eY=()=>!!window.matchMedia&&window.matchMedia(eV).matches;function eZ(){return!1}function eX(){return(0,i.useSyncExternalStore)(eJ,eY,eZ)}let eG="pi-chat-content-width",eQ="pi-chat-content-font-size",e0={width:820,fontSize:14},e1=null,e2=new Set;function e4(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function e8(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function e5(e){try{return window.localStorage.getItem(e)}catch{return null}}function e6({width:e,fontSize:t}){"u">typeof document&&(document.documentElement.style.setProperty("--chat-content-max-width",`${e}px`),document.documentElement.style.setProperty("--chat-content-font-size",`${t}px`))}function e3(){return e1||e6(e1={width:e4(e5(eG)),fontSize:e8(e5(eQ))}),e1}function e7(e){return e2.add(e),()=>{e2.delete(e)}}function e9(e,t){let n="width"===e?e4(t):e8(t);e6(e1={...e3(),[e]:n});try{window.localStorage.setItem("width"===e?eG:eQ,String(n))}catch{}e2.forEach(e=>e())}let te=e=>e9("width",e),tt=e=>e9("fontSize",e);function tn(){return{...(0,i.useSyncExternalStore)(e7,e3,()=>e0),setWidth:te,setFontSize:tt}}var tr=n(14755);function ti(e,t){if(null==e||Number.isNaN(e))return"?";if(e<=0)return"0";if(e<1e3)return String(e);if(e>=1e6){let t=Math.round(e/1e6*100)/100;return`${t}M`}let n=e/1e3;if(n<10){let e=Math.round(10*n)/10;return`${e}k`}return`${Math.round(n).toLocaleString(t)}k`}let to="pi-shift-enter-to-send";function ts(){try{return"true"===window.localStorage.getItem(to)}catch{return!1}}let tl=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function ta(e,t){return tl.compare(e.name||e.modelId,t.name||t.modelId)||tl.compare(e.provider,t.provider)||tl.compare(e.modelId,t.modelId)}function td({options:e,value:t,onChange:n,onClear:o,emptyLabel:s,selectedLabel:l,disabled:a=!1,busy:d=!1,isAutoSelection:c=!1,ariaLabel:u,variant:h="toolbar",placement:p="up"}){let f,g,m,x,v,y,b,w,k=eX(),j=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),E=(0,i.useId)(),[N,I]=(0,i.useState)(!1),[M,T]=(0,i.useState)(0),[L,R]=(0,i.useState)(null),$=a||d,W=(0,i.useMemo)(()=>[...e].sort(ta),[e]),z=[];for(let e of W){let t=z.find(t=>t.provider===e.provider);t?t.options.push(e):z.push({provider:e.provider,options:[e]})}let P=l??(t?W.find(e=>e.modelId===t.modelId&&e.provider===t.provider)?.name??t.modelId:s??(W.length>0?"Select model":"No models")),A=(0,i.useMemo)(()=>o?[null,...W]:W,[o,W]),D=A.findIndex(e=>null!==e?e.modelId===t?.modelId&&e.provider===t?.provider:!t),H=A.length?Math.min(M,A.length-1):0,B=A.length?`${E}-option-${H}`:void 0,F=(0,i.useCallback)(()=>{let e=S.current?.getBoundingClientRect();e&&R({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},[]);(0,i.useEffect)(()=>{let e=e=>{j.current&&!j.current.contains(e.target)&&C.current&&!C.current.contains(e.target)&&I(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{$&&I(!1)},[$]),(0,i.useEffect)(()=>{if(!N)return;F();let e=window.visualViewport;return window.addEventListener("scroll",F,!0),window.addEventListener("resize",F),e?.addEventListener("scroll",F),e?.addEventListener("resize",F),()=>{window.removeEventListener("scroll",F,!0),window.removeEventListener("resize",F),e?.removeEventListener("scroll",F),e?.removeEventListener("resize",F)}},[N,F]),(0,i.useEffect)(()=>{N&&T(Math.max(0,Math.min(D>=0?D:0,A.length-1)))},[N,D,A.length]),(0,i.useEffect)(()=>{N&&B&&document.getElementById(B)?.scrollIntoView({block:"nearest"})},[N,B]);let O="field"===h?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:4,background:$?"var(--bg-panel)":"var(--bg)",color:$?"var(--text-dim)":"var(--text)",cursor:$?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:"flex-start",textAlign:"left",gap:6,width:void 0,maxWidth:220,height:k?32:28,padding:"0 4px",overflow:"visible",border:"none",borderRadius:4,background:N?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:$?"not-allowed":"pointer",fontSize:12,lineHeight:1.25,opacity:$?.5:1,transition:"background 0.12s, color 0.12s"},U=e=>{let r=e.modelId===t?.modelId&&e.provider===t?.provider;I(!1),(!r||c)&&n(e.provider,e.modelId)};return(0,r.jsxs)("div",{ref:j,className:`model-selector is-${h}${$?" is-disabled":""}`,style:{position:"relative",width:"field"===h?"100%":void 0,minWidth:0,display:"toolbar"===h?"flex":void 0,alignItems:"toolbar"===h?"center":void 0},onKeyDown:e=>{"Escape"===e.key&&N&&(e.preventDefault(),e.stopPropagation(),I(!1))},children:[(0,r.jsxs)("button",{ref:S,type:"button",role:"combobox","aria-label":u,"aria-haspopup":"listbox","aria-controls":E,"aria-activedescendant":N?B:void 0,"aria-expanded":N,onKeyDown:e=>{if("Escape"===e.key&&N){e.preventDefault(),I(!1);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!N){F(),T(D>=0?D:0),I(!0);return}let t="ArrowDown"===e.key?1:-1;T(e=>A.length?(e+t+A.length)%A.length:0);return}if(N&&A.length){if("Home"===e.key||"End"===e.key)e.preventDefault(),T("Home"===e.key?0:A.length-1);else if("Enter"===e.key||" "===e.key){e.preventDefault();let t=A[H];null===t?(I(!1),o?.()):t&&U(t)}}},"aria-busy":d||void 0,disabled:$,title:d?"Switching model":$?P:W.length>0||o?"Change model":"No available models",style:O,onClick:()=>{F(),I(e=>!e)},onMouseEnter:e=>{$||k&&"toolbar"===h||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if($){e.currentTarget.style.background="field"===h?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===h?"var(--text-dim)":"var(--text-muted)";return}k&&"toolbar"===h||(e.currentTarget.style.background=N?"var(--bg-hover)":"field"===h?"var(--bg)":"none",e.currentTarget.style.color="field"===h?"var(--text)":"var(--text-muted)")},children:[d?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",display:"block",flexShrink:0,transform:"translateY(-1px)"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):"field"===h?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}):null,(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.25},children:P}),"field"===h&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),N&&L&&(f=window.visualViewport?.height??window.innerHeight,g=window.visualViewport?.width??window.innerWidth,m=L.top-8,x=f-L.bottom-8,y=Math.max(120,Math.min((v="up"===p||m>x)?m:x,.6*f)),b=v?{bottom:f-L.top+6}:{top:L.bottom+6},w=k?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:L.left,width:"max-content",minWidth:L.width,maxWidth:Math.max(L.width,g-L.left-8)},(0,r.jsx)("div",{ref:C,id:E,role:"listbox","aria-label":u,"aria-activedescendant":B,style:{position:"fixed",...b,...w,zIndex:500,display:"flex",flexDirection:"column",maxHeight:y,overflow:"hidden",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:v?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[o&&(0,r.jsx)(tc,{id:`${E}-option-0`,active:!t,highlighted:0===H,label:s??"Default",onActive:()=>T(0),onClick:()=>{I(!1),o()}}),0===z.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:"No available models"}):z.map((e,n)=>(0,r.jsxs)("div",{children:[z.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",borderTop:n>0||o?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:"uppercase"},children:e.provider}),e.options.map(e=>(0,r.jsx)(tc,{id:`${E}-option-${A.indexOf(e)}`,active:e.modelId===t?.modelId&&e.provider===t?.provider,highlighted:H===A.indexOf(e),label:e.name,onActive:()=>T(A.indexOf(e)),onClick:()=>U(e)},`${e.provider}:${e.modelId}`))]},e.provider))]})}))]})}function tc({id:e,active:t,highlighted:n,label:i,onActive:o,onClick:s}){return(0,r.jsxs)("button",{id:e,type:"button",role:"option","aria-selected":t,"data-active":n||void 0,onClick:s,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",border:"none",background:t?"var(--bg-selected)":n?"var(--bg-hover)":"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{o?.(),t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{title:i,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:i})]})}let tu=["configured","chat-only","read-only","default","full"],th={configured:tr.Q8,"chat-only":"none","read-only":"read-only",default:"default",full:"full"},tp=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function tf(e,t){let n=null,r=()=>{n=null,t(function(e,t,n=8){return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let o=e.parentElement,s=o?.parentElement,l="u">typeof ResizeObserver&&o?new ResizeObserver(i):null;o&&l?.observe(o),s&&l?.observe(s);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{l?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let tg=["auto",...eI],tm={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},tx=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"reload",description:"chat.commandReload",source:"builtin"},{name:"name",description:"chat.commandName",source:"builtin"},{name:"session",description:"chat.commandSession",source:"builtin",availableWhileStreaming:!0},{name:"copy",description:"chat.commandCopy",source:"builtin",availableWhileStreaming:!0},{name:"clone",description:"chat.commandClone",source:"builtin"},{name:"bug",description:"chat.commandBug",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",source:"builtin"}];function tv(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return tx.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}function ty(e,t){return`${t.map(e=>eq(e,!1)).join("")}${e.trim()}`.trim()}let tb=["builtin","extension","prompt","skill"],tw={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},tk={builtin:0,extension:1,prompt:2,skill:3};function tj(e,t,n){let r=e.name.toLowerCase(),i=tS(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function tS(e,t){return"builtin"===e.source?t(e.description):e.description??""}function tC(e,t){requestAnimationFrame(()=>{let n=e.current;n&&(n.focus(),n.setSelectionRange(t,t),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})}let tE={name:"<session-title>",session:"[session-id]",clone:"[new-title]"};function tN(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function tI(e){let t=()=>{var t;return t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})};if(!(e.size>1048576&&"image/gif"!==e.type)||"function"!=typeof createImageBitmap)return t();let n=await createImageBitmap(e).catch(()=>null);if(!n)return t();try{let r=Math.min(1,1024/Math.max(n.width,n.height)),i=document.createElement("canvas");i.width=Math.max(1,Math.round(n.width*r)),i.height=Math.max(1,Math.round(n.height*r));let o=i.getContext("2d");if(!o)return t();o.fillStyle="#fff",o.fillRect(0,0,i.width,i.height),o.drawImage(n,0,0,i.width,i.height);let s=i.toDataURL("image/jpeg",.85).split(",")[1];return s&&s.length<4*Math.ceil(e.size/3)?{data:s,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function tM(e){return{data:e.data,mimeType:e.mimeType}}function tT(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function tL(e){return(e??[]).map(tT)}function tR(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function t$({kind:e,text:t}){return(0,r.jsxs)("div",{title:t,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:4,border:`1px solid ${"steer"===e?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===e?"var(--accent)":"var(--text-dim)"},children:e}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]})}function tW({tone:e,title:t,body:n,onClose:i}){let o="error"===e?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${o},0.3)`,borderRadius:4,background:`rgba(${o},0.07)`,color:`rgb(${o})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]}),i&&(0,r.jsx)("button",{type:"button",onClick:i,"aria-label":"Dismiss",style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function tz({error:e}){let{t}=(0,w.s)();return e?(0,r.jsx)(tW,{tone:"error",title:t("chat.modelError"),body:e}):null}function tP({warnings:e}){let{t}=(0,w.s)();return e&&0!==e.length?(0,r.jsx)(tW,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let tA=(0,i.forwardRef)(function({onSend:e,onOpenImageGeneration:t,onAbort:n,onSteer:o,onFollowUp:s,isStreaming:l,disabled:a=!1,model:d,isAutoModelSelection:c,modelNames:u,modelList:h,modelError:p,modelScopeWarnings:f,onModelChange:g,modelSwitching:m,onCompact:x,onAbortCompaction:v,isCompacting:y,compactError:b,compactResult:k,toolPreset:j,onToolPresetChange:S,contextUsage:C,cacheHitRate:E,onOpenSessionStats:N,thinkingLevel:I,onThinkingLevelChange:M,availableThinkingLevels:T,thinkingLevelMap:L,retryInfo:R,queuedMessages:$,inputHistory:z=[],onRecallQueue:P,slashCommands:D,slashCommandsLoading:H,onLoadSlashCommands:B,onBuiltinCommand:F,soundEnabled:O,onSoundToggle:U,onAudioUnlock:_,onPromptWithStreamingBehavior:q,draftKey:K,onDraftChange:V,draftPersistenceWarning:J=!1,cwd:Y,compact:Z=!1},X){let G,Q,ee,et,en,er,ei,eo,es,{t:el}=(0,w.s)(),{fontSize:ea}=tn(),ed=eX(),ec=(0,i.useId)(),[eu,eh]=(0,i.useState)(()=>K?ez(K)?.value??"":""),[ep,ef]=(0,i.useState)(!1),[eg,em]=(0,i.useState)(!1),[ex,ev]=(0,i.useState)(!1),[ey,eb]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(!1),[ej,eC]=(0,i.useState)([]),eE=(0,i.useRef)([]);eE.current=ej;let[eN,eI]=(0,i.useState)(()=>K?tL(ez(K)?.images):[]),eM=eu.trimStart(),eT=0===eN.length&&eM.startsWith("!"),eL=eT&&eM.startsWith("!!"),[eR,e$]=(0,i.useState)(!1),[eW,eH]=(0,i.useState)(null),[eq,eV]=(0,i.useState)(0),[eJ,eY]=(0,i.useState)(null),[eZ,eG]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(0),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(!1),[tt,to]=(0,i.useState)(0),tl=(0,i.useRef)(null),[ta,tc]=(0,i.useState)(!1),[tT,tA]=(0,i.useState)(null),[tD,tH]=(0,i.useState)(!1),[tB,tF]=(0,i.useState)(null),[tO,tU]=(0,i.useState)(null),t_=Y&&tO?.cwd===Y?tO.values:{},tq=(0,i.useRef)(null),tK=(0,i.useRef)(null),tV=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tY=(0,i.useRef)(null),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tG=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(0),t4=(0,i.useRef)(!1),t8=(0,i.useRef)(null),t5=(0,i.useRef)([]),t6=(0,i.useRef)(null),t3=(0,i.useRef)([]),t7=(0,i.useRef)(!1),t9=(0,i.useRef)([]),ne=(0,i.useRef)(null),nt=(0,i.useRef)(null),nn=(0,i.useRef)(0),nr=(0,i.useRef)(K),ni=(0,i.useRef)(eu),no=(0,i.useRef)(eN),ns=(0,i.useRef)(0);ni.current=eu,no.current=eN,(0,i.useImperativeHandle)(X,()=>({insertIfEmpty(e){let t=tq.current;(t?t.value:eu).trim()||(ni.current=e,eh(e),eG(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){var t,n,r;let i=tq.current;if(t=i?i.value:eu,n=no.current.length,r=ns.current,t.trim()||0!==n||0!==r)return;let o="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),s=tL("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return!function(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}(r)?[]:[r]}));ni.current=o,no.current=s,eh(o),eG(null),te(!1),eI(e=>(e.forEach(tR),s)),requestAnimationFrame(()=>{i&&(i.focus(),i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight,200)}px`)})},prependText(e){if(!e.trim())return;let t=tq.current,n=[e,t?t.value:eu].filter(e=>e.trim()).join("\n\n");ni.current=n,eh(n),eG(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(nr.current!==e)return void eF(e,t);let n={value:ni.current,images:no.current.map(tM)},r=eF(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(nr.current=t,i)return;let o=tL(r.images);ni.current=r.value,no.current=o,eh(r.value),eI(e=>(e.forEach(tR),o)),eG(null),te(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=nr.current,i=n??r,o=i===r,s=!o&&i?ez(i):null,l=eB(e,t,o?ni.current:s?.value??"",o?no.current.map(tM):s?.images??[]);if(i&&eP(i,l),!o)return;let a=tL(l.images);ni.current=l.value,no.current=a,eh(t=>{let n=eD(e,t);return ni.current=n,n}),eG(null),te(!1),eI(e=>(e.forEach(tR),no.current=a,a)),requestAnimationFrame(()=>{let e=tq.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tq.current;if(!t)return void eh(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),o=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+o;ni.current=l,eh(l),eG(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){nl(e)},mentionImage(e){eC(t=>t.includes(e)?t:[...t,e]),requestAnimationFrame(()=>tq.current?.focus())},removeAttachedImage(e){let t=no.current.findIndex(t=>t.data===e);t>=0&&na(t)}}));let nl=(0,i.useCallback)(async e=>{if(Z)return;let t=Math.max(0,10-no.current.length-ns.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(!n.length)return;let r=nn.current;ns.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await tI(e),previewUrl:URL.createObjectURL(e)})));eI(t=>{if(r!==nn.current)return e.forEach(tR),t;let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(tR);let i=[...t,...n];return no.current=i,i})}finally{ns.current-=n.length}},[Z]),na=(0,i.useCallback)(e=>{eI(t=>{let n=[...t],[r]=n.splice(e,1);return r&&tR(r),no.current=n,n})},[]),nd=(0,i.useCallback)(()=>{no.current=[],eI(e=>(e.forEach(tR),[]))},[]),nc=(0,i.useCallback)(()=>{nn.current+=1,tl.current=null,ni.current="",eh(""),eG(null),te(!1),K&&eA(K),nr.current&&nr.current!==K&&eA(nr.current),nd(),eE.current=[],eC([]),tq.current&&(tq.current.style.height="auto")},[nd,K]);(0,i.useEffect)(()=>{K&&nr.current===K&&(tc(!eP(K,{value:eu,images:eN.map(tM)})),V?.(K,eu,eN.length))},[eN,K,V,eu]),(0,i.useEffect)(()=>{let e=nr.current;if(e===K)return;e&&eP(e,{value:ni.current,images:no.current.map(tM)});let t=K?ez(K):null;nr.current=K;let n=t?.value??"",r=tL(t?.images);nn.current+=1,ni.current=n,no.current=r,eh(n),eG(null),te(!1),eI(e=>(e.forEach(tR),r)),K&&V?.(K,n,r.length)},[K,V]);let nu=(0,i.useCallback)(()=>{let e=tq.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(nu,[eu,ea,nu]),(0,i.useEffect)(()=>{let e=tq.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,nu())});return n.observe(e),()=>n.disconnect()},[nu]),(0,i.useEffect)(()=>()=>{nn.current+=1,no.current.forEach(tR)},[]);let nh=(0,i.useCallback)(async e=>{if(eN.length||!e.startsWith("/")||!F)return!1;if(t7.current)return!0;t7.current=!0,e6(!0);try{var t,n;let r=await F(e);if(!r.handled)return!1;return r.error||(t=ni.current,n=no.current.length,0!==n||t.trim()!==e)||nc(),!0}finally{t7.current=!1,e6(!1)}},[eN.length,nc,F]),np=(0,i.useCallback)(async()=>{if(a)return;let t=eu.trim();if(eN.length>10)return;let n=ty(t,ej);if(!n&&!eN.length||(_?.(),(!l||tv(t))&&await nh(t)||l))return;let r=eN.length?eN:void 0;nc(),e(n,r)},[a,eu,eN,ej,l,nh,e,nc,_]),nf=!Z&&eu.startsWith("/")&&!/\s/.test(eu.slice(1))?eu.slice(1).toLowerCase():null,ng=null===nf?[]:[...l?tx.filter(e=>e.availableWhileStreaming):tx,...D??[]].filter(e=>{let t=e.name.toLowerCase(),n=tS(e,el).toLowerCase();return t.includes(nf)||n.includes(nf)}).sort((e,t)=>{let n=tj(e,nf,el)-tj(t,nf,el);return 0!==n?n:tk[e.source]-tk[t.source]||tp.compare(e.name,t.name)}),{commands:nm,groups:nx}=(G=0,{commands:(Q=tb.map(e=>{let t=ng.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!tN(e,t_)),...t.filter(e=>tN(e,t_))]:t;return{source:e,items:n.map(e=>({command:e,index:G++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:Q}),nv=(()=>{if(Z)return null;let e=eW??eu.length,t=eu.slice(0,e);if(t.includes("\n"))return null;let n=/^\/([^\s]+)\s(.*)$/.exec(t);return n&&tE[n[1]]?{command:n[1],signature:tE[n[1]],hasArgument:n[2].trim().length>0}:null})(),ny=1===ng.length?el(nf?"chat.match":"chat.command"):el(nf?"chat.matches":"chat.commands",{count:ng.length}),nb=!!eu.trim(),nw=eN.length>10,nk=!nw&&(nb||eN.length>0||ej.length>0),nj=!a&&!nw&&(nb||eN.length>0||ej.length>0),nS=eN.length>0&&!function(e,t){if(!e)return!0;let n=t?.find(t=>t.provider===e.provider&&t.id===e.modelId);return!n||!n.input||n.input.includes("image")}(d,h)&&!e3;(0,i.useEffect)(()=>{0===eN.length&&e7(!1)},[eN.length]);let nC=(0,i.useCallback)((e,t)=>{if(!Y)return void eG(null);let n=t??e.length;eG(eO(e.slice(0,n)))},[Y]),nE=eZ?.query??null,nN=i.useMemo(()=>null!==nE&&tT&&tT.cwd===Y?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:e_(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:e_(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||eU(e.entry.path)-eU(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tT.entries,nE):[],[nE,tT,Y]),nI=!!(nE&&tT?.clientTruncated&&tT.cwd===Y);(0,i.useEffect)(()=>{if(!nI||!Y||!nE)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(Y)}&q=${encodeURIComponent(nE)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tF({cwd:Y,query:nE,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nI,nE,Y]);let nM=nI&&null!==tB&&tB.cwd===Y&&tB.query===nE,nT=nM?tB.matches:nN,nL=null===eZ?null:`${eZ.start}:${+!!eZ.quoted}:${eZ.query}`;(0,i.useEffect)(()=>{if(null===nL){e0(!1),e8(0);return}e0(!0),e8(0)},[nL]);let nR=null!==eZ;(0,i.useEffect)(()=>{if(!nR||!Y)return;let e=ne.current;e&&e.cwd===Y&&Date.now()-e.fetchedAt<1e4||nt.current===Y||(nt.current=Y,tH(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(Y)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tA({cwd:Y,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>eU(e.path)-eU(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),clientTruncated:!!e.clientTruncated,serverHardTruncated:!!e.serverHardTruncated}),ne.current={cwd:Y,fetchedAt:Date.now()}}).catch(()=>{ne.current=null}).finally(()=>{nt.current=null,tH(!1)}))},[nR,Y]);let n$=(0,i.useCallback)(e=>{if(!eZ)return;let t=tq.current,n=t?.selectionStart??eu.length,r=eu.slice(0,eZ.start),i=eu.slice(n);eZ.quoted&&i.startsWith('"')&&(i=i.slice(1));let o=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let o=i?`@"${r}" `:`@${r} `;return{text:o,cursorOffset:o.length}}(e.path,e.isDir,eZ.quoted),s=r+o.text+i,l=r.length+o.cursorOffset;ni.current=s,eh(s),eH(l),eG(eO(s.slice(0,l))),tC(tq,l)},[eZ,eu]);(0,i.useEffect)(()=>{e4>=nT.length&&e8(Math.max(0,nT.length-1))},[nT.length,e4]),(0,i.useEffect)(()=>{t3.current.length=nT.length},[nT.length]),(0,i.useEffect)(()=>{eQ&&t3.current[e4]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e4,eQ]),(0,i.useEffect)(()=>{tt>=z.length&&to(Math.max(0,z.length-1))},[z.length,tt]),(0,i.useEffect)(()=>{t9.current.length=z.length},[z.length]),(0,i.useEffect)(()=>{e9&&t9.current[tt]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tt,e9]);let nW=(0,i.useCallback)(()=>{let e=tl.current;tl.current=null,e&&(ni.current=e.text,eh(e.text)),te(!1)},[]),nz=(0,i.useCallback)(e=>{tl.current=null,ni.current=e,eh(e),eH(e.length),te(!1),to(0),eG(null),tC(tq,e.length)},[]),nP=(0,i.useCallback)(e=>{let t=`/${e.name} `;ni.current=t,eh(t),eH(t.length),e$(!1),eV(0),tC(tq,t.length)},[]),nA=(0,i.useCallback)(e=>{let t=eu.trim();if(eN.length>10)return;let n=ty(t,ej);if(!n&&!eN.length)return;if(_?.(),!eN.length&&F&&tv(t))return void nh(t);let r=eN.length?eN:void 0;if(t.startsWith("/")&&q){nc(),q(t,"steer"===e?"steer":"followUp",r);return}nc(),"steer"===e&&o?o(n,r):"followup"===e&&s&&s(n,r)},[eu,eN,ej,F,q,o,s,nc,_,nh]),nD=(0,i.useCallback)(e=>{let t=e.nativeEvent,r=!ed&&ts(),i="Enter"===e.key&&e.shiftKey===r&&(!ed||e.ctrlKey||e.metaKey),a=Date.now()-t2.current<100,d=t1.current||t.isComposing||229===t.keyCode;if(i&&(d||a)){a&&e.preventDefault();return}if(e9&&!d){if("ArrowDown"===e.key){e.preventDefault(),to(e=>Math.min(Math.max(0,z.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),to(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),nW();return}if(("Tab"===e.key||i)&&z[tt]){e.preventDefault(),nz(z[tt]);return}}if(eR&&null!==nf&&!d){if("ArrowDown"===e.key){e.preventDefault(),eV(e=>0===nm.length?0:(e+1)%nm.length);return}if("ArrowUp"===e.key){e.preventDefault(),eV(e=>0===nm.length?0:(e-1+nm.length)%nm.length);return}if("Escape"===e.key){e.preventDefault(),e$(!1);return}let t=nm[eq];if("Tab"===e.key&&t){e.preventDefault(),nP(t);return}if(i&&t)return void((e.preventDefault(),l&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||eu.trim()!==`/${t.name}`)?nP(t):(e$(!1),np()))}if(eQ&&null!==eZ&&!d){if("ArrowDown"===e.key){e.preventDefault(),e8(e=>0===nT.length?0:(e+1)%nT.length);return}if("ArrowUp"===e.key){e.preventDefault(),e8(e=>0===nT.length?0:(e-1+nT.length)%nT.length);return}if("Escape"===e.key){e.preventDefault(),e0(!1);return}if(("Tab"===e.key||i)&&nT[e4]){e.preventDefault(),n$(nT[e4]);return}}if("ArrowUp"===e.key&&!d&&!l&&z.length>0){e.preventDefault(),e$(!1),e0(!1),tl.current={text:eu},to(z.length-1),te(!0);return}if("Escape"===e.key&&ey){e.preventDefault(),eb(!1);return}if("Escape"===e.key&&!d&&l&&n){e.preventDefault(),n();return}i&&(e.preventDefault(),l&&(o||s)?nA(e.altKey&&s||!o?"followup":"steer"):np())},[ed,l,o,s,n,ey,eR,nf,nm,eq,nP,nA,np,eQ,eZ,nT,e4,n$,e9,z,tt,nz,nW,eu]),nH=(0,i.useCallback)(()=>{let e=tq.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nB=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!Z&&t.length){e.preventDefault(),nl(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),o=function(e,t){let n="",r=0,i=!1;for(let{label:o,href:s,occurrence:l}of t){if(!o||!s)continue;let t=0;for(let n=0;n<=l&&!((t=e.indexOf(o,n?t+o.length:0))<0);n++);if(t<r)continue;let a=o.replace(/([\\[\]])/g,"\\$1"),d=s.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+o.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===o)return;let s=e.currentTarget,l=s.selectionStart,a=s.value.slice(0,l)+o+s.value.slice(s.selectionEnd);e.preventDefault(),ni.current=a,eh(a),te(!1),nC(a,l+o.length),requestAnimationFrame(()=>{s.focus(),s.setSelectionRange(l+o.length,l+o.length)})},[Z,nl,nC]);(0,i.useEffect)(()=>{if(null===nf){e$(!1),eV(0),t4.current=!1;return}e$(!0),eV(0),!t4.current&&B&&(t4.current=!0,Promise.resolve(B()).catch(()=>{t4.current=!1}))},[nf,B]),(0,i.useEffect)(()=>{if(!eR||!Y)return;let e=!1;return tU({cwd:Y,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(Y)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tU({cwd:Y,values:n})}).catch(()=>{e||tU({cwd:Y,values:{}})}),()=>{e=!0}},[eR,Y]),(0,i.useEffect)(()=>{eq>=nm.length&&eV(Math.max(0,nm.length-1))},[nm.length,eq]),(0,i.useEffect)(()=>{t5.current.length=nm.length},[nm.length]),(0,i.useEffect)(()=>{eR&&t5.current[eq]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eq,eR]),(0,i.useLayoutEffect)(()=>{if(!eR||null===nf)return void eY(null);let e=t8.current;if(e)return tf(e,e=>{eY(t=>t===e?t:e)})},[eR,nf]),(0,i.useLayoutEffect)(()=>{if(!eQ||null===eZ)return void e2(null);let e=t6.current;if(e)return tf(e,e=>{e2(t=>t===e?t:e)})},[eQ,eZ]);let nF=h&&h.length>0?h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(u??{}).map(([e,t])=>({provider:d?.provider??"unknown",modelId:e,name:t})),nO=k?Math.max(0,k.tokensBefore-k.estimatedTokensAfter):0,nU=k?`${k.reason&&"manual"!==k.reason?`${k.reason[0].toUpperCase()}${k.reason.slice(1)} `:el("chat.compacted")} ${ti(k.tokensBefore)} -> ${ti(k.estimatedTokensAfter)} tokens (${el("chat.tokensSaved",{saved:ti(nO)})})`:null,n_="auto"!==(ee=I??"auto")&&L?L[ee]??ee:ee,nq=Object.entries(th).find(([,e])=>e===(j??tr.Q8))?.[0]??"configured",nK="chat-only"===nq?el("chat.chatOnly"):nq,nV=C?.percent??null,nJ=[n_,null!=nV&&nV>=70?`${Math.round(nV)}%`:null].filter(Boolean).join(" \xb7 ");(0,i.useEffect)(()=>{let e=e=>{let t=e.target;tK.current&&!tK.current.contains(t)&&ef(!1),tV.current&&!tV.current.contains(t)&&em(!1),tJ.current&&!tJ.current.contains(t)&&eb(!1),tY.current&&!tY.current.contains(t)&&ek(!1),tG.current&&!tG.current.contains(t)&&ev(!1),!t8.current||t8.current.contains(t)||tq.current?.contains(t)||e$(!1),!t6.current||t6.current.contains(t)||tq.current?.contains(t)||e0(!1),!tQ.current||tQ.current.contains(t)||tq.current?.contains(t)||nW()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[nW]),(0,i.useEffect)(()=>{ed||ek(!1)},[ed]);let nY=e=>{if(!C||C.contextWindow<=0)return null;let t=C.contextWindow,n=C.tokens,i=C.percent??(null!==n?n/t*100:null),o=null!==i?Math.min(100,Math.max(0,i)):0,s=null!==i&&i>=85,l=null!==i&&i>=70&&i<85,a=null!==n?`${ti(n)}/${ti(t)}`:`?/${ti(t)}`,d=null!==n?Math.max(0,t-n):null,c=[`${el("chat.contextUsage")}: ${null!==n?ti(n):"?"} / ${ti(t)} (${null!==i?i.toFixed(1):"?"}%)`,null!==d?`${el("chat.contextRemaining")}: ${ti(d)}`:null,null!=E?`${el("session.cacheHitRate")}: ${E.toFixed(1)}%`:null,s?`⚠️ ${el("chat.contextHighWarning")}`:null].filter(Boolean).join("\n");return(0,r.jsxs)("button",{ref:tG,type:"button",onClick:()=>{ev(e=>!e),N?.()},title:c,"aria-label":c,"data-top-panel-trigger":N?"session":void 0,"aria-controls":N?"workspace-top-panel":void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",height:e?32:28,background:ex?s?"rgba(239,68,68,0.12)":"var(--bg-hover)":s?"rgba(239,68,68,0.06)":"none",border:s?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:s?"#ef4444":l?"rgba(234,179,8,0.95)":"var(--text-muted)",cursor:N?"pointer":"default",fontSize:e?11:12,lineHeight:1,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:t=>{e||!N||ex||(t.currentTarget.style.background=s?"rgba(239,68,68,0.12)":"var(--bg-hover)")},onMouseLeave:t=>{e||!N||ex||(t.currentTarget.style.background=s?"rgba(239,68,68,0.06)":"none")},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",style:{display:"block",flexShrink:0,transform:"rotate(-90deg)"},children:[(0,r.jsx)("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",opacity:"0.22"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"5.5",pathLength:"100",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:`${o} 100`,style:{transition:"stroke-dasharray 0.3s ease"}})]}),(0,r.jsx)("span",{style:{fontWeight:s?600:400,letterSpacing:"-0.01em",lineHeight:1},children:a}),null!=E&&(0,r.jsxs)("span",{style:{lineHeight:1},children:[E.toFixed(0),"%"]})]})};(0,i.useLayoutEffect)(()=>{if(!ed||!ew)return;let e=tX.current;if(e)return e.style.height="32px",()=>{e.style.height=""}},[ed,ew]),(0,i.useEffect)(()=>{l&&(em(!1),ef(!1),eb(!1))},[l]);let nZ=`${ec}-history`,nX=`${ec}-slash`,nG=`${ec}-files`,nQ=e9&&z.length>0?nZ:eR&&null!==nf?nX:eQ&&null!==eZ?nG:void 0,n0=nQ===nZ&&void 0!==z[tt]?`${nZ}-${tt}`:nQ===nX&&nm[eq]?`${nX}-${eq}`:nQ===nG&&nT[e4]?`${nG}-${e4}`:void 0;return(0,r.jsxs)("fieldset",{disabled:e5,"aria-busy":e5,className:Z?"chat-input is-compact":"chat-input",style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:Z?0:"0 16px 8px",paddingRight:16*!Z,opacity:e5?.5:1,transition:"opacity 0.15s"},children:[!Z&&(0,r.jsx)("input",{ref:t0,type:"file",accept:"image/*",multiple:!0,disabled:a,style:{display:"none"},onChange:e=>{nl(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{style:{maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(0,r.jsx)(tz,{error:p}),(0,r.jsx)(tP,{warnings:f}),nw&&(0,r.jsx)(tW,{tone:"error",title:el("chat.tooManyImagesTitle"),body:el("chat.tooManyImagesBody",{count:eN.length,max:10})}),nS&&(et=h?.find(e=>e.provider===d?.provider&&e.id===d?.modelId),(0,r.jsx)(tW,{tone:"warning",title:el("chat.imageNotSupportedTitle"),body:el("chat.imageNotSupportedBody",{model:et?.name||d?.modelId||""}),onClose:()=>e7(!0)})),($?.steering.length??0)+($?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:el("chat.queued",{count:($?.steering.length??0)+($?.followUp.length??0)})}),P&&(0,r.jsxs)("button",{onClick:P,title:el("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),el("chat.recall")]})]}),$?.steering.map((e,t)=>(0,r.jsx)(t$,{kind:"steer",text:e},`steer-${t}`)),$?.followUp.map((e,t)=>(0,r.jsx)(t$,{kind:"follow-up",text:e},`followup-${t}`))]}),R&&(0,r.jsxs)("div",{className:"chat-input-feedback chat-input-feedback-warning",children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),el("chat.retrying",{attempt:R.attempt,max:R.maxAttempts}),R.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",R.errorMessage]})]}),nU&&(0,r.jsxs)("div",{className:"chat-input-feedback chat-input-feedback-success",children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nU]}),b&&(0,r.jsx)("div",{role:"alert",className:"chat-input-feedback chat-input-feedback-error chat-input-feedback-detail",style:{whiteSpace:"pre-wrap"},children:b}),(ta||J)&&(0,r.jsx)("div",{role:"status",className:"chat-input-feedback chat-input-feedback-warning chat-input-feedback-draft",children:el("chat.draftPageOnly")}),(eN.length>0||ej.length>0)&&(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:8,flexWrap:"wrap",padding:"0 2px"},children:[ej.map(e=>(0,r.jsx)(eS,{path:e,cwd:Y??void 0,onRemove:()=>eC(t=>t.filter(t=>t!==e))},e)),eN.map((e,t)=>(0,r.jsxs)("div",{className:"chat-input-image-preview",style:{position:"relative",flexShrink:0,borderRadius:6,overflow:"visible",border:"1px solid var(--border)",boxShadow:"0 1px 3px rgba(0,0,0,0.05)"},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",display:"block"}}),(0,r.jsx)("button",{className:"chat-input-image-remove",onClick:()=>na(t),title:el("i18n.close"),"aria-label":el("i18n.close"),style:{position:"absolute",top:3,right:3,width:18,height:18,borderRadius:"50%",background:"rgba(0, 0, 0, 0.55)",border:"none",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--accent-contrast)",backdropFilter:"blur(4px)",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(0, 0, 0, 0.85)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(0, 0, 0, 0.55)"},children:(0,r.jsxs)("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},t))]}),(0,r.jsxs)("div",{ref:tZ,style:{position:"relative",minWidth:0},children:[nv&&!eR&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,bottom:"calc(100% + 6px)",zIndex:119,height:24,display:"inline-flex",alignItems:"center",gap:6,padding:"0 8px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 2px 8px rgba(0,0,0,0.06)",fontFamily:"var(--font-mono)",fontSize:11.5,lineHeight:1,color:"var(--text-dim)",opacity:nv.hasArgument?.45:.85,pointerEvents:"none"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontWeight:500},children:"Usage:"}),(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["/",nv.command]}),(0,r.jsx)("span",{children:nv.signature})]}),e9&&z.length>0&&(0,r.jsxs)("div",{ref:tQ,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:el("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{id:nZ,role:"listbox",style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:z.map((e,t)=>{let n=t===tt;return(0,r.jsxs)("button",{ref:e=>{t9.current[t]=e},type:"button",id:`${nZ}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nz(e)},onMouseEnter:()=>to(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eR&&null!==nf&&(0,r.jsxs)("div",{ref:t8,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eJ?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eJ}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:H?el("chat.loadingCommands"):el("chat.slashCommands",{label:ny})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:el("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nX,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:6},children:H||0!==ng.length?nx.map(e=>(0,r.jsxs)("section",{style:{marginBottom:8},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-6,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 8px 3px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:el(tw[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:1},children:e.items.map(({command:e,index:t})=>{let n=t===eq,i=tN(e,t_);return(0,r.jsxs)("button",{ref:e=>{t5.current[t]=e},type:"button",id:`${nX}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nP(e)},onMouseEnter:()=>eV(t),style:{width:"100%",minWidth:0,height:30,display:"flex",alignItems:"center",gap:12,padding:"0 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:i?"var(--text-dim)":"var(--text)",cursor:"pointer",textAlign:"left",transition:"background 0.08s ease"},children:[(0,r.jsxs)("span",{style:{flexShrink:0,fontSize:12.5,fontFamily:"var(--font-mono)",whiteSpace:"nowrap",color:n?"var(--text)":i?"var(--text-dim)":"var(--text)",fontWeight:500},children:[function(e,t){if(!t)return`/${e}`;let n=e.toLocaleLowerCase().indexOf(t.toLocaleLowerCase());return n<0?`/${e}`:(0,r.jsxs)(r.Fragment,{children:[`/${e.slice(0,n)}`,(0,r.jsx)("span",{style:{color:"var(--accent)",fontWeight:600},children:e.slice(n,n+t.length)}),e.slice(n+t.length)]})}(e.name,nf),"builtin"===e.source&&tE[e.name]&&(0,r.jsx)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11,fontWeight:400},children:tE[e.name]}),i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:el("chat.dormant")})]}),(0,r.jsx)("span",{style:{flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:12},children:tS(e,el)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"4px 8px",fontSize:12,color:"var(--text-dim)"},children:el("chat.noCommands")})})]}),eQ&&null!==eZ&&(en=tD&&(!tT||tT.cwd!==Y),er=1===nT.length?el("chat.match"):el("chat.matches",{count:nT.length}),ei=tT?.serverHardTruncated?el("chat.serverIndexTruncated"):tT?.clientTruncated&&!nM?eZ.query?el("chat.searchingAll"):el("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:t6,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e1?"min(48vh, 400px)":`min(48vh, 400px, ${e1}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:en?el("chat.loadingFiles"):el("chat.files",{label:er,hint:ei})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:el("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nG,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:en||0!==nT.length?nT.map((e,t)=>{let n=t===e4,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{t3.current[t]=e},type:"button",id:`${nG}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),n$(e)},onMouseEnter:()=>e8(t),style:{width:"100%",height:30,display:"flex",alignItems:"center",gap:8,padding:"0 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)",transition:"background 0.08s ease"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",color:"var(--text-muted)"},children:e.isDir?(0,r.jsx)(W,{size:14}):A(i,14)}),(0,r.jsxs)("span",{style:{flexShrink:0,fontWeight:500,color:"var(--text)",whiteSpace:"nowrap"},children:[function(e,t){if(!t)return e;let n=e.toLocaleLowerCase().indexOf(t.toLocaleLowerCase());return n<0?e:(0,r.jsxs)(r.Fragment,{children:[e.slice(0,n),(0,r.jsx)("mark",{style:{padding:0,color:"var(--accent)",background:"transparent",fontWeight:700},children:e.slice(n,n+t.length)}),e.slice(n+t.length)]})}(i,eZ?.query??null),e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]}),o&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11.5},children:o})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:nI&&!nM?el("chat.searching"):el("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-input-composer${eT?" is-bash-mode":""}`,style:{minWidth:0,display:"flex",flexDirection:Z?"column":"row",gap:8,alignItems:Z?"stretch":"center",background:eT?"color-mix(in srgb, var(--bg-panel) 75%, var(--bg))":"var(--bg)",border:Z?"none":`1px solid ${eT?eL?"rgba(100,116,139,0.45)":"color-mix(in srgb, var(--accent) 45%, var(--border))":l&&(o||s)?"color-mix(in srgb, var(--border) 80%, transparent)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:6*!Z,padding:Z?0:"4px 6px 4px 10px",boxShadow:Z?"none":eT?"0 0 0 1px rgba(37,99,235,0.12)":"0 1px 2px rgba(15,23,42,0.04)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[eT&&(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2px 6px",borderRadius:4,background:eL?"rgba(100,116,139,0.12)":"rgba(37,99,235,0.12)",color:eL?"var(--text-muted)":"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,flexShrink:0,userSelect:"none"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",transform:"translateY(0.5px)"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}),(0,r.jsx)("span",{style:{lineHeight:1},children:eL?"Local":"Shell"})]}),(0,r.jsx)("textarea",{ref:tq,className:"chat-input-textarea",role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-expanded":!!nQ,"aria-controls":nQ,"aria-activedescendant":n0,"aria-label":Z?el("chat.quoteQuestion"):el("chat.message"),disabled:a,placeholder:a?el("agentSwitcher.status.queued"):void 0,value:eu,onChange:e=>{ni.current=e.target.value,eh(e.target.value),eH(e.target.selectionStart),tl.current=null,te(!1),nC(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;eH(t.selectionStart),nC(t.value,t.selectionStart)},onKeyDown:nD,onCompositionStart:()=>{t1.current=!0},onCompositionEnd:e=>{t1.current=!1,t2.current=Date.now();let t=e.currentTarget;eH(t.selectionStart),nC(t.value,t.selectionStart)},onInput:nH,onPaste:nB,rows:1,style:{flex:Z?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.5,padding:0,fontFamily:eT?"var(--font-mono)":"var(--font-chat)",minHeight:Z?96:24,maxHeight:200,overflow:"auto"}}),l?nk?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[(0,r.jsx)("button",{type:"button",className:"chat-input-action","aria-label":el("chat.stop"),title:el("chat.stopAgent"),onClick:n,style:{display:"flex",alignItems:"center",justifyContent:"center",width:ed?32:28,height:ed?32:28,padding:0,background:"color-mix(in srgb, #ef4444 10%, transparent)",border:"1px solid color-mix(in srgb, #ef4444 24%, transparent)",borderRadius:5,color:"#ef4444",cursor:"pointer",transition:"background 0.15s, border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, #ef4444 18%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, #ef4444 40%, transparent)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, #ef4444 10%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, #ef4444 24%, transparent)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block",flexShrink:0},children:(0,r.jsx)("rect",{x:"5.5",y:"5.5",width:"13",height:"13",rx:"2",fill:"currentColor"})})}),s&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":el("chat.followUp"),onClick:()=>nA("followup"),title:`${el("chat.followUpHint")} (${ed?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":ed?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:"color-mix(in srgb, var(--accent) 10%, transparent)",border:"1px solid color-mix(in srgb, var(--accent) 26%, transparent)",borderRadius:5,color:"var(--accent)",cursor:"pointer",fontSize:12.5,fontWeight:600,letterSpacing:"-0.01em",lineHeight:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--accent) 16%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 40%, transparent)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 26%, transparent)"},children:[(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 17V5m-6 6 6-6 6 6M5 21h14"})}),(0,r.jsx)("span",{className:"chat-input-action-label",children:el("chat.followUp")})]}),o&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":el("chat.steer"),onClick:()=>nA("steer"),title:el("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:"var(--accent)",border:"none",borderRadius:5,color:"#ffffff",cursor:"pointer",fontSize:12.5,fontWeight:600,letterSpacing:"-0.01em",lineHeight:1,transition:"background 0.12s, filter 0.12s"},onMouseEnter:e=>{e.currentTarget.style.filter="brightness(1.08)"},onMouseLeave:e=>{e.currentTarget.style.filter="none"},children:[(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14m-6-6 6 6-6 6"})}),(0,r.jsx)("span",{className:"chat-input-action-label",children:el("chat.steer")})]})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":el("chat.stop"),title:el("chat.stopAgent"),onClick:n,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:"color-mix(in srgb, #ef4444 12%, transparent)",border:"1px solid color-mix(in srgb, #ef4444 26%, transparent)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12.5,fontWeight:600,letterSpacing:"-0.01em",lineHeight:1,transition:"background 0.15s, border-color 0.15s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, #ef4444 18%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, #ef4444 40%, transparent)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, #ef4444 12%, transparent)",e.currentTarget.style.borderColor="color-mix(in srgb, #ef4444 26%, transparent)"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block",flexShrink:0},children:(0,r.jsx)("rect",{x:"5.5",y:"5.5",width:"13",height:"13",rx:"2",fill:"currentColor"})}),(0,r.jsx)("span",{className:"chat-input-action-label",children:el("chat.stop")})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":el("chat.send"),title:nw?el("chat.tooManyImagesTitle"):el("chat.send"),onClick:np,disabled:!nj,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:nj?"var(--accent)":"none",border:"none",borderRadius:5,color:nj?"var(--accent-contrast)":"var(--text-dim)",opacity:nj?1:.45,cursor:nj?"pointer":"not-allowed",fontSize:12.5,fontWeight:600,letterSpacing:"-0.01em",lineHeight:1,transition:"background 0.15s, color 0.15s, opacity 0.15s, filter 0.15s"},onMouseEnter:e=>{nj&&(e.currentTarget.style.filter="brightness(1.08)")},onMouseLeave:e=>{nj&&(e.currentTarget.style.filter="none")},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 19V5m-7 7 7-7 7 7"})}),(0,r.jsx)("span",{className:"chat-input-action-label",children:el("chat.send")})]})]})]}),eT&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eL?"var(--text-muted)":"var(--accent)",marginTop:4},children:[el("chat.shell")," \xb7 ",eL?el("chat.outputLocal"):el("chat.outputModel")]}),!Z&&(0,r.jsxs)("div",{className:"chat-input-toolbar",style:{marginTop:4*!ed,padding:ed?0:"0 2px",display:ed?"grid":"flex",gridTemplateColumns:ed?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:4},children:[(0,r.jsxs)("div",{style:{flex:ed?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:1},children:[(0,r.jsxs)("div",{ref:tJ,style:{position:"relative",display:"flex",alignItems:"center"},children:[(0,r.jsx)("button",{type:"button",disabled:a,onClick:()=>{t?eb(e=>!e):t0.current?.click()},title:t?`${el("chat.attachImage")} / ${el("image.title")}`:el("chat.attachImage"),"aria-label":t?`${el("chat.attachImage")} / ${el("image.title")}`:el("chat.attachImage"),"aria-expanded":t?ey:void 0,"aria-haspopup":t?"menu":void 0,style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",height:ed?32:28,padding:"0 4px",background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:4,color:eN.length?"var(--accent)":ey?"var(--text)":"var(--text-muted)",cursor:a?"not-allowed":"pointer",opacity:a?.45:1,lineHeight:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{ed||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eN.length?"var(--accent)":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=ey?"var(--bg-hover)":"none",e.currentTarget.style.color=eN.length?"var(--accent)":ey?"var(--text)":"var(--text-muted)")},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),ey&&t&&(0,r.jsxs)("div",{role:"menu",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),eb(!1))},style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 4px 20px rgba(0,0,0,0.15), 0 1px 4px rgba(0,0,0,0.08)",overflow:"hidden",minWidth:120},children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{eb(!1),t0.current?.click()},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:"none",border:"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]}),(0,r.jsx)("span",{children:el("chat.attachImage")})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{eb(!1);let[e]=1===no.current.length?no.current:[];t(e?tM(e):void 0)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:"none",border:"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"m15 4 5 5L8 21l-5-5L15 4Z"}),(0,r.jsx)("path",{d:"m14 5 5 5M6 4v3M4.5 5.5h3M19 16v4M17 18h4"})]}),(0,r.jsx)("span",{children:el("image.title")})]})]})]}),(nF.length>0||d||p)&&g&&(0,r.jsx)(td,{options:nF,value:d,onChange:g,disabled:l,busy:m,isAutoSelection:c})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),ed&&ew&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent"},onClick:()=>{ef(!1),em(!1),ek(!1)}}),ed&&(ew||ep||eg||ey)&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent",WebkitTapHighlightColor:"transparent"},onClick:()=>{ef(!1),em(!1),eb(!1),ek(!1),ev(!1)},"aria-hidden":"true"}),(0,r.jsxs)("div",{ref:tY,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto",zIndex:ed&&ew?60:void 0},children:[ed&&nY(!0),ed&&(eo=!!(null!=nV&&nV>=85),(0,r.jsxs)("button",{type:"button",title:ew?el("chat.collapseControls"):el("chat.moreControls"),"aria-label":el("chat.moreControls"),"aria-expanded":ew,onClick:()=>{ew?(ef(!1),em(!1),ek(!1)):ek(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,maxWidth:"min(48vw, 200px)",height:32,padding:"0 6px",background:ew?eo?"rgba(239,68,68,0.12)":"var(--bg-hover)":eo?"rgba(239,68,68,0.06)":"none",border:eo?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:eo?"#ef4444":null!=nV&&nV>=70&&nV<85?"rgba(234,179,8,0.95)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:400,lineHeight:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},children:[(0,r.jsx)(eK,{size:14,style:{display:"block"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:nJ})]})),(0,r.jsxs)("div",{ref:tX,className:"chat-input-toolbar-controls",style:{display:ed?ew?"flex":"none":"flex",alignItems:"center",gap:1,...ed?{position:"absolute",right:0,bottom:"100%",height:32,zIndex:60,boxSizing:"border-box",padding:"1px 2px",width:"max-content",maxWidth:"calc(100vw - 32px)",overflow:"visible",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 4px 16px rgba(0,0,0,0.12), 0 1px 3px rgba(0,0,0,0.06)"}:null},children:[M&&(0,r.jsxs)("div",{ref:tV,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!l&&(ef(!1),em(e=>!e)),disabled:l,title:el("chat.changeReasoning",{level:n_}),"aria-label":el("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",width:ed?"auto":void 0,height:ed?32:28,background:eg?"var(--bg-hover)":"none",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||ed||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=eg?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)")},children:[(0,r.jsx)(eK,{size:14,style:{display:"block"}}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:n_})]}),eg&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:"calc(100vw - 24px)",zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 4px 20px rgba(0,0,0,0.15), 0 1px 4px rgba(0,0,0,0.08)",overflow:"hidden",minWidth:180},children:tg.filter(e=>!T||"auto"===e||T.includes(e)).map(e=>{let t=(I??"auto")===e,n=el(tm[e]),i="auto"!==e&&L?L[e]:void 0,o=null!=i&&i!==e?i:e,s=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{em(!1),ed&&ek(!1),t||M(e)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[o,s&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!ed&&nY(!1),!l&&S&&(0,r.jsxs)("div",{ref:tK,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!l&&(em(!1),ef(e=>!e)),disabled:l,title:el("chat.changeToolPreset")+`: ${nK}`,"aria-label":el("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",width:ed?"auto":void 0,height:ed?32:28,background:ep?"var(--bg-hover)":"none",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||ed||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=ep?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)")},children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:nK})]}),ep&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,maxWidth:"calc(100vw - 24px)",zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 4px 20px rgba(0,0,0,0.15), 0 1px 4px rgba(0,0,0,0.08)",overflow:"hidden",minWidth:120},children:tu.map(e=>{let t,n=th[e],i=(j??tr.Q8)===n;return t="configured"===e?el("chat.configuredTools"):"chat-only"===e?el("chat.chatOnly"):"read-only"===e?el("chat.readOnlyTools",{count:4}):"default"===e?el("chat.builtInTools",{count:4}):el("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ef(!1),ed&&ek(!1),i||S(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),!l&&x&&(es=!!(C?.percent&&C.percent>=85),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center"},children:(0,r.jsx)("button",{onClick:()=>{ed&&ek(!1),y?v?.():x?.()},disabled:l&&!y,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",width:ed?"auto":void 0,height:ed?32:28,background:y?"rgba(239,68,68,0.08)":es?"rgba(239,68,68,0.06)":"none",border:es&&!y?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:y||es?"#ef4444":"var(--text-muted)",cursor:l&&!y?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:l&&!y?.5:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{ed||l&&!y||(e.currentTarget.style.background=y?"rgba(239,68,68,0.16)":es?"rgba(239,68,68,0.12)":"var(--bg-hover)",e.currentTarget.style.color=y||es?"#ef4444":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=y?"rgba(239,68,68,0.08)":es?"rgba(239,68,68,0.06)":"none",e.currentTarget.style.color=y||es?"#ef4444":"var(--text-muted)")},title:y?el("chat.stopCompaction"):es?`${el("chat.compactContext")} (${el("chat.contextHighWarning")})`:el("chat.compactContext"),"aria-label":y?el("chat.stopCompaction"):el("chat.compactContext"),children:y?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block",flexShrink:0},children:(0,r.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2",fill:"currentColor"})}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:el("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:el("chat.compact")})]})})})),void 0!==U&&(0,r.jsx)("button",{onClick:()=>{ed&&ek(!1),U?.()},title:O?el("chat.disableSound"):el("chat.enableSound"),"aria-label":O?el("chat.disableSound"):el("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:ed?32:28,padding:"0 4px",background:"none",border:"none",borderRadius:4,color:O?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:O?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{ed||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1")},onMouseLeave:e=>{ed||(e.currentTarget.style.background="none",e.currentTarget.style.color=O?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=O?"1":"0.55")},children:O?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,r.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,r.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})})]})]})]})]})]})});function tD(e,t,n,r){let i=e?.capabilities[t];if(r&&i?.includes(r))return r;let o=e?.defaults?.[n];return o&&i?.includes(o)?o:i?.includes("auto")?"auto":i?.[0]??""}function tH({value:e,label:t,onChange:n,children:i}){return(0,r.jsxs)("label",{className:"relative inline-flex flex-none items-center",children:[(0,r.jsx)("select",{"aria-label":t,value:e,onChange:e=>n(e.target.value),className:"image-generation-select appearance-none bg-transparent py-1 pl-1.5 pr-5 text-[12px] text-text-muted outline-none hover:text-text focus:text-text",children:i}),(0,r.jsx)("svg",{className:"pointer-events-none absolute right-0.5 top-1/2 -translate-y-1/2 text-text-dim",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})]})}function tB({config:e,edit:t,editPreviewUrl:n,initialSourceImage:o,onClose:s,onSubmit:l}){let{t:a}=(0,w.s)(),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),[h,p]=(0,i.useState)(""),f=e.connections.filter(e=>!0===e.capabilities.editing),[g,m]=(0,i.useState)(()=>t||!f.length?void 0:o),x=!!(t||g),v=x?f:e.connections,[y,b]=(0,i.useState)(()=>t?.connection&&e.connections.some(e=>e.id===t.connection)?t.connection:e.defaultConnection);(0,i.useEffect)(()=>{v.some(e=>e.id===y)||b(v.some(t=>t.id===e.defaultConnection)?e.defaultConnection:v[0]?.id??"")},[e.defaultConnection,v,y]);let k=v.find(e=>e.id===y)??v[0],j=!t&&f.length>0,S=e=>{let t=Array.from(e).find(e=>e.type.startsWith("image/"));return!!t&&(tI(t).then(m,e=>console.error("Failed to read source image:",e)),!0)},[C,E]=(0,i.useState)(()=>tD(k,"sizes","size",t?.size)),[N,I]=(0,i.useState)(()=>tD(k,"resolutions","resolution",t?.resolution)),[M,T]=(0,i.useState)(()=>tD(k,"qualities","quality",t?.quality)),L=k?.capabilities.sizes??[],R=k?.capabilities.resolutions??[],$=k?.capabilities.qualities??[],W=v.length>1,z=t?n:g?`data:${g.mimeType};base64,${g.data}`:void 0;(0,i.useLayoutEffect)(()=>{let e=c.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`)},[h]),(0,i.useEffect)(()=>{let e=document.activeElement;return window.matchMedia("(max-width: 640px)").matches||c.current?.focus(),()=>{e?.isConnected&&e.focus()}},[]),(0,i.useEffect)(()=>{let e=t&&k?.id===t.connection?t:void 0;E(tD(k,"sizes","size",e?.size)),I(tD(k,"resolutions","resolution",e?.resolution)),T(tD(k,"qualities","quality",e?.quality))},[k,t]);let P=()=>{if(!h.trim()||!k)return;let e={prompt:h.trim(),connection:k.id,...C?{size:C}:{},...N?{resolution:N}:{},...M?{quality:M}:{},...t?{target:t.path}:g?{}:{new_image:!0}};s(),l(e,t?void 0:g)};return(0,r.jsx)("div",{role:"presentation",className:"fixed inset-0 z-[1100] flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4",onClick:e=>{e.target===e.currentTarget&&s()},children:(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"image-generation-title",tabIndex:-1,onDragOver:e=>{j&&e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{j&&S(e.dataTransfer.files)&&e.preventDefault()},className:"flex max-h-[min(92dvh,100%)] w-full max-w-full flex-col overflow-hidden rounded-t-[16px] border border-border/80 bg-bg-panel shadow-2xl sm:max-h-[calc(100dvh-2rem)] sm:w-[480px] sm:rounded-[12px]",onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),s();return}if((e.metaKey||e.ctrlKey)&&"Enter"===e.key){e.preventDefault(),P();return}if("Tab"!==e.key)return;let t=Array.from(d.current?.querySelectorAll("button:not(:disabled), textarea:not(:disabled), select:not(:disabled), input:not(:disabled)")??[]).filter(e=>null!==e.offsetParent);if(!t.length)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n.focus())},children:[(0,r.jsx)("div",{className:"flex justify-center pt-2 sm:hidden","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-1 w-10 rounded-full bg-border"})}),(0,r.jsxs)("header",{className:"flex h-10 shrink-0 items-center px-4 sm:h-11",children:[(0,r.jsx)("h2",{id:"image-generation-title",className:"text-[14px] font-medium text-text",children:x?a("image.editTitle"):a("image.title")}),(0,r.jsx)("button",{type:"button",onClick:s,className:"ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md border-0 bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",title:a("trust.cancel"),"aria-label":a("trust.cancel"),children:(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:z?"flex flex-col gap-3 sm:flex-row sm:items-start":void 0,children:[z?(0,r.jsxs)("div",{className:"relative overflow-hidden rounded-[10px] sm:shrink-0",children:[(0,r.jsx)("img",{src:z,alt:t?.prompt??a("image.editSource"),className:"block h-auto w-full sm:h-28 sm:w-auto sm:max-w-[7.5rem]"}),t?null:(0,r.jsx)("button",{type:"button",onClick:()=>m(void 0),className:"absolute right-1 top-1 inline-flex h-6 w-6 items-center justify-center rounded-full border-0 bg-black/60 text-white hover:bg-black/80",title:a("image.removeSource"),"aria-label":a("image.removeSource"),children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]}):null,(0,r.jsx)("textarea",{ref:c,id:"image-prompt",rows:2,value:h,maxLength:32e3,"aria-label":a("image.prompt"),onChange:e=>p(e.target.value),onPaste:e=>{j&&S(e.clipboardData.files)&&e.preventDefault()},placeholder:x?a("image.editPromptPlaceholder"):a("image.promptPlaceholder"),className:`image-generation-prompt w-full resize-none rounded-[10px] border-0 bg-bg px-3 py-2.5 leading-[1.5] text-text outline-none ring-1 ring-inset ring-transparent placeholder:text-text-dim focus:ring-accent/50 ${z?"sm:min-h-28 sm:flex-1":""}`,style:{fontFamily:"var(--font-chat)",fontSize:"var(--chat-content-font-size, 14px)"}})]})}),(0,r.jsxs)("footer",{className:"flex shrink-0 items-center gap-2 px-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-3",children:[(0,r.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-x-1 gap-y-0.5",children:[j&&!g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",onClick:()=>u.current?.click(),className:"inline-flex h-7 w-7 flex-none items-center justify-center rounded-md border-0 bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",title:a("image.addSource"),"aria-label":a("image.addSource"),children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(0,r.jsx)("input",{ref:u,type:"file",accept:"image/*",hidden:!0,onChange:e=>{S(e.target.files??[]),e.target.value=""}})]}):null,W?(0,r.jsx)(tH,{value:y,label:a("image.connection"),onChange:b,children:e.connections.map(e=>(0,r.jsx)("option",{value:e.id,children:e.label},e.id))}):null,L.length?(0,r.jsx)(tH,{value:C,label:a("image.aspect"),onChange:E,children:L.map(e=>{let t,n,i;return(0,r.jsx)("option",{value:e,children:"auto"===(t="auto"===(i=e.trim())?"auto":(n=function(e){let t=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(e.trim())??/^(\d+)x(\d+)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?null:{width:n,height:r}}(i))?n.width===n.height?"square":n.width>n.height?"landscape":"portrait":null)?a("image.aspectAuto"):"square"===t?`${a("image.aspectSquare")} ${e}`:"portrait"===t?`${a("image.aspectPortrait")} ${e}`:"landscape"===t?`${a("image.aspectLandscape")} ${e}`:e},e)})}):null,R.length?(0,r.jsx)(tH,{value:N,label:a("image.resolution"),onChange:I,children:R.map(e=>(0,r.jsx)("option",{value:e,children:e.toUpperCase()},e))}):null,$.length?(0,r.jsx)(tH,{value:M,label:a("image.quality"),onChange:T,children:$.map(e=>(0,r.jsx)("option",{value:e,children:"auto"===e?a("image.qualityAuto"):"low"===e?a("image.qualityLow"):"medium"===e?a("image.qualityMedium"):"high"===e?a("image.qualityHigh"):e},e))}):null]}),(0,r.jsx)("button",{type:"button",disabled:!h.trim(),onClick:P,className:"h-8 shrink-0 rounded-md border-0 bg-accent px-3 text-[12.5px] font-medium text-white disabled:cursor-not-allowed disabled:opacity-50",children:x?a("image.edit"):a("image.generate")})]})]})})}let tF=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,tO=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,tU=/\x1B_pi:c\x07/g;function t_(e){return e.replace(tU,"").replace(tF,"")}function tq(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(tO);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function tK(e,t){let n=tq(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function tV(e){return tq(e)[0]?.char}let tJ={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},tY={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function tZ(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function tX(e){return"custom"===e.role&&"pi-web:subagent-notification"===e.customType}function tG(e){return tZ(e)||tX(e)}function tQ(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function t0(e,t={}){return(e.content??[]).filter(e=>!tQ(e,t)&&!function(e,t={}){return"text"===e.type&&!t.isStreaming&&""===e.text.trim()}(e,t))}function t1(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function t2(e,t={}){return"image"===e.type||"text"===e.type&&(t.isStreaming?e.text.length>0:e.text.trim().length>0)}function t4(e,t={}){let n=t0(e,t),r=n.findLastIndex(e=>!t2(e,t));return -1===r?{answerBlocks:n,processBlocks:[]}:{processBlocks:n.slice(0,r+1),answerBlocks:n.slice(r+1)}}function t8(e,t={}){return t4(e,t).answerBlocks.some(e=>t2(e,t))}function t5(e){return e.filter(e=>"toolCall"===e.type).length}function t6(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),n.omitError&&("error"===r.stopReason&&(r.stopReason="stop"),r.errorMessage=void 0),r}function t3(e,t={}){let n=function(e,t={}){let{processBlocks:n,answerBlocks:r}=t4(e,t),i=[],o=[];for(let e of n)"text"===e.type&&e.text.trim().length>400?o.push(e):i.push(e);return{answerBlocks:[...o,...r],processBlocks:i}}(e,t),r=t8(e,t),i=!!t1(e,t),o=n.answerBlocks.length>0?t6(e,n.answerBlocks,{omitError:!r}):null;return{processMessage:t0({...e,content:n.processBlocks},t).length>0||i&&!r?t6(e,n.processBlocks,{omitUsage:!!o&&!t.isStreaming,omitError:r}):null,answerMessage:o}}let t7=/^\*\*\* (Add|Update|Delete) File: (.+)$/,t9=/^\*\*\* Move to: (.+)$/;function ne(){return{lineNo:null,text:"",type:"empty"}}function nt(e){if(!e.includes("*** Begin Patch"))return null;let t=[],n=null,r=!1,i=[],o=[],s=()=>{if(!n){i=[],o=[];return}let e=Math.max(i.length,o.length);for(let t=0;t<e;t+=1){let e=i[t]?{lineNo:i[t].lineNo,text:i[t].text,type:"removed"}:ne(),r=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"added"}:ne();n.rows.push({type:"line",left:e,right:r})}i=[],o=[]};for(let l of e.split(/\r?\n/)){if(l.startsWith("*** Begin Patch")||l.startsWith("*** End Patch")){s(),r=!1;continue}let e=l.match(t7);if(e){s(),r=!1;let i=e[1].toLowerCase();n={path:e[2].trim(),operation:i,rows:[]},t.push(n);continue}if(!n)continue;let a=l.match(t9);if(a){n.moveTo=a[1].trim();continue}if(l.startsWith("@@")){s(),r=!0,n.rows.push({type:"hunk",text:l});continue}if(l.startsWith("*** "))return null;if(""===l){s();continue}if(!r&&"update"===n.operation)continue;let d=l[0]??"",c=l.slice(1);"+"===d?o.push({lineNo:null,text:c}):"-"===d?i.push({lineNo:null,text:c}):" "===d&&(s(),n.rows.push({type:"line",left:{lineNo:null,text:c,type:"context"},right:{lineNo:null,text:c,type:"context"}}))}return s(),t.length>0?t:null}function nn(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function nr(e){try{return decodeURIComponent(e)}catch{return e}}function ni(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function no(e){let t=ni(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,o=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){o.length>0&&".."!==o[o.length-1]?o.pop():i||n||r||o.push(e);continue}o.push(e)}let s=o.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function ns(e,t,n=t){let r,i,o,s,l;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=nr(a),h=u.startsWith("\\\\"),p=ni(u),f=p.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!h&&p.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(p)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(p))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=nr(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(a))?"absolute":null:/^[a-zA-Z]:\//.test(p)||p.startsWith("/")?(d=p,c="absolute"):t&&!(p.startsWith("#")||p.startsWith("?"))&&(p.startsWith("./")||p.startsWith("../")||p.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(p))&&(d=`${ni(t).replace(/\/+$/,"")}/${p}`,c="relative"),!d)return null;let g=no(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=no(g).replace(/\/+$/,""),i=no(n).replace(/\/+$/,""),s=(o=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(s===(l=o?i.toLowerCase():i)||s.startsWith(`${l}/`)))?null:g}function nl(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function na(e){let t=e.toLowerCase();return"apply_patch"===t||t.endsWith(".apply_patch")||t.endsWith("/apply_patch")||t.endsWith("_apply_patch")}function nd(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
5
|
+
|
|
6
|
+
${r}
|
|
7
|
+
|
|
8
|
+
${n}`}function nc(e,t,n=50){let r=Math.max(0,e),i=Math.min(Math.max(0,t),Math.max(0,r-Math.min(n,r))),o=r-i;return{startIndex:Math.max(0,o-n),endIndex:o}}function nu(e,t,n,r=8){return e+t>=n-r}class nh extends Error{constructor(e,t){super(t),this.name="OutlineLocateError",this.reason=e}}function np(e,t){return e.entry.id===t||!!e.compressedEntryIds?.includes(t)}function nf(e,t){if(!e)return null;let n=new Map,r=[];for(let t=e.length-1;t>=0;t--)n.set(e[t],null),r.push(e[t]);for(;r.length>0;){let e=r.pop();if(np(e,t)){let t=[],r=e;for(;r;)t.push(r),r=n.get(r)??null;return t.reverse(),t}let i=e.children;if(i&&0!==i.length)for(let t=i.length-1;t>=0;t--)n.set(i[t],e),r.push(i[t])}return null}async function ng(e,t,n,r){let i=t,o=new Set;for(;;){if(r.throwIfAborted(),i.entryIds.includes(e))return;let t=i.oldestEntryId;if(!i.hasMore||!t)throw new nh("exhausted","Question is no longer in this branch. Refresh the outline and try again.");if(o.has(t))throw new nh("stalled","History did not advance. Please try again.");o.add(t);let s=await n(t);if(r.throwIfAborted(),!s)throw new nh("load_failed","Could not load this question. Please try again.");if(s.entryIds.includes(e))return;if(s.oldestEntryId===t||null!==s.oldestEntryId&&o.has(s.oldestEntryId))throw new nh("stalled","History did not advance. Please try again.");i=s}}function nm(e,t){return t.aborted||e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&"AbortError"===e.name}var nx=n(32316),nv=n(88374),ny=n(5924),nb=n(94764),nw=n(63835),nk=n(23135),nj=n(54152),nS=n(84678),nC=n(98164);let nE={...nb.j,attributes:{...nb.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...nb.j.protocols,href:[...nb.j.protocols?.href??[],"file"]},strip:[...nb.j.strip||[],"iframe","object","style","form"]};function nN(e){return/^file:/i.test(e)?e:(0,nx.Lv)(e)}let nI=/(?<![\\`])`((?:[^`\n]|\\`)+?)(?<![\\`])`(?!`)/g;function nM(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,o=0,s=null,l=new Map,a=new Set;for(let e=0;e<n.length;e++){var d,c;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let u=t.match(/^ {0,3}(`{3,}|~{3,})/);if(u){let e=u[1][0],n=u[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},o=0,r.push(t);continue}if(i){r.push(t);continue}let h=t.match(/<(code|pre|script|style)\b/i);if(h){let e=h[1].toLowerCase(),n=t.slice((h.index??0)+h[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(s=e),o=0,r.push(t);continue}if(""===t.trim()||/^(?: {4}|\t)/.test(t)&&!/^[ \t]*\$\$/.test(t)||a.has(e)){o=0,r.push(t);continue}if(o||(t=t.replace(nI,(e,t)=>{let n=t.replace(/\\`/g,"`");if(n===t)return e;let r="`".repeat(Math.max(...n.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${r}${n}${r}`})),o||t.includes("`")){o=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,o),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let f=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(f){let e=f[2].trim();if(d=e,/\\[A-Za-z]+/.test(d)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(d)){r.push(`${f[1]}$$`,`${f[1]}${e}`,`${f[1]}$$`);continue}}let g=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(g){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${g[1]}$$`,...n.slice(e+1,t).map(e=>n$(e,g[1])),`${g[1]}$$`),e=t;continue}}let m=t.match(/^([ \t]*)\$\$(.+)\$\$[ \t]*$/);if(m){let e=m[2].trim();if(e){r.push(`${m[1]}$$`,`${m[1]}${e}`,`${m[1]}$$`);continue}}let x=t.match(/^([ \t]*)\$\$(.+)$/);if(x){let i=x[1],o=x[2].trimEnd();if(o&&!o.includes("$$")){let s=nT(n,e+1,i,l);if(s){r.push(`${i}$$`,`${i}${o}`);for(let t=e+1;t<s.index;t++)r.push(n$(n[t],i));s.content&&r.push(`${i}${s.content}`),r.push(`${i}$$`),e=s.index;continue}r.push(nL(t));continue}}let v=t.match(/^([ \t]*)\$\$\s*$/);if(v){let i=v[1],o=nT(n,e+1,i,l);if(o&&(o.glued||""!==i)){r.push(`${i}$$`);for(let t=e+1;t<o.index;t++)r.push(n$(n[t],i));o.content&&r.push(`${i}${o.content}`),r.push(`${i}$$`),e=o.index;continue}if(o){a.add(o.index),r.push(t);continue}r.push(nL(t));continue}r.push((c=t,/^\s{0,3}\[[^\]]+\]:/.test(c)||/]\s*\(/.test(c)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(c)||/\b(?:https?|file|mailto):/i.test(c)||/\b[A-Za-z]:\\/.test(c)?c:c.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function nT(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var o,s;let t=e[i];if(function(e,t){if(""===t)return/^ {0,3}\$\$\s*$/.test(e);let n=nR(e,t);return null!==n&&/^\$\$\s*$/.test(n)}(t,n))return{index:i,content:"",glued:!1};if(o=t,/^ {0,3}(`{3,}|~{3,})/.test(o)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(o)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(o)||/^ {0,3}>/.test(o)||/<(code|pre|script|style)\b/i.test(o)||(s=t,/^[ \t]*\$\$(?:\S|[ \t]+\S)/.test(s)))return r.set(n,i),null;let l=function(e,t){let n=nR(e,t);if(null===n)return null;let r=n.match(/^(.+?)\$\$\s*$/);if(!r)return null;let i=r[1].trimEnd();return i&&!i.includes("$$")?i:null}(t,n);if(null!==l)return{index:i,content:l,glued:!0}}return r.set(n,e.length),null}function nL(e){return e.replace(/^([ \t]*)\$\$/,(e,t)=>`${t}\\$\\$`)}function nR(e,t){if(e.startsWith(t))return e.slice(t.length);let n=e.match(/^[ \t]*/)?.[0]??"";return t&&n.length<t.length?e.slice(n.length):null}function n$(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let nW={singleTilde:!1},nz=[[nj.A,["yaml"]],[nS.A,nW],nC.A,nk.A],nP=[[nj.A,["yaml"]],[nS.A,nW],nC.A,nk.A],nA=[ny.A,[nw.A,nE],[nv.A,{throwOnError:!1,strict:!1}]],nD=[ny.A,[nw.A,nE],[nv.A,{throwOnError:!1,strict:!1}]];var nH=n(7644);let nB="pi-theme",nF=["light","dark","auto"],nO={preference:"auto",theme:"light"},nU=new Set,n_=null,nq=!1;function nK(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function nV(e){return"auto"===e?nK():e}let nJ={light:"#f5f5f5",dark:"#242424"};function nY(e){"u">typeof document&&(document.documentElement.classList.toggle("dark","dark"===e),function(e){if("u"<typeof document)return;let t=nJ[e],n=document.querySelectorAll('meta[name="theme-color"]');if(0===n.length){let e=document.createElement("meta");e.name="theme-color",e.content=t,document.head.appendChild(e);return}for(let e of n)e.removeAttribute("media"),e.content=t}(e))}function nZ(){if(n_)return n_;let e=function(){try{let e=localStorage.getItem(nB);if("light"===e||"dark"===e||"auto"===e)return e}catch{}return"auto"}(),t=nV(e);return nY(t),n_={preference:e,theme:t}}function nX(e,t,n){if(nY(t),n)try{localStorage.setItem(nB,e)}catch{}n_={preference:e,theme:t},nU.forEach(e=>e())}function nG(){let e=nZ();if("auto"!==e.preference)return;let t=nK();t!==e.theme&&nX("auto",t,!1)}function nQ(e){return nU.add(e),nZ(),nq||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",nG),window.addEventListener("focus",nG),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&nG()}),nq=!0),nG(),()=>{nU.delete(e)}}function n0(){return nZ()}function n1(){return nO}function n2(){let e=(0,i.useSyncExternalStore)(nQ,n0,n1),t=(0,i.useCallback)((e,t)=>{if(nZ().preference===e)return;let n=nV(e),r=()=>{nX(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let o=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(o,window.innerWidth-o),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${o}px ${s}px)`,`circle(${l}px at ${o}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),n=(0,i.useCallback)(e=>{var n;let r;t((n=nZ().preference,r=nF.indexOf(n),nF[(r+1)%nF.length]),e)},[t]);return{theme:e.theme,preference:e.preference,setThemePreference:t,toggleTheme:n,isDark:"dark"===e.theme}}function n4(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}var n8=n(65063);function n5({code:e,isStreaming:t,defaultPreview:o=!1}){let{isDark:s}=n2(),{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(o),[c,u]=(0,i.useState)(null),[h,p]=(0,i.useState)(!1),f=(0,i.useRef)(null),g=`${s?"dark":"light"}
|
|
9
|
+
${e}`,m=a&&!t;(0,i.useEffect)(()=>{if(!m)return;let t=!1;return u({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(988),n.e(9425),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:s?"dark":"default"}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(i,e);t||u({key:g,status:"ready",svg:o.svg})})().catch(()=>{t||u({key:g,status:"error"})}),()=>{t=!0}},[e,g,s,m]);let x=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?l("i18n.previewAfterStreaming"):m?l("i18n.showMermaidSource"):l("i18n.previewMermaid"),className:["markdown-code-action",m?"is-active":""].filter(Boolean).join(" "),children:m?l("i18n.source"):l("i18n.preview")}),[t,m,l]);if(!m)return(0,r.jsx)(n3,{code:e,lang:"mermaid",headerAction:x,isStreaming:t});let v=c?.key===g&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:l("i18n.invalidMermaid")}):c?.key!==g||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":l("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!h&&(0,r.jsx)("button",{ref:f,type:"button",className:"mermaid-block mermaid-preview-button",title:l("i18n.openMermaidViewer"),"aria-label":l("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),h&&(0,r.jsx)(n6,{svg:c.svg,onClose:()=>p(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[c?.key===g&&"ready"===c.status&&(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${l("i18n.downloadFile")} (SVG)`,"aria-label":`${l("i18n.downloadFile")} (SVG)`,onClick:()=>{let e,t,n,r=f.current?.querySelector("svg");r&&(e=new XMLSerializer().serializeToString(r),t=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),(n=document.createElement("a")).href=t,n.download="mermaid-diagram.svg",n.click(),setTimeout(()=>URL.revokeObjectURL(t),0))},children:"SVG"}),x]})]}),v]})}function n6({svg:e,onClose:t}){let{t:n}=(0,w.s)(),o=(0,i.useRef)(null),[s,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:o,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:s>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>l(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let n3=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:o}){let{isDark:s}=n2(),{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsxs)("button",{type:"button",onClick:()=>{n4(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",title:l(a?"i18n.copied":"i18n.copy"),"aria-label":l(a?"i18n.copied":"i18n.copy"),children:[a?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,r.jsx)("span",{children:l(a?"i18n.copied":"i18n.copy")})]})]})]}),o?(0,r.jsx)("pre",{style:{margin:0,padding:"6px 10px",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.54,overflowX:"auto",scrollbarWidth:"thin",border:"none",borderRadius:0,background:"transparent",backgroundColor:"transparent"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(n8.A,{language:t||"text",style:s?nH.xJ:nH.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",opacity:.45,paddingRight:"0.8em",userSelect:"none"},customStyle:{margin:0,padding:"6px 10px",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.54,borderRadius:0,border:"none",boxShadow:"none",background:"transparent",backgroundColor:"transparent",overflowX:"auto",scrollbarWidth:"thin"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function n7({children:e,className:t,isStreaming:n,cwd:o,onOpenFile:s}){let l=(0,i.useMemo)(()=>nM(e),[e]),a=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let o=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===o?(0,r.jsx)(n5,{code:s.replace(/\n$/,""),isStreaming:n,defaultPreview:!0}):(0,r.jsx)(n3,{code:s.replace(/\n$/,""),lang:o,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=s?ns(e,o):null;if(!i||!s)return(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t});let l=function(e){if(!e)return null;let t=e.split("#",2)[1];if(!t)return null;let n=new URLSearchParams(t).get("page");if(null===n||!/^\d+$/.test(n))return null;let r=Number(n);return Number.isSafeInteger(r)&&r>0?r:null}(e);return(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(!nn(e))return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(i,l??void 0))},children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?ns(e,o):null,s=i?`/api/files/${j(i)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[o,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(nx.oz,{remarkPlugins:nz,rehypePlugins:nA,urlTransform:s?nN:void 0,components:a,children:l})})}function n9({toolName:e,isError:t,size:n=12}){if(t)return(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]});let i=e.toLowerCase();return i.includes("bash")||i.includes("sh")||i.includes("terminal")||i.includes("powershell")||i.includes("command")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-text-muted",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):"read"===i||i.includes("read_file")||i.includes("view")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-text-muted",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"9",y1:"13",x2:"15",y2:"13"}),(0,r.jsx)("line",{x1:"9",y1:"17",x2:"13",y2:"17"})]}):i.includes("write")||i.includes("edit")||i.includes("patch")||i.includes("apply")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-text-muted",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),(0,r.jsx)("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}):i.includes("todo")||i.includes("task")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-text-muted",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"5",width:"6",height:"6",rx:"1"}),(0,r.jsx)("path",{d:"m3 17 2 2 4-4"}),(0,r.jsx)("path",{d:"M13 6h8"}),(0,r.jsx)("path",{d:"M13 12h8"}),(0,r.jsx)("path",{d:"M13 18h8"})]}):i.includes("agent")||i.includes("subagent")?(0,r.jsx)(X,{size:n,strokeWidth:2.2,className:"shrink-0 text-text-muted",style:{display:"block"}}):i.includes("search")||i.includes("fetch")||i.includes("web")||i.includes("browser")?(0,r.jsxs)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-text-muted",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}):(0,r.jsx)("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-text-muted",style:{display:"block"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})})}let re=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,rt=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function rn(e){let t,n=[],r=null,i=0,o=0,s=0,l=0,a=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){a=[],d=[];return}let e=Math.max(a.length,d.length);for(let t=0;t<e;t++){let e=a[t]?{lineNo:a[t].lineNo,text:a[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}a=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(s>0||l>0)){if(c.startsWith("--- ")){u(),t=rr(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:rr(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),o=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let h=c[0],p=c.slice(1);" "===h?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:p,type:"context"},right:{lineNo:o++,text:p,type:"context"}}),s>0&&s--,l>0&&l--):"-"===h?(a.push({lineNo:i++,text:p}),s>0&&s--):"+"===h?(d.push({lineNo:o++,text:p}),l>0&&l--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let h=n.filter(e=>e.rows.some(e=>"line"===e.type));return h.length>0?h:null}function rr(e){return e.split(" ")[0].trim()}let ri="pi-thinking-expanded",ro="pi-thinking-expanded-changed";function rs(){return"true"===window.localStorage.getItem(ri)}function rl({files:e,onOpenFile:t}){let{t:n}=(0,w.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=S(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2.5px 7px",minHeight:22,fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",fontFamily:"var(--font-mono)",lineHeight:1,color:"var(--text-muted)",background:"color-mix(in srgb, var(--bg-subtle) 65%, var(--bg))",border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",borderRadius:5,cursor:"pointer",transition:"background 0.12s ease, color 0.12s ease"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--bg-subtle) 65%, var(--bg))",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,transform:"translateY(0.5px)"},children:A(i,12)}),(0,r.jsx)("span",{style:{lineHeight:1},children:i})]},e)})})}let ra=new Map;function rd({children:e,className:t,...n}){let{t:o}=(0,w.s)(),[s,l]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(n7,{className:t,...n,children:e});if(!s){var a;return(0,r.jsxs)("button",{onClick:()=>l(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",o("i18n.largeMessageReveal",{size:(a=e.length)>=1e6?`${(a/1e6).toFixed(1)} MB`:a>=1e3?`${Math.round(a/1e3)} KB`:`${a} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}function rc(e,t){if("number"!=typeof e||"number"!=typeof t)return;let n=Math.round((t-e)/1e3);return n>0?n:void 0}function ru(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let o=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${o} ${i}`}let rh=(0,i.memo)(function({message:e,modelName:t,isStreaming:n,toolResults:i,cwd:o,onOpenFile:s,onOpenSession:l,entryId:a,searchBlock:d,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:f,isTurnEnd:g,sessionId:m,writtenFiles:x,isProcess:v,runningToolIds:y}){return"user"===e.role?(0,r.jsx)(rg,{message:e,cwd:o,onOpenFile:s,entryId:a,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:f}):"assistant"===e.role?(0,r.jsx)(rm,{message:e,modelName:t,isStreaming:n,toolResults:i,cwd:o,onOpenFile:s,onOpenSession:l,isTurnEnd:g,sessionId:m,entryId:a,searchBlock:d,writtenFiles:x,isProcess:v,runningToolIds:y}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(rR,{message:e}):tX(e)?(0,r.jsx)(rz,{message:e,cwd:o,onOpenFile:s}):(0,r.jsx)(rP,{message:e,cwd:o,onOpenFile:s}):"bashExecution"===e.role?(0,r.jsx)(rB,{message:e,sessionId:m}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onOpenSession===t.onOpenSession&&e.entryId===t.entryId&&e.searchBlock===t.searchBlock&&e.onFork===t.onFork&&e.forking===t.forking&&e.onNavigate===t.onNavigate&&e.prevAssistantEntryId===t.prevAssistantEntryId&&e.onEditContent===t.onEditContent&&e.isTurnEnd===t.isTurnEnd&&e.modelName===t.modelName&&e.writtenFiles===t.writtenFiles&&e.sessionId===t.sessionId&&e.isProcess===t.isProcess);function rp({text:e,cwd:t,onOpenFile:n}){let i=function(e){let t=[],n=0;for(let r of e.matchAll(ex)){let i=function(e){let t=(e[1]??e[2]??"").replace(/[),.;]+$/,"");if(!(!ev.test(t)||t.split(/[\\/]/).includes("..")))return t}(r),o=r.index??0;i&&(o>n&&t.push({type:"text",value:e.slice(n,o)}),t.push({type:"mention",path:i}),n=o+r[0].length)}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length?t:[{type:"text",value:e}]}(e),o=i.filter(e=>"mention"===e.type),s=i.filter(e=>"text"===e.type).map(e=>e.value).join("").trim();return o.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!s},children:o.map(e=>(0,r.jsx)(eS,{path:e.path,cwd:t},e.path))}),s?(0,r.jsx)(rd,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:s}):null]}):(0,r.jsx)(rd,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:e})}let rf=/^\[Image(?:: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by \d+\.\d{2} to map to original image\.| converted from \S+ to \S+\.)\]$/;function rg({message:e,cwd:t,onOpenFile:n,entryId:o,onFork:s,forking:l,onNavigate:a,prevAssistantEntryId:d,onEditContent:c}){let{t:h}=(0,w.s)(),[p,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),y=function(e){let t=e.split("\n"),n=t.length;for(;n>0&&(""===t[n-1].trim()||rf.test(t[n-1].trim()));)n-=1;return t.slice(0,n).join("\n")}("string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")),b="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),k=u(y),j=k?.search(/\s/)??-1,S=k?-1===j?k:k.slice(0,j):"",C=k&&-1!==j?k.slice(j+1):"",E=ru(e.timestamp),N=!!o&&!!s,I=k??y,M=k?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(e,k):e,T=b.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!y},children:b.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(eh,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:8,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t)})}),L=!!d&&!!a;return(0,r.jsxs)("div",{style:{marginBottom:10,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"min(85%, 680px)"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--user-border, var(--border))",borderRadius:6,padding:"6px 11px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.58,color:"var(--text)",wordBreak:"break-word",maxHeight:480,overflowY:"auto"},children:k?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[T,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:h(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),C&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.58,whiteSpace:"pre-wrap",wordBreak:"break-word",flex:"1 0 auto",width:"max-content",maxWidth:"100%"},children:C})]}),x&&(0,r.jsx)(n7,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:y})]}):(0,r.jsxs)(r.Fragment,{children:[T,y&&(0,r.jsx)(rp,{text:y,cwd:t,onOpenFile:n})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:2},children:[(0,r.jsx)("div",{className:"message-action-group",style:{opacity:+!!p,pointerEvents:p?"auto":"none"},children:(0,r.jsx)("button",{type:"button",className:"message-action-button","data-copied":g?"true":void 0,onClick:()=>{n4(I).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},title:h(g?"i18n.copied":"i18n.copyMessage"),"aria-label":h(g?"i18n.copied":"i18n.copy"),children:g?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})}),(N||L)&&(0,r.jsxs)("div",{className:"message-action-group",style:{opacity:p||l?1:0,pointerEvents:p||l?"auto":"none"},children:[L&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{a(d),c?.(M)},title:h("i18n.editFromHereTitle"),"aria-label":h("i18n.editFromHere"),children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"15 10 20 15 15 20"}),(0,r.jsx)("path",{d:"M4 4v7a4 4 0 0 0 4 4h12"})]})}),N&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{s(o)},disabled:l,title:h(l?"i18n.creatingSession":"i18n.newSessionTitle"),"aria-label":h(l?"i18n.creating":"i18n.newSession"),children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),E&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",userSelect:"none"},children:E})]})]})}function rm({message:e,modelName:t,isStreaming:n,toolResults:o,cwd:s,onOpenFile:l,onOpenSession:a,isTurnEnd:d,sessionId:c,entryId:u,searchBlock:h,writtenFiles:p,isProcess:f,runningToolIds:g}){let{t:m}=(0,w.s)(),[x,v]=(0,i.useState)(!1),y=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!tQ(e,{isStreaming:n})),[e.content,n]),b=(0,i.useMemo)(()=>y.map(({block:e})=>e),[y]),k=e.completedAt??e.timestamp,j=(0,i.useMemo)(()=>{let t=new Map;if(!o||void 0===k)return t;for(let n of e.content){if("toolCall"!==n.type)continue;let e=o.get(n.toolCallId),r=rc(k,e?.timestamp);void 0!==r&&t.set(n.toolCallId,r)}return t},[e.content,o,k]),S=t1(e,{isStreaming:n}),C=function(e,t={}){return!t.isStreaming&&"length"===e.stopReason}(e,{isStreaming:n}),E=b.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),N=d&&!n?ru(e.timestamp):null,I=d&&!n&&(t||e.model)||null,M=d&&!n&&!!(I||E||N);return 0!==b.length||n||S||C?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":u,style:{marginBottom:d?16:8},children:[(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:y.map(({block:t,originalIndex:i},d)=>{let p="thinking"===t.type?t:null,f=p?p.startedAt??e.timestamp:void 0,m=p?rc(f,p.endedAt??e.completedAt):void 0,x=!!(n&&p&&d===y.length-1&&void 0===m&&"number"==typeof f);return(0,r.jsx)(ry,{block:t,searchTarget:t===h,toolResults:o,isStreaming:n,streamingDuration:m,startTime:"toolCall"===t.type?k:f,live:x||"toolCall"===t.type&&!!g?.has(t.toolCallId),toolCallDurations:j,cwd:s,onOpenFile:l,onOpenSession:a,sessionId:c,entryId:u,blockIndex:i},`${u??"stream"}-${i}`)})}),S&&(f?(0,r.jsx)("div",{style:{marginTop:4*(b.length>0)},children:(0,r.jsx)(rx,{error:S})}):(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(b.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",S]})),C&&(0,r.jsx)("div",{role:"status",style:{marginTop:8*(b.length>0),padding:"7px 10px",border:"1px solid rgba(234,179,8,0.35)",borderRadius:6,background:"rgba(234,179,8,0.08)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:m("chat.truncatedByOutputLimit")}),p&&p.length>0&&(0,r.jsx)(rl,{files:p,onOpenFile:l}),M&&(0,r.jsxs)("div",{"data-answer-footer":!0,style:{display:"flex",alignItems:"center",gap:6,marginTop:2},children:[I&&(0,r.jsx)("div",{"data-answer-model":!0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-ui)"},children:I}),(E||N)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:"auto",flexShrink:0},children:[E&&(0,r.jsx)("button",{type:"button",className:"answer-copy-button message-action-button","data-copied":x?"true":void 0,onClick:()=>{n4(E).then(()=>{v(!0),setTimeout(()=>v(!1),1500)})},title:m(x?"i18n.copied":"i18n.copyMessage"),"aria-label":m(x?"i18n.copied":"i18n.copy"),children:x?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),N&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)",userSelect:"none"},children:N})]})]})]}):null}function rx({error:e}){let{t}=(0,w.s)(),[n,o]=(0,i.useState)(!1),s=(0,i.useId)(),l=(0,i.useMemo)(()=>{let t=e.replace(/^(Error:\s*)+/i,"").trim();return t.split("\n")[0]||t},[e]);return(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",border:"1px solid rgba(248,113,113,0.35)",background:"rgba(248,113,113,0.05)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:(0,r.jsxs)("button",{type:"button","aria-expanded":n,"data-step-trigger":"","aria-controls":s,title:t(n?"chat.collapseProcess":"chat.expandProcess"),onClick:()=>o(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,opacity:.85,transform:"translateY(0.5px)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#f87171",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]})}),(0,r.jsx)("span",{style:{color:"#f87171",fontFamily:"var(--font-mono)",fontWeight:500,fontSize:11,lineHeight:1.35,flexShrink:0},children:t("chat.modelError")}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,opacity:.85,lineHeight:1.35},children:l}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:n?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),n&&(0,r.jsxs)("div",{id:s,style:{padding:"8px 10px",background:"var(--bg)",borderTop:"1px solid rgba(248,113,113,0.2)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,color:"#f87171",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",e]})]})}function rv({seconds:e,startTime:t,live:n}){let{t:o}=(0,w.s)(),[s,l]=(0,i.useState)(Date.now);(0,i.useEffect)(()=>{if(!n)return;let e=setInterval(()=>l(Date.now()),500);return()=>clearInterval(e)},[n]);let a=n&&void 0!==t?Math.max(0,Math.round((s-t)/1e3)):e;if(void 0===a)return null;let d=void 0!==t?o("chat.stepStartedAt",{time:new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):void 0;return(0,r.jsx)("span",{title:d,style:{fontSize:10,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums",lineHeight:1.35},children:(0,b.a3)(a,o)})}function ry({block:e,searchTarget:t,toolResults:n,isStreaming:i,streamingDuration:o,startTime:s,live:l,toolCallDurations:a,cwd:d,onOpenFile:c,onOpenSession:u,sessionId:h,entryId:p,blockIndex:f}){if("text"===e.type){let n=e.text;return i||n&&""!==n.trim()?(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":t||void 0,children:(0,r.jsx)(rb,{block:e,isStreaming:i,cwd:d,onOpenFile:c})}):null}if("image"===e.type){let n=rH(e);return n?(0,r.jsx)("div",{"data-search-target":t||void 0,style:{margin:"8px 0"},children:(0,r.jsx)(eh,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})})}):null}if("thinking"===e.type)return(0,r.jsx)(rw,{block:e,duration:o,startTime:s,live:l,sessionId:h,entryId:p,blockIndex:f});if("toolCall"===e.type){let t=n?.get(e.toolCallId),i=a?.get(e.toolCallId);return(0,r.jsx)(rk,{block:e,result:t,duration:i,startTime:s,live:l,onOpenSession:u})}return null}function rb({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(rd,{className:"markdown-assistant-message",isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rw({block:e,duration:t,startTime:n,live:o,sessionId:s,entryId:l,blockIndex:a}){var d;let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(rs),[p,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),y=(0,i.useRef)(c);y.current=c;let b=(d=e.thinking,d.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>h(rs());return window.addEventListener(ro,e),()=>window.removeEventListener(ro,e)},[]),(0,i.useEffect)(()=>{if(!u||!e.deferred||null!==p)return;if(!s||!l)return void v(y.current("i18n.thinkingUnavailable"));let t=!1;return m(!0),v(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=ra.get(r);if(i)return ra.delete(r),ra.set(r,i),i;let o=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw ra.delete(r),e});if(ra.set(r,o),ra.size>100){let e=ra.keys().next().value;e&&ra.delete(e)}return o})(s,l,a).then(e=>{t||(f(e),m(!1))}).catch(e=>{t||(v(e instanceof Error?e.message:String(e)),m(!1))}),()=>{t=!0}},[u,e.deferred,p,s,l,a]),(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",border:"1px solid var(--border)",background:"var(--bg-subtle)",transition:"border-color 0.15s ease"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:(0,r.jsxs)("button",{type:"button","aria-expanded":u,"data-step-trigger":"","aria-label":`${c("i18n.thinking")}${b?`: ${b}`:""}`,title:c("i18n.thinking"),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,opacity:.85,transform:"translateY(0.5px)"},children:(0,r.jsx)(eK,{active:u,size:12})}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-ui)",fontWeight:500,fontSize:11.5,lineHeight:1.35,flexShrink:0},children:c("i18n.thinking")}),!u&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-ui)",fontSize:11.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,opacity:.85,lineHeight:1.35},children:b?(0,r.jsx)(nx.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:b}):"..."}),u&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsx)(rv,{seconds:t,startTime:n,live:o}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:u?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),u&&(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,color:x?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:g?c("i18n.loadingThinking"):x??(e.deferred?p:e.thinking)})]})}function rk({block:e,result:t,duration:n,startTime:o,live:s,onOpenSession:l}){var a,d;let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(!1),p=(d=e).rawInput??JSON.stringify(d.input,null,2),f=void 0!==e.rawInput,g=nl(e.toolName),m=na(e.toolName),x=m?"string"==typeof e.input?.patch?e.input.patch:function(e){if(!e)return;let t=/"patch"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(e);if(!t)return;let n=t[1];if(!n.endsWith("\\")||n.endsWith("\\\\"))try{return JSON.parse(`"${n}"`)}catch{return}}(e.rawInput):void 0,v=ew(e.toolName,e.input,t?.details),y="edit"===v?c("image.edit"):"generate"===v?c("image.generate"):e.toolName,b=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,k=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,j=rD(t?.content??[]),S=null!==k&&("(no output)"===k.trim()||""===k.trim()),C=t?.isError??!1,E=(a=t?.details)&&"object"==typeof a&&"pi-web-subagent"===a.kind&&"string"==typeof a.sessionId?t.details:null;return(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",border:C?"1px solid rgba(248,113,113,0.45)":"1px solid var(--border)",background:C?"rgba(248,113,113,0.05)":"var(--bg-subtle)",transition:"border-color 0.15s ease"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u,"data-step-trigger":"",onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,opacity:.85,transform:"translateY(0.5px)"},children:(0,r.jsx)(n9,{toolName:e.toolName,isError:C,size:12})}),(0,r.jsx)("span",{style:{color:C?"#f87171":"var(--text)",fontFamily:"var(--font-mono)",fontWeight:500,fontSize:11,lineHeight:1.35,flexShrink:0},children:y}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,opacity:.85,lineHeight:1.35},children:f?c("chat.generatingToolInput"):function(e){let t=e.input;if(!t||"object"!=typeof t)return"";let n=Object.keys(t);return 0===n.length?"":"command"in t?String(t.command).slice(0,120):"path"in t?String(t.path).slice(0,120):"file_path"in t?String(t.file_path).slice(0,120):"pattern"in t?String(t.pattern).slice(0,120):"query"in t?String(t.query).slice(0,120):String(t[n[0]]).slice(0,120)}(e)}),(0,r.jsx)(rv,{seconds:n,startTime:o,live:s}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:u?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),E&&l&&(0,r.jsx)("button",{type:"button",onClick:()=>l(E.sessionId),title:c("subagent.open"),"aria-label":c("subagent.open"),style:{width:30,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})})]}),u&&(f||!g)&&!m&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg)",borderTop:C?"1px solid rgba(239,68,68,0.25)":"1px solid color-mix(in srgb, var(--border) 80%, transparent)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:p}),u&&m&&void 0!==x&&(0,r.jsx)("div",{style:{borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)(rE,{patch:x})}),u&&m&&void 0===x&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(11.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:c("chat.generatingToolInput")}),u&&t&&!(m&&void 0!==x)&&(b?(0,r.jsx)(rS,{diff:b}):(0,r.jsx)(rL,{text:k??"",images:j,isEmpty:S,isError:C})),!u&&j.length>0&&(0,r.jsx)("div",{style:{padding:"6px 10px 8px",borderTop:C?"1px solid rgba(239,68,68,0.25)":"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:(0,r.jsx)(rj,{images:j,thumbnails:!0})})})]})}function rj({images:e,thumbnails:t=!1}){return(0,r.jsx)(r.Fragment,{children:e.map((e,n)=>{let i=rH(e);return i?(0,r.jsx)(eh,{src:i,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:i,alt:"",loading:"lazy",style:{display:"block",borderRadius:6,objectFit:"contain",border:"1px solid var(--border)",...t?{maxWidth:220,maxHeight:150}:{maxWidth:"min(100%, 720px)",maxHeight:520}}})},`${i}-${n}`):null})})}function rS({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(rC,{text:e.text})})}function rC({text:e}){let t=(0,i.useMemo)(()=>rn(e),[e]);return t?(0,r.jsx)(rN,{files:t}):(0,r.jsx)(rT,{text:e})}function rE({patch:e}){let t=(0,i.useMemo)(()=>nt(e),[e]);return t?(0,r.jsx)(rN,{files:t.map(e=>({oldPath:"add"===e.operation?void 0:e.path,newPath:"delete"===e.operation?void 0:e.moveTo??e.path,rows:e.rows}))}):(0,r.jsx)(rT,{text:e})}function rN({files:e}){let{t}=(0,w.s)(),n=e.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:e.map((e,i)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===i?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(rI,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rI,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(rM,{cell:e.left,side:"left"}),(0,r.jsx)(rM,{cell:e.right,side:"right"})]},t))})]},i))})}function rI({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function rM({cell:e,side:t}){let n="added"===e.type?"rgba(34,197,94,0.12)":"removed"===e.type?"rgba(248,113,113,0.13)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"#22c55e":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:o,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function rT({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{maxHeight:520,overflowY:"auto",overflowX:"hidden",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"rgba(34,197,94,0.12)":"removed"===n?"rgba(248,113,113,0.13)":"hunk"===n?"rgba(96,165,250,0.12)":"transparent",borderLeft:"added"===n?"3px solid #22c55e":"removed"===n?"3px solid #f87171":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"#22c55e":"removed"===n?"#f87171":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function rL({text:e,images:t,isEmpty:n,isError:i}){let{t:o}=(0,w.s)(),s=!n||0===t.length;return(0,r.jsxs)("div",{style:{borderTop:`1px solid ${i?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:i?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:[t.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)"},children:(0,r.jsx)(rj,{images:t})}),s&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?o("i18n.noOutput"):e})]})}function rR({message:e}){let{t}=(0,w.s)(),n=rA(e.content),o=(0,i.useMemo)(()=>{let e,t,r,i,o;return e=[],t=[],r=n.match(rt),i=r?.[1]??"",o=r?.index===void 0?n:n.slice(0,r.index),i.replace(re,(n,r,i)=>{let o=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...o):t.push(...o),""}),{body:o.trim(),readFiles:e,modifiedFiles:t}},[n]),s=ru(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:t("i18n.compactionDescription")}),o.body?(0,r.jsx)(n7,{className:"markdown-compaction-message",children:o.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(r$,{readFiles:o.readFiles,modifiedFiles:o.modifiedFiles})]})]})})}function r$({readFiles:e,modifiedFiles:t}){let{t:n}=(0,w.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(rW,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rW,{title:n("i18n.readFiles"),files:e})]})}function rW({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function rz({message:e,cwd:t,onOpenFile:n}){let{t:o}=(0,w.s)(),[s,l]=(0,i.useState)(!1),a=(e.details?.sessionIds??[]).length||1,d=1===a?o("subagent.notificationSingle"):o("subagent.notificationMany",{count:a}),c=rA(e.content);return(0,r.jsxs)("div",{"data-step-card":"",style:{overflow:"hidden",borderRadius:4},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":s,"data-step-trigger":"",title:d,onClick:()=>l(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:24,padding:"3px 8px",border:"none",background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{width:14,height:14,display:"grid",placeItems:"center",flexShrink:0},children:(0,r.jsx)(X,{size:12,strokeWidth:2})}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:500},children:d}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,transform:s?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),s&&c&&(0,r.jsx)("div",{style:{padding:"7px 10px 8px 28px",borderTop:"1px solid color-mix(in srgb, var(--border) 65%, transparent)",color:"var(--text-muted)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.48},children:(0,r.jsx)(rd,{className:"markdown-subagent-notification",cwd:t,onOpenFile:n,children:c})})]})}function rP({message:e,cwd:t,onOpenFile:n}){let o,{t:s}=(0,w.s)(),l=!1===e.display,[a,d]=(0,i.useState)(!l),[c,u]=(0,i.useState)(!1),[h,p]=(0,i.useState)(!1),f=rA(e.content),g=rD(e.content),m=void 0!==e.details,x=m?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",v=e.customType||"extension",y=ru(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:l?"var(--bg-subtle)":"var(--bg)",opacity:l&&!a?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:v}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:s("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),a?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=rH(e);return n?(0,r.jsx)(eh,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),f?(0,r.jsx)(n7,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:s("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(o=f.replace(/\s+/g," ").trim())?o.length>140?`${o.slice(0,140)}...`:o:"Show extension message":s("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||x?(0,r.jsx)("button",{onClick:()=>{n4(f||x).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:s(h?"i18n.copied":"i18n.copy")}):null,(m||l)&&(0,r.jsx)("button",{onClick:()=>{l?d(e=>!e):u(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:s(l?a?"i18n.collapse":"i18n.expand":c?"i18n.hideDetails":"i18n.showDetails")})]}),m&&(l&&a||!l&&c)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:x})]})})}function rA(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rD(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function rH(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}function rB({message:e,sessionId:t}){let[n,o]=(0,i.useState)(null),[s,l]=(0,i.useState)(!1),[a,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,h=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,p=e.truncated&&h&&null===n,f=n??e.output;async function g(){if(h){l(!0),d(null);try{let e=await fetch(h),t=await e.json();t.success?o(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{l(!1)}}}let m=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:m,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:m,content:f?[{type:"text",text:f}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rk,{block:x,result:v}),e.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[p&&(0,r.jsx)("button",{onClick:g,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${h}&download=1`,style:{marginLeft:10*!!p,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),a&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",a,")"]})]})]})}function rF(e,t){let n=new Set(e),r=new Map,i=t.find(e=>n.has(e)),o=void 0===i?e.length:e.indexOf(i),s=e[o-1]??null;for(let e of t)n.has(e)&&(s=e),null!==s&&r.set(e,s);for(let t of e)r.set(t,t);return r}function rO(e,t,n){return n-t>0&&e+t>=n-8?1/0:e+48}function rU(e,t){if(!e.length)return null;let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;e[i].top<=t?n=i+1:r=i}return e[Math.max(0,n-1)].userId}var r_=n(88576),rq=n.n(r_);function rK({items:e,activeEntryId:t,onJumpToEntry:n,label:o,left:s,top:l,maxHeight:a=360,width:d=310}){var c,u;let h,p,f,{t:g}=(0,w.s)(),m=(0,i.useRef)(null),x=(0,i.useRef)(null),[v,y]=(0,i.useState)(!1),[b,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(0),[C,E]=(0,i.useState)(null),N=(0,i.useRef)(0),I=(0,i.useRef)(null),M=(0,i.useRef)(!1),T=(0,i.useRef)(null),L=(0,i.useRef)(null),R=(0,i.useRef)(null),$=(0,i.useId)(),W=e.findIndex(e=>e.entryId===t),z={start:h=Math.max(0,Math.min(W-Math.floor(7.5),(c=e.length)-15)),end:Math.min(c,h+15)},P=Math.min(28*e.length,a-28*(C?.state==="error")),{start:A,end:D}=(u=e.length,p=Math.min(P,28*u),{start:Math.max(0,Math.floor((f=Math.max(0,Math.min(b,28*u-p)))/28)-1),end:Math.min(u,Math.ceil((f+p)/28)+1)});(0,i.useEffect)(()=>()=>{N.current++,T.current&&clearTimeout(T.current),L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current)},[]);let H=(0,i.useCallback)(()=>{T.current&&clearTimeout(T.current),L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),I.current=null,y(!1)},[]),B=(0,i.useCallback)(()=>{L.current&&(clearTimeout(L.current),L.current=null),v||(T.current=setTimeout(()=>{y(!0)},100))},[v]),F=(0,i.useCallback)(e=>{T.current&&(clearTimeout(T.current),T.current=null);let t=document.activeElement;t instanceof HTMLElement&&e.currentTarget.contains(t)&&t.matches(":focus-visible")||(L.current=setTimeout(()=>{H()},150))},[H]);async function O(e){let t=++N.current;E({entryId:e,state:"loading"});try{await n(e),N.current===t&&(E(null),R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{H()},160))}catch(n){if(N.current!==t)return;if(n&&"object"==typeof n&&"name"in n&&"AbortError"===n.name)return void E(null);E({entryId:e,state:"error",message:n instanceof Error?n.message:String(n)})}}function U(t){let n=Math.max(0,Math.min(e.length-1,t));I.current=n,S(n);let r=x.current;if(r){var i;let e;i=r.scrollTop,r.scrollTop=(e=28*n)<i?e:e+28>i+P?e+28-P:i,k(r.scrollTop);let t=r.querySelector(`[data-outline-index="${n}"]`);t&&(I.current=null,t.focus({preventScroll:!0}))}y(!0)}return((0,i.useLayoutEffect)(()=>{if(!v){M.current=!1;return}let e=x.current;if(e){if(!M.current){let t=Math.max(0,W);e.scrollTop=Math.max(0,(t+.5)*28-P/2),S(t),M.current=!0}k(e.scrollTop)}},[v,W,P]),(0,i.useLayoutEffect)(()=>{if(!v||null===I.current)return;let e=x.current?.querySelector(`[data-outline-index="${I.current}"]`);e&&(I.current=null,e.focus({preventScroll:!0}))}),e.length)?(0,r.jsxs)("div",{className:rq().minimap,style:{left:s,top:l},onMouseEnter:B,onMouseLeave:F,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||H()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),H(),m.current?.focus({preventScroll:!0}))},children:[(0,r.jsx)("button",{ref:m,type:"button",className:rq().trigger,style:{height:Math.min(a,Math.max(20,(z.end-z.start)*8+6))},"aria-label":o,"aria-expanded":v,"aria-controls":v?$:void 0,"aria-busy":C?.state==="loading"||void 0,onClick:e=>{0===e.detail?U(Math.max(0,W)):(T.current&&clearTimeout(T.current),L.current&&clearTimeout(L.current),y(e=>!e))},onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),U(Math.max(0,W)))},children:e.slice(z.start,z.end).map((e,n)=>(0,r.jsx)("span",{className:rq().marker,"data-marker-index":z.start+n,"data-active":t===e.entryId?"true":void 0,"aria-hidden":"true"},e.entryId))}),v&&(0,r.jsx)("div",{className:rq().panel,style:{width:d},children:(0,r.jsxs)("nav",{id:$,className:rq().menu,"aria-label":o,children:[(0,r.jsx)("div",{ref:x,className:rq().list,style:{height:P},onScroll:e=>k(e.currentTarget.scrollTop),children:(0,r.jsx)("div",{className:rq().track,style:{height:28*e.length},children:e.slice(A,D).map((n,i)=>{let o=A+i;return(0,r.jsx)("button",{type:"button",className:rq().row,style:{top:28*o},"data-outline-index":o,"aria-current":t===n.entryId?"location":void 0,"aria-label":n.preview,tabIndex:o===(j>=A&&j<D?j:A)?0:-1,onFocus:()=>S(o),onKeyDown:t=>{let n={ArrowDown:o+1,ArrowUp:o-1,Home:0,End:e.length-1,PageDown:o+Math.max(1,Math.floor(P/28)),PageUp:o-Math.max(1,Math.floor(P/28))};t.key in n&&(t.preventDefault(),U(n[t.key]))},onClick:()=>{O(n.entryId)},children:(0,r.jsx)("span",{className:rq().rowText,children:n.preview})},n.entryId)})})}),C?.state==="error"&&(0,r.jsxs)("div",{className:rq().status,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{children:`${g("chatMinimap.jumpFailed")||"跳转失败:"}${C.message||"请重试"}`}),(0,r.jsx)("button",{type:"button",onClick:()=>{O(C.entryId)},children:g("chatMinimap.retry")||"重试"})]})]})})]}):null}function rV({items:e,scrollContainer:t,contentContainer:n,loadedEntryIds:o,onJumpToEntry:s,label:l}){let[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),h=(0,i.useMemo)(()=>rF(e.map(e=>e.entryId),o),[e,o]);return((0,i.useEffect)(()=>{let r=t.current,i=n.current;if(!r||!i)return;let o=0,s=!0,l=[],a=[],c=new ResizeObserver(()=>f()),p=()=>{o||(o=requestAnimationFrame(g))},f=()=>{s=!0,p()};function g(){if(o=0,s){s=!1;let t=r.getBoundingClientRect(),n=Math.max(0,t.top),o=Math.min(window.innerHeight,t.bottom),d=Math.min(window.innerWidth,t.right),p=Math.max(0,Math.min(360,o-n-16)),f={left:d-26,top:(n+o-Math.min(p,Math.max(20,8*Math.min(15,e.length)+6)))/2,maxHeight:p,width:Math.max(0,Math.min(310,d-Math.max(0,t.left)-36))};u(e=>e&&e.left===f.left&&e.top===f.top&&e.maxHeight===p&&e.width===f.width?e:f);let g=Array.from(i.children).filter(e=>e instanceof HTMLElement&&e.hasAttribute("data-entry-id"));l=g.flatMap(e=>{let n=h.get(e.dataset.entryId);return n?[{userId:n,top:e.getBoundingClientRect().top-t.top-r.clientTop+r.scrollTop}]:[]}).sort((e,t)=>e.top-t.top);let m=new Set(g),x=new Set(a);for(let e of a)m.has(e)||c.unobserve(e);for(let e of g)x.has(e)||c.observe(e);a=g}d(rU(l,rO(r.scrollTop,r.clientHeight,r.scrollHeight)))}c.observe(r),c.observe(i);let m=new MutationObserver(f);m.observe(i,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),r.addEventListener("scroll",p,{passive:!0}),window.addEventListener("resize",f);let x=e=>{e.target!==r&&e.target instanceof Node&&e.target.contains(r)&&f()};return window.addEventListener("scroll",x,!0),p(),()=>{cancelAnimationFrame(o),c.disconnect(),m.disconnect(),r.removeEventListener("scroll",p),window.removeEventListener("resize",f),window.removeEventListener("scroll",x,!0)}},[e.length,h,t,n]),!c||c.maxHeight<52||c.width<80)?null:(0,I.createPortal)((0,r.jsx)(rK,{items:e,activeEntryId:a,onJumpToEntry:s,label:l,...c}),document.body)}function rJ(e,t,n){let r=JSON.stringify([e,t]),[o,s]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return;let n=new AbortController,i=new URLSearchParams;t&&i.set("leafId",t);let o=i.toString();return fetch(`/api/sessions/${encodeURIComponent(e)}/outline${o?`?${o}`:""}`,{signal:n.signal}).then(async e=>e.ok?e.json():{items:[]}).then(e=>{n.signal.aborted||s({key:r,items:e.items??[]})}).catch(()=>{n.signal.aborted||s({key:r,items:[]})}),()=>n.abort()},[e,t,n,r]),e&&o?.key===r)?o.items:[]}function rY({sessionId:e,leafId:t,outlineRevision:n,...i}){let{t:o}=(0,w.s)(),s=rJ(e,t,n);return e&&s.length?(0,r.jsx)(rV,{...i,items:s,label:o("chatMinimap.userOutline")},JSON.stringify([e,t])):null}function rZ({sessionId:e,leafId:t,outlineRevision:n,scrollContainer:o,contentContainer:s,loadedEntryIds:l,onJumpToEntry:a}){let{t:d}=(0,w.s)(),c=rJ(e,t,n),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(null),g=(0,i.useRef)(null);return((0,i.useEffect)(()=>{let e=()=>h(e=>!e);return window.addEventListener("pi-toggle-outline",e),()=>window.removeEventListener("pi-toggle-outline",e)},[]),(0,i.useEffect)(()=>{if(!u||!c.length||!o?.current||!s?.current)return;let e=o.current,t=s.current,n=rF(c.map(e=>e.entryId),l??[]),r=e.getBoundingClientRect(),i=[];for(let o of t.children)if(o instanceof HTMLElement&&o.dataset.entryId){let t=n.get(o.dataset.entryId);t&&i.push({userId:t,top:o.getBoundingClientRect().top-r.top-e.clientTop+e.scrollTop})}i.sort((e,t)=>e.top-t.top),f(rU(i,rO(e.scrollTop,e.clientHeight,e.scrollHeight)))},[u,c,l,o,s]),(0,i.useEffect)(()=>{u&&g.current&&g.current.scrollIntoView({block:"center"})},[u,p]),u&&c.length&&!("u"<typeof document))?(0,I.createPortal)((0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"fixed inset-0 z-[120] bg-black/50 transition-opacity",onClick:()=>h(!1),"aria-hidden":"true"}),(0,r.jsx)("section",{className:"fixed bottom-0 left-0 right-0 z-[121] flex max-h-[72dvh] flex-col overflow-hidden rounded-t-[16px] border-t border-[var(--border)] bg-[var(--bg-panel)] shadow-2xl pb-[max(12px,env(safe-area-inset-bottom))]",role:"dialog","aria-modal":"true","aria-label":d("i18n.outline")||"目录",children:(0,r.jsx)("div",{className:"flex-1 overflow-y-auto overscroll-contain px-2 py-2.5 space-y-0.5",children:c.map((e,t)=>{let n=p===e.entryId;return(0,r.jsxs)("button",{ref:n?g:void 0,type:"button",className:`relative flex w-full items-start gap-2.5 rounded-[4px] py-2 pl-2.5 pr-2 text-left transition-colors [-webkit-tap-highlight-color:transparent] ${n?"bg-[var(--bg-selected)] font-medium text-[var(--text)] before:absolute before:left-0 before:top-1.5 before:bottom-1.5 before:w-[2.5px] before:rounded-r-[1.5px] before:bg-[var(--accent)]":"text-[var(--text)] hover:bg-[var(--bg-hover)] active:bg-[var(--bg-hover)]"}`,"aria-current":n?"location":void 0,onClick:()=>{h(!1),a(e.entryId)},children:[(0,r.jsx)("span",{className:`w-5 shrink-0 text-right tabular-nums text-[13px] leading-5 select-none ${n?"font-semibold text-[var(--accent)]":"text-[var(--text-dim)]"}`,"aria-hidden":"true",children:t+1}),(0,r.jsx)("span",{className:"flex-1 min-w-0 line-clamp-2 text-[13px] leading-5",style:{hangingPunctuation:"first"},children:e.preview})]},e.entryId)})})})]}),document.body):null}var rX=n(42790);function rG({text:e}){let t=(0,i.useMemo)(()=>new rX.v().ansi_to_html(e),[e]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:t}})}let rQ="/icons/icon-192.png";function r0(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function r1(e){let t;if("u"<typeof Notification)return()=>{};e(Notification.permission);let n="u"<typeof navigator?void 0:navigator.permissions;if(!n?.query)return()=>{};let r=!1;return n.query({name:"notifications"}).then(n=>{r||(t=n,n.onchange=()=>e(Notification.permission))}).catch(()=>{}),()=>{r=!0,t&&(t.onchange=null)}}function r2(e){switch(e.method){case"select":case"confirm":case"input":case"editor":return!0;case"custom":return!0!==e.closed;default:return!1}}async function r4(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,icon:rQ,badge:rQ,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}function r8(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r5(e,t={}){if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e,t={}){if(!r8(e)||"toolCall"!==e.type)return null;let n={type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input},r=t.includeStreamingRawInput?function(e){if("string"==typeof e.rawInput)return e.rawInput;if("string"==typeof e.partialJson)return e.partialJson;if("string"==typeof e.partialArgs)return e.partialArgs;let t=r8(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=r8(e.arguments)?e.arguments:null;return n&&r&&"string"==typeof r[n]?r[n]:void 0}(e):void 0;return void 0===r?n:{...n,rawInput:r}})(e,t)??e);return{...e,content:r}}class r6 extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function r3(e){return e instanceof r6&&"prompt_rejected"===e.code&&!1===e.accepted}async function r7(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new r6(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let r9=["off","minimal","low","medium","high","xhigh","max"],ie="pi-tool-preset";function it(){try{return window.localStorage}catch{return null}}function ir(e,t){t&&(e.tokens.input+=t.input??0,e.tokens.output+=t.output??0,e.tokens.cacheRead+=t.cacheRead??0,e.tokens.cacheWrite+=t.cacheWrite??0,e.cost+=t.cost?.total??0)}function ii(e){let t={userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0};for(let n of e)"custom"!==n.role&&(t.totalMessages+=1,"user"===n.role?t.userMessages+=1:"toolResult"===n.role?(t.toolResults+=1,ir(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),ir(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function io(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function is(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(io).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class il extends Error{constructor(e,t){super(t??("ready_timeout"===e?"Timed out starting the agent session. Please try again.":"Failed to connect to the agent event stream. Please try again.")),this.status=e,this.name="AgentEventConnectionError"}}class ia{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0,this.epoch=0}close(){this.epoch+=1,this.stopRetrying(),this.current&&this.discard(this.current,new il("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof il?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}reconnect(e){return this.ensureConnected(e,!0)}async ensureConnected(e,t=!1){let n=this.epoch,r=t;for(;;){if(this.epoch!==n)throw new il("closed");let t=this.current;if(!t||t.sessionId!==e||r)r=!1,t=this.open(e);else if(t.attempt.ready&&1===t.source.readyState)return;try{await t.attempt.promise}catch(r){if(this.epoch!==n)throw r;if(this.current!==t&&this.current?.sessionId===e)continue;throw r}if(this.epoch!==n)throw new il("closed");if(this.current!==t){if(this.current?.sessionId===e)continue;throw new il("closed")}if(1===t.source.readyState)return;this.discard(t,new il("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new il("closed"));try{t=this.options.createSource(e)}catch(e){throw new il("closed",e instanceof Error?e.message:String(e))}let i=!1,o=new Promise((e,t)=>{n=e,r=t}),s=setTimeout(()=>{this.fail(a,new il("ready_timeout"))},this.options.readinessTimeoutMs),l={promise:o,ready:!1,succeed(){i||(i=!0,clearTimeout(s),n())},fail(e){i||(i=!0,clearTimeout(s),r(e))}},a={sessionId:e,source:t,attempt:l};return this.current=a,t.onmessage=e=>{let t;if(this.current===a){try{t=JSON.parse(e.data)}catch{return}if("connected"===t.type)l.ready=!0,l.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(a,new il("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new il("closed"))},a}fail(e,t){this.current===e&&(this.discard(e,t),"startup_error"===t.status?this.stopRetrying():this.scheduleRetry(e.sessionId))}discard(e,t){e.attempt.fail(t),e.source.close(),this.current===e&&(this.current=null)}scheduleRetry(e){if(!this.options.shouldMaintain(e)||this.retry?.sessionId===e)return;this.clearRetry();let t=setTimeout(()=>{this.retry?.timer===t&&(this.retry=null,this.maintain(e))},this.options.reconnectDelayMs);this.retry={sessionId:e,timer:t}}stopRetrying(){this.retryGeneration+=1,this.clearRetry()}clearRetry(){this.retry&&clearTimeout(this.retry.timer),this.retry=null}}function id(e){var t;return("message_start"===e.type||"message_end"===e.type)&&"object"==typeof(t=e.message)&&null!==t&&!Array.isArray(t)&&"system"===e.message.role}let ic={isStreaming:!1,streamingMessage:null};function iu(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],o=n(i[t]);return o?(i[t]=o,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function ih(e,t){switch(t.type){case"text_start":return iu(e,t.contentIndex,()=>({type:"text",text:""}));case"text_delta":return iu(e,t.contentIndex,e=>e?.type==="text"?{...e,text:e.text+t.delta}:null);case"text_end":return iu(e,t.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:t.content}));case"thinking_start":{let n=Date.now(),r=e.streamingMessage;if(!r)return e;let i=[...r.content];for(let e=0;e<i.length;e++){let r=i[e];e!==t.contentIndex&&r?.type==="thinking"&&"number"!=typeof r.endedAt&&(i[e]={...r,endedAt:n})}return i[t.contentIndex]={type:"thinking",thinking:"",startedAt:n},{isStreaming:!0,streamingMessage:{...r,content:i}}}case"thinking_delta":return iu(e,t.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+t.delta,startedAt:e.startedAt??Date.now()}:null);case"thinking_end":return iu(e,t.contentIndex,e=>({...e?.type==="thinking"?e:{startedAt:Date.now()},type:"thinking",thinking:t.content,endedAt:Date.now()}));case"toolcall_start":return iu(e,t.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:t.id??e.toolCallId,toolName:t.toolName??e.toolName,rawInput:""}:"string"!=typeof t.toolName?null:{type:"toolCall",toolCallId:t.id??"",toolName:t.toolName,input:{},rawInput:""});case"toolcall_delta":return iu(e,t.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:t.id||e.toolCallId,toolName:t.toolName||e.toolName,rawInput:(e.rawInput??"")+t.delta}:null);case"toolcall_end":return iu(e,t.contentIndex,()=>({type:"toolCall",toolCallId:t.toolCall.id,toolName:t.toolCall.name,input:t.toolCall.arguments}));default:return e}}function ip(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=r5(t.message,{includeStreamingRawInput:!0});if("assistant"!==n.role)return e;let r="number"==typeof n.timestamp?n.timestamp:Date.now(),i=e.streamingMessage,o=n.content.map((e,t)=>{if("thinking"!==e.type)return e;let n=i?.content[t],o=e.startedAt??(n?.type==="thinking"?n.startedAt:void 0)??r,s=e.endedAt??(n?.type==="thinking"?n.endedAt:void 0);return e.startedAt===o&&e.endedAt===s?e:{...e,startedAt:o,..."number"==typeof s?{endedAt:s}:{}}});return{isStreaming:!0,streamingMessage:{...n,timestamp:r,content:o}}}case"delta":return ih(e,t.event);case"deltas":return t.events.reduce(ih,e);case"end":return ic;default:return e}}class ig{begin(e){this.inFlight.add(e)}cancel(e){this.cancelled.add(e)}markDispatched(e){this.dispatched.add(e)}isCancelled(e){return this.cancelled.has(e)}wasDispatched(e){return this.dispatched.has(e)}isInFlight(e){return this.inFlight.has(e)}shouldAbandonUnsent(e){return this.isCancelled(e)&&!this.wasDispatched(e)}forget(e){this.cancelled.delete(e),this.dispatched.delete(e),this.inFlight.delete(e)}constructor(){this.cancelled=new Set,this.dispatched=new Set,this.inFlight=new Set}}function im(e,t,n,r){return e===t&&"string"==typeof n&&n.length>0&&n===r}async function ix(e){let{gate:t,runId:n}=e;t.begin(n);let r=()=>!(!t.isCancelled(n)||t.wasDispatched(n))&&(e.abandonUnsent(),!0),i=null,o=!1;try{if(r()||(i=await e.prepare(),r()))return{status:"abandoned"};if(!i)throw Error("No active session for the prompt");if(o=!0,t.markDispatched(n),e.onDispatched?.(),await e.send(i),!t.isCancelled(n))return{status:"sent",sessionId:i};if(e.promptPending()&&im(n,e.currentRunId(),i,e.currentSessionId()))return await e.abort(i),{status:"aborted",sessionId:i};return{status:"stale"}}catch(r){if(!t.isCancelled(n))return{status:"failed",sessionId:i,error:r,requestStarted:o};if(!o)return e.abandonUnsent(),{status:"abandoned"};if(e.promptPending()&&im(n,e.currentRunId(),i,e.currentSessionId()))return{status:"cancelled_after_dispatch",sessionId:i};return{status:"stale"}}finally{t.forget(n)}}async function iv(e){let t=null,n=!1;try{if(t=await e.prepare(),e.abortRequested())return e.restoreUnsent(),{status:"restored_unsent"};if(!t)throw Error("Unable to create a session for the shell command");return n=!0,await e.send(t),await e.loadResults(t),e.abortRequested()?{status:"cancelled_after_dispatch",sessionId:t}:{status:"completed",sessionId:t}}catch(r){if(!e.abortRequested())throw r;if(!n)return e.restoreUnsent(),{status:"restored_unsent"};if(t)try{await e.loadResults(t)}catch{}return{status:"cancelled_after_dispatch",sessionId:t}}}function iy(e){return(e??[]).map(e=>"string"==typeof e?{text:e,images:[]}:{text:"string"==typeof e.text?e.text:"",images:Array.isArray(e.images)?e.images.flatMap(e=>{let t=e&&"object"==typeof e&&"string"==typeof e.data&&0!==e.data.length&&"string"==typeof e.mimeType&&e.mimeType.startsWith("image/")?{data:e.data,mimeType:e.mimeType}:null;return t?[t]:[]}):[]})}let ib=new Map,iw=new Map;function ik(e){return"string"==typeof e?e:e?.text??""}function ij(e){return{steering:(e?.steering??[]).map(ik),followUp:(e?.followUp??[]).map(ik)}}function iS(e,t){return e===t||null!==e&&null!==t&&e.tokens===t.tokens&&e.percent===t.percent&&e.contextWindow===t.contextWindow?e:t}let iC=[2e3,5e3,1e4];function iE(e){return new Promise(t=>setTimeout(t,e))}function iN(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iI(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:iN(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iN(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=iN(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function iM(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function iT(e){if(!e?.defaultModel)return null;let t=e.modelList?.find(t=>t.id===e.defaultModel?.modelId&&t.provider===e.defaultModel?.provider);return t?{provider:t.provider,modelId:t.id}:null}function iL({showCurrentVersion:e=!1}){let{t}=(0,w.s)(),[n,o]=(0,i.useState)(null),[s,l]=(0,i.useState)(!1),[a,d]=(0,i.useState)("idle"),[c,u]=(0,i.useState)(null),h=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e;if("waiting"!==a||!n)return;let t=new AbortController,r=!1,i=setTimeout(()=>{r=!0,t.abort(),clearTimeout(e),d("timeout")},18e4),o=async()=>{try{let e=await fetch("/api/app-update?status=1",{cache:"no-store",signal:t.signal});if(e.ok){let t=await e.json();if(!r&&t.currentVersion&&t.currentVersion!==n.currentVersion){r=!0,clearTimeout(i),window.location.reload();return}}}catch{}r||(e=setTimeout(()=>{o()},2e3))};return o(),()=>{r=!0,t.abort(),clearTimeout(i),clearTimeout(e)}},[a,n]);let p=async()=>{if(!h.current&&window.confirm(t("appUpdate.confirm"))){h.current=!0,u(null),d("requesting");try{let e=await fetch("/api/app-update",{method:"POST"});if(202!==e.status){let n=await e.json().catch(()=>null);throw Error(n?.error||t("appUpdate.failed"))}d("waiting")}catch(e){u(e instanceof Error?e.message:t("appUpdate.failed")),d("idle"),h.current=!1}}};(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/app-update",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}).then(e=>{o(e)}).catch(()=>{e.signal.aborted||l(!0)}),()=>e.abort()},[]);let f=n?.updateAvailable&&n.latestVersion&&n.releaseUrl;if(!e&&!f)return null;let g=t("appUpdate.releaseNotes",{version:n?.latestVersion??""});return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:e?"flex-start":"center",gap:6},children:[e&&(0,r.jsxs)("p",{style:{fontSize:12},children:[t("appUpdate.currentVersion",{version:n?.currentVersion??"1.1.6"??"dev"}),!f&&(0,r.jsxs)("span",{role:"status",style:{color:"var(--text-muted)"},children:[" \xb7 ",t(s?"appUpdate.checkFailed":n?n.releaseUrl?"appUpdate.upToDate":"appUpdate.checkDisabled":"appUpdate.checking")]})]}),f&&n&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("a",{href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:g,"aria-label":g,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},style:{display:"inline-flex",alignItems:"center",alignSelf:"center",gap:3,minHeight:32,minWidth:0,padding:"0 4px",background:"transparent",borderRadius:4,color:"var(--accent)",fontSize:12,fontWeight:600,lineHeight:1.2,textDecoration:"none",transition:"background 0.12s",whiteSpace:"nowrap"},children:[(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:["v",n.latestVersion]}),(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]}),n.canUpdate&&(0,r.jsx)("button",{type:"button",disabled:"idle"!==a,onClick:()=>{p()},style:{color:"var(--accent)",fontSize:12,cursor:"idle"===a?"pointer":"default"},children:t("appUpdate.updateAndRestart")})]}),e&&f&&!n?.canUpdate&&(0,r.jsx)("p",{style:{color:"var(--text-muted)",fontSize:12},children:t("appUpdate.manualUpdate")}),("requesting"===a||"waiting"===a)&&(0,r.jsx)("p",{role:"status",style:{color:"var(--text-muted)",fontSize:12},children:t("appUpdate.waiting")}),c&&(0,r.jsx)("p",{role:"alert",style:{color:"var(--text-muted)",fontSize:12},children:c}),"timeout"===a&&(0,r.jsxs)("div",{role:"alert",style:{color:"var(--text-muted)",fontSize:12,textAlign:"center"},children:[(0,r.jsx)("p",{children:t("appUpdate.timeout")}),(0,r.jsx)("code",{children:"npm install -g @calmabacus/pi-web@latest"}),(0,r.jsx)("p",{children:t("appUpdate.thenStart")}),(0,r.jsx)("code",{children:"pi-web"})]})]})}function iR(e,t){let n=e[0];for(let r of e){if(r.top>t)break;n=r}return n?{anchorEntryId:n.entryId,anchorOffset:n.top-t}:null}function i$({label:e}){return(0,r.jsx)("div",{role:"status","aria-label":e,className:"flex h-[28px] items-center",style:{marginBottom:8},children:(0,r.jsx)(Z,{size:12})})}function iW({cwd:e,onChange:t,recentPaths:n,pinnedPaths:o,onTogglePinnedCwd:s,homeDir:l,worktreeInfo:a}){let{t:d}=(0,w.s)(),c=(0,i.useRef)(null),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(null),k=[...o.map(e=>({path:e,pinned:!0})),...n.filter(e=>!o.includes(e)).map(e=>({path:e,pinned:!1}))],j=a&&(a.forCwd===e||a.projectRoot===e||a.currentWorktreePath===e||a.worktrees.some(t=>t.path===e))?a:null;(0,i.useEffect)(()=>{if(!u&&!p)return;let e=e=>{c.current?.contains(e.target)||(h(!1),f(!1))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[u,p]);let S=j?.worktrees??[],C=S.find(t=>t.path===e||t.path===j?.currentWorktreePath)??S.find(e=>e.isMain),E=C?.branch??null,N=j?.projectRoot??e,I=l&&N.startsWith(l)?`~${N.slice(l.length)}`:N,M=()=>{h(!1),f(!1)},T=n=>{n===e?M():(v(!0),t(n).then(M).finally(()=>v(!1)))};return(0,r.jsxs)("div",{ref:c,style:{position:"relative",marginTop:10,maxWidth:"100%",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",title:d("chat.changeWorkingDirectory"),"aria-label":`${d("chat.changeWorkingDirectory")}: ${N}`,"aria-expanded":u,onClick:()=>{h(e=>!e),f(!1)},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},style:{maxWidth:"min(80vw, 360px)",border:"none",background:"none",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.4,padding:0,cursor:"pointer"},children:(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"center"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:I})})}),E&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{color:"var(--text-dim)",fontSize:12,userSelect:"none"},children:"|"}),(0,r.jsx)("button",{type:"button",title:C?.path,"aria-label":`${d("sidebar.switchWorktree")}: ${E}`,"aria-expanded":p,onClick:()=>{f(e=>!e),h(!1)},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},style:{maxWidth:220,border:"none",background:"none",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.4,padding:0,cursor:"pointer",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E})]}),u&&(0,r.jsxs)("div",{role:"listbox","aria-label":d("chat.changeWorkingDirectory"),style:{position:"absolute",top:"calc(100% + 6px)",left:"50%",transform:"translateX(-50%)",width:"max-content",minWidth:200,maxWidth:"min(90vw, 260px)",zIndex:50,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden",textAlign:"left"},children:[(0,r.jsx)("div",{style:{maxHeight:280,overflowY:"auto"},children:k.map(({path:t,pinned:n})=>{let i=t===e||!!(j?.projectRoot&&t===j.projectRoot);return(0,r.jsxs)("div",{className:"project-pin-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":i,disabled:x,onClick:()=>T(t),title:t,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"8px 10px",background:"var(--bg)",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:x?"default":"pointer",fontSize:11,fontFamily:"var(--font-mono)",textAlign:"left"},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l&&t.startsWith(l)?`~${t.slice(l.length)}`:t})]}),(0,r.jsx)("button",{type:"button",className:"project-pin-btn",title:d(n?"sidebar.unpinDirectory":"sidebar.pinDirectory"),"aria-label":d(n?"sidebar.unpinDirectory":"sidebar.pinDirectory"),"aria-pressed":n,onClick:()=>s?.(t),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,marginRight:4,padding:0,background:"none",border:"none",borderRadius:4,cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:n?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12",y2:"22"}),(0,r.jsx)("path",{d:"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"})]})})]},t)})}),(0,r.jsx)("button",{type:"button",onClick:()=>{h(!1),m(!0),b(null)},style:{display:"block",width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,textAlign:"left"},children:d("sidebar.customPath")})]}),p&&S.length>0&&(0,r.jsx)("div",{role:"listbox","aria-label":d("sidebar.switchWorktree"),style:{position:"absolute",top:"calc(100% + 6px)",left:"50%",transform:"translateX(-50%)",width:"max-content",minWidth:180,maxWidth:"min(90vw, 260px)",zIndex:50,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden",textAlign:"left"},children:(0,r.jsx)("div",{style:{maxHeight:280,overflowY:"auto"},children:S.map(t=>{let n=t.path===e||t.path===j?.currentWorktreePath;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":!!n,disabled:x,onClick:()=>T(t.path),title:t.path,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"var(--bg)",border:"none",borderBottom:"1px solid var(--border)",color:n?"var(--text)":"var(--text-muted)",cursor:x?"default":"pointer",fontSize:11,fontFamily:"var(--font-mono)",textAlign:"left"},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.branch??t.path}),t.isMain&&(t.branch??"").toLowerCase()!==d("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:d("sidebar.main")})]},t.path)})})}),g&&(0,r.jsx)(R,{initialPath:e,busy:x,error:y,onCancel:()=>{m(!1),b(null)},onSelect:e=>{v(!0),b(null),t(e).then(()=>m(!1),e=>b(e instanceof Error?e.message:String(e))).finally(()=>v(!1))}})]})}function iz(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&t8(r))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}function iP(e){return e?.content.at(-1)}function iA(e,t,n,r,i=!1){if(!e)return!1;if(r?.kind==="running_tools")return!0;let o=iP(n);return!!t&&(o?.type==="thinking"||o?.type==="toolCall")||!i}function iD(e,t,n){if(!e)return null;let r=ew(e,t);return"edit"===r?n("image.edit"):"generate"===r?n("image.generate"):null}function iH(e,t,n){if(t?.kind==="running_tools"){let e=t.tools[t.tools.length-1]?.name??null;return iD(e,void 0,n)??e}let r=iP(e);return r?.type==="thinking"?n("chat.thinking"):r?.type==="toolCall"?iD(r.toolName,r.input,n)??r.toolName??null:null}function iB(e,t,n,r){return t?(e&&(n.current=e),n.current??r):(n.current=null,null)}function iF(e,t){if("number"==typeof e&&"number"==typeof t&&Number.isFinite(e)&&Number.isFinite(t)&&!(t<=e))return Math.max(1,Math.round((t-e)/1e3))}function iO({startTime:e,t}){let[n,o]=(0,i.useState)(()=>Math.max(0,Math.round((Date.now()-e)/1e3)));return(0,i.useEffect)(()=>{let t=setInterval(()=>{o(Math.max(0,Math.round((Date.now()-e)/1e3)))},500);return()=>clearInterval(t)},[e]),(0,r.jsx)("span",{style:{fontSize:11.5,color:"var(--accent)",fontVariantNumeric:"tabular-nums",flexShrink:0},children:(0,b.a3)(n,t)})}function iU({messageCount:e,toolCallCount:t,durationSeconds:n,startTime:o,defaultExpanded:s=!1,reveal:l=!1,isMobile:a=!1,activeStepSummary:d=null,isStreaming:c=!1,children:u,t:h}){let[p,f]=(0,i.useState)(s),g=(0,i.useRef)(null),m=(0,i.useRef)(!1),x=(0,i.useRef)(!1);(0,i.useLayoutEffect)(()=>{x.current||f(s)},[s]);let v=p||l,y=h(1===t?"chat.step":"chat.steps"),w=void 0!==n&&n>0?(0,b.a3)(n,h):null,k=w?t>0?h("chat.workedForSteps",{duration:w,count:t,steps:y}):h("chat.workedFor",{duration:w}):t>0?`${t} ${y}`:h("chat.processDetails");return(0,i.useLayoutEffect)(()=>{if(!v){m.current=!1;return}let e=g.current;!e||m.current||e.scrollHeight<=e.clientHeight+1||(e.scrollTop=e.scrollHeight)},[v,e,t]),(0,r.jsxs)("div",{style:{marginBottom:v?8:2},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":v,onClick:()=>{x.current=!0,f(e=>!e)},className:"process-details-summary",style:{display:"inline-flex",alignItems:"center",gap:5,maxWidth:"100%",minHeight:24,padding:"2px 0",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11.5,fontFamily:"var(--font-ui)",fontWeight:400,textAlign:"left",transition:"color 0.12s ease"},title:h(v?"chat.collapseProcess":"chat.expandProcess"),children:[c?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Z,{size:12}),o&&(0,r.jsx)(iO,{startTime:o,t:h}),(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,minWidth:0,fontSize:11.5,color:"var(--accent)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[o&&(0,r.jsx)("span",{style:{opacity:.5,color:"var(--text-dim)"},children:"\xb7"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d||h("chat.thinking")})]})]}):(0,r.jsx)("span",{"data-summary-label":"",style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:400,color:"inherit",lineHeight:1.35,transition:"color 0.12s ease"},children:k}),(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.45,display:"block",transform:v?"rotate(90deg)":"none",transition:"transform 0.15s ease"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3.5 2 6.5 5 3.5 8"})})]}),v&&(0,r.jsx)("div",{ref:g,onScroll:()=>{let e=g.current;e&&(m.current=!(e.scrollTop+e.clientHeight>=e.scrollHeight-20))},className:"process-details-list",style:{display:"flex",flexDirection:"column",gap:1,padding:"2px 0 4px 0",maxHeight:a?220:280,overflowY:"auto",overflowX:"hidden",overscrollBehavior:"contain",overflowAnchor:"none"},children:u})]})}function i_({session:e,searchTarget:t,onSearchTargetHandled:o,initialScrollPosition:s,onScrollPositionChange:l,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onDraftChange:u,onKeepTabOpen:h,onNewSessionCwdChange:p,recentProjectPaths:f=[],pinnedCwds:g=[],onTogglePinnedCwd:m,homeDir:x="",worktreeInfo:v=null,draftPersistenceWarning:y=!1,onAgentEnd:b,onAttentionNeeded:k,onSessionCreated:S,onSessionForked:C,modelsRefreshKey:E,chatInputRef:M,isFocusedPane:T=!1,isVisiblePane:L=T,onBranchDataChange:R,onSystemPromptChange:$,onSystemToolsChange:W,onSystemInfoLoaderChange:z,onSessionStatsChange:P,onSessionStatsPanelOpen:A,onContextUsageChange:D,onOpenFile:H,onOpenSession:B,onAskInNewChat:F,quoteSelectionEnabled:O=!1,initialPrompt:U,onInitialPromptConsumed:_,soundEnabled:q=!0,onSoundToggle:K,playDoneSound:V=()=>{},unlockAudio:J}){var Y;let Z,{t:X}=(0,w.s)(),G=eX(),Q=e?.relation?.kind!=="subagent",ee=(0,i.useRef)(V);ee.current=V;let et=(0,i.useRef)(q);et.current=q;let en=(0,i.useRef)(e);en.current=e;let er=(0,i.useRef)(null),ei=(0,i.useCallback)(e=>{let t=er.current;er.current=e,M&&(e?M.current=e:M.current===t&&(M.current=null))},[M]),eo=(0,i.useRef)(null),es=(0,i.useCallback)(()=>{Q&&et.current&&ee.current(),b?.(en.current)},[Q,b]),el=(0,i.useCallback)(e=>{k?.(e,en.current)},[k]),ea=(0,i.useCallback)(e=>{C?.(e,en.current?.id??null)},[C]),ed=(0,i.useCallback)((e,t)=>{H?.(e,en.current?.id??null,t)},[H]),ec=(0,i.useCallback)(()=>{let e=en.current?.id;e&&h?.(e)},[h]),eu=(0,i.useCallback)(e=>{er.current?.replaceMessage(e)},[]),eh=(0,i.useRef)(t?null:s??null),[ef,eg]=(0,i.useState)(()=>{let e=eh.current;return e&&!e.atBottom?e:null}),[em,ex]=(0,i.useState)(!1),{data:ev,loading:ey,error:ew,messages:ek,activeToolResults:ej,entryIds:eS,historyCursor:eC,hasEarlierMessages:eI,streamState:eM,agentRunning:eT,directImageRunning:eL,bashRunning:eR,pendingBash:e$,modelNames:eW,modelList:eA,modelError:eD,modelScopeWarnings:eH,modelThinkingLevels:eO,modelThinkingLevelMaps:eU,toolPreset:e_,thinkingLevel:eq,retryInfo:eK,contextUsage:eV,forkingEntryId:eJ,isCompacting:eY,compactError:eZ,compactResult:eG,displayModel:eQ,modelSwitching:e0,sessionStats:e1,slashCommands:e2,slashCommandsLoading:e4,queuedMessages:e8,notices:e5,extensionDialog:e6,extensionCustomUi:e3,respondToExtensionUi:e7,sendExtensionCustomInput:e9,addNotice:te,setNoticePaused:tt,isAutoModelSelection:tn,agentPhase:ti,isNew:to,sessionIdRef:ts,scrollContainerRef:tl,handleSend:ta,handleDirectImageGeneration:td,abortDirectImageGeneration:tc,handleAbort:tu,handleFork:th,handleNavigate:tp,handleModelChange:tf,handleCompact:tg,handleSteer:tm,handleFollowUp:tx,handlePromptWithStreamingBehavior:tv,handleAbortCompaction:ty,handleRecallQueue:tb,handleBuiltinSlashCommand:tw,handleToolPresetChange:tk,handleThinkingLevelChange:tj,loadSlashCommands:tS,loadContext:tC,activeLeafId:tE,scrollToBottom:tN,scrollToMessage:tI}=function(e){let{session:t,sessionRunning:r,newSessionCwd:o,newSessionDraftKey:s,onAgentEnd:l,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:h,onSystemPromptChange:p,onSystemToolsChange:f,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:m,isVisiblePane:x=!1}=e,v=null===t&&null!==o,y=o??t?.cwd??"",b=y?`/api/models?cwd=${encodeURIComponent(y)}`:"/api/models",w=ib.get(b)?.data,k=v?iT(w):null,j=k?w?.thinkingLevelPins?.[`${k.provider}/${k.modelId}`]:void 0,[S,C]=(0,i.useState)(null),[E,N]=(0,i.useState)(!v),[I,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(null),[R,$]=(0,i.useState)([]),[W,z]=(0,i.useState)(new Map),[P,A]=(0,i.useState)([]),[D,H]=(0,i.useState)(null),[B,F]=(0,i.useState)(!1),O=(0,i.useRef)({messages:R,entryIds:P,oldestEntryId:D,hasMore:B});O.current={messages:R,entryIds:P,oldestEntryId:D,hasMore:B};let[U,_]=(0,i.useReducer)(ip,ic),q=(0,i.useRef)(U);q.current=U;let[K,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),[Z,X]=(0,i.useState)(null),[G,Q]=(0,i.useState)(!1),ee=(0,i.useRef)(!1),et=(0,i.useRef)(null),en=(0,i.useRef)(!1),[er,ei]=(0,i.useState)(()=>w?.models??{}),[eo,es]=(0,i.useState)(()=>w?.modelList??[]),[el,ea]=(0,i.useState)(()=>w?.modelError??null),[ed,ec]=(0,i.useState)(()=>w?.modelScopeWarnings??[]),[eu,eh]=(0,i.useState)(()=>w?.thinkingLevels??{}),[ep,ef]=(0,i.useState)(()=>w?.thinkingLevelMaps??{}),[eg,em]=(0,i.useState)(()=>w?.thinkingLevelPins??{}),[ex,ev]=(0,i.useState)(null),[ey,eb]=(0,i.useState)(k),[ew,ek]=(0,i.useState)(tr.Q8),[ej,eS]=(0,i.useState)(j??"auto"),[eC,eE]=(0,i.useState)(null),[eN,eI]=(0,i.useState)(null),[eM,eT]=(0,i.useState)(null),[eL,eR]=(0,i.useState)(null),[e$,eW]=(0,i.useState)(null),[eA,eD]=(0,i.useState)(null),[eH,eO]=(0,i.useState)(!1),[eU,e_]=(0,i.useState)(!1),[eq,eK]=(0,i.useState)(!0),[eV,eJ]=(0,i.useState)(null),[eY,eZ]=(0,i.useState)(null),[eX,eG]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)([]),[e1,e2]=(0,i.useState)(!1),[e4,e8]=(0,i.useReducer)(iI,{visible:[],pending:[]}),[e5,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)({steering:[],followUp:[]}),ti=(0,i.useRef)(null),to=(0,i.useRef)(null),ts=(0,i.useRef)(0),tl=(0,i.useRef)(!1),ta=(0,i.useRef)(!1),td=(0,i.useRef)(t?.id??null),tc=(0,i.useRef)(t?.id??null),tu=(0,i.useRef)(!!r),th=(0,i.useRef)(x),tp=(0,i.useRef)(!1),tf=(0,i.useRef)(!1),tg=(0,i.useRef)(!1),tm=(0,i.useRef)(-1),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(!1),ty=(0,i.useRef)(0),tb=(0,i.useRef)(null),tw=(0,i.useRef)(!!e.deferInitialScroll),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(!0),tS=(0,i.useRef)(0),tC=(0,i.useRef)(null),tE=(0,i.useRef)([]),tN=(0,i.useRef)(void 0),tI=(0,i.useRef)(null),tM=(0,i.useRef)(null),tT=(0,i.useRef)(!1),tL=(0,i.useRef)(null),tR=(0,i.useRef)(null),t$=(0,i.useRef)(0),tW=(0,i.useRef)(new ig),tz=(0,i.useRef)(null),tP=(0,i.useRef)(!1),tA=(0,i.useRef)(null),tD=(0,i.useRef)(!1),tH=(0,i.useRef)(u),tB=(0,i.useRef)(new Map),tF=(0,i.useRef)(!0);tc.current=t?.id??null,tu.current=!!r,th.current=x,ti.current||(ti.current=new ia({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tb.current?.(e),shouldMaintain:e=>tF.current&&td.current===e&&(th.current||tp.current||tl.current||tc.current===e&&tu.current),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tO=e.setToolPreset??ek,tU=t?.id;(0,i.useLayoutEffect)(()=>{(tU||v&&!td.current)&&tO(function(e=it()){if(!e)return tr.Q8;try{let t=e.getItem(ie);return(0,tr.sn)(t)?t:tr.Q8}catch{return tr.Q8}}())},[tU,v,tO]);let t_=(0,i.useCallback)((e="instant")=>{let t=tI.current;t&&(tj.current=!0,t.scrollTo({top:Math.max(0,t.scrollHeight-t.clientHeight),behavior:e}),tS.current=t.scrollTop)},[]),tq=e$??S?.context.model??eA??null,tK=v?ex??ey:tq,tV=t?.id??s??void 0,tJ=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tB.current.get(t);if(!e)break;t=e}return t},[]),tY=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=tJ(r);if(!tF.current&&!tT.current&&r===s)return;let l=e.chatInputRef?.current;if(l)l.restoreSubmission(t,i,o);else{let e,n;o&&(n=eB(t,i,(e=ez(o)??{value:"",images:[]}).value,e.images),eP(o,n))}},[s,e.chatInputRef,tJ]),tZ=(0,i.useMemo)(()=>{if(e5)return{...e5,totalActiveMs:S?.totalActiveMs,...eN?{contextUsage:eN}:{}};let e=S?.stats,n=function(e,t,n){let r=ii(n);if(!e)return r;let i=ii(t),o=(e,t)=>Math.max(0,e-t),s={input:e.tokens.input+o(r.tokens.input,i.tokens.input),output:e.tokens.output+o(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+o(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+o(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return s.total=s.input+s.output+s.cacheRead+s.cacheWrite,{userMessages:e.userMessages+o(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+o(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+o(r.toolCalls,i.toolCalls),toolResults:e.toolResults+o(r.toolResults,i.toolResults),totalMessages:e.totalMessages+o(r.totalMessages,i.totalMessages),tokens:s,cost:e.cost+o(r.cost,i.cost)}}(e,S?.context.messages??[],R);return 0!==n.tokens.total||0!==R.length||e?{sessionFile:S?.filePath||void 0,sessionId:td.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:S?.totalActiveMs,...eN?{contextUsage:eN}:{}}:null},[R,e5,eN,S?.context.messages,S?.filePath,S?.totalActiveMs,S?.stats,t?.id,t?.name]),tX=(0,i.useCallback)(async(e,t=!1,n=!1)=>{let r=!1;try{t&&N(!0);let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});n&&i.set("force","1");let o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${i}`);if(404===o.status)return t&&(C(null),L(null),$([]),A([]),H(null),F(!1),eI(null),M(null)),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let s=await o.json();if(td.current!==e)return null;let l={messages:s.context.messages,entryIds:s.context.entryIds??[],oldestEntryId:s.context.oldestEntryId,hasMore:s.context.hasMore},a=t?l:function(e,t){if(0===e.entryIds.length||0===t.entryIds.length)return t;let n=new Set(t.entryIds),r=e.entryIds.findIndex(e=>n.has(e));return r<=0?t:{messages:[...e.messages.slice(0,r),...t.messages],entryIds:[...e.entryIds.slice(0,r),...t.entryIds],oldestEntryId:e.oldestEntryId??e.entryIds[0]??t.oldestEntryId,hasMore:e.hasMore}}(O.current,l);if(C({...s,context:{...s.context,...a}}),L(s.leafId),$(a.messages),A(a.entryIds),H(a.oldestEntryId),F(a.hasMore),ta.current=void 0!==s.toolNames,tO(void 0!==s.toolNames?(0,tr.YO)(s.toolNames):tr.Q8),eW(e=>tD.current?e:null),M(null),s.context.thinkingLevel&&"off"!==s.context.thinkingLevel&&eS(s.context.thinkingLevel),void 0!==s.contextUsage&&eI(s.contextUsage??null),r=!0,t&&N(!1),!n)return null;try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(td.current!==e)return null;let r=n.state;return r?(void 0!==r.contextUsage&&eI(r.contextUsage??null),void 0!==r.systemPrompt&&eT(r.systemPrompt??null),void 0!==r.thinkingLevel&&eS(r.thinkingLevel??"auto"),void 0!==r.queuedMessages&&tn(ij(r.queuedMessages))):n.running||tn({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return M(String(e)),null}finally{t&&!r&&N(!1)}},[tO]),tG=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let o=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,s=await fetch(o,{signal:r?.signal});if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(td.current!==e||r?.signal?.aborted||!tF.current)return;return H(l.context.oldestEntryId),F(l.context.hasMore),C(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...l.context.messages,...t.context.messages],entryIds:[...l.context.entryIds,...t.context.entryIds],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore}:l.context;return{...t,context:r}}),n?($(e=>[...l.context.messages,...e]),A(e=>[...l.context.entryIds,...e])):($(l.context.messages),A(l.context.entryIds??[])),l.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),tQ=(0,i.useCallback)(async e=>{try{let t=await r7(e,{type:"get_tools"});if(!t||!tF.current||td.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tO(ta.current?r(t):tr.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,tO]),t0=(0,i.useCallback)((t=0,n="(no messages)")=>{let r=td.current;if(v&&o&&r&&!tT.current&&(tT.current=!0,s)){if(s!==r){tB.current.set(s,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(s,r):eF(s,r)}d?.({id:r,path:"",cwd:o,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},s)}},[v,o,s,d,e.chatInputRef]),t1=(0,i.useCallback)(e=>{e instanceof il||console.error("Failed to maintain the agent event stream:",e)},[]),t2=(0,i.useCallback)(async()=>{if(td.current||!v||!o)return td.current;if(tM.current)return tM.current;let e=(async()=>{let e=tL.current,t=tR.current;e&&eD(e);let n=(0,tr.xG)(ew);ta.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:o,type:"ensure_session",...void 0!==n?{toolNames:n}:{},...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json(),s=i.sessionId;return td.current=s,th.current&&ti.current?.ensureConnected(s).catch(t1),void 0!==i.contextUsage&&eI(i.contextUsage??null),i.model&&tL.current===e&&(eD(i.model),e||eb(i.model)),i.thinkingLevel&&tR.current===t&&eS(i.thinkingLevel),s})();tM.current=e;try{return await e}finally{tM.current=null}},[t1,v,o,ew]),t4=(0,i.useCallback)(async()=>{let e=td.current??await t2();if(!e)return;let[t]=await Promise.all([r7(e,{type:"get_state"}),tQ(e)]);tF.current&&td.current===e&&eT(t.systemPrompt??"")},[t2,tQ]),t8=(0,i.useCallback)(async()=>{let e=td.current??await t2();if(!e)return e0([]),[];e2(!0);try{let t=await r7(e,{type:"get_commands"}),n=t?.commands??[];return e0(n),n}catch(e){return console.error("Failed to load slash commands:",e),e0([]),[]}finally{e2(!1)}},[t2]),t5=(0,i.useCallback)(()=>{ts.current+=1,tl.current=!1,to.current&&(clearTimeout(to.current),to.current=null)},[]),t6=(0,i.useCallback)(()=>{ti.current?.close()},[]),t3=(0,i.useCallback)(e=>ti.current.ensureConnected(e),[]),t7=(0,i.useCallback)(e=>{ti.current.maintain(e)},[]),t9=(0,i.useCallback)(e=>{ti.current?.reconnect(e).catch(t1)},[t1]);(0,i.useEffect)(()=>{if(t?.id&&r)return t7(t.id),()=>{td.current!==t.id||tp.current||tl.current||th.current||tc.current===t.id&&tu.current||ti.current?.close()}},[t7,t?.id,r]),(0,i.useEffect)(()=>{if(!x){tp.current||tu.current||tl.current||t6();return}let e=t?.id??td.current??null;e&&(t5(),ti.current?.ensureConnected(e).catch(t1))},[t5,t6,t1,x,t?.id]);let ne=(0,i.useCallback)(async(e,t)=>{let n=td.current;if(e7(t=>t?.id===e.id?null:t),n)try{await r7(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nt=(0,i.useCallback)(async(e,t)=>{let n=td.current;if(n)try{await r7(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nn=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e8({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),nr=(0,i.useCallback)(t=>{switch(r2(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":e7(t);break;case"notify":nn({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":te(e=>t.closed?e?.id===t.id?null:e:t)}},[nn,a,e.chatInputRef]),ni=(0,i.useCallback)(()=>{null!==tC.current&&(cancelAnimationFrame(tC.current),tC.current=null);let e=tE.current;0!==e.length&&(tE.current=[],_({type:"deltas",events:e}))},[]),no=(0,i.useCallback)(e=>{tE.current.push(e),null===tC.current&&(tC.current=requestAnimationFrame(()=>{tC.current=null,ni()}))},[ni]),ns=(0,i.useCallback)(()=>{ni();let e=tp.current;return tp.current=!1,V(!1),eG(null),eE(null),z(new Map),_({type:"end"}),e},[ni]),nl=(0,i.useCallback)(e=>tm.current!==e&&(tm.current=e,l?.(),!0),[l]),na=(0,i.useCallback)(e=>{if(th.current&&td.current===e)return void t5();t5(),tl.current=!0;let t=ts.current,n=async()=>{if(t===ts.current&&td.current===e&&tl.current)try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(t!==ts.current||td.current!==e||!tl.current)return;let o=i.state;if(i.running&&o&&(o.isStreaming||o.isPromptRunning)){tl.current=!1,to.current=null,tf.current=!!o?.isStreaming,tg.current=!!o?.isPromptRunning,tp.current=!0,V(!0),eG(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){e_(!0),to.current=setTimeout(()=>void n(),600);return}tl.current=!1,to.current=null,t6()}catch{if(t!==ts.current||td.current!==e||!tl.current)return;to.current=setTimeout(()=>void n(),600)}};to.current=setTimeout(()=>void n(),3e4)},[t5,t6]),nd=(0,i.useCallback)(async(e=td.current,t=t$.current)=>{if(t$.current===t)try{e&&await tX(e)}finally{if(t$.current!==t)return;let n=tg.current,r=tf.current;tg.current=!1,tf.current=!1,tA.current=null;let i=ns();n?nl(t):r&&i&&l?.(),e&&na(e)}},[tX,nl,l,na,ns]),nc=(0,i.useCallback)(async(e,t)=>{await iE(800);let n=Date.now();for(;tp.current&&Date.now()-n<2e4;){if(void 0!==t&&t$.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nd(e,t)}}catch{}await iE(600)}},[nd]),nh=(0,i.useCallback)(async e=>{let t=ty.current+1;for(ty.current=t;tx.current&&ty.current===t&&td.current===e;){await iE(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await tX(e),ty.current!==t||td.current!==e)return;tx.current=!1,Y(!1),X(null);return}catch{}}},[tX]),np=(0,i.useCallback)(async e=>{if(!tp.current||td.current!==e)return;let t=t$.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(td.current!==e||t$.current!==t)return;let i=r.state;if(e_(i?.isCompacting??!1),tn(ij(i?.queuedMessages)),"boolean"==typeof i?.autoCompactionEnabled&&eK(i.autoCompactionEnabled),i?.contextUsage!==void 0&&eI(e=>iS(e,i.contextUsage??null)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){tf.current=!!i.isStreaming,tg.current=!!i.isPromptRunning;return}if(!tp.current)return;i&&void 0!==i.systemPrompt&&eT(i.systemPrompt??null),await nd(e,t)}catch{}},[nd]);(0,i.useEffect)(()=>{if(!K)return;let e=()=>{let e=td.current;e&&np(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[K,np]),(0,i.useEffect)(()=>{let e=()=>{let e=td.current;if(e&&"hidden"!==document.visibilityState){if(th.current)return void t9(e);(tp.current||tl.current||tc.current===e&&tu.current)&&t7(e)}},t=()=>{"visible"===document.visibilityState&&e()};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[t7,t9]),(0,i.useEffect)(()=>{tp.current=K},[K]),tb.current=(0,i.useCallback)(e=>{switch("message_update"!==e.type&&ni(),e.type){case"connected":_({type:!0===e.isStreaming?"resume":"end"}),!0===e.isStreaming&&(t5(),tf.current=!0,tp.current=!0,V(!0),eG({kind:"waiting_model"}));break;case"agent_start":t5(),tf.current=!0,tp.current=!0,V(!0),eG({kind:"waiting_model"}),_({type:"start"});break;case"agent_end":if(!tp.current)break;eG(null),eE(null),_({type:"end"}),td.current&&(tX(td.current),fetch(`/api/agent/${encodeURIComponent(td.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eI(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eT(e.state.systemPrompt??null),tn(ij(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=tf.current;if(tf.current=!1,!e||tg.current)break;let t=td.current,n=ns();e_(!1),t&&(tX(t),na(t)),n&&l?.();break}case"prompt_done":{let e=t$.current,t=tg.current;tg.current=!1,tA.current=null;let n=nl(e);if(!t&&!n)break;let r=td.current;r&&tX(r),!tf.current&&(ns(),r&&na(r))}break;case"prompt_error":nn({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":nn({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tp.current||id(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(_({type:"snapshot",message:t}),t.content.length>0&&eG(null)):t&&eG(null)}else{let t=e.assistantMessageEvent;t&&(no(t),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eG(null))}break;case"message_end":{if(!tp.current||id(e))break;let t=e.message;if(t&&"user"===t.role){let e=r5(t),n=is(e),r=tA.current;tA.current=null,$(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&is(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let e=r5(t);if("assistant"===e.role){let t=function(e){if("assistant"!==e.role||"aborted"===e.stopReason||"error"===e.stopReason)return null;let t=e.usage;if(!t)return null;let n=t.totalTokens,r=n&&n>0?n:t.input+t.output+t.cacheRead+t.cacheWrite;return r>0?r:null}(e);null!==t&&eI(e=>{let n=e?.contextWindow??0;return n<=0?e:iS(e,{tokens:t,contextWindow:n,percent:t/n*100})});let n=Date.now(),r=function(e,t,n){if(!t)return e;let r=!1,i=e.content.map((e,i)=>{if("thinking"!==e.type)return e;let o=t.content[i],s=(o?.type==="thinking"?o.startedAt:void 0)??e.startedAt??t.timestamp,l=(o?.type==="thinking"?o.endedAt:void 0)??e.endedAt??n;return e.startedAt===s&&e.endedAt===l?e:(r=!0,{...e,..."number"==typeof s?{startedAt:s}:{},..."number"==typeof l?{endedAt:l}:{}})});return r?{...e,content:i}:e}({...e,completedAt:n},q.current.streamingMessage,n);$(e=>[...e,r])}else"system"!==e.role&&$(t=>[...t,e])}_({type:"end"}),eG({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;eG(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n)&&Array.isArray(i)&&z(e=>{let o=new Map(e);return o.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),o}),eG(e=>{let r=e?.kind==="running_tools"?e.tools:[],i=r.find(e=>e.id===t),o=n||i?.name||"tool";return i?.name===o?e:{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),{id:t,name:o}]}});break}case"tool_execution_end":{let t=e.toolCallId;z(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),eG(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":tn({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eE({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eE(null);break;case"auto_compaction_start":case"compaction_start":e_(!0),eJ(null),eZ(null);break;case"auto_compaction_end":case"compaction_end":e_(!1),e.errorMessage?(eJ(e.errorMessage),eZ(null)):!e.aborted&&(eZ(iM(e.result,e.reason??"auto")),td.current&&tX(td.current));break;case"extension_ui_request":nr(e);break;case"extension_ui_closed":e7(t=>t?.id===e.id?null:t)}},[nn,t5,ni,nr,tX,nl,l,no,na,ns]);let nf=(0,i.useCallback)(async(e,n)=>{let r=e.trim();if(!r&&!n?.length)return;if(tp.current||tx.current)return void tY(e,n,tV);let i=!n?.length&&r.startsWith("/");if(!n?.length&&r.startsWith("!")){let t=r.startsWith("!!"),i=(t?r.slice(2):r.slice(1)).trim();return i?void await tN.current?.(i,t):void tY(e,n,tV)}let s=t$.current+1;t5(),tg.current=!0;let l=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:l?.length?[...e.trim()?[{type:"text",text:e}]:[],...l]:e,timestamp:Date.now()};$(e=>[...e,a]),tA.current=is(a),t$.current=s,tp.current=!0,V(!0),eG(i?{kind:"running_command"}:{kind:"waiting_model"}),_({type:"start"}),tk.current=!0,tz.current={runId:s,message:e,images:n,userMsg:a};let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=!1;tW.current.begin(s);let u=async e=>{try{await r7(e,{type:"abort"})}catch(e){nn({type:"error",message:e instanceof Error?e.message:String(e)})}},h=await ix({gate:tW.current,runId:s,currentRunId:()=>t$.current,currentSessionId:()=>td.current,promptPending:()=>tg.current,abandonUnsent:()=>{tz.current?.runId===s&&(tz.current=null,tg.current=!1,$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tY(e,n,tV),tA.current=null,t$.current===s&&(tp.current=!1,V(!1),eG(null),_({type:"end"})))},onDispatched:()=>{tz.current?.runId===s&&(tz.current=null)},abort:u,prepare:async()=>{if(v&&o){let e=td.current??await tM.current;if(tW.current.isCancelled(s))return null;let t=e??await t2();if(tW.current.isCancelled(s))return null;if(!t)throw Error("Unable to create a session for the prompt");if(ex&&(eD(ex),e)){let e=await r7(t,{type:"set_model",provider:ex.provider,modelId:ex.modelId});if(e?.thinkingLevel&&"off"!==e.thinkingLevel&&eS(e.thinkingLevel),tW.current.isCancelled(s))return null}return(await t3(t),tW.current.isCancelled(s))?null:t}if(t)return(await t3(t.id),tW.current.isCancelled(s))?null:t.id;throw Error("No active session for the prompt")},send:async t=>{let n=await r7(t,{type:"prompt",message:e,...d?.length?{images:d}:{}});c=n?.subagentAction==="steered"||n?.subagentAction==="resumed"}});if("abandoned"!==h.status&&"aborted"!==h.status&&"stale"!==h.status){if("cancelled_after_dispatch"===h.status)return void nc(h.sessionId,s);if("failed"===h.status){let t=h.error,r=h.sessionId,i=h.requestStarted;return(console.error("Failed to send message:",t),!(!i||r3(t))&&r)?void nc(r,s):(tg.current=!1,tz.current?.runId===s&&(tz.current=null),$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nn({type:"error",message:t instanceof Error?t.message:String(t)}),tY(e,n,tV),tA.current=null,r)?void np(r):(tp.current=!1,t6(),V(!1),eG(null),void _({type:"end"}))}if(v&&o&&t0(1,e),c&&h.sessionId){tg.current=!1,nc(h.sessionId,s);return}i&&h.sessionId&&nc(h.sessionId,s)}},[v,o,ex,t,t2,t3,t0,nc,nn,t5,t6,tV,np,tY]),ng=(0,i.useCallback)(async(e,n)=>{if(tp.current||tx.current||ee.current)throw Error("Cannot generate an image while the session is busy");let r=crypto.randomUUID();ee.current=!0,et.current=r,en.current=!1,Q(!0);try{let i=t?.id??(v&&o?await t2():null);if(!i)throw Error("No active session for image generation");if(en.current)throw new DOMException("Image generation cancelled","AbortError");let s=await r7(i,{type:"generate_image_direct",requestId:r,arguments:e,...n?{sourceImage:n}:{}});return await tX(i),v&&o&&t0(1,e.prompt),s}finally{et.current===r&&(ee.current=!1,et.current=null,en.current=!1,Q(!1))}},[t2,v,tX,o,t0,t?.id]),nm=(0,i.useCallback)(async()=>{en.current=!0;let e=td.current,t=et.current;e&&t&&await r7(e,{type:"abort_image_generation",requestId:t})},[]);tN.current=(0,i.useCallback)(async(e,n)=>{if(tp.current||tx.current)return;let r=`${n?"!!":"!"}${e}`;tP.current=!1,tx.current=!0,X({command:e,excludeFromContext:n}),Y(!0);try{let i=await iv({abortRequested:()=>tP.current,prepare:async()=>td.current??t?.id??await t2(),send:async t=>{await r7(t,{type:"bash",command:e,excludeFromContext:n})},loadResults:async e=>{td.current===e&&await tX(e)},restoreUnsent:()=>tY(r,void 0,tV)});("completed"===i.status||"cancelled_after_dispatch"===i.status)&&t0(1,r)}catch(e){console.error("Failed to execute shell command:",e),nn({type:"error",message:e instanceof Error?e.message:String(e)}),tY(r,void 0,tV)}finally{tx.current=!1,X(null),Y(!1)}},[nn,tV,t2,tX,t0,tY,t]);let nx=(0,i.useCallback)(async()=>{var e;let n=t$.current,r=td.current,i=async e=>{if(r&&!tv.current){tv.current=!0;try{await r7(r,{type:e})}catch(e){console.error("Failed to abort:",e),nn({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tv.current=!1}}};if(tx.current){tP.current=!0,await i("abort_bash");return}let o=tz.current;(tW.current.isInFlight(n)||o?.runId===n)&&tW.current.cancel(n);let s=!!(o&&o.runId===n&&tW.current.shouldAbandonUnsent(n));if(s&&o){tz.current=null,tg.current=!1,$(e=>{let t=e.lastIndexOf(o.userMsg);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tY(o.message,o.images,tV),tA.current=null,tp.current=!1,V(!1),eG(null),_({type:"end"});return}let l=(e={bashRunning:!1,hasSessionId:!!r,localUnsent:s,agentRunning:tp.current||tg.current}).bashRunning?e.hasSessionId?"abort_bash":"none":!e.agentRunning||e.localUnsent?"none":e.hasSessionId?"abort":"none";t?.relation?.kind==="subagent"&&"queued"===t.relation.status&&r?await i("abort"):"none"!==l&&r&&await i("abort_bash"===l?"abort_bash":"abort")},[nn,tV,tY,t]),nv=(0,i.useCallback)(async e=>{if(tx.current)return;let t=td.current;if(t){eR(e);try{let{cancelled:n,newSessionId:r}=await r7(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e)}finally{eR(null)}}},[c]),ny=(0,i.useCallback)(async e=>{if(tx.current)return;let t=td.current;t&&(r7(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),L(e),await tG(t,e))},[tG]),nb=(0,i.useCallback)(async e=>{if(tx.current)return;L(e);let t=td.current;t&&(await tG(t,e),e&&r7(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tG]),nw=(0,i.useCallback)(async(e,t)=>{if(v){let n={provider:e,modelId:t};tL.current=n,ev(n),eD(n);let r=td.current??await tM.current;if(!r){let n=eg[`${e}/${t}`];n&&null===tR.current?eS(n):eS(function(e,t){if(!e?.length||e.includes(t)||"auto"===t)return t;let n=r9.indexOf(t);if(-1===n)return e[0];for(let t=n+1;t<r9.length;t++)if(e.includes(r9[t]))return r9[t];for(let t=n-1;t>=0;t--)if(e.includes(r9[t]))return r9[t];return e[0]}(eu[`${e}:${t}`],ej));return}try{let n=await r7(r,{type:"set_model",provider:e,modelId:t});n?.thinkingLevel&&"off"!==n.thinkingLevel&&eS(n.thinkingLevel)}catch(e){console.error("Failed to set model:",e)}return}let n=td.current;if(n&&!tD.current){tD.current=!0,eW({provider:e,modelId:t}),eO(!0);try{await r7(n,{type:"set_model",provider:e,modelId:t}),tD.current=!1,await tX(n)}catch(e){console.error("Failed to set model:",e),tD.current=!1,eW(e$),nn({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await tX(n)}finally{tD.current=!1,eO(!1)}}},[nn,e$,v,tX,eg,eu,ev,ej]),nk=(0,i.useCallback)(async()=>{let e=td.current;if(e&&!eU){e_(!0),eJ(null),eZ(null);try{let t=await r7(e,{type:"compact"});eZ(iM(t,"manual")),await tX(e,!0)}catch(e){eJ(e instanceof Error?e.message:String(e)),eZ(null)}finally{e_(!1)}}},[eU,tX]),nj=(0,i.useCallback)(async(e,t=!1,n)=>{let r;try{r=await function(e,t,n={}){let r=ib.get(e);if(!n.force&&r&&r.loadedAt+6e4>Date.now())return Promise.resolve(r.data);let i=iw.get(e);if(i&&(!n.force||i.forced&&i.refreshToken===n.refreshToken))return i.promise;let o=(i?i.promise.catch(()=>void 0):Promise.resolve()).then(t).then(t=>{if(t.modelError&&(t.modelList?.length??0)===0)throw Error(t.modelError);for(ib.delete(e),ib.set(e,{data:t,loadedAt:Date.now()});ib.size>32;){let e=ib.keys().next().value;if(void 0===e)break;ib.delete(e)}return t}).finally(()=>{iw.get(e)?.promise===o&&iw.delete(e)});return iw.set(e,{promise:o,forced:!0===n.force,...void 0!==n.refreshToken?{refreshToken:n.refreshToken}:{}}),o}(b,async()=>{let e=await fetch(b);if(!e.ok){let t="";try{let n=await e.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(t=n.error)}catch{}throw Error(t||`Failed to load models (HTTP ${e.status})`)}return e.json()},{force:t,refreshToken:n}),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||ea(t instanceof Error?t.message:String(t)),t}if(ei(r.models),ea(r.modelError??null),ec(r.modelScopeWarnings??[]),eh(r.thinkingLevels??{}),ef(r.thinkingLevelMaps??{}),em(r.thinkingLevelPins??{}),es(r.modelList??[]),v&&!td.current){let e=iT(r);eb(e);let t=e&&r.thinkingLevelPins?.[`${e.provider}/${e.modelId}`];null===tR.current&&eS(t??"auto")}},[v,b]),nS=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),o=td.current??await t2(),s=e=>(e.handled&&(e.error?nn({type:"error",message:e.error}):"openSessionStats"!==e.action&&nn({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eU)return s({handled:!0,error:"No active session to compact"});e_(!0),eJ(null),eZ(null);let e=await r7(o,{type:"compact",...i?{customInstructions:i}:{}});return eZ(iM(e,"manual")),await tX(o,!0)&&t0(),s({handled:!0,message:"Compacted context"})}case"reload":if(!o)return s({handled:!0,error:"No active session to reload"});return await r7(o,{type:"reload"}),await Promise.all([tX(o,!1,!0),tQ(o),t8(),nj(void 0,!0)]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await r7(o,{type:"set_session_name",name:i}),await tX(o)&&t0(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return s({handled:!0,error:"No active session"});let e=await r7(o,{type:"get_session_stats"});return e&&e6(e),m?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!o)return s({handled:!0,error:"No active session"});let e=await r7(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"auto-compact":{if(!o)return s({handled:!0,error:"No active session"});let e=await r7(o,{type:"get_state"}),t=!("boolean"!=typeof e?.autoCompactionEnabled||e.autoCompactionEnabled);return await r7(o,{type:"set_auto_compaction",enabled:t}),eK(t),s({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"clone":{if(!o)return s({handled:!0,error:"No active session to clone"});if(tp.current||tx.current)return s({handled:!0,error:"Cannot clone while the session is running"});let e=await r7(o,{type:"clone",leafId:T});if(e?.cancelled||!e?.newSessionId)return s({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=s({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}case"bug":{if(!o)return s({handled:!0,error:"No active session to report"});if(tp.current||tx.current)return s({handled:!0,error:"Cannot report a bug while the session is running"});let e=await r7(o,{type:"bug_report",...i?{hint:i}:{}});if(!e)return s({handled:!0,error:"Bug report failed"});return s({handled:!0,message:"upload"===e.delivery?`Bug report uploaded. Report ID: ${e.id}`:`Upload failed (${e.error??"unknown error"}); exported to ${e.path}`})}default:return{handled:!1}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&e_(!1)}},[T,nn,t2,eU,nj,tX,t8,tQ,t0,c,m]),nC=(0,i.useCallback)(async(e,t,n)=>{let r=td.current;if(!r){tY(e,n,tV),nn({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await r7(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),r3(t)&&tY(e,n,tV),nn({type:"error",message:t instanceof Error?t.message:String(t)})}},[nn,tV,tY]),nE=(0,i.useCallback)(async(e,t)=>{await nC(e,"steer",t)},[nC]),nN=(0,i.useCallback)(async(e,t,n)=>{await nC(e,t,n)},[nC]),nI=(0,i.useCallback)(async(e,t)=>{await nC(e,"followUp",t)},[nC]),nM=(0,i.useCallback)(async()=>{let e=td.current;if(e)try{await r7(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nT=(0,i.useCallback)(async()=>{let e=td.current;if(e)try{let t=await r7(e,{type:"clear_queue"});tn({steering:[],followUp:[]});let n=[...iy(t?.steering),...iy(t?.followUp)];if(0===n.length)return;tY(n.map(e=>e.text).filter(Boolean).join("\n\n"),n.flatMap(e=>e.images).map(e=>({...e,previewUrl:""})),tV)}catch(e){console.error("Failed to recall queued messages:",e),nn({type:"error",message:e instanceof Error?e.message:"Failed to recall queued messages"})}},[nn,tV,tY]),nL=(0,i.useCallback)(async e=>{if(eS(e),v&&!td.current&&(tR.current="auto"===e?null:e),"auto"===e)return;let t=td.current??await tM.current;if(t)try{await r7(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[v]),nR=(0,i.useCallback)(async e=>{let t=(0,tr.xG)(e);!function(e,t=it()){if(t)try{t.setItem(ie,e)}catch{}}(e),tO(e);let n=td.current??await tM.current;if(!n){ta.current=void 0!==t;return}try{let e=await r7(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});ta.current=void 0!==t;let r=e?.sessionId??n,i=e?.recreated===!0;r!==n&&(t5(),t6(),td.current=r),e0([]),th.current&&(i||r!==n)&&t9(r);let[o]=await Promise.all([r7(r,{type:"get_state"}),tQ(r)]);tF.current&&td.current===r&&eT(o.systemPrompt??"")}catch(e){console.error("Failed to set tools:",e)}},[t5,t6,tQ,t9,tO]),n$=(0,i.useCallback)((e,t=16)=>{let n=tI.current;n&&(tw.current=!0,tk.current=!1,tj.current=!1,n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tS.current=n.scrollTop)},[]),nW=(0,i.useCallback)(()=>{let e=tI.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tp.current,o=tj.current,s=function(e,t,n,r,i,o=96){return!!nu(n,r,i)||!(n<t)&&(!!(!e&&n>t&&nu(n,r,i,o))||e)}(o,tS.current,t,n,r,i?96:8);tj.current=s,tS.current=t,!o&&s&&i&&t_("instant")}},[t_]);(0,i.useEffect)(()=>(tF.current=!0,t&&(td.current=t.id,tX(t.id,!0,!0).then(e=>{e?.running&&(tQ(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tf.current=!!e.state.isStreaming,tg.current=!!e.state.isPromptRunning,tp.current=!0,V(!0),eG(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),_({type:"resume"}),t7(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nc(t.id)),e.state?.isBashRunning&&(tx.current=!0,Y(!0),nh(t.id))),e?.state&&(void 0!==e.state.isCompacting&&e_(e.state.isCompacting),"boolean"==typeof e.state.autoCompactionEnabled&&eK(e.state.autoCompactionEnabled),void 0!==e.state.contextUsage&&eI(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eT(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eS(e.state.thinkingLevel??"auto"),void 0!==e.state.queuedMessages&&tn(ij(e.state.queuedMessages)))})),()=>{tF.current=!1,null!==tC.current&&cancelAnimationFrame(tC.current),tC.current=null,tE.current=[],ty.current+=1,t5(),t6()}),[]),(0,i.useEffect)(()=>{p?.(eM)},[eM,p]),(0,i.useEffect)(()=>(g?.(t4),()=>g?.(null)),[t4,g]),(0,i.useEffect)(()=>{h&&h(S?.tree??[],T,nb)},[S?.tree,T,nb,h]),(0,i.useEffect)(()=>{let e=tI.current;if(e)return tS.current=e.scrollTop,e.addEventListener("scroll",nW,{passive:!0}),()=>{e.removeEventListener("scroll",nW)}},[R.length,E,nW]),(0,i.useLayoutEffect)(()=>{R.length>0&&(tk.current?(tk.current=!1,tw.current=!0,t_("instant")):tw.current?tj.current&&t_("instant"):(tw.current=!0,t_("instant")))},[R.length,K,t_,U.streamingMessage]),(0,i.useEffect)(()=>{let e=new AbortController,t=tH.current!==u;return tH.current=u,(async()=>{for(let n=0;;n++)try{await nj(e.signal,t,u);return}catch(t){if(e.signal.aborted||t instanceof DOMException&&"AbortError"===t.name||n>=iC.length||(await iE(iC[n]),e.signal.aborted))return}})(),()=>e.abort()},[nj,u]),(0,i.useEffect)(()=>{if(!eY)return;let e=setTimeout(()=>eZ(null),6e3);return()=>clearTimeout(e)},[eY]);let[nz,nP]=(0,i.useState)(null),nA=(0,i.useRef)(5e3),nD=(0,i.useRef)(null),nH=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===e4.visible.length){nH.current=null;return}let e=e4.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e8({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e4.visible[0];if(!t||(nH.current!==t.id&&(nH.current=t.id,nA.current=5e3),e4.visible.some(e=>e.id===nz)))return;nD.current=Date.now();let n=setTimeout(()=>{e8({type:"mark_oldest_exiting"})},nA.current);return()=>{clearTimeout(n),null!==nD.current&&(nA.current=Math.max(0,nA.current-(Date.now()-nD.current)),nD.current=null)}},[e4.visible,nz]),(0,i.useEffect)(()=>{e6(null)},[R.length,eN?.tokens,eN?.percent,eN?.contextWindow]),{data:S,loading:E,error:I,activeLeafId:T,messages:R,activeToolResults:W,entryIds:P,historyCursor:D,hasEarlierMessages:B,streamState:U,agentRunning:K,directImageRunning:G,modelNames:er,modelList:eo,modelError:el,modelScopeWarnings:ed,modelThinkingLevels:eu,modelThinkingLevelMaps:ep,newSessionModel:ex,toolPreset:ew,thinkingLevel:ej,retryInfo:eC,contextUsage:eN,systemPrompt:eM,forkingEntryId:eL,isCompacting:eU,autoCompactionEnabled:eq,compactError:eV,compactResult:eY,currentModel:tq,displayModel:tK,modelSwitching:eH,sessionStats:tZ,slashCommands:eQ,slashCommandsLoading:e1,queuedMessages:tt,notices:e4.visible,extensionDialog:e3,extensionCustomUi:e9,respondToExtensionUi:ne,sendExtensionCustomInput:nt,isAutoModelSelection:v&&null===ex,agentPhase:eX,isNew:v,sessionIdRef:td,scrollContainerRef:tI,initialScrollDoneRef:tw,handleSend:nf,handleDirectImageGeneration:ng,abortDirectImageGeneration:nm,handleAbort:nx,handleFork:nv,handleNavigate:ny,handleModelChange:nw,handleCompact:nk,handleSteer:nE,handleFollowUp:nI,handlePromptWithStreamingBehavior:nN,handleAbortCompaction:nM,handleRecallQueue:nT,handleBuiltinSlashCommand:nS,addNotice:nn,setNoticePaused:nP,handleToolPresetChange:nR,handleThinkingLevelChange:nL,loadTools:tQ,loadSlashCommands:t8,setActiveLeafId:L,setData:C,setMessages:$,loadContext:tG,scrollToBottom:t_,scrollToMessage:n$,dispatch:_,setAgentRunning:V,setForkingEntryId:eR,bashRunning:J,pendingBash:Z,handleAgentEventRef:tb}}({session:e,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onAgentEnd:es,onAttentionNeeded:el,onSessionCreated:S,onSessionForked:ea,modelsRefreshKey:E,chatInputRef:er,onBranchDataChange:R,onSystemPromptChange:$,onSystemToolsChange:W,onSystemInfoLoaderChange:z,onSessionStatsPanelOpen:A,deferInitialScroll:!!ef,isVisiblePane:L}),tM=eT||eL||eR,tT=(0,i.useCallback)(()=>eL?tc():tu(),[tc,eL,tu]),tL=(0,i.useRef)(null),tR=e1?e1.tokens.input+e1.tokens.cacheRead+e1.tokens.cacheWrite:0,t$=e1&&tR>0?e1.tokens.cacheRead/tR*100:null,[tW,tz]=(0,i.useState)(null),tP=to&&0===ek.length&&!eM.isStreaming&&!tM&&null===tW,[tD,tH]=(0,i.useState)(!1),[tF,tO]=(0,i.useState)(null),[tU,t_]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(void 0),[tY,tQ]=(0,i.useState)(0),[t2,t4]=(0,i.useState)(null),[t8,t6]=(0,i.useState)(!1),[t7,t9]=(0,i.useState)(!1),[ne,nn]=(0,i.useState)(null),nr=(0,i.useRef)(null),ni=(0,i.useRef)(null),ns=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/image-generation",{signal:e.signal}).then(async e=>{let t=await e.json();e.ok&&t.available&&t.config?.connections.length?tO(t.config):(tO(null),t_(!1),tK(null))}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load image generation config:",e)}),()=>e.abort()},[tY,E]);let nx=(0,i.useCallback)(async(t,n)=>{ec();let r=null;for(let e=ek.length-1;e>=0;e--){let t=eb(ek[e].details);if(t){r=t;break}}let i=e?.cwd??d,o=t.target,s=o&&(o.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(o)?o:i?N(i,o):o);tz({prompt:t.prompt,size:t.size,width:n?void 0:r?.width,height:n?void 0:r?.height,previewUrl:n?`data:${n.mimeType};base64,${n.data}`:s?`/api/files/${j(s)}?type=read`:void 0});try{await td(t,n),n&&er.current?.removeAttachedImage(n.data)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;te({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tz(null)}},[te,td,ec,ek,d,e?.cwd]),nv=(0,i.useCallback)(async e=>{let t=await tw(e);return!("error"in t)&&/^\/reload(?:\s|$)/.test(e.trim())&&tQ(e=>e+1),t},[tw]),ny=(0,i.useCallback)(()=>{t4(null),t6(!1),nn(null)},[]);(0,i.useEffect)(()=>{O||ny()},[O,ny]);let nb=(0,i.useCallback)(e=>{let t=ns.current;if(t&&!(null!=e&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)||!O||t8)return;let n=window.getSelection(),r=n?.rangeCount?n.getRangeAt(0):null,i=nR.current;if(!n||n.isCollapsed||!r||!i||!i.contains(r.commonAncestorContainer))return void t4(null);let o=n.toString().trim();if(!o)return void t4(null);let s=r.getBoundingClientRect(),l=[r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentElement,r.startContainer.nodeType===Node.ELEMENT_NODE?r.startContainer:r.startContainer.parentElement,r.endContainer.nodeType===Node.ELEMENT_NODE?r.endContainer:r.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);t4({text:o,top:Math.min(window.innerHeight-44,s.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,s.left+s.width/2)),sourceEntryId:l})},[O,t8]);(0,i.useEffect)(()=>{t8&&t2&&ni.current?.insertIfEmpty(nd(t2.text,X("chat.quoteIntro"),X("chat.quoteQuestion")))},[t8,t2,X]),(0,i.useLayoutEffect)(()=>{let e=nr.current;if(!e||!t2)return;let t=window.visualViewport,n=()=>{let n=e.getBoundingClientRect(),r=t?.offsetTop??0,i=t?.offsetLeft??0;e.style.top=`${Math.max(r+8,Math.min(t2.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(t2.left-n.width/2,i+(t?.width??window.innerWidth)-n.width-8))}px`};n();let r=new ResizeObserver(n);return r.observe(e),window.addEventListener("resize",n),t?.addEventListener("resize",n),t?.addEventListener("scroll",n),()=>{r.disconnect(),window.removeEventListener("resize",n),t?.removeEventListener("resize",n),t?.removeEventListener("scroll",n)}},[t2,t8,ne]),(0,i.useEffect)(()=>{if(!t2)return;let e=e=>{if(t8||nr.current?.contains(e.target))return;ns.current={x:e.clientX,y:e.clientY};let t=()=>{document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),queueMicrotask(()=>{ns.current=null})};document.addEventListener("pointerup",t),document.addEventListener("pointercancel",t),ny()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),t7||ny())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[t2,t8,t7,ny]);let nw=(0,i.useCallback)(()=>{t2&&(er.current?.insertText(nd(t2.text,X("chat.quoteIntro"),X("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),ny())},[t2,ny,X]),nk=(0,i.useCallback)(async t=>{let n=ts.current??e?.id;if(!t7&&t.trim()&&t2?.sourceEntryId&&n&&F){t9(!0),nn(null),J?.();try{await F(t,n,t2.sourceEntryId),ny()}catch(e){ni.current?.restoreSubmission(t),nn(e instanceof Error?e.message:String(e))}finally{t9(!1)}}},[F,t2,t7,e?.id,ts,ny,J]),nj=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(ey||ew||!U||nj.current)return;let t=ts.current??e?.id;t&&(nj.current=!0,_?.(t),ec(),ta(U))},[U,ey,ew,ta,_,ec,e?.id,ts]),(0,i.useEffect)(()=>{Q&&e6&&eo.current!==e6.id&&(eo.current=e6.id,ee.current())},[Q,e6]);let[nS,nC]=(0,i.useState)(0),[nE,nN]=(0,i.useState)(50),nI=(0,i.useRef)(null),nM=(0,i.useRef)(null),nT=(0,i.useRef)({startIndex:0,endIndex:0,totalCount:0}),nL=(0,i.useRef)(null),nR=(0,i.useRef)(null),n$=(0,i.useRef)(null),nW=(0,i.useRef)(!1),nz=(0,i.useRef)(null),[nP,nA]=(0,i.useState)(null),nD=(0,i.useRef)(!1),nH=(0,i.useRef)(tE),nB=(0,i.useRef)(ef);nB.current=ef;let[nF,nO]=(0,i.useState)(null),nU=ek[eS.indexOf(nF?.entryId??"")],n_=nU?.role==="assistant"?nF?.blockIndex===void 0?nU.content.find(e=>"text"===e.type):nU.content[nF.blockIndex]:void 0,nq=(0,i.useRef)({entryIds:eS,historyCursor:eC,hasEarlierMessages:eI});nq.current={entryIds:eS,historyCursor:eC,hasEarlierMessages:eI},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=tl.current,r=nR.current;if(t&&l&&n&&r)return()=>{if(nB.current)return;if(nu(n.scrollTop,n.clientHeight,n.scrollHeight))return void l(t,{atBottom:!0});let e=n.getBoundingClientRect().top,i=iR(Array.from(r.children).flatMap(e=>{if(!(e instanceof HTMLElement)||!e.dataset.entryId)return[];let t=e.getBoundingClientRect();return[{entryId:e.dataset.entryId,top:t.top,bottom:t.bottom}]}),e);i&&l(t,{atBottom:!1,...i,oldestEntryId:nq.current.historyCursor})}},[ey,l,tl,e?.id]),(0,i.useEffect)(()=>{t&&eg(null)},[t]);let nK=(0,i.useCallback)(async(e,t,n)=>{do await new Promise(e=>requestAnimationFrame(()=>e())),n.throwIfAborted();while(nW.current);nW.current=!0;try{let r=nq.current;await ng(e,{entryIds:r.entryIds,oldestEntryId:r.historyCursor,hasMore:r.hasEarlierMessages},e=>tC(t,tE,e,{signal:n}),n)}finally{nW.current=!1}},[tE,tC]),nV=(0,i.useRef)(nK);nV.current=nK;let nJ=(0,i.useCallback)(()=>{let e=nT.current;nC(e.totalCount-e.endIndex),nN(50)},[]);(0,i.useEffect)(()=>{let n=e?.id;if(!ef||!n||ey||t||nD.current)return;nD.current=!0,nz.current?.abort();let r=new AbortController;nz.current=r,nA(null),nO(null);let i=()=>{ex(!1),eg(null)};return(async()=>{try{if(await nV.current(ef.anchorEntryId,n,r.signal),r.signal.aborted)return void i();ex(!0)}catch(e){if(nm(e,r.signal))return void i();tN("instant"),eg(null)}})(),()=>{r.abort(),nz.current===r&&(nz.current=null),eg(null),ex(!1)}},[ey,ef,tN,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=nR.current;if(!ef||!e||t)return;let n=e.querySelector(`[data-entry-id="${CSS.escape(ef.anchorEntryId)}"]`);if(n){nJ(),tI(n,ef.anchorOffset),eg(null);return}em&&(tN("instant"),eg(null))},[eS,nJ,ef,em,tN,tI,t,nE,nS]),(0,i.useEffect)(()=>{if(!t||ey)return;nz.current?.abort();let e=new AbortController;nz.current=e,nA(null),nO(null);let n=t.sessionId;return(async()=>{try{if(await nV.current(t.entryId,n,e.signal),e.signal.aborted)return;n$.current=null,nO(t)}catch(n){if(nm(n,e.signal))return;te({type:"warning",message:"other_branch"===(n instanceof nh&&"exhausted"===n.reason?function(e,t,n){if(!t||!n)return"not_found";let r=nf(t,n);return!r||r.some(t=>np(t,e))?"not_found":nf(t,e)?"other_branch":"not_found"}(t.entryId,ev?.tree,tE):"not_found")?X("chat.locateOtherBranch"):n instanceof nh&&"stalled"===n.reason?X("chat.locateHistoryStalled"):n instanceof nh&&"load_failed"===n.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")}),o?.(t)}})(),()=>{e.abort(),nz.current===e&&(nz.current=null)}},[tE,te,ev?.tree,ey,o,t,X]),(0,i.useLayoutEffect)(()=>{var e;let n=nF?`[data-entry-id="${CSS.escape(nF.entryId)}"]`:null,r=n?tl.current?.querySelector(nU?.role==="user"?n:`${n} [data-search-target]`)??tl.current?.querySelector(n):null,i=(e={pending:nF??null,searchTarget:t??null,elementFound:!!r}).pending?e.pending!==e.searchTarget?"clear-stale":e.elementFound?"commit":"retry":"ignore";"ignore"===i||"retry"===i||("clear-stale"===i?nO(null):r&&nF&&(nJ(),tI(r),r.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500}),nO(null),o?.(nF)))},[eS,nJ,ek.length,nE,nF,t,nU,tl,tI,o,nS]),(0,i.useEffect)(()=>{nC(0),nN(50)},[e?.id]),(0,i.useEffect)(()=>{let e=tl.current;e&&(tM||eM.isStreaming)&&nu(e.scrollTop,e.clientHeight,e.scrollHeight)&&nC(0)},[tM,eM.isStreaming,tl]),(0,i.useEffect)(()=>{let e=tl.current;if(!e)return void tH(!1);let t=()=>{let t=e.scrollHeight-e.scrollTop-e.clientHeight;tH(nS>0||t>160)},n=()=>{t(),nz.current||nS>0||nu(e.scrollTop,e.clientHeight,e.scrollHeight)&&(nC(0),nN(50))};t();let r=new ResizeObserver(t);return r.observe(e),nR.current&&r.observe(nR.current),e.addEventListener("scroll",n,{passive:!0}),()=>{r.disconnect(),e.removeEventListener("scroll",n)}},[tP,ey,tl,e?.id,nS]);let nY=(0,i.useCallback)(()=>{if(nW.current||nz.current)return;let t=tl.current;if(nT.current.startIndex>0){let e=nR.current;if(e&&t){let n=t.getBoundingClientRect().top;nL.current=iR(Array.from(e.children).flatMap((e,t)=>{if(!(e instanceof HTMLElement))return[];let n=e.dataset.entryId||e.dataset.slotIndex||`slot-${t}`,r=e.getBoundingClientRect();return[{entryId:n,top:r.top,bottom:r.bottom}]}),n)}nC(e=>e+25),nN(50);return}if(!eI||!eC)return;let n=e?.id??ts.current;n&&(nW.current=!0,t&&(n$.current=t.scrollHeight-t.scrollTop),tC(n,tE,eC).finally(()=>{nW.current=!1}))},[eC,eI,e,tE,tC,ts,tl]);(0,i.useEffect)(()=>{let e=nI.current,t=tl.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nY()},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nY,tl]),(0,i.useEffect)(()=>{let e=nM.current,t=tl.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&!nz.current&&nC(e=>Math.max(0,e-25))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nS,tl]),(0,i.useLayoutEffect)(()=>{let e=nL.current,t=nR.current;if(!e||!t)return;let n=Array.from(t.children).find((t,n)=>t instanceof HTMLElement&&(t.dataset.entryId||t.dataset.slotIndex||`slot-${n}`)===e.anchorEntryId);n instanceof HTMLElement&&tI(n,e.anchorOffset),nL.current=null},[nS,tI]),(0,i.useEffect)(()=>{if(null==n$.current)return;let e=tl.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-n$.current),n$.current=null}},[ek.length,tl]);let nZ=e1?[e1.sessionId,e1.sessionFile??"",e1.sessionName??"",e1.userMessages,e1.assistantMessages,e1.toolCalls,e1.toolResults,e1.totalMessages,e1.tokens.input,e1.tokens.output,e1.tokens.cacheRead,e1.tokens.cacheWrite,e1.tokens.total,e1.cost??0,e1.totalActiveMs??0,e1.contextUsage?.percent??"null",e1.contextUsage?.contextWindow??"",e1.contextUsage?.tokens??"null"].join("|"):null,nX=(0,i.useRef)(e1);nX.current=e1,(0,i.useEffect)(()=>{ey||P?.(nX.current)},[ey,nZ,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let nG=eV?`${eV.percent??"null"}|${eV.contextWindow}|${eV.tokens??"null"}`:null,nQ=(0,i.useRef)(eV);nQ.current=eV,(0,i.useEffect)(()=>{ey||D?.(nQ.current)},[nG,ey,D]),(0,i.useEffect)(()=>()=>{D?.(null)},[D]);let{isDragOver:n0,handleDragEnter:n1,handleDragOver:n2,handleDragLeave:n4,handleDrop:n8}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:o,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{er.current?.addImages(e)},[])),n5=e?.cwd??d??void 0,n6=(0,i.useMemo)(()=>ek.filter(e=>tG(e)||"assistant"===e.role||"toolResult"===e.role&&!e.isError&&eb(e.details)),[ek]),n3=(0,i.useMemo)(()=>{let e=new Map(ej);for(let t of ek)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ej,ek]),n7=(0,i.useMemo)(()=>new Set(ti?.kind==="running_tools"?ti.tools.map(e=>e.id):[]),[ti]),n9=(0,i.useMemo)(()=>ek.map(e=>"assistant"===e.role?t3(e):null),[ek]),re=(0,i.useMemo)(()=>{let e=new Map;for(let t=0;t<ek.length;){let n=tG(ek[t])?t:-1,r=n>=0?t+1:t;for(;r<ek.length&&!tG(ek[r]);)r+=1;let i=iz(ek,n,r);if(i>=0&&n9[i]?.answerMessage){let t=[];for(let e=n+1;e<=i;e+=1){let n=ek[e];n?.role==="assistant"&&t.push(...n.content)}e.set(i,function(e,t,n){let r=new Set,i=[];for(let o of e){if("toolCall"!==o.type||!function(e){let t;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||nl(e)||na(e)}(o.toolName))continue;let e=t?.get(o.toolCallId);if(e&&!e.isError)for(let e of function(e){let t=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(e);if(t)return[t];let n="string"==typeof e?.patch?e.patch:null;return n?function(e){let t=nt(e);if(!t)return[];let n=[];for(let e of t){let t=e.moveTo??e.path;t&&!n.includes(t)&&n.push(t)}return n}(n):[]}(o.input)){let t=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,o=i(e),s=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(o),a=o.startsWith("//");if(l||a)n=o;else if(o.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${o}`:o}else{if(!s)return null;n=`${s}/${o}`}return no(n)}(e,n);t&&(r.has(t)||(r.add(t),i.push({filePath:t})))}}return i}(t,n3,n5))}t=r}return e},[n9,n5,ek,n3]),rt=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ek.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(ek[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ek]),rn=(Y=n6.length,(Z=(0,i.useRef)([])).current=Array(Y).fill(null).map((e,t)=>Z.current[t]??null),Z),rr=(0,i.useMemo)(()=>{for(let e=ek.length-1;e>=0;e--)if(ek[e]?.role==="user")return eS[e]??"";return""},[eS,ek]);(0,i.useEffect)(()=>{let e=nH.current;nH.current=tE,null!==e&&e!==tE&&(nz.current?.abort(),nB.current&&(eg(null),ex(!1)))},[tE]),(0,i.useEffect)(()=>()=>{nz.current?.abort()},[e?.id]);let ri=(0,i.useCallback)(async t=>{let n=e?.id??ts.current;if(!n)return;nz.current?.abort();let r=new AbortController;nz.current=r,nA(null),nO(null);try{n$.current=null,nL.current=null,await nK(t,n,r.signal),r.signal.throwIfAborted(),await new Promise((e,n)=>{r.signal.addEventListener("abort",()=>n(r.signal.reason),{once:!0}),nA({entryId:t,signal:r.signal,resolve:e})})}catch(e){if(nm(e,r.signal))return;te({type:"warning",message:e instanceof nh&&"stalled"===e.reason?X("chat.locateHistoryStalled"):e instanceof nh&&"load_failed"===e.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")})}finally{nA(e=>e?.signal===r.signal?null:e),nz.current===r&&(nz.current=null)}},[te,nK,e?.id,ts,X]);(0,i.useLayoutEffect)(()=>{if(!nP||nP.signal.aborted)return;let e=nR.current?.querySelector(`[data-entry-id="${CSS.escape(nP.entryId)}"]`);e&&(nJ(),tI(e),nP.resolve())},[nP,eS,nJ,ek.length,nE,nS,tI]);let ro=!!eM.streamingMessage?.content.length,rs=(0,i.useMemo)(()=>{let e=-1;for(let t=ek.length-1;t>=0;t--)if(tG(ek[t])){e=t;break}let t=e>=0&&tX(ek[e])?e:e+1;for(let e=t;e<ek.length;e++){let t=ek[e];if("custom"===t.role||"assistant"===t.role&&(t0(t).length>0||t1(t)))return!0}return!1},[ek]),rl=eM.streamingMessage?.role==="assistant"?eM.streamingMessage:null,ra=rl?t3(rl,{isStreaming:!0}):{processMessage:null,answerMessage:null},rd=(0,i.useRef)(T);(0,i.useLayoutEffect)(()=>{let e=rd.current;rd.current=T,!e&&T&&tM&&!tD&&tN("instant")},[T,tM,tD,tN]);let rc=eQ?eO[`${eQ.provider}:${eQ.modelId}`]??null:null,ru=eQ?eU[`${eQ.provider}:${eQ.modelId}`]??null:null,rp=(0,i.useCallback)(async(e,t)=>{ec(),nz.current?.abort(),nA(null),nO(null),nC(0),nN(50),await ta(e,t)},[ta,ec]),rf=(0,i.useCallback)(e=>(ec(),th(e)),[th,ec]),rg=(0,i.useCallback)((e,t)=>(ec(),tm(e,t)),[tm,ec]),rm=(0,i.useCallback)((e,t)=>(ec(),tx(e,t)),[tx,ec]),rx=(0,i.useCallback)((e,t,n)=>(ec(),tv(e,t,n)),[tv,ec]),rv=!to&&ey,ry=e?.relation?.kind==="subagent"&&"queued"===e.relation.status,rb=(0,r.jsx)(tA,{ref:ei,onSend:rp,onOpenImageGeneration:!tF||rv||tM||ry?void 0:e=>{tK(null),tJ(e),tQ(e=>e+1),t_(!0)},onAbort:tT,onSteer:eT?rg:void 0,onFollowUp:eT?rm:void 0,onPromptWithStreamingBehavior:eT?rx:void 0,isStreaming:tM||ry,disabled:ry,model:rv?null:eQ,isAutoModelSelection:!rv&&tn,modelNames:eW,modelList:eA,modelError:rv?null:eD,modelScopeWarnings:rv?[]:eH,onModelChange:rv||ry?void 0:tf,modelSwitching:e0,onCompact:!ry&&(e||to)?tg:void 0,onAbortCompaction:ty,isCompacting:eY,compactError:eZ,compactResult:eG,contextUsage:rv?null:eV,cacheHitRate:t$,onOpenSessionStats:A,toolPreset:e_,onToolPresetChange:!ry&&(e||to)?tk:void 0,thinkingLevel:rv?void 0:eq,onThinkingLevelChange:rv||ry?void 0:e||to?tj:void 0,availableThinkingLevels:rc,thinkingLevelMap:ru,retryInfo:eK,queuedMessages:e8,inputHistory:rt,onRecallQueue:tb,slashCommands:e2,slashCommandsLoading:e4,onLoadSlashCommands:tS,onBuiltinCommand:nv,soundEnabled:q,onSoundToggle:K,onAudioUnlock:J,draftKey:e?.id??c??void 0,onDraftChange:u,draftPersistenceWarning:y,cwd:e?.cwd??d});return ey?(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[(0,r.jsx)("div",{className:"relative flex min-h-0 min-w-0 flex-1 items-center justify-center",children:(0,r.jsx)("div",{className:"text-sm text-text-muted",children:X("chat.loadingSession")})}),(0,r.jsx)("div",{className:"relative shrink-0",children:rb})]}):ew?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ew}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:n1,onDragOver:n2,onDragLeave:n4,onDrop:n8,children:[n0&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{className:"notice-shelf-wrapper",style:{position:"absolute",top:12,left:0,right:0,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(iK,{notices:e5,floating:!0,onPauseChange:tt})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[tU&&tF&&(0,r.jsx)(tB,{config:tF,edit:tq,initialSourceImage:tV,editPreviewUrl:tq?`/api/files/${j(tq.path.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(tq.path)?tq.path:n5?N(n5,tq.path):tq.path)}?type=read`:void 0,onClose:()=>{t_(!1),tK(null)},onSubmit:nx}),e6&&(0,r.jsx)(iV,{request:e6,onRespond:e7},e6.id),e3&&(0,r.jsx)(iJ,{request:e3,onInput:e9},e3.id),!tP&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:tl,className:"min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",style:{overflowAnchor:"none",overscrollBehaviorY:"contain",visibility:ef?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:nR,onPointerUp:nb,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var n,i;let o=-1;for(let e=ek.length-1;e>=0;e--)if(tG(ek[e])){o=e;break}let s=new Map,l=0;ek.forEach((e,t)=>{let n=("toolResult"!==e.role||e.isError)&&("custom"!==e.role||e.customType!==ep)?null:eb(e.details);(tG(e)||"assistant"===e.role||n)&&s.set(t,l++)});let a=(t,n={})=>{var i,o;let l,a,d,c=n.messageOverride??ek[t],u="user"===c.role&&t>0&&"assistant"===ek[t-1].role?eS[t-1]:void 0,h=("toolResult"!==c.role||c.isError)&&("custom"!==c.role||c.customType!==ep)?null:eb(c.details),p=tG(c)||"assistant"===c.role||!!h,f=s.get(t),g=n.keyPrefix??"message",m=eS[t]??t,x=h?(0,r.jsx)(eE,{value:h,cwd:n5,onEdit:tF&&!tM&&tF.connections.some(e=>e.id===h.connection&&!0===e.capabilities.editing)?e=>{tK(e),tQ(e=>e+1),t_(!0)}:void 0,onMention:tF?e=>{er.current?.mentionImage(e)}:void 0,showPrompt:"custom"===c.role,createdAt:c.timestamp},`${g}-image-${m}`):(0,r.jsx)(rh,{message:c,modelName:n.isTurnEnd&&"assistant"===c.role?(i=c.provider??"",o=c.model??"",l=i.toLowerCase(),a=o.toLowerCase(),d=Object.entries(eW??{}).flatMap(([e,t])=>{let n=e.indexOf(":");return n>0&&e.slice(0,n).toLowerCase()===l?[{id:e.slice(n+1).toLowerCase(),name:t}]:[]}),d.find(e=>e.id===a)?.name??d.find(e=>a.endsWith(`/${e.id}`))?.name??Object.entries(eW??{}).find(([e])=>e.toLowerCase()===a)?.[1]??(i&&o?`${i}/${o}`:o)):void 0,toolResults:n3,cwd:n5,onOpenFile:ed,onOpenSession:B,entryId:eS[t],searchBlock:eS[t]===nF?.entryId?n_:void 0,onFork:tM||to?void 0:rf,forking:eJ===eS[t],onNavigate:tM?void 0:tp,prevAssistantEntryId:tM?void 0:u,onEditContent:eu,isTurnEnd:n.isTurnEnd,sessionId:e?.id??ts.current??void 0,writtenFiles:n.writtenFiles,isProcess:n.isProcess,runningToolIds:"assistant"===c.role&&c.content.some(e=>"toolCall"===e.type&&n7.has(e.toolCallId))?n7:void 0},`${g}-view-${m}`);return p?(0,r.jsx)("div",{"data-entry-id":eS[t],"data-slot-index":`msg-${t}`,ref:!1===n.attachRef||void 0===f?void 0:e=>{rn.current[f]=e},children:x},`${g}-${m}`):x},d=(n={outline:nP?{entryId:nP.entryId,aborted:nP.signal.aborted}:null,search:nF?{entryId:nF.entryId,matchesTarget:nF===t}:null,restore:ef?{entryId:ef.anchorEntryId}:null}).outline&&!n.outline.aborted?n.outline.entryId:n.search&&n.search.matchesTarget?n.search.entryId:n.restore?n.restore.entryId:null,c=[],u=-1,h=e=>{var t,n;t=u,n=c.length,u=d&&e.includes(d)?n:t},p=0;for(let e=0;e<ek.length;){let t,n,i,l=tG(ek[e]),u=tZ(ek[e]),f=l?e:-1,g=f>=0&&tX(ek[f]),m=l?e+1:e;for(;m<ek.length&&!tG(ek[m]);)m+=1;let x=l?f:e,v=g?f:f+1,y=iz(ek,f,m),b=(tM||eM.isStreaming)&&m===ek.length&&f===o;if(b&&(p=m-x),-1===y&&!g){for(let e=x;e<m;e++)h([eS[e]]),c.push(a(e));if(b&&ra.processMessage){h([]);let e=iA(!0,eM.isStreaming,rl,ti,!!ra.answerMessage),t=f>=0&&"number"==typeof ek[f]?.timestamp&&Number.isFinite(ek[f].timestamp)?ek[f].timestamp:ra.processMessage.timestamp,n=iF(t,ra.processMessage.completedAt);c.push((0,r.jsx)("div",{children:(0,r.jsx)(iU,{messageCount:1,toolCallCount:t5(ra.processMessage.content??[]),durationSeconds:n,startTime:t,defaultExpanded:!0,isMobile:G,activeStepSummary:iB(iH(ra.processMessage,ti,X),e,tL,X("chat.thinking")),isStreaming:e,t:X,children:(0,r.jsx)(rh,{message:ra.processMessage,isStreaming:!0,isProcess:!0,toolResults:n3,cwd:n5,onOpenFile:ed,onOpenSession:B},"streaming-process-view")})},`process-group-${eS[x]??x}`))}e=m;continue}u&&(h([eS[f]]),c.push(a(f)));let w=n9[y],k=w?.answerMessage??null,j=y>=0?y:m-1,S=[],C=[],E=[],N=0,I=!1;for(let e=v;e<=j;e++){let r=ek[e];if("number"==typeof r.timestamp&&Number.isFinite(r.timestamp)&&(n=void 0===n?r.timestamp:Math.min(n,r.timestamp),i=void 0===i?r.timestamp:Math.max(i,r.timestamp)),"assistant"===r.role&&"number"==typeof r.completedAt&&Number.isFinite(r.completedAt)&&(i=void 0===i?r.completedAt:Math.max(i,r.completedAt)),"custom"===r.role){t??=s.get(e),I||=!!(d&&d===eS[e]),eS[e]&&C.push(eS[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",isProcess:!0}));continue}if("assistant"!==r.role)continue;let o=n9[e];e!==y&&o?.answerMessage&&E.push({idx:e,message:o.answerMessage});let l=o?.processMessage;if(!l)continue;let c=t0(l),u=!!t1(l);(0!==c.length||u)&&(t??=s.get(e),N+=t5(c),I||=!!(d&&eS[e]===d&&(!n_||nF?.entryId!==d||c.includes(n_))),eS[e]&&C.push(eS[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",messageOverride:l,isTurnEnd:!1,isProcess:!0})))}b&&ra.processMessage&&(N+=t5(ra.processMessage.content??[]),S.push((0,r.jsx)(rh,{message:ra.processMessage,isStreaming:!0,isProcess:!0,toolResults:n3,cwd:n5,onOpenFile:ed,onOpenSession:B},"streaming-process-view")));let M=!!(k||ra.answerMessage),T=iA(b,eM.isStreaming,rl,ti,M),L=iB(iH(rl,ti,X),T,tL,X("chat.thinking")),R=f>=0&&"number"==typeof ek[f]?.timestamp&&Number.isFinite(ek[f].timestamp)?ek[f].timestamp:n,$=iF(R??n,i);S.length>0&&(h(C),c.push((0,r.jsx)("div",{"data-entry-id":eS[v],ref:void 0===t?void 0:e=>{rn.current[t]=e},children:(0,r.jsx)(iU,{messageCount:S.length,toolCallCount:N,durationSeconds:$,startTime:R??n,defaultExpanded:!k&&m===ek.length,reveal:I,isMobile:G,activeStepSummary:L,isStreaming:T,t:X,children:S})},`process-group-${eS[x]??x}`)));for(let e=x;e<=j;e++){let t=ek[e];"toolResult"===t.role&&!t.isError&&eb(t.details)&&(h([eS[e]]),c.push(a(e)))}for(let e of E)h([eS[e.idx]]),c.push(a(e.idx,{keyPrefix:"promoted",messageOverride:e.message}));if(k&&(h([eS[y]]),c.push(a(y,{isTurnEnd:!0,messageOverride:k,writtenFiles:re.get(y)}))),y>=0)for(let e=y+1;e<m;e++)h([eS[e]]),c.push(a(e));e=m}let f=Math.max(nE,50+p),{startIndex:g,endIndex:m}=u>=0?nc(i=c.length,i-Math.max(0,u-5)-50):nc(c.length,nS,f);nT.current={startIndex:g,endIndex:m,totalCount:c.length};let x=g>0||eI;return(0,r.jsxs)(r.Fragment,{children:[x&&(0,r.jsx)("button",{type:"button",ref:nI,onClick:nY,className:"w-full cursor-pointer py-3 text-center text-xs text-text-muted transition-colors hover:text-text focus-visible:outline-2 focus-visible:outline-accent",children:X("chat.loadEarlier")}),c.slice(g,m),m<c.length&&(0,r.jsx)("div",{ref:nM,className:"py-3 text-center text-xs text-text-muted"})]})})(),eM.isStreaming&&ra.answerMessage&&(0,r.jsx)(rh,{message:ra.answerMessage,isStreaming:!0,cwd:n5,onOpenFile:ed,onOpenSession:B}),eT&&!ro&&!rs&&(0,r.jsx)(i$,{label:X("chat.agentWorking")}),eR&&!e$&&(0,r.jsx)(i$,{label:X("chat.agentWorking")}),e$&&(0,r.jsx)(rh,{message:{role:"bashExecution",command:e$.command,output:"",excludeFromContext:e$.excludeFromContext},sessionId:e?.id??ts.current??void 0,onOpenSession:B}),tW&&(0,r.jsx)(eN,{prompt:tW.prompt,size:tW.size,width:tW.width,height:tW.height,previewUrl:tW.previewUrl})]})})}),tD&&!ef&&(0,r.jsx)("button",{type:"button",onClick:()=>{nz.current?.abort(),nA(null),nO(null),nC(0),nN(50),requestAnimationFrame(()=>tN("smooth"))},className:"absolute bottom-3 right-5 z-30 inline-flex h-7 w-7 items-center justify-center rounded-[4px] border border-[var(--border)] bg-[var(--bg)] text-[var(--text-muted)] transition-colors hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:X("chat.scrollToBottom"),"aria-label":X("chat.scrollToBottom"),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m7 10 5 5 5-5"})})}),G&&L&&(0,r.jsx)(rZ,{sessionId:e?.id??ts.current,leafId:tE,outlineRevision:rr,scrollContainer:tl,contentContainer:nR,loadedEntryIds:eS,onJumpToEntry:ri}),!L||G||ef?null:(0,r.jsx)(rY,{sessionId:e?.id??ts.current,leafId:tE,outlineRevision:rr,scrollContainer:tl,contentContainer:nR,loadedEntryIds:eS,onJumpToEntry:ri})]})]}),O&&t2&&(0,I.createPortal)((0,r.jsx)("div",{ref:nr,role:t8?"dialog":"toolbar","aria-label":X(t8?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:t2.top,left:t2.left,zIndex:130,display:"flex",flexWrap:"wrap",gap:2,width:t8?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:t8?12:2,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)"},children:t8?(0,r.jsxs)("fieldset",{disabled:t7,"aria-busy":t7,style:{width:"100%",minWidth:0,margin:0,padding:0,border:"none",display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12,fontWeight:600},children:X("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:X("i18n.close"),"aria-label":X("i18n.close"),disabled:t7,onClick:ny,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(tA,{ref:ni,compact:!0,onSend:nk,onAbort:ny,isStreaming:!1}),ne&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:ne})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[4px] border-0 bg-transparent px-2 text-[11px] font-medium text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:X("chat.askInCurrent"),"aria-label":X("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:nw,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"@"}),(0,r.jsx)("span",{children:X("chat.askInCurrent")})]}),F&&t2.sourceEntryId&&!tM&&(0,r.jsxs)("button",{type:"button",className:"inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[4px] border-0 bg-transparent px-2 text-[11px] font-medium text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:X("chat.askInNewChat"),"aria-label":X("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{t6(!0),window.getSelection()?.removeAllRanges()},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:X("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[tP&&(0,r.jsxs)("div",{className:"mx-auto mb-6 flex select-none flex-col items-center justify-center text-center",style:{maxWidth:"var(--chat-content-max-width, 820px)",padding:"0 16px"},children:[(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:10,lineHeight:1},children:[(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 82 32",width:"82",height:"32",fill:"currentColor",role:"img","aria-label":"Pi Web",style:{color:"var(--text)",flexShrink:0,display:"block"},children:(0,r.jsx)("path",{d:"M0 0H24V16H16V8H0ZM0 8H8V16H16V24H8V32H0ZM24 16H32V32H24ZM44 16H46V26H44ZM46 26H48V32H46ZM48 22H50V26H48ZM50 26H52V32H50ZM52 16H54V26H52ZM60 16H68V18H60ZM58 18H60V30H58ZM60 22H66V24H60ZM60 30H68V32H60ZM72 16H80V18H74V22H80V24H74V30H80V32H72ZM80 18H82V22H80ZM80 24H82V30H80Z"})}),(0,r.jsx)(iL,{})]}),d&&p&&(0,r.jsx)(iW,{cwd:d,onChange:p,recentPaths:f,pinnedPaths:g,onTogglePinnedCwd:m,homeDir:x,worktreeInfo:v})]}),rb]}),tP&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function iq({type:e}){return"success"===e?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#10b981",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})}):"error"===e?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),(0,r.jsx)("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}):"warning"===e?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#d97706",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function iK({notices:e,floating:t=!1,onPauseChange:n}){return 0===e.length?null:(0,r.jsx)("div",{className:"notice-shelf-root",style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!t},children:e.map((i,o)=>(0,r.jsxs)("div",{className:"notice-shelf-item",onMouseEnter:()=>n?.(i.id),onMouseLeave:e=>{e.currentTarget.contains(document.activeElement)||n?.(null)},onFocus:()=>n?.(i.id),onBlur:e=>{e.currentTarget.matches(":hover")||n?.(null)},style:{display:"flex",alignItems:"flex-start",gap:8,minHeight:34,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(o!==e.length-1),overflow:"hidden",borderRadius:8,border:"1px solid var(--border)",background:"color-mix(in srgb, var(--bg) 95%, var(--bg-panel))",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"var(--text)",width:"fit-content",maxWidth:"min(100%, 540px)",boxShadow:t?"0 4px 16px -2px rgba(0, 0, 0, 0.12), 0 2px 6px -1px rgba(0, 0, 0, 0.06)":"0 2px 8px -2px rgba(0, 0, 0, 0.08)",fontSize:13,lineHeight:1.45,transformOrigin:"top right",animation:i.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"8px 12px"},children:[(0,r.jsx)(iq,{type:i.type}),(0,r.jsx)("span",{tabIndex:0,style:{minWidth:0,maxWidth:"100%",maxHeight:480,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:i.message})]},i.id))})}function iV({request:e,onRespond:t}){let{t:n}=(0,w.s)(),[o,s]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(()=>Date.now()),u=(0,i.useCallback)(e=>e?.focus(),[]),h=function(e){if("select"===e.method&&e.options.length>0)return e.options[0];if("confirm"===e.method){let t=e.message.split("\n").find(e=>e.trim());return t?.trim()}}(e),p=void 0===e.expiresAt?null:Math.max(0,Math.ceil((e.expiresAt-d)/1e3));(0,i.useEffect)(()=>{if(void 0===e.expiresAt)return;let t=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(t)},[e.expiresAt]);let f=null!==p&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionExpiresIn",{seconds:p})}),g=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};return(0,r.jsx)("div",{onKeyDown:n=>{"Escape"!==n.key||n.nativeEvent.isComposing||(n.preventDefault(),n.stopPropagation(),t(e,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:l?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:l?(0,r.jsxs)("button",{type:"button",onClick:()=>a(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:e.title}),h&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:h}),f,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:n("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog","aria-label":e.title,style:{pointerEvents:"auto",width:"min(560px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"flex-start",gap:8,padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650},children:e.title}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:3,color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:n("chat.extensionRequest")}),f]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>a(!0),"aria-expanded":!0,title:n("chat.extensionCollapse"),"aria-label":n("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===e.method&&(0,r.jsx)(n7,{children:e.message}),"select"===e.method&&(0,r.jsx)("div",{onKeyDown:e=>{if(!["ArrowDown","ArrowRight","ArrowUp","ArrowLeft","Home","End"].includes(e.key))return;let t=Array.from(e.currentTarget.querySelectorAll("[data-extension-option]")),n=t.indexOf(e.target);if(n<0)return;e.preventDefault();let r="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key||"ArrowRight"===e.key?1:-1)+t.length)%t.length;t[r].focus({preventScroll:!0}),t[r].scrollIntoView({block:"nearest"})},style:{display:"grid",gap:8},children:e.options.map((n,i)=>(0,r.jsx)("div",{role:"button",tabIndex:0,"data-extension-option":!0,"aria-label":n,ref:0===i?u:void 0,onClick:()=>t(e,{value:n}),onKeyDown:r=>{("Enter"===r.key||" "===r.key)&&(r.preventDefault(),t(e,{value:n}))},style:{width:"100%",padding:"9px 10px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13,overflowWrap:"anywhere"},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(n7,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>s(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||g()},style:{width:"100%",padding:"9px 10px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&g()},style:{width:"100%",minHeight:220,padding:10,borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:13,lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 14px",borderTop:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("button",{autoFocus:"confirm"===e.method||"select"===e.method&&0===e.options.length,onClick:()=>t(e,{cancelled:!0}),style:{padding:"6px 10px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"},children:n("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:g,style:{padding:"6px 10px",borderRadius:4,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:n("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:g,style:{padding:"6px 10px",borderRadius:4,border:"1px solid var(--accent)",background:"var(--accent)",color:"#fff",cursor:"pointer"},children:n("chat.submit")}):null]})]})})}function iJ({request:e,onInput:t}){let{t:n}=(0,w.s)(),o=(0,i.useRef)(null),s=(0,i.useRef)(!1),[l,a]=(0,i.useState)(!1),d=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(tU,""),i=t_(e).trimEnd();if(t.test(i))continue;let o=e,s=tV(o);("│"===s||"┃"===s)&&" "===tV(o=tK(o,0))&&(o=tK(o,0));let l=function(e){let t=tq(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=l>=0?tq(o)[l]?.char:void 0;("│"===a||"┃"===a)&&(o=tK(o,l)),n.push(function(e){let t=e;for(;;){let e=tq(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(o))}for(;n.length>0&&""===t_(n[0]).trim();)n.shift();for(;n.length>0&&""===t_(n[n.length-1]).trim();)n.pop();return n.length?n:e}(e.lines),c=d.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{l||o.current?.focus()},[l]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:l?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:l?(0,r.jsxs)("button",{type:"button",onClick:()=>a(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n("chat.extensionPanel")}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:c}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:n("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||o.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:o,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=tY[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":tJ[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("button",{type:"button",onClick:()=>a(!0),"aria-expanded":!0,title:n("chat.extensionCollapse"),"aria-label":n("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,minHeight:0,overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(0,r.jsx)(rG,{text:d.join("\n")})})]})})}function iY({tabs:e,activeTabId:t,splitTabId:n=null,activePane:o="primary",runningSessionIds:s,onSelectTab:l,onCloseTab:a,onPinTab:d,onNewTab:c,onToggleSplit:u,onClosePane:h,canSplit:p=!0,isSecondaryPane:f=!1,unifiedHeader:g=!1,isMobile:m=!1}){let{t:x}=(0,w.s)(),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(!1),[j,S]=(0,i.useState)(!1),[C,E]=(0,i.useState)({top:0,left:0,width:320}),N=(0,i.useRef)(null),M=(0,i.useRef)(null),T=(0,i.useRef)(null),L=(0,i.useRef)(null);(0,i.useEffect)(()=>{N.current&&N.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),(0,i.useEffect)(()=>{let e=M.current;if(!e)return;let t=()=>k(e.scrollWidth>e.clientWidth+1);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[e]),(0,i.useEffect)(()=>{if(!j)return;let e=e=>{let t=e.composedPath();L.current&&t.includes(L.current)||T.current&&t.includes(T.current)||S(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),S(!1),T.current?.focus())},n=()=>S(!1);return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),window.addEventListener("resize",n),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0),window.removeEventListener("resize",n)}},[j]),(0,i.useEffect)(()=>{b||S(!1)},[b]);let R=!!(n&&!m),$=e=>{let t=e?Array.from(document.querySelectorAll("[data-chat-tab-id]")).find(t=>t.dataset.chatTabId===e):null,n=N.current??document.querySelector('[data-chat-tab="true"][tabindex="0"]'),r=Array.from(document.querySelectorAll(".chat-input-textarea")).find(e=>e.getClientRects().length>0);(t??n??r)?.focus()};return(0,r.jsxs)("div",{role:"tablist","aria-label":x("chatTabs.label",{defaultValue:"对话标签"}),style:{display:"flex",alignItems:"stretch",background:g?"transparent":"var(--bg-panel)",borderBottom:g?"none":"1px solid var(--border)",height:"var(--workspace-header-height, 30px)",minHeight:"var(--workspace-header-height, 30px)",maxHeight:"var(--workspace-header-height, 30px)",width:g?"auto":"100%",maxWidth:"100%",minWidth:0,flex:g?"0 1 auto":"0 0 auto",flexShrink:0,overflow:"hidden",position:"relative"},children:[(0,r.jsx)("div",{ref:M,onWheel:e=>{e.deltaY&&!e.deltaX&&(e.currentTarget.scrollLeft+=e.deltaY)},style:{display:"flex",alignItems:"stretch",flex:"0 1 auto",minWidth:0,overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none",WebkitOverflowScrolling:"touch",touchAction:"pan-x",overscrollBehaviorX:"contain"},children:e.map((i,c)=>{let u=i.id===t,h=i.id===n,p=u||h,f=u&&"primary"===o||h&&"secondary"===o,g="session"===i.kind&&!!(i.session&&s?.has(i.session.id));return(0,r.jsxs)("div",{"data-chat-tab":"true","data-chat-tab-id":i.id,ref:u?N:void 0,role:"tab","aria-label":i.dirty?`${i.title}, ${x("chatTabs.unsentDraft")}`:i.title,"aria-selected":p,tabIndex:f||!t&&0===c?0:-1,onClick:()=>l(i.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),a(i.id))},onDoubleClick:()=>d?.(i.id),onKeyDown:t=>{if(t.target===t.currentTarget){if("Enter"===t.key||" "===t.key)t.preventDefault(),l(i.id);else if(["ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault();let n=(c+("ArrowRight"===t.key?1:-1)+e.length)%e.length;l(e[n].id),t.currentTarget.parentElement?.children[n]?.focus()}else if("Delete"===t.key){if(t.preventDefault(),!1===a(i.id))return;requestAnimationFrame(()=>{$()})}}},style:{display:"flex",alignItems:"center",gap:m?4:6,height:"100%",paddingLeft:m?8:10,paddingRight:m?p?4:8:4,borderRight:"1px solid var(--border)",background:p?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:p?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:m?130:200,minWidth:m?70:84,flexShrink:0,userSelect:"none",WebkitUserSelect:"none",touchAction:"pan-x",position:"relative",transition:"background 0.12s, color 0.12s",boxShadow:f?"inset 0 -2px 0 var(--accent)":void 0},title:i.preview?`${i.title} \xb7 ${x("chatTabs.previewTabHint",{defaultValue:"预览标签,双击固定"})}`:i.title,children:[(g||"draft"===i.kind)&&(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:g?"var(--accent)":p?"var(--text)":"var(--text-dim)"},children:g?(0,r.jsx)(Z,{size:12,ariaLabel:"Running"}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:p?500:400,fontStyle:i.preview?"italic":"normal"},children:i.title}),"draft"===i.kind&&i.dirty&&(0,r.jsx)("span",{title:x("chatTabs.unsentDraft"),"aria-hidden":"true",style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",flexShrink:0}}),(!m||p)&&(0,r.jsx)("button",{type:"button",tabIndex:-1,onClick:e=>{e.stopPropagation(),a(i.id)},onDoubleClick:e=>e.stopPropagation(),onMouseEnter:()=>y(i.id),onMouseLeave:()=>y(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:m?22:20,height:m?22:20,background:v===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:3,color:v===i.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:x("chatTabs.closeTab",{defaultValue:"关闭标签"}),"aria-label":`${x("chatTabs.closeTab",{defaultValue:"关闭标签"})}: ${i.title}`,children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},i.id)})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,background:g?"transparent":"var(--bg-panel)",boxShadow:m?"-4px 0 10px -2px rgba(0,0,0,0.18)":void 0,zIndex:2,position:"relative"},children:[b&&!m&&(0,r.jsx)("button",{ref:T,type:"button",onClick:()=>{if(j)return void S(!1);let e=T.current.getBoundingClientRect(),t=Math.min(320,window.innerWidth-16);E({top:e.bottom+4,left:Math.max(8,Math.min(e.right-t,window.innerWidth-t-8)),width:t}),S(!0)},"aria-expanded":j,title:x("chatTabs.allTabs"),"aria-label":x("chatTabs.allTabs"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",padding:0,border:"none",background:j?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13M8 12h13M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01M3 12h.01M3 18h.01"})]})}),(0,r.jsx)("button",{type:"button",onClick:c,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:x("chatTabs.newTab",{defaultValue:"新建对话标签"}),"aria-label":x("chatTabs.newTab",{defaultValue:"新建对话标签"}),onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="transparent"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),!f&&p&&!m&&u&&(0,r.jsx)("button",{type:"button",onClick:u,"aria-pressed":R,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:R?"var(--bg-selected)":"transparent",border:"none",color:R?"var(--accent)":"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:R?x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):x("chatTabs.splitView",{defaultValue:"向右分屏"}),"aria-label":R?x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):x("chatTabs.splitView",{defaultValue:"向右分屏"}),onMouseEnter:e=>{R||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{R||(e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="transparent")},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]})}),f&&h&&(0,r.jsx)("button",{type:"button",onClick:h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),"aria-label":x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="transparent"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),j&&(0,I.createPortal)((0,r.jsx)("div",{ref:L,role:"dialog","aria-label":x("chatTabs.allTabs"),style:{position:"fixed",top:C.top,left:C.left,width:C.width,zIndex:700,padding:6,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",boxShadow:"0 8px 24px rgba(0,0,0,0.16)"},children:(0,r.jsx)("div",{style:{maxHeight:"min(50vh, 360px)",overflowY:"auto"},children:e.map((e,i)=>{let o=e.id===t||e.id===n,d="session"===e.kind&&!!(e.session&&s?.has(e.session.id));return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",minWidth:0,background:o?"var(--bg-selected)":"transparent",borderRadius:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{S(!1),l(e.id),requestAnimationFrame(()=>$(e.id))},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,height:30,padding:"0 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12},children:[d?(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:12,height:12,flexShrink:0},children:(0,r.jsx)(Z,{size:10})}):(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",flexShrink:0,background:e.dirty?"var(--accent)":"transparent"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title})]}),(0,r.jsx)("button",{type:"button","data-tab-menu-close":e.id,onClick:()=>{!1!==a(e.id)&&requestAnimationFrame(()=>{let e=M.current;if(e&&e.scrollWidth>e.clientWidth+1){let e=L.current?.querySelectorAll("[data-tab-menu-close]"),t=e?.[Math.min(i,e.length-1)];if(t)return void t.focus()}S(!1),$()})},title:`${x("chatTabs.closeTab")}: ${e.title}`,"aria-label":`${x("chatTabs.closeTab")}: ${e.title}`,style:{width:28,height:28,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M2 2l6 6M8 2 2 8"})})})]},e.id)})})}),document.body)]})}function iZ(e,t){let n=e.split(/\r?\n/).find(e=>e.trim())?.trim();if(!n)return t;let r=Array.from(n);return r.length<=48?n:`${r.slice(0,47).join("")}…`}function iX(e){return e.pane??"primary"}function iG(e,t){return e.filter(e=>iX(e)===t)}function iQ(e,t,n="primary"){let r=e.findIndex(e=>e.id===t.id),i=p(t);if(r>=0){let n=[...e];return n[r]={...n[r],session:t,title:i,projectKey:t.projectKey??t.cwd},{tabs:n,tabId:t.id}}let o=e.findIndex(e=>!0===e.preview&&iX(e)===n);if(o>=0){let r=[...e];return r[o]={id:t.id,kind:"session",title:i,session:t,newSessionCwd:null,newSessionDraftKey:null,projectKey:t.projectKey??t.cwd,preview:!0,pane:n},{tabs:r,tabId:t.id}}return{tabs:[...e,{id:t.id,kind:"session",title:i,session:t,newSessionCwd:null,newSessionDraftKey:null,projectKey:t.projectKey??t.cwd,preview:!0,pane:n}],tabId:t.id}}function i0(e,t){let n=e.findIndex(e=>e.id===t);if(-1===n||!0!==e[n].preview)return e;let r=[...e];return r[n]={...r[n],preview:!1},r}function i1(e,t){let n=[...iG(e,"primary"),...iG(e,"secondary")],r=n.find(e=>e.id===t&&e.preview)??n.find(e=>e.preview);return n.map(e=>({...e,pane:"primary",preview:!0===e.preview?e.id===r?.id:e.preview}))}function i2(e,t,n="primary"){let r=e.findIndex(e=>e.id===t.id),i=p(t);if(r>=0){let n=[...e];return n[r]={...n[r],session:t,title:i,projectKey:t.projectKey??t.cwd,preview:!1},{tabs:n,tabId:t.id}}return{tabs:[...e,{id:t.id,kind:"session",title:i,session:t,newSessionCwd:null,newSessionDraftKey:null,projectKey:t.projectKey??t.cwd,pane:n}],tabId:t.id}}function i4(e,t,n,r="新会话",i="primary"){let o=`draft:${n}`;return e.find(e=>e.id===o)?{tabs:e,tabId:o}:{tabs:[...e,{id:o,kind:"draft",title:r,session:null,newSessionCwd:t,newSessionDraftKey:n,projectKey:t,dirty:!1,pane:i}],tabId:o}}function i8(e,t,n,r=null){let i=e.findIndex(e=>e.id===t);if(-1===i)return{tabs:e,nextActiveTabId:n,nextSplitTabId:r};let o=e.filter(e=>e.id!==t),s=iX(e[i]),l=iG(e,s),a=iG(o,s),d=a[Math.min(l.findIndex(e=>e.id===t),a.length-1)]?.id??null,c=t===n?d:n,u=t===r?d:r;if(r&&0===a.length){let e="primary"===s?u:c;return{tabs:i1(o,e),nextActiveTabId:e,nextSplitTabId:null}}return{tabs:o,nextActiveTabId:c,nextSplitTabId:u}}var i5=n(50640);let i6={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},i3={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},i7={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function i9(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function oe(e){return null!==(i6[i9(e)]??null)}function ot(e){return null!==(i3[i9(e)]??null)}function on(e){return null!==(i7[i9(e)]??null)}function or(e){let t;return null!==("pdf"===(t=i9(e))||"docx"===t?t:null)}let oi=new Set(["md","mdx","html","htm"]);var oo=n(73620);let os=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function ol(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}function oa(e,t){if(e[t]?.level!==3)return -1;for(let n=t-1;n>=0;n--)if(e[n].level<3)return n;return -1}let od=/^ {0,3}(`{3,}|~{3,})/,oc=/^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*#*[ \t]*$/,ou=["tags","categories","keywords","tag","category"];function oh({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,o=ou.find(t=>Array.isArray(e[t])),s=o?e[o].map(ol).filter(Boolean):[],l=n.filter(([e])=>e!==o&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=ol(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}function op({items:e,scrollRoot:t}){let{t:n}=(0,w.s)(),o=(0,i.useId)(),s=(0,i.useRef)(null),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(()=>new Set),u=e.length>20;if((0,i.useEffect)(()=>{a(!1),c(new Set)},[e]),(0,i.useEffect)(()=>{if(!l)return;let e=e=>{s.current?.contains(e.target)||a(!1)},t=e=>{"Escape"===e.key&&a(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[l]),0===e.length)return null;let h=e.map(()=>!1);if(u)for(let t=0;t<e.length;t++){let n=oa(e,t);n>=0&&(h[n]=!0)}return(0,r.jsxs)("div",{ref:s,className:"file-outline",children:[(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button","aria-expanded":l,"aria-haspopup":"menu","aria-controls":o,"aria-label":n("i18n.outline"),title:n("i18n.outline"),onClick:()=>a(e=>!e),style:{background:l?"var(--bg-selected)":"transparent",color:l?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13"}),(0,r.jsx)("path",{d:"M8 12h13"}),(0,r.jsx)("path",{d:"M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01"}),(0,r.jsx)("path",{d:"M3 12h.01"}),(0,r.jsx)("path",{d:"M3 18h.01"})]})}),l&&(0,r.jsx)("div",{className:`file-outline-menu${u?" is-collapsible":""}`,id:o,role:"menu",children:e.map((n,i)=>{if(u&&3===n.level){let t=oa(e,i);if(t>=0&&!d.has(t))return null}return(0,r.jsxs)("div",{className:"file-outline-item","data-level":n.level,children:[h[i]?(0,r.jsx)("button",{type:"button",className:"file-outline-fold","aria-expanded":d.has(i),"aria-label":n.text,onClick:()=>{c(e=>{let t=new Set(e);return t.has(i)?t.delete(i):t.add(i),t})},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}):null,(0,r.jsx)("button",{type:"button",role:"menuitem",className:"file-outline-jump",title:n.text,onClick:()=>{!function(e,t,n){let r=t[n];if(!e||!r)return;let i=t.slice(0,n).filter(e=>e.text===r.text).length,o=0;for(let t of e.querySelectorAll(".markdown-file-preview :is(h1, h2, h3)"))if(t.textContent?.replace(/\s+/g," ").trim()===r.text){if(o===i)return void t.scrollIntoView({block:"start",inline:"nearest"});o++}}(t.current,e,i),a(!1)},children:n.text})]},`${n.level}-${i}-${n.text}`)})})]})}function of(e,t,n){var r;return r=n??(oi.has(i9(e))?"preview":void 0),t?.displayMode??r??"source"}let og={fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.6},om={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:1.6,userSelect:"none",flexShrink:0,verticalAlign:"top"};function ox(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function ov(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function oy(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=ov(n.startContainer),i=ov(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let o=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(o)||!Number.isInteger(s))return null;if(o<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(o=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return o>s?null:{startLine:o,endLine:s}}function ob({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,o)=>{let s=e.children??[],l=s[0]?.properties?.className,a=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=a?s[0]:null,c=a?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":o+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,i5.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${o}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,i5.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${o}-${r}`}))})]},`source-line-${o}`)})}function ow(e,t,n,r={}){let i=j(e),o=new URLSearchParams({type:t});for(let[e,t]of(n&&o.set("sessionId",n),Object.entries(r)))void 0!==t&&o.set(e,String(t));return`/api/files/${i}?${o.toString()}`}function ok({filePath:e,sourceSessionId:t}){let{t:n}=(0,w.s)();return(0,r.jsx)("a",{href:ow(e,"download",t),download:S(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function oj(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function oS({patch:e}){let{t}=(0,w.s)(),n=(0,i.useMemo)(()=>{let t;return(t=rn(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[{type:"hunk",text:e.text}];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[]},[e]),o=e.split(/\r?\n/).filter(e=>/^(?:similarity index|dissimilarity index|rename from|rename to|copy from|copy to|old mode|new mode|new file mode|deleted file mode|Binary files|Submodule )/.test(e));return o.length>0||n.some(e=>"added"===e.type||"removed"===e.type)?(0,r.jsxs)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...og},children:[o.map((e,t)=>(0,r.jsx)("div",{style:{padding:"2px 12px",color:"var(--text-muted)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:e},`${t}:${e}`)),n.map((e,t)=>{if("hunk"===e.type)return(0,r.jsx)("div",{style:{padding:"2px 12px",color:"var(--accent)",background:"var(--bg-panel)",borderBlock:"1px solid var(--border)"},children:e.text},`hunk-${t}`);let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{...om,width:40,minWidth:40,paddingInline:6},children:e.oldLineNo}),(0,r.jsx)("span",{style:{...om,width:40,minWidth:40,paddingInline:6},children:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:o,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)})]}):(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:t("i18n.noChanges")})}function oC({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:s}=(0,w.s)(),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),m(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),x.current&&(x.current.close(),x.current=null),!o)return;let t=!0,r=new EventSource(ow(e,"watch",n));x.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ow(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void m(e.error);"number"==typeof e.size&&h(e.size),f(null),m(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&m(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}f(null),m(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),x.current===r&&(x.current=null)}},[e,n,o]);let b=ow(e,"read",n,d?{v:d}:void 0),k=null!=u?oj(u):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:E(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),k&&(0,r.jsx)("span",{children:k}),(0,r.jsxs)("span",{title:s(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?"live":"static"]}),(0,r.jsx)(ok,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:b,alt:e,onLoad:e=>{let t=e.currentTarget;f({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>m("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function oE(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function oN({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:s}=(0,w.s)(),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),m(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),x.current&&(x.current.close(),x.current=null),!o)return;let t=!0,r=new EventSource(ow(e,"watch",n));x.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ow(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void m(e.error);"number"==typeof e.size&&h(e.size),f(null),m(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&m(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}f(null),m(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),x.current===r&&(x.current=null)}},[e,n,o]);let b=ow(e,"read",n,d?{v:d}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:E(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=p&&(0,r.jsx)("span",{children:oE(p)}),null!=u&&(0,r.jsx)("span",{children:oj(u)}),(0,r.jsxs)("span",{title:s(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?"live":"static"]}),(0,r.jsx)(ok,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:b,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>m("Failed to load audio"),style:{width:"100%"}},b)]})})]})}function oI({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:s}=(0,w.s)(),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),m(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),x.current&&(x.current.close(),x.current=null),!o)return;let t=!0,r=new EventSource(ow(e,"watch",n));x.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ow(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void m(e.error);"number"==typeof e.size&&h(e.size),f(null),m(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&m(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}f(null),m(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),x.current===r&&(x.current=null)}},[e,n,o]);let b=ow(e,"read",n,d?{v:d}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:E(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=p&&(0,r.jsx)("span",{children:oE(p)}),null!=u&&(0,r.jsx)("span",{children:oj(u)}),(0,r.jsxs)("span",{title:s(l?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?"live":"static"]}),(0,r.jsx)(ok,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:b,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>m("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},b)]})})]})}function oM({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0,pdfPage:s}){let{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),m=(0,i.useRef)(null),x=(0,i.useRef)(0),v=i9(e),y="pdf"===v,b=y?ow(e,"read",n,c?{v:c}:void 0)+(s?`#page=${s}`:""):ow(e,"preview",n,c?{v:c}:void 0);return(0,i.useEffect)(()=>{u(0),p(null),g(null),d(!1);let t=!0,r=++x.current;return fetch(ow(e,"meta",n)).then(e=>e.json()).then(e=>{t&&r===x.current&&(e.error&&g(e.error),"number"==typeof e.size&&(p(e.size),!y&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===x.current&&g(String(e))}),()=>{t=!1}},[e,y,n]),(0,i.useEffect)(()=>{if(d(!1),m.current&&(m.current.close(),m.current=null),!o)return;let t=!0,r=new EventSource(ow(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;d(!0),r=++x.current,fetch(ow(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===x.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(p(e.size),!y&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),u(e=>e+1)}}).catch(e=>{t&&r===x.current&&g(String(e))})}),r.addEventListener("change",e=>{x.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(p(t.size),!y&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),u(e=>e+1)});let i=()=>{d(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,y,n,o]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:E(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===v?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:oj(h)}),(0,r.jsx)(ok,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:l(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:f?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:f}):(0,r.jsx)("iframe",{src:b,sandbox:y?void 0:"allow-same-origin",title:l("i18n.previewFile",{file:S(e)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},b)})]})}function oT({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:s,gitRefreshKey:l,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u=!0,pdfPage:h}){let p="diff"===of(e,d,a);return!p&&oe(e)?(0,r.jsx)(oC,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&ot(e)?(0,r.jsx)(oN,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&on(e)?(0,r.jsx)(oI,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&or(e)?(0,r.jsx)(oM,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u,pdfPage:h}):(0,r.jsx)(oL,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:s,gitRefreshKey:l,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u})}function oL({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:o,onMentionLines:s,onAtMention:l,gitRefreshKey:a,initialDisplayMode:d,initialState:c,onStateChange:u,watchEnabled:h=!0}){let{isDark:p}=n2(),{t:f}=(0,w.s)(),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(!1),[k,j]=(0,i.useState)(!1),[S,N]=(0,i.useState)(null),[I,M]=(0,i.useState)(!0),[T,L]=(0,i.useState)(!1),[R,$]=(0,i.useState)(null),W=of(e,c,d),z="diff"===W&&(oe(e)||ot(e)||on(e)||or(e)),P=c?.wrapLines??!1,A=c?.scrollByMode?.[W],D=A?.scrollTop??c?.scrollTop??0,H=A?.scrollLeft??c?.scrollLeft??0,B=c?.loadedBytes??0,[F,O]=(0,i.useState)(W),[U,_]=(0,i.useState)(P),[q,K]=(0,i.useState)(!1),V=(0,i.useRef)(null),J=(0,i.useRef)(0),Y=(0,i.useRef)(null),Z=(0,i.useRef)(0),X=(0,i.useRef)(null),G=(0,i.useRef)(!1),Q=(0,i.useRef)(0),ee=(0,i.useRef)(null),et=(0,i.useRef)(!1),en=(0,i.useRef)(!0),er=(0,i.useRef)({displayMode:W,wrapLines:P,scrollTop:D,scrollLeft:H,loadedBytes:B,scrollByMode:{...c?.scrollByMode}}),ei=(0,i.useRef)(u),[eo,es]=(0,i.useState)(null);ei.current=u;let el=(0,i.useCallback)(e=>{er.current.displayMode=e,O(e)},[]),ea=(0,i.useCallback)(()=>{_(e=>{let t=!e;return er.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(er.current={displayMode:W,wrapLines:P,scrollTop:D,scrollLeft:H,loadedBytes:B,scrollByMode:{...c?.scrollByMode}},en.current=!0,et.current=!1,O(W),_(P),()=>{ei.current?.({...er.current})}),[e,n,W,P,D,H,B,c?.scrollByMode]);let ed=(0,i.useCallback)(async(e,t=0)=>{let r=++J.current,i=async t=>(await fetch(ow(e,"read",n,{offset:t||void 0}))).json();try{let e=t,n=await i(e);if(r!==J.current||e&&"Invalid text preview offset"===n.error&&(e=0,n=await i(0),r!==J.current))return null;if(n.error)return $(n.error),null;if(e&&(Y.current!==n.version||Z.current!==e)){if(e=0,n=await i(0),r!==J.current)return null;if(n.error)return $(n.error),null}return $(null),Y.current=n.version,Z.current=n.nextOffset,er.current.loadedBytes=n.nextOffset,m(t=>e&&t?{...n,content:t.content+n.content}:n),n}catch(e){if(r!==J.current)return null;return $(String(e)),null}},[n]),ec=(0,i.useCallback)(async e=>{let n=++Q.current;if(b(!0),N(null),!t){v(null),b(!1),j(!0);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),o=await i.json();if(n!==Q.current)return;i.ok||N(o.error??`Failed to load diff (HTTP ${i.status})`),v(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch(e){n===Q.current&&(v(null),N(e instanceof Error?e.message:String(e)))}finally{n===Q.current&&(b(!1),j(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;if(M(!0),$(null),m(null),v(null),j(!1),N(null),K(!1),Y.current=null,Z.current=0,G.current=!1,z)return M(!1),X.current=null,()=>{t=!1,J.current+=1};let n=(async()=>{let n=await ed(e);for(;t&&n?.truncated&&n.nextOffset<B;)n=await ed(e,n.nextOffset);return n})();return X.current=n,n.finally(()=>{X.current===n&&(X.current=null),t&&M(!1)}),()=>{t=!1,J.current+=1}},[e,ed,B,z,n]),(0,i.useEffect)(()=>{if(K(!1),V.current&&(V.current.close(),V.current=null),!h)return;let t=new EventSource(ow(e,"watch",n));V.current=t,t.addEventListener("connected",n=>{K(!0);let r=G.current;if(G.current=!0,r&&ec(e),z)return;let i=(()=>{try{return JSON.parse(n.data).version??null}catch{return null}})();(X.current??Promise.resolve()).then(()=>{V.current===t&&i!==Y.current&&(ed(e,0),ec(e))})}),t.addEventListener("change",()=>{z||ed(e,0),ec(e)});let r=()=>{K(!1)};return t.addEventListener("error",r),t.onerror=r,()=>{t.close(),V.current===t&&(V.current=null)}},[e,ed,ec,z,n,h]),(0,i.useEffect)(()=>{ec(e)},[ec,e,a]);let eu=x?.supported===!0&&"string"==typeof x.patch,eh=eu&&"deleted"===x.status;(0,i.useEffect)(()=>{k&&!eu&&"diff"===F&&el("source")},[F,k,eu,el]),(0,i.useEffect)(()=>{"diff"===W&&eu&&!et.current&&(et.current=!0,el("diff"))},[W,eu,el]);let ep=(0,i.useMemo)(()=>g?.language==="markdown"?nM(g.content):"",[g]),ef=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=os.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,oo.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(g.content):null,[g]),eg=(0,i.useMemo)(()=>(function(e){let t=[],n=null;for(let r of e.split(/\r?\n/)){let e=od.exec(r);if(e){let t=e[1][0],r=e[1].length;n?n.ch===t&&r>=n.n&&(n=null):n={ch:t,n:r};continue}if(n)continue;let i=oc.exec(r);if(!i)continue;let o=i[2].replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").trim();o&&t.push({level:i[1].length,text:o})}return t})(ef?.rest??""),[ef]),em=g?.content??"",ex=(0,i.useMemo)(()=>em.split("\n"),[em]),ev=g?.language??"text",ey="html"===ev,eb="markdown"===ev,ew=!g?.truncated&&(ey||eb),ek=eh?"diff":"preview"!==F||ew?F:"source",ej=(ex.length>1e3||(g?.size??0)>131072)&&!("diff"===ek&&eu)&&!("preview"===ek&&ew),eS=!ej&&!("diff"===ek&&eu)&&!("preview"===ek&&ew),eC=(0,i.useMemo)(()=>eS?(0,r.jsx)(n8.A,{className:U?"file-source-view is-wrapped":"file-source-view",language:"text"===ev?"plaintext":ev,style:p?nH.xJ:nH.vs,showLineNumbers:!0,lineNumberStyle:{...om},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...og,width:U?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:U?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(ob,{...e,wrapLines:U}),wrapLongLines:U,children:em}):null,[p,ev,eS,em,U]),eE=(0,i.useMemo)(()=>ej?ex.map((e,t)=>(0,r.jsxs)("span",{className:"file-source-line","data-line-number":t+1,style:{display:"flex",minWidth:"100%"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:om,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:U?"anywhere":"normal",whiteSpace:U?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[ex,ej,U]);(0,i.useEffect)(()=>{let e=()=>{let e=ee.current;es(t=>{let n=s&&"source"===F&&e?oy(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),s&&"source"===F)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,F,s]);let eN=(0,i.useCallback)(n=>{s&&n&&s(E(e,t),n.startLine,n.endLine,t)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==F)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=ee.current,r=n?oy(n,window.getSelection()):null;r&&(e.preventDefault(),eN(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[F,eN,s]),(0,i.useEffect)(()=>{if(!en.current||I||R&&!eh||"diff"===W&&!k||"diff"===W&&eu&&"diff"!==F)return;let e=ee.current;e&&(e.scrollTop=er.current.scrollTop,e.scrollLeft=er.current.scrollLeft,en.current=!1)},[g?.content,F,R,k,eu,eh,I,W]),(0,i.useLayoutEffect)(()=>{if(en.current)return;let e=ee.current;if(!e)return;let t=er.current.scrollByMode?.[ek];e.scrollTop=t?.scrollTop??0,e.scrollLeft=t?.scrollLeft??0},[ek]),I||"diff"===W&&y&&!k)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:f("i18n.loading")});if("diff"===W&&k&&S)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:S});if(R&&!("diff"===ek&&eu))return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:R});if(!g&&!("diff"===ek&&eu))return null;let eI=C(e),eM=!g||eh?["diff"]:["source",...ew?["preview"]:[],...eu?["diff"]:[]],eT=eh?f("files.deleted"):g?`${ev} \xb7 ${ex.length} lines \xb7 ${oj(g.size)}`:f("i18n.diff");return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",position:"relative"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:E(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eT,children:eT}),g&&!eh&&(0,r.jsx)("span",{title:q?f("i18n.liveSync"):f("i18n.notWatching"),"aria-label":q?f("i18n.liveSync"):f("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:q?"#4ade80":"var(--border)",boxShadow:q?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[eM.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":f("i18n.fileViewMode"),children:eM.map(e=>{let t=ek===e;return(0,r.jsx)("button",{type:"button",onClick:()=>el(e),title:"diff"===e?f("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:"source"===e?f("i18n.source"):"preview"===e?f("i18n.preview"):f("i18n.diff")},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[eb&&"preview"===ek&&(0,r.jsx)(op,{items:eg,scrollRoot:ee}),(l||s)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{eo&&s?eN(eo):l?.(E(e,t),!1,t)},title:eo&&s?`${f("i18n.mentionSelectedLines")} (L${eo.startLine}${eo.startLine!==eo.endLine?`-L${eo.endLine}`:""})`:f("files.insertPath"),"aria-label":f("files.mention"),disabled:!l&&!s,className:"file-viewer-icon-button",children:(0,r.jsx)(ox,{})}),"source"===ek&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:ea,title:U?f("i18n.disableWrap"):f("i18n.enableWrap"),"aria-label":U?f("i18n.disableWrap"):f("i18n.enableWrap"),"aria-pressed":U,className:"file-viewer-icon-button",style:{background:U?"var(--bg-selected)":"transparent",color:U?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!eh&&(0,r.jsx)(ok,{filePath:e,sourceSessionId:n})]})]}),g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",children:[(0,r.jsxs)("span",{children:[oj(g.nextOffset)," / ",oj(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:T,onClick:()=>{L(!0),ed(e,g.nextOffset).finally(()=>L(!1))},children:T?f("i18n.loading"):f("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:ee,className:"file-viewer-content",onScroll:e=>{let t={scrollTop:e.currentTarget.scrollTop,scrollLeft:e.currentTarget.scrollLeft};er.current.scrollTop=t.scrollTop,er.current.scrollLeft=t.scrollLeft,er.current.scrollByMode={...er.current.scrollByMode,[ek]:t}},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:g?.truncated?48:void 0},children:"diff"===ek&&eu?(0,r.jsx)(oS,{patch:x.patch}):ey&&"preview"===ek?(0,r.jsx)("iframe",{srcDoc:em,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:f("i18n.htmlPreview")}):eb&&"preview"===ek?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ef?.data&&(0,r.jsx)(oh,{data:ef.data}),(0,r.jsx)(nx.oz,{remarkPlugins:nP,rehypePlugins:nD,urlTransform:o?nN:void 0,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",o=String(t);return e?.includes("language-")||o.includes("\n")?"mermaid"===i?(0,r.jsx)(n5,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(n3,{code:o.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:["markdown-inline-code",e].filter(Boolean).join(" "),...n,children:t})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})}),pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let s=o?ns(e,eI,t??eI):null;return s&&o?(0,r.jsx)("a",{href:e,...i,onClick:e=>{nn(e)&&(e.preventDefault(),o(s))},children:n}):(0,r.jsx)("a",{href:e,...i,target:"_blank",rel:"noopener noreferrer",children:n})},img({src:e,alt:i,...o}){delete o.node;let s="string"==typeof e?ns(e,eI,t??eI):null,l=s?ow(s,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...o})}},children:ep})]}):ej?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:U?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...og},children:eE}):eC})]})}function oR(e,t){if(t<=0)return"";let n=Math.max(0,e.length-1-t);return e.slice(n,-1).join("/")||e[0]||""}function o$(e,t){return t?`${e} \xb7 ${t}`:e}function oW(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function oz({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:o}){let{t:s}=(0,w.s)(),[l,a]=(0,i.useState)(null),d=(0,i.useRef)(null),c=(0,i.useRef)(!1),u=(0,i.useMemo)(()=>(function(e){let t=new Map,n=new Map;for(let t of e){let e=function(e){let t=e.label?.trim();return t||S(e.path)||e.path}(t),r=n.get(e);r?r.push(t):n.set(e,[t])}for(let[e,r]of n){if(1===r.length){t.set(r[0].id,e);continue}let n=r.map(e=>(function(e){let t=k(e).replace(/\/+$/,"");return t?/^[a-zA-Z]:$/.test(t)?[t]:t.split("/").filter((e,t)=>e.length>0||0===t):[]})(e.path)),i=n.map(e=>Math.max(0,e.length-1)),o=r.map(()=>0),s=!0;for(;s;){s=!1;let t=r.map((t,r)=>o$(e,oR(n[r],o[r]))),l=oW(t);for(let e=0;e<r.length;e+=1)!((l.get(t[e])??0)<=1)&&(o[e]>=i[e]||(o[e]+=1,s=!0))}let l=r.map((t,r)=>o$(e,oR(n[r],o[r]))),a=oW(l);r.forEach((n,r)=>{t.set(n.id,(a.get(l[r])??0)>1?e:l[r])})}return t})(e.map(e=>({id:e.id,path:e.filePath,label:e.label}))),[e]);return(0,i.useEffect)(()=>{d.current?.scrollIntoView({block:"nearest",inline:"nearest"}),c.current&&(c.current=!1,d.current?.focus())},[t,e]),(0,r.jsx)("div",{role:"tablist",style:{display:"flex",alignItems:"stretch",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:"100%"},children:e.map(i=>{let h=i.id===t,p=u.get(i.id)??i.label;return(0,r.jsxs)("div",{ref:h?d:null,role:"tab","aria-label":"terminal"===i.kind?s("terminal.tabLabel",{name:p}):p,"aria-selected":h,tabIndex:h||!t&&e[0].id===i.id?0:-1,onKeyDown:t=>{if(t.target===t.currentTarget){if("Enter"===t.key||" "===t.key)t.preventDefault(),n(i.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(t.key)){t.preventDefault();let r=e.findIndex(e=>e.id===i.id),o="Home"===t.key?0:"End"===t.key?e.length-1:(r+("ArrowRight"===t.key?1:-1)+e.length)%e.length;n(e[o].id),t.currentTarget.parentElement?.children[o]?.focus()}}},onClick:()=>n(i.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),i.closing||o(i.id))},style:{display:"flex",alignItems:"center",gap:6,height:"100%",paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:h?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:h?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:h?1:.7,display:"inline-flex",alignItems:"center",transform:"translateY(0.5px)"},children:"terminal"===i.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):A(i.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,lineHeight:1,fontWeight:h?500:400},title:i.filePath,children:p}),(0,r.jsx)("button",{type:"button",className:"file-tab-close",disabled:i.closing,onClick:e=>{e.stopPropagation(),a(null),c.current=!0,o(i.id)},onMouseEnter:()=>a(i.id),onMouseLeave:()=>a(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,background:l===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:l===i.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("terminal"===i.kind?"terminal.close":"i18n.close"),"aria-label":`${s("terminal"===i.kind?"terminal.close":"i18n.close")} ${p}`,children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},i.id)})})}function oP(e,t){let n=e.findIndex(e=>e.id===t);if(-1===n)return null;let r=e.filter(e=>e.id!==t);return r[Math.min(n,r.length-1)]?.id??null}let oA=["general","models","agents","images","skills","plugins"],oD="pi-web:settings-navigation",oH=new Set(["skills","agents","plugins"]);function oB(){try{return window.localStorage}catch{return null}}function oF(e){let t=e.getItem(oD);if(!t)return{};try{let e=JSON.parse(t);if(null===e||"object"!=typeof e||Array.isArray(e))return{};return{section:"string"==typeof e.section?e.section:void 0,selections:null===e.selections||"object"!=typeof e.selections||Array.isArray(e.selections)?void 0:e.selections}}catch{return{}}}function oO(e,t){return"models"===e?e:t?JSON.stringify([e,t]):null}function oU(e,t=oB()){if(t)try{let n=oF(t);n.section=e,t.setItem(oD,JSON.stringify(n))}catch{}}function o_(e,t,n=oB()){if(!n)return null;let r=oO(e,t);if(!r)return null;try{let e=oF(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function oq(e,t,n,r=oB()){if(!r||!t)return;let i=oO(e,n);if(i)try{let e=oF(r);e.selections={...e.selections,[i]:t},r.setItem(oD,JSON.stringify(e))}catch{}}let oK="pi-auto-session-title";function oV(){try{return"false"!==window.localStorage.getItem(oK)}catch{return!0}}let oJ=["input","output","cacheRead","cacheWrite"];function oY(e){return{input:e?.input===void 0?"":String(e.input),output:e?.output===void 0?"":String(e.output),cacheRead:e?.cacheRead===void 0?"":String(e.cacheRead),cacheWrite:e?.cacheWrite===void 0?"":String(e.cacheWrite)}}function oZ(e){if(!oX(e))return;let t=e=>{if(!e.trim())return 0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0},n=t(e.input),r=t(e.output),i=t(e.cacheRead),o=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==o)return{input:n,output:r,cacheRead:i,cacheWrite:o}}function oX(e){return oJ.some(t=>""!==e[t].trim())}let oG=["name","reasoning","thinkingLevelMap","input","contextWindow","maxTokens","cost","headers","compat"];function oQ(e,t){return`${e}/${t}`}function o0(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function o1(e,t){let n=o0(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function o2(e){let t=e.trim(),n=t.match(eM),r=n?t.slice(0,-n[0].length):t,i=n?.[1];if(!r||/[*?\[]/.test(r))return null;let o=r.indexOf("/");return o===r.length-1?null:o<=0?{id:r,...i?{pin:i}:{},ref:r}:{provider:r.slice(0,o),id:r.slice(o+1),...i?{pin:i}:{},ref:r}}function o4(e,t){let n=t.trim();return o0(e).filter(e=>e!==n)}function o8(e){let t=o0(e);return t.length>0&&t.every(e=>null!==o2(e))}function o5({embedded:e,title:t,subtitle:n,closeLabel:i="Close",onClose:o,children:s,width:l=900,height:a="78vh"}){let d=e?void 0:{"--config-panel-width":`${l}px`,"--config-panel-height":a};return(0,r.jsx)("div",{role:e?void 0:"dialog","aria-modal":e?void 0:"true","aria-label":t,className:`config-panel-root ${e?"is-embedded":"is-modal"}`,onClick:t=>{e||t.target!==t.currentTarget||o()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:d,children:[!e&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:t}),n&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:n,children:n}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:o,title:i,"aria-label":i,children:"\xd7"})]}),s]})})}function o6({children:e}){return(0,r.jsx)("div",{className:"config-split-view",children:e})}function o3({children:e}){return(0,r.jsx)("aside",{className:"config-sidebar",children:e})}function o7({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-list",children:e})}function o9({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-group-label",children:e})}function se({active:e=!1,className:t,children:n,...i}){return(0,r.jsx)("button",{type:"button",...i,"aria-current":e?"page":void 0,className:["config-sidebar-item",t].filter(Boolean).join(" "),children:n})}function st({className:e,...t}){return(0,r.jsx)("span",{...t,className:["config-sidebar-text",e].filter(Boolean).join(" ")})}function sn({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-stack",e].filter(Boolean).join(" ")})}function sr({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header",e].filter(Boolean).join(" ")})}function si({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header-info",e].filter(Boolean).join(" ")})}function so({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-actions",e].filter(Boolean).join(" ")})}function ss({children:e}){return(0,r.jsx)("div",{className:"config-detail-title",children:e})}function sl({children:e}){return(0,r.jsx)("div",{className:"config-section-title",children:e})}function sa({label:e,children:t,style:n}){return(0,r.jsxs)("div",{className:"config-field",style:n,children:[(0,r.jsx)("span",{className:"config-field-label",children:e}),t]})}function sd({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function sc({children:e,style:t}){return(0,r.jsx)("div",{className:"config-detail",style:t,children:e})}function su({status:e,children:t}){return(0,r.jsxs)("footer",{className:"config-footer",children:[(0,r.jsx)("div",{className:"config-footer-status",children:e}),(0,r.jsx)("div",{className:"config-footer-actions",children:t})]})}function sh({variant:e="secondary",size:t="default",className:n,children:i,...o}){return(0,r.jsx)("button",{type:"button",...o,className:["config-button",`config-button-${e}`,`config-button-${t}`,n].filter(Boolean).join(" "),children:i})}function sp({checked:e,disabled:t=!1,loading:n=!1,label:i,onChange:o}){let s=t||n;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":e,"aria-busy":n||void 0,"aria-label":i,title:i,disabled:s,className:`config-switch${n?" is-loading":""}`,onClick:()=>o(!e),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function sf({active:e=!1,children:t,className:n,...i}){return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...i,"aria-current":e?"page":void 0,className:["config-list-action-button",n].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),t]})})}function sg({active:e,color:t}){return(0,r.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${e?" is-active":!1===e?" is-inactive":""}`,style:t?{backgroundColor:t}:void 0})}let sm={anthropic:{symbol:"anthropic",color:!1},openai:{symbol:"openai",color:!1},"openai-codex":{symbol:"openai",color:!1},google:{symbol:"google",color:!0},"google-vertex":{symbol:"google",color:!0},"ant-ling":{symbol:"antgroup",color:!0},deepseek:{symbol:"deepseek",color:!0},groq:{symbol:"groq",color:!1},mistral:{symbol:"mistral",color:!0},moonshotai:{symbol:"moonshot",color:!1},"moonshotai-cn":{symbol:"moonshot",color:!1},moonshot:{symbol:"moonshot",color:!1},minimax:{symbol:"minimax",color:!0},"minimax-cn":{symbol:"minimax",color:!0},fireworks:{symbol:"fireworks",color:!0},huggingface:{symbol:"huggingface",color:!0},cerebras:{symbol:"cerebras",color:!0},openrouter:{symbol:"openrouter",color:!1},xai:{symbol:"xai",color:!1},"cloudflare-ai-gateway":{symbol:"cloudflare",color:!0},"cloudflare-workers-ai":{symbol:"cloudflare",color:!0},"vercel-ai-gateway":{symbol:"vercel",color:!1},"github-copilot":{symbol:"githubcopilot",color:!1},"amazon-bedrock":{symbol:"aws",color:!0},"azure-openai-responses":{symbol:"azure",color:!0},"kimi-coding":{symbol:"kimi",color:!0},nvidia:{symbol:"nvidia",color:!0},opencode:{symbol:"opencode",color:!1},"opencode-go":{symbol:"opencode",color:!1},qwen:{symbol:"qwen",color:!0},xiaomi:{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-ams":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-cn":{symbol:"xiaomimimo",color:!1},"xiaomi-token-plan-sgp":{symbol:"xiaomimimo",color:!1},zai:{symbol:"zai",color:!1},"zai-coding-cn":{symbol:"zai",color:!1},zhipu:{symbol:"zhipu",color:!0},cohere:{symbol:"cohere",color:!0},perplexity:{symbol:"perplexity",color:!0},together:{symbol:"together",color:!0},grok:{symbol:"grok",color:!1}};function sx({id:e,size:t}){let n=sm[e];if(n)return(0,r.jsx)("svg",{"aria-hidden":"true",width:t,height:t,viewBox:"0 0 24 24",fill:n.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${n.symbol}`})});let i=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:i})}function sv({value:e,onChange:t,placeholder:n,mono:i,disabled:o,id:s}){return(0,r.jsx)("input",{id:s,className:`models-input${i?" is-mono":""}`,value:e,onChange:e=>t(e.target.value),placeholder:n,disabled:o})}function sy({value:e,onChange:t,placeholder:n,mono:o,onKeyDown:s}){let[l,a]=(0,i.useState)(!1),{t:d}=(0,w.s)();return(0,i.useEffect)(()=>{e||a(!1)},[e]),(0,r.jsxs)("div",{className:"models-secret",children:[(0,r.jsx)("input",{type:l?"text":"password",className:`models-input${o?" is-mono":""}`,value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:n,autoComplete:"off",spellCheck:!1}),(0,r.jsx)("button",{type:"button",className:"models-secret-toggle",onClick:()=>a(e=>!e),"aria-label":d(l?"i18n.hideDetails":"i18n.showDetails"),title:d(l?"i18n.hideDetails":"i18n.showDetails"),children:l?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function sb({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",className:"models-input",value:e,onChange:e=>t(e.target.value),placeholder:n})}function sw({value:e,onChange:t,options:n,required:i}){let{t:o}=(0,w.s)();return(0,r.jsxs)("select",{className:"models-input",value:e,onChange:e=>t(e.target.value),children:[!i&&(0,r.jsx)("option",{value:"",children:o("models.useDefault")}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function sk({label:e,description:t,checked:n,onChange:i}){return(0,r.jsxs)("div",{className:"models-switch-row",children:[(0,r.jsxs)("span",{className:"models-switch-copy",children:[(0,r.jsx)("span",{children:e}),t&&(0,r.jsx)("span",{className:"models-hint",children:t})]}),(0,r.jsx)(sp,{checked:n,label:e,onChange:i})]})}function sj({title:e,hint:t,actions:n}){return(0,r.jsxs)("div",{className:"models-section-header",children:[(0,r.jsxs)("div",{className:"models-section-heading",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:e}),t&&(0,r.jsx)("p",{className:"settings-general-description",children:t})]}),n&&(0,r.jsx)("span",{className:"models-form-actions",children:n})]})}function sS({children:e}){return(0,r.jsx)("span",{className:"models-hint",children:e})}function sC({tone:e="info",children:t,action:n}){return(0,r.jsxs)("div",{className:`models-notice is-${e}`,role:"danger"===e?"alert":"status",children:[(0,r.jsx)("div",{className:"models-notice-body",children:t}),n]})}function sE({headers:e,onChange:t}){let{t:n}=(0,w.s)(),[o,s]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),l=(0,i.useRef)(o.length),a=e=>{s(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},d=(e,t)=>{a(o.map(n=>n.id===e?{...n,...t}:n))};return(0,r.jsxs)("div",{className:"models-header-list",children:[o.map(e=>(0,r.jsxs)("div",{className:"models-header-row",children:[(0,r.jsx)("input",{className:"models-input is-mono",value:e.name,onChange:t=>d(e.id,{name:t.target.value}),placeholder:"Header-Name"}),(0,r.jsx)("input",{className:"models-input is-mono",value:e.value,onChange:t=>d(e.id,{value:t.target.value}),placeholder:"value"}),(0,r.jsx)("button",{type:"button",className:"models-icon-button is-danger",onClick:()=>{var t;return t=e.id,void a(o.filter(e=>e.id!==t))},"aria-label":n("i18n.remove"),title:n("i18n.remove"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.id)),(0,r.jsx)(sh,{size:"small",className:"models-self-start",onClick:()=>s(e=>[...e,{id:l.current++,name:"",value:""}]),children:n("models.addHeader")})]})}function sN({value:e,onChange:t}){let{t:n}=(0,w.s)(),i=e??{},o=(e,n)=>{let r={...i};"omit"===n?delete r[e]:r[e]=n,t(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{className:"models-thinking-map",children:eI.map(e=>{let t=i[e],s=e in i?null===t?"null":"string":"omit",l="string"==typeof t?t:"";return(0,r.jsxs)("div",{className:`models-thinking-row is-${s}`,children:[(0,r.jsx)("span",{className:"models-thinking-level",children:e}),(0,r.jsxs)("div",{className:"models-segmented",role:"radiogroup","aria-label":e,children:[(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"omit"===s,onClick:()=>o(e,"omit"),children:n("models.levelDefault")}),(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"null"===s,className:"is-danger",onClick:()=>o(e,null),children:n("models.levelDisabled")}),(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"string"===s,onClick:()=>o(e,l||e),children:n("models.levelCustom")})]}),(0,r.jsx)("input",{className:"models-input is-mono models-thinking-input",value:l,onChange:t=>o(e,t.target.value),onFocus:()=>{"string"!==s&&o(e,l||e)},placeholder:e,maxLength:10,"aria-label":`${e} ${n("models.levelCustom")}`})]},e)})})}function sI({title:e,description:t,width:n=560,onClose:i,children:o,footer:s,header:l}){return(0,r.jsx)("div",{className:"models-dialog-backdrop",onClick:e=>{e.target===e.currentTarget&&i()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),i())},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":e,className:"models-dialog",style:{width:n},children:[l??(0,r.jsxs)("div",{className:"models-dialog-header",children:[(0,r.jsx)("strong",{children:e}),t&&(0,r.jsx)("span",{children:t})]}),(0,r.jsx)("div",{className:"models-dialog-body",children:o}),s&&(0,r.jsx)("div",{className:"models-dialog-footer",children:s})]})})}function sM(e,t){return window.confirm(e("models.disconnectConfirm",{name:t}))}function sT({tone:e,children:t}){return(0,r.jsxs)("span",{className:`models-status is-${e}`,children:[(0,r.jsx)("span",{className:"models-status-dot","aria-hidden":"true"}),t]})}function sL({provider:e,onRefresh:t,cwd:n}){let[o,s]=(0,i.useState)({phase:"idle"}),{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===o.phase||"prompt"===o.phase)&&setTimeout(()=>u.current?.focus(),50)},[o.phase]),(0,i.useEffect)(()=>{s({phase:"idle"}),d(""),c.current?.close(),c.current=null},[e.id]),(0,i.useEffect)(()=>()=>{c.current?.close()},[]);let h=(0,i.useCallback)(()=>{c.current?.close(),s({phase:"connecting"}),d("");let r=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}${n?`?cwd=${encodeURIComponent(n)}`:""}`);c.current=r,r.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(s({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(s({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),window.open(n.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===n.type?s({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?s({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?s({phase:"progress",message:n.message}):"success"===n.type?(r.close(),s({phase:"success"}),t()):"error"===n.type?(r.close(),s({phase:"error",message:n.message})):"cancelled"===n.type&&(r.close(),s({phase:"idle"}))},r.onerror=()=>{r.close(),s(e=>"success"===e.phase?e:{phase:"error",message:l("models.loginConnectionLost")})}},[e.id,t,n,l]),p=(0,i.useCallback)(async()=>{sM(l,e.name)&&(await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),s({phase:"idle"}),t())},[e.id,e.name,t,l,n]),f=(0,i.useCallback)(async(t,n,r)=>{s({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));s({phase:"error",message:e.error??`HTTP ${r.status}`});return}d("")}catch(e){s({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e.id]),g=(e,t)=>{t.trim()&&f(e,t.trim(),l("models.loginVerifying"))},m="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return(0,r.jsxs)("div",{className:"models-auth",children:[(0,r.jsxs)("div",{className:"models-auth-row",children:[(0,r.jsxs)("div",{className:"models-auth-copy",children:[(0,r.jsx)("strong",{children:l("models.oauthTitle")}),(0,r.jsx)(sT,{tone:e.loggedIn?"success":"muted",children:e.loggedIn?l("i18n.connected"):l("i18n.notConnected")})]}),(0,r.jsx)("div",{className:"models-auth-actions",children:m?(0,r.jsx)(sh,{size:"small",onClick:()=>{c.current?.close(),s({phase:"idle"})},children:l("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[e.loggedIn&&(0,r.jsx)(sh,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:p,children:l("i18n.disconnect")}),(0,r.jsx)(sh,{size:"small",variant:e.loggedIn?"secondary":"primary",onClick:h,children:e.loggedIn?l("i18n.relogin"):l("i18n.login")})]})})]}),"idle"===o.phase&&!e.loggedIn&&(0,r.jsx)("p",{className:"models-muted",children:l("models.oauthConnectHint",{name:e.name})}),"connecting"===o.phase&&(0,r.jsx)("p",{className:"models-muted",children:l("i18n.openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:o.message}),(0,r.jsx)("div",{className:"models-auth-options",children:o.options.map(e=>(0,r.jsx)(sh,{className:"models-auth-option",onClick:()=>void f(o.token,e.id,l("models.loginContinuing")),children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:"auth"===o.phase?l("models.oauthPasteRedirect"):o.message}),"auth"===o.phase&&(0,r.jsxs)("p",{className:"models-hint",children:[l("models.oauthBrowserNotOpened")," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:"models-link",children:l("models.oauthOpenLoginPage")})]}),(0,r.jsxs)("div",{className:"models-inline-form",children:[(0,r.jsx)("input",{ref:u,className:"models-input is-mono",value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&g(o.token,a)},placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??l("models.enterValue")}),(0,r.jsx)(sh,{variant:"primary",size:"small",onClick:()=>g(o.token,a),disabled:!a.trim(),children:l("i18n.submit")})]})]}),"device_code"===o.phase&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:l("models.deviceCodeHint")}),(0,r.jsx)("div",{className:"models-device-code",children:o.userCode}),(0,r.jsxs)("p",{className:"models-hint",children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"models-link",children:o.verificationUri}),o.expiresInSeconds?` \xb7 ${l("models.deviceCodeExpires",{minutes:Math.ceil(o.expiresInSeconds/60)})}`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{className:"models-muted",children:o.message}),"success"===o.phase&&(0,r.jsx)(sC,{tone:"success",children:l("i18n.connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)(sC,{tone:"danger",children:o.message})]})}function sR({provider:e,onRefresh:t,cwd:n}){let[o,s]=(0,i.useState)(""),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(!1),{t:g}=(0,w.s)();(0,i.useEffect)(()=>{s(""),h(null),f(!1)},[e.id]);let m=(0,i.useCallback)(async()=>{if(o.trim()){a(!0),h(null),f(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o.trim(),cwd:n})}),i=await r.json();!r.ok||i.error?h(i.error??`HTTP ${r.status}`):(s(""),f(!0),setTimeout(()=>f(!1),2e3),t())}catch(e){h(String(e))}finally{a(!1)}}},[o,e.id,t,n]),x=(0,i.useCallback)(async()=>{if(sM(g,e.displayName)){c(!0),h(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),i=await r.json();!r.ok||i.error?h(i.error??`HTTP ${r.status}`):t()}catch(e){h(String(e))}finally{c(!1)}}},[e.id,e.displayName,t,g,n]);return(0,r.jsxs)("div",{className:"models-auth",children:[(0,r.jsxs)("div",{className:"models-auth-row",children:[(0,r.jsxs)("div",{className:"models-auth-copy",children:[(0,r.jsx)("strong",{children:g("models.apiKeyTitle")}),(0,r.jsx)(sT,{tone:e.configured?"success":"muted",children:e.configured?g("i18n.configured"):g("i18n.notConfigured")})]}),e.configured&&(0,r.jsx)("div",{className:"models-auth-actions",children:(0,r.jsx)(sh,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:x,disabled:d,children:d?g("i18n.removing"):g("i18n.disconnect")})})]}),(0,r.jsxs)("div",{className:"models-inline-form",children:[(0,r.jsx)(sy,{value:o,onChange:s,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&m()},placeholder:e.configured?g("models.replaceKeyPlaceholder"):"sk-…",mono:!0}),(0,r.jsx)(sh,{variant:"primary",size:"small",onClick:m,disabled:l||!o.trim()||p,className:p?"is-success":void 0,children:p?g("i18n.saved"):l?g("i18n.saving"):e.configured?g("models.updateKey"):g("models.saveKey")})]}),u&&(0,r.jsx)(sC,{tone:"danger",children:u})]})}let s$=/^[a-z0-9][a-z0-9._-]*$/;function sW(){let e=(0,i.useRef)(null);return(0,i.useEffect)(()=>{setTimeout(()=>e.current?.focus(),30)},[]),e}function sz({oauthProviders:e,apiKeyProviders:t,existingIds:n,onSelectOAuth:o,onSelectApiKey:s,onAddCustom:l,onClose:a}){let[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(""),{t:g}=(0,w.s)(),m=sW(),x=d.trim().toLowerCase(),v=e.filter(e=>!e.loggedIn&&(!x||e.name.toLowerCase().includes(x))),y=t.filter(e=>!e.configured&&(!x||e.displayName.toLowerCase().includes(x)||e.id.toLowerCase().includes(x))),b=!x||"custom".includes(x)||"openai-compatible".includes(x)||"anthropic-compatible".includes(x),k=v.length+y.length+ +!!b,j=p.trim(),S=s$.test(j)&&!n.has(j),C=(e,t,n,i,o)=>(0,r.jsxs)("button",{type:"button",className:"models-card",onClick:o,children:[(0,r.jsxs)("span",{className:"models-card-copy",children:[(0,r.jsx)("strong",{children:t}),(0,r.jsx)("span",{children:n})]}),i]},e);return(0,r.jsx)(sI,{title:g("models.addProviderTitle"),width:820,onClose:a,header:(0,r.jsxs)("div",{className:"models-dialog-search",children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:m,value:d,onChange:e=>c(e.target.value),placeholder:g("i18n.searchProviders"),"aria-label":g("i18n.searchProviders")})]}),children:0===k?(0,r.jsx)("p",{className:"models-empty",children:g("i18n.noProviders")}):(0,r.jsxs)("div",{className:"models-card-grid",children:[b&&(0,r.jsx)("div",{className:"models-card-group",children:g("i18n.custom")}),b&&!u&&C("custom",g("models.customCompatible"),g("i18n.customEndpoint"),(0,r.jsx)("span",{className:"models-card-plus","aria-hidden":"true",children:"+"}),()=>h(!0)),b&&u&&(0,r.jsxs)("form",{className:"models-custom-form",onSubmit:e=>{e.preventDefault(),S&&(l(j),a())},children:[(0,r.jsx)("label",{htmlFor:"custom-provider-id",className:"config-field-label",children:g("models.providerId")}),(0,r.jsx)("input",{id:"custom-provider-id",autoFocus:!0,className:"models-input is-mono",value:p,onChange:e=>f(e.target.value),placeholder:"my-provider","aria-describedby":"custom-provider-id-hint"}),(0,r.jsx)("span",{id:"custom-provider-id-hint",children:(0,r.jsx)(sS,{children:n.has(j)?g("models.providerIdTaken"):g("models.providerIdFormat")})}),(0,r.jsxs)("div",{className:"models-form-actions",children:[(0,r.jsx)(sh,{size:"small",onClick:()=>h(!1),children:g("i18n.cancel")}),(0,r.jsx)(sh,{size:"small",type:"submit",variant:"primary",disabled:!S,children:g("models.createProvider")})]})]}),v.length>0&&(0,r.jsx)("div",{className:"models-card-group",children:g("i18n.subscriptions")}),v.map(e=>C(e.id,e.name,g("models.kindOAuth"),(0,r.jsx)(sx,{id:e.id,size:28}),()=>{o(e.id),a()})),y.length>0&&(0,r.jsx)("div",{className:"models-card-group",children:g("models.kindApiKey")}),y.map(e=>C(e.id,e.displayName,g("models.modelCount",{count:e.modelCount}),(0,r.jsx)(sx,{id:e.id,size:28}),()=>{s(e.id),a()}))]})})}function sP({catalog:e,listedRefs:t,mode:n,providerLabel:o,saving:s,error:l,onClose:a,onApply:d}){let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(""),[p,f]=(0,i.useState)(new Set),g=sW(),m=u.trim().toLocaleLowerCase(),x=e.filter(e=>!m||e.id.toLocaleLowerCase().includes(m)||e.name?.toLocaleLowerCase().includes(m)),v=e=>t.has(oQ(e.provider,e.id)),y=new Map;for(let e of x){let t=y.get(e.provider)??[];t.push(e),y.set(e.provider,t)}return(0,r.jsxs)(sI,{title:c("models.pickModels"),description:"replace"===n?c("models.pickReplaceHint"):c("models.pickAddHint"),onClose:a,footer:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"models-hint",children:c("models.pickSelected",{count:p.size})}),(0,r.jsxs)("span",{className:"models-form-actions",children:[(0,r.jsx)(sh,{onClick:a,children:c("i18n.cancel")}),(0,r.jsx)(sh,{variant:"primary",disabled:0===p.size||s,onClick:()=>d([...p]),children:c("models.pickApply",{count:p.size})})]})]}),children:[(0,r.jsx)("input",{ref:g,className:"models-input",value:u,onChange:e=>h(e.target.value),placeholder:c("models.pickFilterPlaceholder"),"aria-label":c("models.pickFilter")}),!x.some(e=>!v(e))&&(0,r.jsx)("p",{className:"models-empty",children:c("models.noExtraModels")}),[...y.entries()].map(([e,t])=>{let n=t.filter(e=>!v(e)).map(e=>oQ(e.provider,e.id)),i=n.length>0&&n.every(e=>p.has(e));return(0,r.jsxs)("section",{className:"models-picker-group",children:[(0,r.jsxs)("label",{className:"models-picker-head",children:[(0,r.jsx)("input",{type:"checkbox",checked:i,disabled:0===n.length,onChange:()=>f(e=>{let t=new Set(e);for(let e of n)i?t.delete(e):t.add(e);return t})}),(0,r.jsx)(sx,{id:e,size:14}),(0,r.jsx)("span",{children:o(e)}),(0,r.jsx)("span",{className:"models-count",children:t.length})]}),t.map(e=>{let t=oQ(e.provider,e.id),n=v(e);return(0,r.jsxs)("label",{className:`models-row${n?" is-disabled":""}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:n||p.has(t),disabled:n,onChange:()=>f(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})}),(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsx)("span",{className:"models-row-title",children:e.name||e.id}),e.name&&e.name!==e.id&&(0,r.jsx)("code",{className:"models-row-sub",children:e.id})]}),n&&(0,r.jsx)("span",{className:"models-tag",children:c("models.alreadyInChat")})]},t)})]},e)}),l&&(0,r.jsx)(sC,{tone:"danger",children:l})]})}let sA=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function sD(e){return{id:e.id,name:e.name,api:e.api,reasoning:e.reasoning,thinkingLevelMap:e.thinkingLevelMap,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,cost:e.cost,headers:e.headers,compat:e.compat}}function sH({providerId:e,provider:t,builtIn:n,namePlaceholder:i,onChange:o}){let{t:s}=(0,w.s)(),l=(e,n)=>o({...t,[e]:n});return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsxs)(sa,{label:s("models.displayName"),children:[(0,r.jsx)(sv,{value:t.name??"",onChange:e=>l("name",e.trim()||void 0),placeholder:i}),(0,r.jsx)(sS,{children:s("models.providerIdHint",{id:e})})]}),(0,r.jsx)(sa,{label:s("models.apiProtocol"),children:n?(0,r.jsx)(sw,{value:t.api??"",onChange:e=>l("api",e||void 0),options:sA}):(0,r.jsx)(sw,{value:t.api??"openai-completions",onChange:e=>l("api",e),options:sA,required:!0})})]}),(0,r.jsx)(sa,{label:s("models.baseUrl"),children:(0,r.jsx)(sv,{value:t.baseUrl??"",onChange:e=>l("baseUrl",e||void 0),placeholder:n?s("models.builtInDefault"):"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(sa,{label:s("models.apiKeyTitle"),children:[(0,r.jsx)(sy,{value:t.apiKey??"",onChange:e=>l("apiKey",e||void 0),placeholder:s(n?"models.builtInKeyPlaceholder":"models.endpointKeyPlaceholder"),mono:!0}),(0,r.jsx)(sS,{children:s("models.endpointKeyHint")})]}),(0,r.jsxs)(sa,{label:s("models.headers"),children:[(0,r.jsx)(sE,{headers:t.headers,onChange:e=>l("headers",e)}),(0,r.jsx)(sS,{children:s("models.providerHeadersHelp")})]})]})}function sB({providerId:e,provider:t,onAddModels:n,onClose:o}){let{t:s}=(0,w.s)(),[l,a]=(0,i.useState)({phase:"idle"}),[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)([]),p=(0,i.useRef)(0),f=(0,i.useRef)(null),g=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim())return;let n=++p.current;a({phase:"loading"}),h([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==p.current)return;if(!r.ok||i.error||!i.models)return void a({phase:"error",message:i.error??`HTTP ${r.status}`});a({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==p.current)return;a({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e,t]);(0,i.useEffect)(()=>{g()},[e,t.baseUrl,t.api,t.apiKey]);let m=new Set((t.models??[]).map(e=>e.id)),x="success"===l.phase?l.models:[],v=d.trim().toLocaleLowerCase(),y=x.filter(e=>!v||e.id.toLocaleLowerCase().includes(v)||e.name?.toLocaleLowerCase().includes(v)),b=y.slice(0,300),k=b.filter(e=>!m.has(e.id)).map(e=>e.id),j=u.filter(e=>!m.has(e)).length,S=k.length>0&&k.every(e=>u.includes(e)),C=!S&&k.some(e=>u.includes(e));return(0,i.useEffect)(()=>{f.current&&(f.current.indeterminate=C)},[C]),(0,r.jsxs)("div",{className:"models-discovery",children:[(0,r.jsxs)("div",{className:"models-discovery-header",children:[(0,r.jsx)("strong",{children:s("models.discoveryTitle")}),(0,r.jsx)(sh,{size:"small",variant:"ghost",onClick:o,children:s("i18n.close")})]}),"loading"===l.phase&&(0,r.jsx)("p",{className:"models-muted",children:s("models.discoveryFetching")}),"error"===l.phase&&(0,r.jsx)(sC,{tone:"danger",action:(0,r.jsx)(sh,{size:"small",onClick:()=>void g(),children:s("models.retry")}),children:l.message}),"success"===l.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"models-input",value:d,onChange:e=>c(e.target.value),placeholder:s("models.discoveryFilterPlaceholder",{count:l.models.length}),"aria-label":s("models.discoveryFilter")}),(0,r.jsxs)("div",{className:"models-list models-discovery-list",children:[(0,r.jsxs)("label",{className:"models-row models-discovery-all",children:[(0,r.jsx)("input",{ref:f,type:"checkbox",checked:S,disabled:0===k.length,onChange:()=>{let e=new Set(k);h(t=>S?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...k])))}}),s("models.discoverySelectShown")]}),0===b.length?(0,r.jsx)("div",{className:"models-row models-muted",children:s("models.discoveryNoMatches")}):b.map(e=>{let t=m.has(e.id);return(0,r.jsxs)("label",{className:`models-row${t?" is-disabled":""}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:u.includes(e.id)||t,disabled:t,onChange:()=>{var t;return t=e.id,void h(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])}}),(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsx)("span",{className:"models-row-title",children:e.name??e.id}),e.name&&(0,r.jsx)("code",{className:"models-row-sub",children:e.id})]}),t&&(0,r.jsx)("span",{className:"models-tag",children:s("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{className:"models-discovery-footer",children:[(0,r.jsx)("span",{className:"models-hint",title:l.endpoint,children:y.length>b.length?s("models.discoveryShowing",{shown:b.length,total:y.length}):s("models.discoveryFetched",{count:l.models.length})}),(0,r.jsx)(sh,{size:"small",variant:"primary",onClick:()=>{if("success"!==l.phase)return;let e=new Set(u),t=l.models.filter(t=>e.has(t.id)&&!m.has(t.id));0!==t.length&&(n(t),h([]))},disabled:0===j,children:j?s("models.discoveryAddSelectedCount",{count:j}):s("models.discoveryAddSelected")})]})]})]})}let sF={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function sO(e){return e.compat?.thinkingFormat==="deepseek"}function sU({providerName:e,provider:t,model:n,onChange:o,onDelete:s,lockId:l=!1,cwd:a=null,shadowsBuiltIn:d=!1}){let[c,u]=(0,i.useState)({phase:"idle"}),{t:h}=(0,w.s)(),[p,f]=(0,i.useState)({phase:"idle"}),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(()=>oY(n.cost)),y=(0,i.useRef)(x),[b,k]=(0,i.useState)(!1),j=(0,i.useRef)(0),S=(0,i.useRef)(null),C=(0,i.useRef)(n.cost),E=(e,t)=>o({...n,[e]:t}),N=(()=>{if("idle"===c.phase||"testing"===c.phase)return null;let e=[void 0!==c.latencyMs?`${c.latencyMs}ms`:null,void 0!==c.status?`HTTP ${c.status}`:null].filter(Boolean);return"success"===c.phase?[h("i18n.connected"),...e,c.responseText||null].filter(Boolean).join(" \xb7 "):[h("i18n.failed"),...e,c.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{u({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{j.current+=1,f({phase:"idle"}),S.current=null},[e,t.baseUrl,n.id]);let I=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==c.phase){u({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n,cwd:a??void 0})}),i=await r.json();if(!r.ok||!i.ok)return void u({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});u({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){u({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,c.phase,a]),M=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===p.phase)return;let i=++j.current;f({phase:"loading"});try{let s=new URLSearchParams({q:r,provider:e,limit:"50"});a&&s.set("cwd",a),t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${s}`),d=await l.json();if(i!==j.current)return;if(!l.ok||d.error||!d.recommendation)return void f({phase:"error",message:d.error??`HTTP ${l.status}`});let c=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},o=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],o+=1);let s=oZ(oY(i));o>0&&s&&(n.cost={...i,...s},r+=o)}return{model:n,appliedCount:r}}(n,d.recommendation.preset);c.appliedCount>0&&(S.current=n,o(c.model)),m(!1),f({phase:"success",recommendation:d.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==j.current)return;f({phase:"error",message:e instanceof Error?e.message:String(e)})}},[p.phase,n,o,t.baseUrl,e,a]),T=(()=>{if("success"!==p.phase)return null;let{recommendation:t,appliedCount:n}=p,r=n>0?h("models.catalogFilled",{count:n}):h("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?h("models.catalogNoExactMatch"):h("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?h("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?h("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):h("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),L="error"===p.phase?p.message:T,R="error"===p.phase?"danger":"success"===p.phase&&"unreliable"===p.recommendation.price.status?"warning":"info",$=[{key:"input",label:h("models.costInput")},{key:"output",label:h("models.costOutput")},{key:"cacheRead",label:h("models.costCacheRead")},{key:"cacheWrite",label:h("models.costCacheWrite")}],W=new Set(Object.keys(n.compat??{})),z=0;sO(n)&&(z+=1,W.delete("thinkingFormat"),W.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&(z+=1,W.delete("supportsDeveloperRole")),z+=W.size;let P=[n.api?`API: ${n.api}`:null,Object.keys(n.headers??{}).length?h("models.headersSummary",{count:Object.keys(n.headers??{}).length}):null,z?h("models.compatSummary",{count:z}):null,Object.keys(n.thinkingLevelMap??{}).length?h("models.thinkingSummary",{count:Object.keys(n.thinkingLevelMap??{}).length}):null].filter(e=>!!e),A=P.length?P.join(" \xb7 "):h("models.providerDefaults");return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)(sr,{children:[(0,r.jsx)(si,{children:(0,r.jsxs)("div",{className:"models-title-block",children:[(0,r.jsx)("strong",{className:"models-title",children:n.name||n.id||h("models.untitledModel")}),(0,r.jsxs)("span",{className:"models-subtitle",children:[(0,r.jsx)("span",{className:"models-tag",children:l?h("models.kindOverride"):h("models.kindDefinition")}),l?h("models.overrideHint"):h("models.definitionHint")]})]})}),(0,r.jsxs)(so,{children:[(0,r.jsx)(sh,{size:"small",onClick:I,disabled:!n.id.trim()||"testing"===c.phase,title:h("i18n.testConnection"),children:"testing"===c.phase?h("i18n.checking"):h("i18n.testConnection")}),s&&(0,r.jsx)(sh,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:s,children:h("models.deleteDefinition")})]})]}),d&&s&&(0,r.jsx)(sC,{tone:"warning",action:(0,r.jsx)(sh,{size:"small",onClick:s,children:h("models.restoreBuiltIn")}),children:h("models.replacesBuiltInHint")}),N&&(0,r.jsx)(sC,{tone:"success"===c.phase?"success":"danger",children:(0,r.jsx)("span",{className:"models-ellipsis",title:N,children:N})}),(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsx)(sa,{label:h("models.modelId"),children:(0,r.jsx)(sv,{value:n.id,onChange:e=>E("id",e),placeholder:"model-id",mono:!0,disabled:l})}),(0,r.jsx)(sa,{label:h("models.displayName"),children:(0,r.jsx)(sv,{value:n.name??"",onChange:e=>E("name",e||void 0),placeholder:n.id||h("models.displayName")})})]}),(0,r.jsxs)("div",{className:"models-catalog-row",children:[(0,r.jsx)(sh,{size:"small",onClick:()=>void M(),disabled:!n.id.trim()||"loading"===p.phase,children:"loading"===p.phase?h("models.catalogFilling"):h("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",className:"models-hint models-push-right",children:h("models.catalogSource")})]}),L&&(0,r.jsx)(sC,{tone:R,action:S.current&&(0,r.jsx)(sh,{size:"small",variant:"ghost",onClick:()=>{let e=S.current;e&&(S.current=null,o(e),f({phase:"idle"}))},children:h("models.catalogUndo")}),children:(0,r.jsx)("span",{className:"models-ellipsis",title:L,children:L})}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(sj,{title:h("models.capabilities")}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(sk,{label:h("models.reasoning"),checked:n.reasoning??!1,onChange:e=>E("reasoning",e||void 0)}),(0,r.jsx)(sk,{label:h("models.imageInput"),checked:n.input?.includes("image")??!1,onChange:e=>E("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(sj,{title:h("models.modelSpecs")}),(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsx)(sa,{label:h("models.contextWindow"),children:(0,r.jsx)(sb,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>E("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(sa,{label:h("models.maxOutputTokens"),children:(0,r.jsx)(sb,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>E("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{className:"models-section-header",children:[(0,r.jsx)("span",{className:"config-field-label",children:h("models.costPerMillion")}),(0,r.jsx)(sh,{size:"small",variant:"ghost",onClick:()=>{if(g)return void m(!1);C.current=n.cost;let e=oY(n.cost);y.current=e,v(e),m(!0)},"aria-expanded":g,children:g?h("models.finishEditingCosts"):h("models.editCosts")})]}),g?(0,r.jsxs)("div",{className:"models-cost-grid",children:[$.map(({key:e,label:t})=>(0,r.jsx)(sa,{label:t,children:(0,r.jsx)(sb,{value:x[e],onChange:t=>{let r,i,s;return i=oZ(r={...y.current,[e]:t}),s={...n},void(y.current=r,v(r),i?(s.cost={...C.current??{},...i},C.current=s.cost):delete s.cost,o(s))},placeholder:"0"})},e)),oX(x)&&!oZ(x)&&(0,r.jsx)("p",{"aria-live":"polite",className:"models-hint is-warning models-grid-full",children:h("models.costAllRequired")})]}):(0,r.jsx)("div",{className:"models-cost-grid",children:$.map(({key:e,label:t})=>{let i;return(0,r.jsxs)("div",{className:"models-cost-cell",children:[(0,r.jsx)("span",{className:"models-hint",children:t}),(0,r.jsx)("span",{className:`models-cost-value${n.cost?.[e]===void 0?" is-missing":""}`,children:void 0===(i=n.cost?.[e])?h("models.notProvided"):`$${String(i)}`})]},e)})})]}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsxs)("button",{type:"button",className:"models-disclosure",onClick:()=>k(e=>!e),"aria-expanded":b,"aria-controls":"model-advanced-settings",children:[(0,r.jsxs)("span",{className:"models-disclosure-copy",children:[(0,r.jsx)("strong",{children:h("models.advancedSettings")}),(0,r.jsx)("span",{children:A})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"models-disclosure-chevron",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",className:"models-form",children:[!l&&(0,r.jsx)(sa,{label:h("models.apiOverride"),children:(0,r.jsx)(sw,{value:n.api??"",onChange:e=>E("api",e||void 0),options:sA})}),(0,r.jsxs)(sa,{label:h("models.headers"),children:[(0,r.jsx)(sE,{headers:n.headers,onChange:e=>E("headers",e)}),(0,r.jsx)(sS,{children:h("models.headersHelp")})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sj,{title:h("models.compatibility")}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(sk,{label:h("models.deepSeekThinkingCompat"),checked:sO(n),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...sF}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(sk,{label:h("models.developerRole"),checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>o({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})})]}),(0,r.jsx)(sj,{title:h("models.thinkingLevelMap"),actions:n.thinkingLevelMap&&(0,r.jsx)(sh,{size:"small",variant:"ghost",onClick:()=>E("thinkingLevelMap",void 0),children:h("models.clearAll")})}),(0,r.jsx)(sN,{value:n.thinkingLevelMap,onChange:e=>E("thinkingLevelMap",e)})]})]})]})]})}function s_(){let e=o_("models");try{let t=e?JSON.parse(e):null;if(t&&"object"==typeof t&&"string"==typeof t.provider)return{provider:t.provider}}catch{}return{provider:null}}function sq({onClose:e,embedded:t=!1,cwd:n=null,onModelsChanged:o,onDirtyChange:s}){var l;let a,d,c,u,h,p,f,g,{t:m}=(0,w.s)(),[x,v]=(0,i.useState)({providers:{}}),[y,b]=(0,i.useState)({providers:{}}),[k,j]=(0,i.useState)(!0),[S,C]=(0,i.useState)(!1),[E,N]=(0,i.useState)(null),[I,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(!1),[R,$]=(0,i.useState)(s_),[W,z]=(0,i.useState)([]),[P,A]=(0,i.useState)([]),[D,H]=(0,i.useState)(!1),[B,F]=(0,i.useState)(null),[O,U]=(0,i.useState)(null),[_,q]=(0,i.useState)([]),[K,V]=(0,i.useState)(new Set),[J,Y]=(0,i.useState)(null),[Z,X]=(0,i.useState)(!1),[G,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,eo]=(0,i.useState)({}),es=(0,i.useCallback)(()=>fetch(`/api/auth/providers${n?`?cwd=${encodeURIComponent(n)}`:""}`).then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&z(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&A(e.apiKeyProviders)}).catch(()=>{}),[n]),el=(0,i.useCallback)(()=>{if(!n)return void q([]);let e=new URLSearchParams({cwd:n});return fetch(`/api/models-config/runtime?${e}`).then(e=>e.json()).then(e=>{Array.isArray(e.catalog)&&q(e.catalog),Array.isArray(e.builtIn)&&V(new Set(e.builtIn)),er(e.modelError??null)}).catch(()=>{})},[n]),ea=(0,i.useCallback)(()=>n?fetch(`/api/models-config/picker?cwd=${encodeURIComponent(n)}`).then(async e=>{let t=await e.json();e.ok&&!t.error&&t.source?(Q(null),Y(t)):Q(t.error??m("models.scopeError"))}).catch(()=>Q(m("models.scopeError"))):void Y(null),[n,m]);(0,i.useEffect)(()=>{if(!ee)return;let e=setTimeout(()=>et(null),4e3);return()=>clearTimeout(e)},[ee]);let ed=(0,i.useCallback)(()=>{es(),el(),ea()},[es,el,ea]);(0,i.useEffect)(()=>{let e=!1;return j(!0),Promise.all([fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};N(e.error??null),v(t),b(t)}).catch(e=>N(String(e))),es(),el(),ea()]).finally(()=>{e||j(!1)}),()=>{e=!0}},[es,el,ea]),(0,i.useEffect)(()=>{oq("models",JSON.stringify({provider:R.provider}))},[R]);let ec=JSON.stringify(x)!==JSON.stringify(y);(0,i.useEffect)(()=>{s?.(ec)},[ec,s]),(0,i.useEffect)(()=>{if(!ec)return;let e=e=>e.preventDefault();return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ec]);let eu=(0,i.useCallback)((e,t)=>{$({provider:e,...t?{model:t}:{}})},[]),eh=(0,i.useCallback)(e=>{v(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),eu(e)},[eu]),ep=(0,i.useCallback)((e,t)=>{v(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),ef=(0,i.useCallback)(e=>{v(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),eu(null)},[eu]),eg=(0,i.useCallback)(e=>{let t=x.providers?.[e]?.models?.length??0;v(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),eu(e,{kind:"definition",index:t})},[x.providers,eu]),em=(0,i.useCallback)((e,t)=>{v(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],o=new Set(i.map(e=>e.id));for(let e of t)o.has(e.id)||(o.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),ex=(0,i.useCallback)((e,t,n)=>{v(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),ev=(0,i.useCallback)((e,t,n)=>{let r=function(e,t){let n={};for(let i of oG){let o=t[i];if(void 0!==o){var r;r=e[i],JSON.stringify(o)!==JSON.stringify(r)&&(n[i]=o)}}return Object.keys(n).length>0?n:void 0}(sD(t),{...n,id:t.id});v(n=>{var i,o;let s,l=n.providers?.[e]??{},a={...l},d=(i=l.modelOverrides,o=t.id,s={...i??{}},delete s[o],r&&(s[o]=r),Object.keys(s).length>0?s:void 0);return d?a.modelOverrides=d:delete a.modelOverrides,{...n,providers:{...n.providers??{},[e]:a}}})},[]),ey=(0,i.useCallback)((e,t)=>{v(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),eu(e)},[eu]),eb=(0,i.useCallback)(async()=>{if(!n)return null;let e=await fetch(`/api/models-config/picker?cwd=${encodeURIComponent(n)}`),t=await e.json();return e.ok&&!t.error&&t.source?t:null},[n]),ew=(0,i.useRef)(0),ek=(0,i.useCallback)(async()=>{let e=++ew.current,t=await eb();return t&&e===ew.current&&Y(t),t},[eb]),ej=(0,i.useRef)(Promise.resolve()),eS=(0,i.useCallback)(e=>{if(!n)return Promise.resolve(!1);let t=ej.current.then(async()=>{let t=await eb();if(!t)return Q(m("models.scopeError")),!1;if(t.readOnly)return!1;let r=e(t);if(0===r.length)return Q(m("models.keepOneModel")),!1;X(!0),Q(null),et(null);try{let e=await fetch("/api/models-config/picker",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n,patterns:r})}),t=await e.json();if(!e.ok||t.error||!t.source)return Q("untrusted"===t.code?m("models.scopeReadOnly"):t.error??m("models.scopeError")),!1;return Y(t),o?.(),!0}catch{return Q(m("models.scopeError")),!1}finally{X(!1)}});return ej.current=t.catch(()=>!1),t},[n,eb,o,m]),eC=(0,i.useCallback)(()=>{n&&J&&U("none"===J.source?"replace":"add")},[n,J]),eE=(0,i.useCallback)(async e=>{let t=!!J&&!o8(J?.patterns??[]);await eS(t=>(function(e){let t=o0(e.patterns);if(o8(t)){let n,r;return r=(n=e.ref.trim()).slice(n.indexOf("/")+1),o0(t).filter(e=>{let t=o2(e);return null===t||t.ref!==n&&(void 0!==t.provider||t.id!==r)})}return e.visible.filter(t=>t!==e.ref).map(t=>`${t}${e.pins[t]?`:${e.pins[t]}`:""}`)})({patterns:t.patterns,visible:t.visible.map(e=>oQ(e.provider,e.id)),pins:t.pins,ref:e}))&&t&&et(m("models.listWritten"))},[eS,J,m]),eN=(0,i.useCallback)(async()=>{C(!0),M(null),L(!1);try{var e;let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)}),n=await t.json();if(!t.ok||n.error)return void M(n.error??`HTTP ${t.status}`);b(x),L(!0),setTimeout(()=>L(!1),2e3),el();let r=J?.defined,i=await ek(),s=r&&i?(e={patterns:r.length?J?.patterns??[]:[],before:new Set(r),after:new Set(i.defined)},o0(e.patterns).filter(t=>{let n=o2(t);return null!==n&&void 0!==n.provider&&e.before.has(n.ref)&&!e.after.has(n.ref)})):[];s.length>0&&await eS(e=>e.patterns.filter(e=>!s.includes(e)))&&et(m("models.removedWithDefinition",{count:s.length})),o?.()}catch(e){M(String(e))}finally{C(!1)}},[x,ek,o,el,eS,J,m]),eI=[E,en].filter(Boolean).map(e=>String(e).split("\n")[0]).join(" \xb7 ")||null,eM=J?.visible??[],eT=new Set(eM.map(e=>oQ(e.provider,e.id))),eL=new Set(_.map(e=>oQ(e.provider,e.id))),eR=J?(a=new Set((l={patterns:J.patterns,visible:[...eT]}).visible),d=new Set(l.visible.map(e=>e.slice(e.indexOf("/")+1))),o0(l.patterns).filter(e=>{let t=o2(e);return null!==t&&(t.provider?!a.has(t.ref):!d.has(t.id))})).filter(e=>!(J.ambiguous??[]).includes(e)):[],e$=new Set([...W.filter(e=>e.loggedIn).map(e=>e.id),...P.filter(e=>e.configured).map(e=>e.id)]),eW=R.provider,ez=[],eP=e=>{e&&!ez.includes(e)&&ez.push(e)};W.filter(e=>e.loggedIn).forEach(e=>eP(e.id)),P.filter(e=>e.configured).forEach(e=>eP(e.id)),Object.keys(x.providers??{}).forEach(eP),_.forEach(e=>eP(e.provider)),eM.forEach(e=>eP(e.provider)),eP(eW);let eA=ez.map(e=>{let t=W.find(t=>t.id===e),n=P.find(t=>t.id===e),r=x.providers?.[e],i=_.filter(t=>t.provider===e);return{id:e,label:r?.name??t?.name??n?.displayName??e,...t?{oauth:t}:{},...n?{apiKey:n}:{},...r?{json:r}:{},models:i,connected:e$.has(e)||i.length>0}}),eD=e=>eM.filter(t=>t.provider===e).length,eH=e=>{let t=e.json,i=!!(e.oauth||e.apiKey),o=e.apiKey&&(!e.oauth||e.apiKey.configured||!e.oauth.loggedIn),s=t?.models??[],l=!!(t&&(t.name&&""!==t.name.trim()||t.api||t.baseUrl&&""!==t.baseUrl.trim()||t.apiKey&&""!==t.apiKey.trim()||t.headers&&Object.keys(t.headers).length>0)),a=ei[e.id]??l,d=[...e.models.map(e=>{let t=s.findIndex(t=>t.id===e.id);return{id:e.id,name:e.name,ref:t>=0?{kind:"definition",index:t}:{kind:"runtime",id:e.id},usable:!0,definition:t>=0}}),...s.map((e,t)=>({model:e,index:t})).filter(({model:t})=>!eL.has(`${e.id}/${t.id}`)).map(({model:e,index:t})=>({id:e.id,name:e.name,ref:{kind:"definition",index:t},usable:!1,definition:!0}))],c=t&&(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(sj,{title:i?m("models.sectionEndpointOverride"):m("models.sectionEndpoint"),hint:i?m("models.sectionOverrideHint"):m("models.sectionDraftHint"),actions:i?(0,r.jsx)(sh,{size:"small",variant:"ghost",onClick:()=>eo(t=>({...t,[e.id]:!a})),children:a?m("i18n.collapse"):m("i18n.expand")}):void 0}),(!i||a)&&(0,r.jsx)(sH,{providerId:e.id,provider:t,builtIn:i,namePlaceholder:e.oauth?.name??e.apiKey?.displayName??e.id,onChange:t=>ep(e.id,t)},e.id)]}),u=e.oauth?.loggedIn?m("models.kindOAuth"):e.apiKey?.configured?m("models.kindApiKey"):null;return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)(sr,{children:[(0,r.jsxs)(si,{children:[(0,r.jsx)(sx,{id:e.id,size:28}),(0,r.jsxs)("div",{className:"models-title-row",children:[(0,r.jsx)("strong",{className:"models-title",children:e.label}),u&&(0,r.jsx)("span",{className:"models-tag is-success",children:u}),e.oauth&&!e.apiKey&&!e.oauth.loggedIn&&(0,r.jsx)("span",{className:"models-tag",children:m("models.kindOAuth")}),t&&(0,r.jsx)("span",{className:`models-tag ${i?"is-override":"is-custom"}`,children:i?m("models.kindOverridden"):m("models.kindCustom")})]})]}),t&&(0,r.jsx)(so,{children:(0,r.jsx)(sh,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:()=>{ef(e.id),i&&eu(e.id)},children:i?m("models.deleteOverride"):m("models.deleteEndpoint")})})]}),(e.oauth||o)&&(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(sj,{title:m("models.sectionConnection"),hint:m("models.sectionConnectionHint")}),e.oauth&&(0,r.jsx)(sL,{provider:e.oauth,onRefresh:ed,cwd:n},e.oauth.id),o&&e.apiKey&&(0,r.jsx)(sR,{provider:e.apiKey,onRefresh:ed,cwd:n},`${e.apiKey.id}-key`)]}),!i&&c,(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(sj,{title:m("models.sectionModels",{count:d.length}),hint:n&&J?m("models.chatSwitchHint"):void 0,actions:t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(sh,{size:"small",disabled:!t.baseUrl?.trim(),title:t.baseUrl?.trim()?void 0:m("models.discoveryNeedsBaseUrl"),onClick:()=>F(e.id),children:m("models.discoveryFetch")}),(0,r.jsx)(sh,{size:"small",onClick:()=>eg(e.id),children:m("models.newModel")})]})}),t&&B===e.id&&(0,r.jsx)(sB,{providerId:e.id,provider:t,onAddModels:t=>em(e.id,t),onClose:()=>F(null)}),0===d.length?(0,r.jsx)("p",{className:"models-empty",children:t?m("models.noDefinitions"):m("models.connectToSeeModels")}):(0,r.jsx)("div",{className:"models-list",children:d.map(t=>{let o,s,l,a,d=oQ(e.id,t.id);return(0,r.jsxs)("div",{className:"models-row",children:[(o=t.name&&t.name!==t.id?t.name:t.id||m("models.untitledModel"),s=t.name&&t.name!==t.id?t.id:void 0,l=(0,r.jsxs)(r.Fragment,{children:[t.definition&&K.has(d)?(0,r.jsx)("span",{className:"models-tag is-warning",title:m("models.replacesBuiltInHint"),children:m("models.replacesBuiltIn")}):i&&t.definition&&(0,r.jsx)("span",{className:"models-tag",children:m("models.kindDefinition")}),!t.usable&&(0,r.jsx)("span",{className:"models-tag is-warning",children:m("models.notUsable")}),J?.pins[d]&&(0,r.jsx)("span",{className:"models-tag",children:m("models.thinkingPin",{level:J.pins[d]})})]}),a=()=>eu(e.id,t.ref),(0,r.jsxs)("button",{type:"button",className:"models-row-main models-row-button",title:m("models.editParams"),onClick:a,children:[(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsxs)("span",{className:"models-row-title-line",children:[(0,r.jsx)("span",{className:"models-row-title",children:o}),l]}),s&&(0,r.jsx)("code",{className:"models-row-sub",children:s})]}),(0,r.jsx)("svg",{className:"models-row-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]})),t.id&&((e,t)=>{if(!n||!J)return null;let i=eT.has(e);return(0,r.jsx)("span",{className:"models-row-switch",children:(0,r.jsx)(sp,{checked:i,disabled:J.readOnly||!t&&!i,loading:Z,label:m("models.showInChat"),onChange:t=>{t?eS(t=>o1(t.patterns,e)):eE(e)}})})})(d,t.usable)]},`${t.ref.kind}:${t.id}:${"definition"===t.ref.kind?t.ref.index:""}`)})})]}),i&&c]})};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(o5,{embedded:t,title:m("common.models"),closeLabel:m("i18n.close"),onClose:e,children:[k?(0,r.jsx)("div",{className:"models-loading",role:"status","aria-busy":"true",children:(0,r.jsx)("span",{children:m("i18n.loading")})}):(0,r.jsx)("div",{className:"models-ready",children:(c=eW??eA[0]?.id??null,u=eA.find(e=>e.id===c),h=R.provider===c?R.model:void 0,p=eA.filter(e=>e.connected),f=eA.filter(e=>!e.connected),g=e=>{let t;return(0,r.jsxs)(se,{active:e.id===c,onClick:()=>eu(e.id),children:[(0,r.jsx)(sx,{id:e.id,size:16}),(0,r.jsx)(st,{className:`is-grow${e.connected?"":" is-muted"}`,children:e.label}),(t=e.id,JSON.stringify(x.providers?.[t]??null)!==JSON.stringify(y.providers?.[t]??null)&&(0,r.jsx)("span",{className:"models-dirty-dot",title:m("models.unsavedProvider")})),J&&e.models.length>0&&(0,r.jsxs)("span",{className:"models-count",title:m("models.inChatCount",{count:eD(e.id),total:e.models.length}),children:[eD(e.id),"/",e.models.length]})]},e.id)},(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{children:[(0,r.jsxs)(o7,{children:[k&&(0,r.jsx)("div",{className:"config-sidebar-message",children:m("i18n.loading")}),p.length>0&&(0,r.jsx)(o9,{children:m("models.groupConnected")}),p.map(g),f.length>0&&(0,r.jsx)(o9,{children:m("models.groupNotConnected")}),f.map(g)]}),(0,r.jsxs)("div",{className:"models-sidebar-actions",children:[(0,r.jsx)(sf,{onClick:()=>eC(),disabled:!n||!J||J.readOnly,children:m("models.pickChatModels")}),(0,r.jsx)(sf,{onClick:()=>H(!0),children:m("models.addProvider")})]})]}),(0,r.jsx)(sc,{children:(0,r.jsxs)(sn,{className:"is-fill",children:[n?J?(0,r.jsxs)(r.Fragment,{children:[J.readOnly&&(0,r.jsx)(sC,{tone:"warning",children:m("models.scopeReadOnly")}),ee&&(0,r.jsx)(sC,{tone:"info",children:ee}),G&&(0,r.jsx)(sC,{tone:"danger",children:G}),eR.length>0&&(0,r.jsx)(sK,{title:m("models.unavailable",{count:eR.length}),hint:m("models.unavailableHint"),entries:eR,readOnly:!!J.readOnly,onRemove:e=>void eS(t=>o4(t.patterns,e))}),(J.ambiguous?.length??0)>0&&(0,r.jsx)(sK,{title:m("models.ambiguous",{count:J.ambiguous?.length??0}),hint:m("models.ambiguousHint"),entries:J.ambiguous??[],readOnly:!!J.readOnly,onRemove:e=>void eS(t=>o4(t.patterns,e))})]}):G?(0,r.jsx)(sC,{tone:"danger",children:G}):null:(0,r.jsx)(sC,{children:m("models.scopeNoCwd")}),k?null:u?h?((e,t)=>{let i=(0,r.jsxs)("button",{type:"button",className:"models-breadcrumb",onClick:()=>eu(e.id),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m15 18-6-6 6-6"})}),(0,r.jsx)(sx,{id:e.id,size:14}),e.label]});if("runtime"===t.kind){var o;let s=_.find(n=>n.provider===e.id&&n.id===t.id);if(!s)return null;let l=x.providers?.[e.id]??{},a=l.modelOverrides?.[s.id],d=(o=sD(s),a?{...o,...a,id:o.id,cost:a.cost?{...o.cost,...a.cost}:o.cost}:{...o,id:o.id});return(0,r.jsxs)(r.Fragment,{children:[i,(0,r.jsx)(sU,{providerName:e.id,provider:l,model:d,lockId:!0,cwd:n,onChange:t=>ev(e.id,s,t)},`${e.id}-${t.id}`)]})}let s=x.providers?.[e.id],l=s?.models?.[t.index];return s&&l?(0,r.jsxs)(r.Fragment,{children:[i,(0,r.jsx)(sU,{providerName:e.id,provider:s,model:l,cwd:n,onChange:n=>ex(e.id,t.index,n),onDelete:()=>ey(e.id,t.index),shadowsBuiltIn:K.has(`${e.id}/${l.id}`)},`${e.id}-${t.index}`)]}):null})(u,h)??eH(u):eH(u):(0,r.jsx)(sd,{children:m("models.noProviders")})]})})]}))}),(ec||S||T||I||eI)&&(0,r.jsxs)(su,{status:I||eI?(0,r.jsx)("span",{className:"models-footer-status is-danger",title:eI??void 0,children:I||eI}):ec?(0,r.jsxs)("span",{className:"models-footer-status",children:[(0,r.jsx)("span",{className:"models-dirty-dot"}),m("models.unsavedChanges")]}):null,children:[!t&&(0,r.jsx)(sh,{onClick:e,children:m("i18n.cancel")}),ec&&!S&&(0,r.jsx)(sh,{onClick:()=>{v(y),M(null),!R.provider||y.providers?.[R.provider]||_.some(e=>e.provider===R.provider)?R.provider&&eu(R.provider):eu(null)},children:m("models.discardChanges")}),(ec||S||T)&&(0,r.jsxs)(sh,{variant:"primary",onClick:eN,disabled:S||T,className:T?"is-success":void 0,children:[T&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:T?m("i18n.saved"):S?m("i18n.saving"):m("models.saveModelsJson")})]})]})]}),D&&(0,r.jsx)(sz,{oauthProviders:W,apiKeyProviders:P,existingIds:new Set([...Object.keys(x.providers??{}),...W.map(e=>e.id),...P.map(e=>e.id),..._.map(e=>e.provider)]),onSelectOAuth:e=>eu(e),onSelectApiKey:e=>eu(e),onAddCustom:eh,onClose:()=>H(!1)}),O&&(0,r.jsx)(sP,{catalog:_,listedRefs:"replace"===O?new Set:eT,mode:O,providerLabel:e=>eA.find(t=>t.id===e)?.label??e,saving:Z,error:G,onClose:()=>U(null),onApply:e=>{U(null),eS(t=>"replace"===O?e:e.reduce((e,t)=>o1(e,t),t.patterns))}})]})}function sK({title:e,hint:t,entries:n,readOnly:i,onRemove:o}){let{t:s}=(0,w.s)();return(0,r.jsxs)(sC,{tone:"warning",children:[(0,r.jsx)("strong",{children:e}),(0,r.jsx)("span",{className:"models-notice-hint",children:t}),(0,r.jsx)("div",{className:"models-notice-list",children:n.map(e=>(0,r.jsxs)("div",{className:"models-notice-entry",children:[(0,r.jsx)("code",{children:o2(e)?.id??e}),!i&&(0,r.jsx)(sh,{size:"small",variant:"ghost",onClick:()=>o(e),children:s("models.removeFromChat")})]},e))})]})}function sV(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function sJ(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function sY(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function sZ(e){return e?e.slice(0,8):"unknown"}function sX({skill:e,cwd:t,onToggle:n,toggling:i,saveError:o,updateStatus:s,checkingUpdate:l,updating:a,updateError:d,onCheckUpdate:c,onUpdate:u,onDelete:h,deleting:p,deleteError:f}){let{t:g}=(0,w.s)(),m=sJ(e),x=!e.disableModelInvocation;return(0,r.jsxs)(sn,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(sr,{children:[(0,r.jsxs)(si,{children:[(0,r.jsx)("span",{className:`config-scope-tag${"project"===m?" is-project":""}`,children:m}),(0,r.jsx)("span",{className:"config-detail-path",children:function(e){if("project"===m&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return sV(e)}(e.filePath)})]}),(0,r.jsx)(so,{children:(0,r.jsx)(sp,{checked:x,loading:i,label:g(x?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>n(e)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!x&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:g("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),e.install?.skillsShUrl&&(0,r.jsx)(sa,{label:"Source",children:(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),e.install&&(0,r.jsxs)(sa,{label:"Version",children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:sZ(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)(sh,{size:"small",onClick:c,disabled:l||a,children:g("i18n.check")}),s?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:sZ(s.latestVersion)}),(l||s&&"update-available"!==s.state)&&(0,r.jsx)("span",{className:`skill-update-status ${l?"is-checking":s?.state==="up-to-date"?"is-success":s?.state==="error"?"is-error":"is-muted"}`,children:l?g("i18n.checking"):s?.state==="up-to-date"?g("i18n.upToDate"):s?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):s?.message||g("i18n.checkFailed")}),s?.state==="update-available"&&(0,r.jsx)(sh,{variant:"primary",size:"small",onClick:u,disabled:a||l,children:g(a?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)(sa,{label:"Name",children:(0,r.jsx)("span",{className:"skill-name-value",children:e.name})}),(0,r.jsx)(sa,{label:"Description",children:(0,r.jsx)("span",{className:"skill-description",children:e.description})}),(0,r.jsxs)("div",{className:"skill-delete-row",children:[e.removable?(0,r.jsx)(sh,{variant:"danger",size:"small",onClick:h,disabled:p,children:g("i18n.delete")}):(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:g("skills.notRemovable")}),f&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444",overflowWrap:"anywhere"},children:f})]})]})}function sG({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:o}){let{t:s}=(0,w.s)(),[l,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(new Set),[k,j]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),f(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void f(n.error);c(n.results??[]),0===(n.results??[]).length&&f("No skills found")}catch(e){f(String(e))}finally{h(!1)}}},[]),E=(0,i.useCallback)(async t=>{m(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:k,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);b(e=>new Set(e).add(`${k}:${t}`)),o()}catch(e){v(String(e))}finally{m(null)}},[o,k,e]),N="global"===k?"~/.pi/agent/skills/":`${sV(e)}/.pi/skills/`;return(0,r.jsxs)(sn,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(ss,{children:s("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(l)},placeholder:s("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(sh,{variant:"primary",onClick:()=>C(l),disabled:u||!l.trim(),children:u?s("i18n.searching"):s("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&j(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:k===e?"var(--bg-selected)":"none",color:k===e?"var(--text)":"var(--text-dim)",fontWeight:k===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),p&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:p}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[k].has(e.package)||y.has(`${k}:${e.package}`),i=g===e.package,o=e.package.indexOf("@"),l=o>-1?e.package.slice(0,o):e.package,a=o>-1?e.package.slice(o+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:a??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(sh,{size:"small",onClick:()=>!n&&!i&&E(e.package),disabled:n||i||null!==g,style:{flexShrink:0,background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:n?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!p&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function sQ({cwd:e,onClose:t,embedded:n=!1}){let{t:o}=(0,w.s)(),[s,l]=(0,i.useState)([]),[a,d]=(0,i.useState)(!0),[c,u]=(0,i.useState)(null),[h,p]=(0,i.useState)(()=>o_("skills",e)),[f,g]=(0,i.useState)(new Set),[m,x]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),[b,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,E]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[M,T]=(0,i.useState)(null),[L,R]=(0,i.useState)(!0),[$,W]=(0,i.useState)(null),[z,P]=(0,i.useState)(null),A=(0,i.useCallback)(async()=>{d(!0),u(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];return l(r),R(n.projectResourcesLoaded??!0),p(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return u(String(e)),[]}finally{d(!1)}},[e]);(0,i.useEffect)(()=>{k({}),T(null),A()},[e]),(0,i.useEffect)(()=>{h&&oq("skills",h,e)},[e,h]);let D=(0,i.useCallback)(async t=>{let n=(t?[t]:s.filter(e=>!!e.install)).map(sY).filter(e=>!!e);if(0!==n.length){T(null),S(e=>new Set([...e,...n])),t||E(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){T(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||E(!1)}}},[e,s]),H=(0,i.useCallback)(async t=>{if(!t.install)return;let n=sY(t);I(n),T(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await A();let o=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){T(e instanceof Error?e.message:String(e))}finally{I(null)}},[e,A]),B=(0,i.useCallback)(async t=>{let n=!t.disableModelInvocation;g(e=>new Set(e).add(t.filePath)),x(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:n})}),i=await r.json();if(!r.ok||i.error)return void x(i.error??`HTTP ${r.status}`);l(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:n}:e))}catch(e){x(String(e))}finally{g(e=>{let n=new Set(e);return n.delete(t.filePath),n})}},[e]),F=(0,i.useCallback)(async t=>{let n=[o("skills.deleteConfirm",{path:sV(t.filePath)}),t.install?o("skills.deleteViaSkillsSh"):null,o("skills.deleteReloadHint")].filter(Boolean).join("\n\n");if(window.confirm(n)){W(t.filePath),P(null);try{let n=await fetch("/api/skills",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath})}),r=await n.json();if(!n.ok||!r.success)throw Error(r.error??`HTTP ${n.status}`);p(null),await A()}catch(e){P(e instanceof Error?e.message:String(e))}finally{W(null)}}},[e,A,o]),O=s.find(e=>e.filePath===h)??null;return(0,r.jsxs)(o5,{embedded:n,title:o("common.skills"),subtitle:sV(e),closeLabel:o("i18n.close"),onClose:t,children:[!L&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:o("trust.skillsNotLoaded")}),(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{children:[(0,r.jsx)(o7,{children:a?(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")}):c?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:c}):0===s.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:o("i18n.noSkills")}):(()=>{let e=[],t={project:o("skills.scope.project"),global:o("skills.scope.global"),path:o("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===sJ(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===sJ(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===sJ(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===sJ(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===sJ(e)}]){let t=s.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!v&&h===e.filePath,s=e.disableModelInvocation;return(0,r.jsxs)(se,{active:i,onClick:()=>{p(e.filePath),y(!1),P(null)},children:[(0,r.jsx)(sg,{active:!s}),(0,r.jsx)(st,{className:`is-grow${s?" is-muted":""}`,children:e.name}),(n=(t=sY(e))?b[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:o("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:t})=>(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o9,{children:e}),[...t.filter(e=>!e.disableModelInvocation),...t.filter(e=>e.disableModelInvocation)].map(n)]},e))})()}),(0,r.jsx)(sf,{onClick:()=>y(!0),active:v,children:o("i18n.addSkill")})]}),(0,r.jsx)(sc,{children:(0,r.jsx)(sn,{className:"is-fill",children:v?(0,r.jsx)(sG,{cwd:e,projectResourcesLoaded:L,installedPackages:{global:new Set(s.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(s.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{A()}}):a?null:O?(0,r.jsx)(sX,{skill:O,cwd:e,onToggle:B,toggling:f.has(O.filePath),saveError:m,updateStatus:sY(O)?b[sY(O)]:void 0,checkingUpdate:!!sY(O)&&j.has(sY(O)),updating:N===sY(O),updateError:M,onCheckUpdate:()=>void D(O),onUpdate:()=>void H(O),onDelete:()=>void F(O),deleting:$===O.filePath,deleteError:z},O.filePath):(0,r.jsx)(sd,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(su,{status:Object.values(b).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(b).filter(e=>"update-available"===e.state).length," ",1===Object.values(b).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!n&&(0,r.jsx)(sh,{onClick:t,children:o("i18n.close")}),s.some(e=>!!e.install)&&(0,r.jsx)(sh,{variant:"secondary",onClick:()=>void D(),disabled:C||null!==N,children:C?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let s0={builtin:0,global:1,workspace:2,project:3};function s1(e,t){let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase()===n).sort((e,t)=>s0[t.scope]-s0[e.scope])}let s2=["read","bash","edit","write","grep","find","ls"],s4=["",...eI],s8={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,inheritContext:!1,runInBackground:!0,enabled:!0},s5={width:"100%",minWidth:0,height:34,padding:"0 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},s6={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function s3(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,loadExtensions:e.loadExtensions,...e.model?{model:e.model}:{},...e.thinking?{thinking:e.thinking}:{},...e.maxTurns?{maxTurns:e.maxTurns}:{},inheritContext:e.inheritContext,runInBackground:e.runInBackground,enabled:e.enabled}}function s7(e){return"builtin"!==e}function s9(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function le(e,t){if(!e.filePath)return null;if(("project"===e.scope||"workspace"===e.scope)&&e.filePath.startsWith(t)){let n=e.filePath.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return s9(e.filePath)}function lt({label:e,children:t}){return(0,r.jsx)(sa,{label:e,children:t})}function ln({checked:e,disabled:t,label:n,onChange:i}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:7,color:t?"var(--text-dim)":"var(--text-muted)",fontSize:12,cursor:t?"default":"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:e,disabled:t,onChange:e=>i(e.target.checked)}),n]})}function lr({cwd:e,sessionId:t=null,onClose:n,onReloaded:o,embedded:s=!1}){let l,a=eX(),{t:d}=(0,w.s)(),[c,u]=(0,i.useState)([]),[h,p]=(0,i.useState)([]),[f,g]=(0,i.useState)(!0),[m,x]=(0,i.useState)(null),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(s8),[j,S]=(0,i.useState)("view"),[C,E]=(0,i.useState)("project"),[N,I]=(0,i.useState)(!0),[M,T]=(0,i.useState)(!1),[L,R]=(0,i.useState)(!1),[$,W]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[A,D]=(0,i.useState)(!0),[H,B]=(0,i.useState)(10),[F,O]=(0,i.useState)(!0),[U,_]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[V,J]=(0,i.useState)(!1),[Y,Z]=(0,i.useState)(!1),X=(0,i.useMemo)(()=>v?s1(c,v):[],[c,v]),G=X[0]??null,Q=X.slice(1),ee=G?.disableStub?Q[0]??G:G,et=(0,i.useMemo)(()=>[...new Set(c.map(e=>e.name.toLowerCase()))].map(e=>{let[t,n]=s1(c,e);return{name:e,top:t,label:(t.disableStub?n??t:t).displayName}}).sort((e,t)=>e.label.localeCompare(t.label)),[c]),en=(0,i.useMemo)(()=>h.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[h]),er=(0,i.useCallback)((e,t)=>{if(y(t),P(null),!t)return;let[n,r]=s1(e,t);if(!n)return;k(s3(n.disableStub?r??n:n));let i=s7(n.scope)&&!n.disableStub&&!n.configurationError;S(i?"edit":"view"),i&&E(n.scope)},[]),ei=(0,i.useCallback)(async()=>{let t=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.profiles??[];return u(r),r},[e]),eo=(0,i.useCallback)(async t=>{I(!0),P(null);try{let n=await ei(),r=new Set(n.map(e=>e.name.toLowerCase())),i=(t??o_("agents",e)??"").toLowerCase();er(n,r.has(i)?i:r.has("general-purpose")?"general-purpose":[...r][0]??null)}catch(e){P(e instanceof Error?e.message:String(e))}finally{I(!1)}},[e,ei,er]);(0,i.useEffect)(()=>{eo()},[eo]),(0,i.useEffect)(()=>{let e=new AbortController;return O(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);D(n.enabled),"number"==typeof n.maxConcurrent&&B(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||O(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{v&&oq("agents",v,e)},[e,v]),(0,i.useEffect)(()=>{let t=new AbortController;return g(!0),x(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(e)}`,{signal:t.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);p(r.modelList??[]),x(r.modelError??null)}catch(e){if(t.signal.aborted)return;x(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||g(!1)}})(),()=>t.abort()},[e]);let es=async e=>{await eo(e),J(!!t)},el=async()=>{if("create"===j&&et.some(e=>e.name===b.name.trim().toLowerCase()))return void P(d("agents.nameExists",{name:b.name.trim()}));T(!0),P(null),R(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:C,profile:b})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await es(n.profile.name),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}},ea=async()=>{if(!G||!ee||!s7(G.scope))return;let t=Q[0],n=t?d("agents.restoreConfirm",{name:ee.displayName,scope:d(`agents.scope.${t.scope}`)}):d("agents.deleteConfirm",{name:ee.displayName});if(window.confirm(n)){T(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:G.scope,name:G.name})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);await es(t?G.name:void 0)}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}}},ed="create"===j||"customize"===j,ec="view"!==j,eu=!ec||M||$,eh=ed?C:G?.scope,ep=ed?"global"===C?`~/.pi/agent/agents/${b.name||"..."}.md`:`./.pi/agents/${b.name||"..."}.md`:G?le(G,e)??d("agents.builtinPath"):"",ef=ed?ep:G?.filePath??ep,eg=!b.model||h.some(e=>`${e.provider}/${e.id}`===b.model),em=(()=>{if(!b.model)return null;let e=b.model.indexOf("/");return e<0?{provider:"",modelId:b.model}:{provider:b.model.slice(0,e),modelId:b.model.slice(e+1)}})(),ex=eu?{...s5,...s6}:s5,ev=(e,t)=>{k(n=>({...n,[e]:t}))},ey=async n=>{if(ed)return void ev("enabled",n);if(G){W(!0),P(null);try{let r=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,name:G.name,enabled:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);await ei(),ev("enabled",n),J(!!t)}catch(e){P(e instanceof Error?e.message:String(e))}finally{W(!1)}}},eb=async e=>{_(!0),K(null);try{let n=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${n.status}`);D(r.enabled),J(!!t)}catch(e){K(e instanceof Error?e.message:String(e))}finally{_(!1)}},ew=async e=>{B(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);B(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ek=async()=>{if(t){Z(!0),K(null);try{await r7(t,{type:"reload"}),J(!1),o?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{Z(!1)}}};return(0,r.jsxs)(o5,{embedded:s,title:d("common.agents"),subtitle:s9(e),closeLabel:d("agents.close"),onClose:n,children:[V&&t&&(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:d("agents.reloadRequired")}),(0,r.jsx)(sh,{size:"small",onClick:()=>void ek(),disabled:Y||U,children:Y?d("agents.reloading"):d("agents.reloadSession")})]}),(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:d("agents.builtInTitle")}),(0,r.jsx)("span",{children:d("agents.builtInDescription")})]}),(0,r.jsx)("div",{className:"agents-feature-actions",children:(0,r.jsx)(sp,{checked:A,disabled:F||Y,loading:U,label:d("agents.builtInTitle"),onChange:e=>void eb(e)})})]}),(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:d("agents.maxConcurrent")}),(0,r.jsx)("span",{children:d("agents.maxConcurrentDescription")})]}),(0,r.jsx)("input",{"aria-label":d("agents.maxConcurrent"),type:"number",min:1,max:32,value:H,disabled:F||U,onChange:e=>B(Number(e.target.value)),onBlur:()=>void ew(H),style:{...s5,width:76}})]}),(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{children:[(0,r.jsx)(o7,{children:N?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:d("agents.loading")}):et.map(({name:e,top:t,label:n})=>(0,r.jsxs)(se,{active:v===e&&"create"!==j,onClick:()=>er(c,e),children:[(0,r.jsx)(sg,{active:t.enabled}),(0,r.jsx)(st,{className:`is-grow${t.enabled?"":" is-muted"}`,children:n}),(0,r.jsx)("span",{className:"agents-scope-label",children:d(`agents.scope.${t.scope}`)})]},e))}),(0,r.jsx)(sf,{active:"create"===j,onClick:()=>{let e="custom-agent",t=2;for(;et.some(t=>t.name===e);)e=`custom-agent-${t++}`;y(null),k({...s8,name:e,displayName:e}),S("create"),E("project"),P(null)},children:d("agents.new")})]}),(0,r.jsx)(sc,{children:(0,r.jsx)(sn,{className:"is-fill",children:G||"create"===j?(0,r.jsxs)(sn,{children:[(0,r.jsxs)(sr,{children:[(0,r.jsxs)(si,{children:[eh&&(0,r.jsx)("span",{className:`config-scope-tag${"project"===eh?" is-project":""}`,children:d(`agents.scope.${eh}`)}),(0,r.jsx)("span",{title:ef,className:"config-detail-path",children:ep})]}),(0,r.jsxs)(so,{children:[G?.scope==="builtin"&&"view"===j&&(0,r.jsx)(sh,{size:"small",onClick:()=>{ee&&(k(s3(ee)),S("customize"),E("project"),P(null))},disabled:M||$,children:d("agents.customize")}),ee&&!ed&&(0,r.jsx)(sh,{size:"small",onClick:()=>{if(!ee)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,o=2;for(;n.has(i.toLowerCase());)i=`${r}-${o++}`;return i}(ee.name,c);y(null),k({...s3(ee),name:e,displayName:d("agents.copyName",{name:ee.displayName}),enabled:!0}),S("create"),E("project"),P(null)},disabled:M||$,children:d("agents.duplicate")}),!ed&&G&&s7(G.scope)&&!G.disableStub&&(0,r.jsx)(sh,{variant:"danger",size:"small",onClick:()=>void ea(),disabled:M||$,children:Q[0]?d("agents.restore",{scope:d(`agents.scope.${Q[0].scope}`)}):d("agents.delete")}),(l=ed?b.enabled:!!G?.enabled,(0,r.jsx)(sp,{checked:l,disabled:M||$||!ed&&!!G?.configurationError,label:l?d("agents.disable"):d("agents.enable"),onChange:e=>void ey(e)}))]})]}),!ed&&G&&(0,r.jsxs)("div",{className:"agents-source-note",children:[G.disableStub&&(0,r.jsx)("span",{children:d("agents.stubNote")}),"global"===G.scope&&(0,r.jsx)("span",{children:d("agents.globalNote")}),Q.map(t=>(0,r.jsx)("span",{title:t.filePath,children:d("agents.shadows",{scope:d(`agents.scope.${t.scope}`),path:le(t,e)??d("agents.builtinPath")})},t.scope))]}),ed&&(0,r.jsx)(lt,{label:d("agents.saveScope"),children:(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:3,padding:3,border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)"},children:["global","project"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>E(e),disabled:M,style:{height:28,border:"none",borderRadius:4,background:C===e?"var(--bg-selected)":"transparent",color:C===e?"var(--text)":"var(--text-muted)",cursor:M?"default":"pointer",fontSize:11,fontWeight:C===e?600:400},children:d(`agents.scope.${e}`)},e))})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:a?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(lt,{label:d("agents.name"),children:"create"===j?(0,r.jsx)("input",{"aria-label":d("agents.name"),value:b.name,disabled:eu,onChange:e=>ev("name",e.target.value),style:s5}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:b.name})}),(0,r.jsx)(lt,{label:d("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":d("agents.displayName"),value:b.displayName,disabled:eu,onChange:e=>ev("displayName",e.target.value),style:ex})})]}),(0,r.jsx)(lt,{label:d("agents.description"),children:(0,r.jsx)("input",{"aria-label":d("agents.description"),value:b.description,disabled:eu,onChange:e=>ev("description",e.target.value),style:ex})}),(0,r.jsx)(lt,{label:d("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":d("agents.prompt"),value:b.systemPrompt,disabled:eu,onChange:e=>ev("systemPrompt",e.target.value),style:{...ex,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:eu?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(lt,{label:d("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:s2.map(e=>(0,r.jsx)(ln,{label:e,disabled:eu,checked:b.tools.includes(e),onChange:t=>ev("tools",t?[...b.tools,e]:b.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(lt,{label:d("agents.resources"),children:(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(ln,{label:d("agents.loadSkills"),disabled:eu,checked:b.loadSkills,onChange:e=>ev("loadSkills",e)}),(0,r.jsx)(ln,{label:d("agents.loadExtensions"),disabled:eu,checked:b.loadExtensions,onChange:e=>ev("loadExtensions",e)})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:a?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(lt,{label:d("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(td,{options:en,value:em,onChange:(e,t)=>ev("model",`${e}/${t}`),onClear:()=>ev("model",void 0),emptyLabel:f?d("agents.modelsLoading"):d("agents.inherit"),selectedLabel:b.model&&!eg?d("agents.modelUnavailable",{model:b.model}):void 0,disabled:eu||f||0===h.length&&!b.model,ariaLabel:d("agents.model"),variant:"field",placement:"auto"}),m&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:m})]})}),(0,r.jsx)(lt,{label:d("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":d("agents.thinking"),value:b.thinking??"",disabled:eu,onChange:e=>ev("thinking",e.target.value||void 0),style:ex,children:s4.map(e=>(0,r.jsx)("option",{value:e,children:e||d("agents.inherit")},e||"default"))})}),(0,r.jsx)(lt,{label:d("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":d("agents.maxTurns"),type:"number",min:1,value:b.maxTurns??"",disabled:eu,onChange:e=>ev("maxTurns",e.target.value?Number(e.target.value):void 0),style:ex})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(ln,{label:d("agents.inheritContext"),disabled:eu,checked:b.inheritContext,onChange:e=>ev("inheritContext",e)}),(0,r.jsx)(ln,{label:d("agents.background"),disabled:eu,checked:b.runInBackground,onChange:e=>ev("runInBackground",e)})]})]}):(0,r.jsx)(sd,{children:d("agents.empty")})})})]}),(0,r.jsx)(su,{status:(q||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:q||z}),children:ec&&(0,r.jsxs)(sh,{variant:"primary",onClick:()=>void el(),disabled:M||L||$||!b.name.trim(),className:L?"is-success":void 0,children:[L&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:L?d("i18n.saved"):M?d("agents.saving"):d("agents.save")})]})})]})}function li(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lo(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function ls(e){return`${e.scope}\0${e.source}`}function ll(e){return`extension\0${e.path}`}function la(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function ld({pkg:e}){let{t}=(0,w.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function lc({scope:e}){return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function lu({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,w.s)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(o=>{let s=e===o,l="project"===o&&!t;return(0,r.jsx)("button",{onClick:()=>{l||n(o)},disabled:l,title:l?i("trust.projectScopeUnavailable"):void 0,style:{width:76,border:"none",borderRight:"global"===o?"1px solid var(--border)":"none",background:s?"var(--bg-selected)":"none",color:s?"var(--text)":"var(--text-muted)",cursor:l?"not-allowed":"pointer",opacity:l?.45:1,fontSize:12},children:o},o)})})}function lh({cwd:e,source:t,scope:n,projectResourcesLoaded:o,busy:s,actionError:l,onSourceChange:a,onScopeChange:d,onInstall:c}){let{t:u}=(0,w.s)(),h=(0,i.useRef)(null);return(0,i.useEffect)(()=>{h.current?.focus()},[]),(0,r.jsxs)(sn,{className:"is-fill",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)(ss,{children:u("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://pi.dev/packages",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"pi.dev/packages"]})]}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===n?`${li(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsx)(sa,{label:"Source",children:(0,r.jsx)("input",{id:"plugin-source",ref:h,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=lo(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(lo(e.currentTarget.value)),placeholder:"npm:@scope/package",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!s&&c()}})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(lu,{value:n,projectResourcesLoaded:o,onChange:d}),(0,r.jsx)(sh,{variant:"primary",onClick:c,disabled:s||!t.trim(),className:"is-pushed-right",children:u(s?"i18n.installing":"i18n.install")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>a(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:l})]})}function lp({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:o,sessionId:s,updateStatus:l,checkingUpdate:a,updateError:d,onAction:c,onCheckUpdate:u,onReloadSession:h}){let p,{t:f}=(0,w.s)(),g=ls(e),m=n?.endsWith(g)??!1,x="reload"===n,v=!e.disabled,y=e.canCheckForUpdates,b=l?.state==="update-available";return(0,r.jsxs)(sn,{children:[(0,r.jsxs)(sr,{className:"is-top-aligned",children:[(0,r.jsxs)(si,{children:[(0,r.jsx)(lc,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:f("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:f("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)(so,{children:[(0,r.jsx)(sh,{size:"small",variant:b?"primary":void 0,onClick:b||!y?()=>c("update",e):u,disabled:m||x||a,title:b?f("i18n.updateAvailable"):void 0,children:f(n===`update:${g}`?"i18n.updating":a?"i18n.checking":b||!y?"i18n.update":"i18n.check")}),(0,r.jsx)(sh,{size:"small",onClick:h,disabled:!s||x||m,title:f(s?"i18n.reloadSession":"i18n.openSessionToReload"),children:f(x?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(sh,{variant:"danger",size:"small",onClick:()=>c("remove",e),disabled:m||x,children:f(n===`remove:${g}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(sp,{checked:v,loading:m||x,onChange:()=>c(e.disabled?"enable":"disable",e),label:f(e.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.status")}),(0,r.jsx)("div",{style:{color:la(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.version")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(p=[],e.version&&p.push(f("i18n.installedVersion",{version:e.version})),e.configuredVersion&&p.push(f("i18n.configuredVersion",{version:e.configuredVersion})),p.length?p.join(" \xb7 "):f("i18n.unknown"))}),b&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:l.displayName,children:f("i18n.updateAvailable")}),y&&(a||l&&!b)&&(0,r.jsx)("span",{className:`skill-update-status ${a?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:a?f("i18n.checking"):l?.state==="up-to-date"?f("i18n.upToDate"):l?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):l?.message||f("i18n.checkFailed")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??f("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(e,f)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?li(e.installedPath):f("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:li(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(sl,{children:f("i18n.resolvedResources")}),(0,r.jsx)(ld,{pkg:e})]}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:o}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function lf({extension:e}){let{t}=(0,w.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsxs)(sn,{children:[(0,r.jsx)(sr,{children:(0,r.jsxs)(si,{children:[(0,r.jsx)(lc,{scope:e.scope}),(0,r.jsx)(ss,{children:e.name})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:t("i18n.status")}),(0,r.jsx)("div",{style:{color:e.enabled?"var(--accent)":"var(--text-dim)"},children:n}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:t("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:li(e.path)})]})]})}function lg({cwd:e,sessionId:t,onClose:n,onReloaded:o,embedded:s=!1}){let{t:l}=(0,w.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(()=>o_("plugins",e)),[m,x]=(0,i.useState)(!1),[v,y]=(0,i.useState)(""),[b,k]=(0,i.useState)("global"),[j,S]=(0,i.useState)(null),[C,E]=(0,i.useState)(null),[N,I]=(0,i.useState)(null),[M,T]=(0,i.useState)({}),[L,R]=(0,i.useState)(new Set),[$,W]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[A,D]=(0,i.useState)(!1),H=(0,i.useMemo)(()=>a?.packages??[],[a?.packages]),B=(0,i.useMemo)(()=>a?.standaloneExtensions??[],[a?.standaloneExtensions]),F=H.find(e=>ls(e)===f)??null,O=B.find(e=>ll(e)===f)??null,U=a?.projectResourcesLoaded??!0,_=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:H.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[H]),q=(0,i.useCallback)(async()=>{u(!0),p(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);d(n),x(e=>0===n.packages.length&&0===n.standaloneExtensions.length||e),g(e=>e&&(n.packages.some(t=>ls(t)===e)||n.standaloneExtensions.some(t=>ll(t)===e))?e:n.packages[0]?ls(n.packages[0]):n.standaloneExtensions[0]?ll(n.standaloneExtensions[0]):null)}catch(e){p(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{T({}),P(null),q()},[e]),(0,i.useEffect)(()=>{f&&oq("plugins",f,e)},[e,f]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:H.filter(e=>e.canCheckForUpdates)).map(ls);if(0!==n.length){P(null),R(e=>new Set([...e,...n])),t||W(!0);try{let n=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,source:t?.source,scope:t?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);T(e=>{let t={...e};for(let e of r.updates??[])t[ls(e)]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{R(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||W(!1)}}},[e,H]),V=(0,i.useCallback)(async()=>{D(!0),E(null),I(null),P(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);d(r),T({}),I(l("i18n.packagesUpdated")),t&&I(`${l("i18n.packagesUpdated")} ${l("agents.reloadRequired")}`)}catch(e){E(e instanceof Error?e.message:String(e))}finally{D(!1)}},[e,t,l]),J=(0,i.useCallback)(async(t,n)=>{let r=ls(n);S(`${t}:${r}`),E(null),I(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),o=await i.json();if(!i.ok||o.error)throw Error(o.error??`HTTP ${i.status}`);d(o),"remove"===t?(g(o.packages[0]?ls(o.packages[0]):o.standaloneExtensions[0]?ll(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&x(!0),I("Package removed."),T(e=>{let t={...e};return delete t[r],t})):(I({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&T(e=>{let t={...e};return delete t[r],t}))}catch(e){E(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=lo(v).trim();if(!t)return;y(t);let n=`${b}\0${t}`;S(`install:${n}`),E(null),I(null);try{var r;let i,o,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:b,cwd:e})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);d(l);let a=(r=l.packages,o=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===b&&e.source===i)??r.find(e=>e.scope===b&&e.source===`npm:${o}`)??r.find(e=>e.scope===b&&e.source.endsWith(i)));g(a?ls(a):n),x(!1),y(""),I("Package installed.")}catch(e){E(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,b,v]),Z=(0,i.useCallback)(async()=>{if(t){S("reload"),E(null),I(null);try{await r7(t,{type:"reload"}),o?.(),await q(),I("Session reloaded.")}catch(e){E(e instanceof Error?e.message:String(e))}finally{S(null)}}},[q,o,t]),X=j?.startsWith("install:")??!1,G=Object.values(M).filter(e=>"update-available"===e.state).length,Q=H.some(e=>e.canCheckForUpdates),ee=c||null!==j||L.size>0||A;return(0,r.jsxs)(o5,{embedded:s,title:l("common.plugins"),subtitle:li(e),closeLabel:l("i18n.close"),onClose:n,children:[!U&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:l("trust.pluginsNotLoaded")}),(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{children:[(0,r.jsx)(o7,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:"Loading..."}):h?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:h}):0===H.length&&0===B.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:"No plugins configured"}):(0,r.jsxs)(r.Fragment,{children:[B.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o9,{children:l("i18n.extensions")}),B.map(e=>{let t=ll(e);return(0,r.jsxs)(se,{active:!m&&f===t,title:e.path,onClick:()=>{g(t),x(!1),E(null),I(null)},children:[(0,r.jsx)(sg,{active:e.enabled}),(0,r.jsx)(st,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),_.map(e=>(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o9,{children:e.scope}),e.packages.map(e=>{let t=ls(e),n=!m&&f===t;return(0,r.jsxs)(se,{active:n,onClick:()=>{g(t),x(!1),E(null),I(null)},children:[(0,r.jsx)(sg,{active:!e.disabled,color:la(e.status)}),(0,r.jsx)(st,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),M[ls(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:l("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope))]})}),(0,r.jsx)(sf,{active:m,onClick:()=>{x(!0),E(null),I(null)},children:l("i18n.addPlugin")})]}),(0,r.jsx)(sc,{children:(0,r.jsx)(sn,{className:"is-fill",children:m?(0,r.jsx)(lh,{cwd:e,source:v,scope:b,projectResourcesLoaded:U,busy:X,actionError:C,onSourceChange:y,onScopeChange:k,onInstall:Y}):c?null:O?(0,r.jsx)(lf,{extension:O}):F?(0,r.jsx)(lp,{pkg:F,cwd:e,busyKey:j,actionError:C,actionMessage:N,sessionId:t,updateStatus:M[ls(F)],checkingUpdate:L.has(ls(F)),updateError:z,onAction:J,onCheckUpdate:()=>void K(F),onReloadSession:Z},ls(F)):(0,r.jsx)(sd,{children:l("i18n.selectPackage")})})})]}),(0,r.jsxs)(su,{status:G>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[G," ",1===G?l("i18n.update"):l("i18n.updates")]}):a?.diagnostics.length?(0,r.jsxs)("span",{title:a.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:a.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[a.diagnostics.length," diagnostic",1===a.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:a?`${a.totals.extensions} ext \xb7 ${a.totals.skills} skills \xb7 ${a.totals.prompts} prompts \xb7 ${a.totals.themes} themes`:""}),children:[!s&&(0,r.jsx)(sh,{onClick:n,children:l("i18n.close")}),Q&&(0,r.jsx)(sh,{variant:G>0?"primary":"secondary",onClick:()=>void(G>0?V():K()),disabled:ee,title:G>0?l("i18n.updateAllPluginsHint"):void 0,children:A?l("i18n.updating"):$?l("i18n.checking"):G>0?`${l("i18n.updateAllPlugins")} (${G})`:l("i18n.checkUpdates")}),(0,r.jsx)(sh,{variant:"secondary",onClick:()=>void q(),disabled:ee,children:l("i18n.refresh")})]})]})}let lm=new Set(["openai-codex","antigravity","xai"]);function lx({sessionId:e=null,onReloaded:t}){let{t:n}=(0,w.s)(),[o,s]=(0,i.useState)(null),[l,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=new AbortController;return a(!0),m(null),(async()=>{try{let t=await fetch("/api/image-generation/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled||!Array.isArray(n.connections))throw Error(n.error??`HTTP ${t.status}`);let r=lv(n);s(r)}catch(e){e instanceof DOMException&&"AbortError"===e.name||m(e instanceof Error?e.message:String(e))}finally{e.signal.aborted||a(!1)}})(),()=>e.abort()},[]);let k=async t=>{let n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled||!Array.isArray(n.connections))throw Error(n.error??`HTTP ${t.status}`);s(lv(n)),f(!!e)},j=async e=>{c(!0),m(null);try{let t=await fetch("/api/image-generation/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});await k(t)}catch(e){m(e instanceof Error?e.message:String(e))}finally{c(!1)}},S=async()=>{if(!y||!y.label.trim())return void b(null);c(!0),m(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:y.id,label:y.label.trim()})});await k(e),b(null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{c(!1)}},C=async()=>{if(x){c(!0),m(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"edit"===x.mode?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify("edit"===x.mode?{id:x.id,label:x.label,provider:x.provider,model:x.model}:{label:x.label,provider:x.provider,model:x.model})});await k(e),v(null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{c(!1)}}},E=async e=>{if(window.confirm(n("agents.deleteConfirm",{name:e.label}))){c(!0),m(null);try{let t=await fetch("/api/image-generation/settings/connections",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e.id})});await k(t),x?.mode==="edit"&&x.id===e.id&&v(null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{c(!1)}}},N=async()=>{if(e){h(!0),m(null);try{await r7(e,{type:"reload"}),f(!1),t?.()}catch(e){m(e instanceof Error?e.message:String(e))}finally{h(!1)}}},I=o?.connections.filter(e=>"custom"!==e.kind)??[],M=o?.connections.filter(e=>"custom"===e.kind)??[],T=o?.providers??[];return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsx)("h2",{className:"settings-general-title",children:n("settings.images")}),(0,r.jsxs)("div",{className:"settings-card-grid",children:[(0,r.jsxs)("section",{className:"settings-card settings-card-wide",children:[(0,r.jsxs)("div",{className:"settings-row",title:n("settings.imagesDescription"),children:[(0,r.jsx)("span",{children:n("settings.imagesEnabled")}),(0,r.jsxs)("div",{className:"settings-image-actions",children:[p&&e&&(0,r.jsx)(sh,{size:"small",onClick:()=>void N(),disabled:u||d,children:u?n("agents.reloading"):n("agents.reloadSession")}),(0,r.jsx)(sp,{checked:o?.enabled===!0,disabled:l||u||!o,loading:d&&!x&&!y,label:n("settings.imagesEnabled"),onChange:e=>void j({enabled:e})})]})]}),o?.enabled&&(0,r.jsx)(r.Fragment,{children:o.connections.some(e=>e.enabled)&&(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("span",{children:n("settings.imagesDefault")}),(0,r.jsx)("select",{className:"settings-select",value:o.defaultConnection,disabled:l||d||u,onChange:e=>void j({default:e.target.value}),children:o.connections.filter(e=>e.enabled).map(e=>(0,r.jsxs)("option",{value:e.id,disabled:!e.signedIn,children:[e.label,e.signedIn?"":` (${n("settings.imagesSignedOut")})`]},e.id))})]})}),p&&(0,r.jsx)("p",{role:"status",className:"settings-image-reload-notice",children:n("agents.reloadRequired")}),g&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:g})]}),o?.enabled&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"settings-card",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:n("settings.imagesBuiltin")}),I.map(e=>(0,r.jsx)(ly,{connection:e,disabled:l||u||d,unsignedLabel:n("settings.imagesSignedOut"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),renaming:y?.id===e.id,renameValue:y?.id===e.id?y.label:e.label,onRenameChange:t=>b({id:e.id,label:t}),onRenameSubmit:()=>void S(),onRenameCancel:()=>b(null),onEdit:()=>{v(null),b({id:e.id,label:e.label})},editLabel:n("i18n.rename")},e.id))]}),(0,r.jsxs)("section",{className:"settings-card",children:[(0,r.jsxs)("div",{className:"settings-image-group-row",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:n("settings.imagesCustom")}),T.length>0&&!x&&(0,r.jsx)(sh,{size:"small",disabled:l||u||d,onClick:()=>{b(null),v({mode:"create",label:"",provider:T.find(e=>!lm.has(e.id))?.id??T[0]?.id??"",model:""})},children:n("settings.imagesAddConnection")})]}),0===T.length&&(0,r.jsx)("p",{className:"settings-general-description",children:n("settings.imagesNoProviders")}),M.map(e=>(0,r.jsx)(ly,{connection:e,disabled:l||u||d,unsignedLabel:n("settings.imagesNotConfigured"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),onEdit:()=>{b(null),v({mode:"edit",id:e.id,label:e.label,provider:e.provider,model:e.model})},onDelete:()=>void E(e),editLabel:n("image.edit"),deleteLabel:n("agents.delete")},e.id)),x&&(0,r.jsxs)("form",{className:"settings-image-form",onSubmit:e=>{e.preventDefault(),C()},children:[(0,r.jsxs)("label",{className:"settings-image-field",children:[(0,r.jsx)("span",{children:n("settings.imagesLabel")}),(0,r.jsx)("input",{value:x.label,onChange:e=>v({...x,label:e.target.value}),required:!0})]}),(0,r.jsxs)("label",{className:"settings-image-field",children:[(0,r.jsx)("span",{children:n("settings.imagesProvider")}),(0,r.jsx)("select",{value:x.provider,onChange:e=>v({...x,provider:e.target.value}),required:!0,children:T.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name===e.id?e.id:`${e.name} (${e.id})`},e.id))})]}),(0,r.jsxs)("label",{className:"settings-image-field",children:[(0,r.jsx)("span",{children:n("settings.imagesModel")}),(0,r.jsx)(lw,{value:x.model,t:n,onChange:e=>{let t=ef.find(t=>t.model===e);v({...x,model:e,..."create"===x.mode&&!x.label.trim()&&t?{label:t.label}:{}})}},"edit"===x.mode?x.id:"create")]}),(0,r.jsxs)("div",{className:"settings-image-form-actions",children:[(0,r.jsx)(sh,{type:"submit",variant:"primary",size:"small",disabled:d||!x.label.trim()||!x.provider||!x.model.trim(),children:d?n("agents.saving"):n("agents.save")}),(0,r.jsx)(sh,{type:"button",size:"small",disabled:d,onClick:()=>v(null),children:n("trust.cancel")})]})]})]})]})]})]})}function lv(e){return{enabled:!0===e.enabled,defaultConnection:e.defaultConnection??"",connections:(e.connections??[]).map(e=>({...e,model:e.model??"",kind:"custom"===e.kind?"custom":"builtin"})),providers:(e.providers??[]).filter(e=>!!(e&&"string"==typeof e.id&&e.id))}}function ly({connection:e,disabled:t,unsignedLabel:n,onChange:o,onEdit:s,onDelete:l,editLabel:a,deleteLabel:d,renaming:c=!1,renameValue:u,onRenameChange:h,onRenameSubmit:p,onRenameCancel:f}){let g=(0,i.useRef)(!1),m=!e.signedIn&&!e.enabled;return(0,r.jsxs)("div",{className:`settings-image-connection${e.signedIn?"":" is-unsigned"}`,children:[(0,r.jsxs)("div",{className:"settings-image-connection-copy",children:[c?(0,r.jsx)("input",{className:"settings-image-rename",value:u,autoFocus:!0,"aria-label":a,onChange:e=>h?.(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),g.current=!0,p?.()),"Escape"===e.key&&(e.preventDefault(),g.current=!0,f?.())},onBlur:()=>{if(g.current){g.current=!1;return}p?.()}}):(0,r.jsx)("strong",{children:e.label}),e.signedIn?null:(0,r.jsx)("span",{children:n})]}),(0,r.jsxs)("div",{className:"settings-image-actions",children:[s&&!c?(0,r.jsx)(sh,{size:"small",disabled:t,onClick:s,children:a}):null,l?(0,r.jsx)(sh,{size:"small",disabled:t,onClick:l,children:d}):null,(0,r.jsx)(sp,{checked:e.enabled,disabled:t||m,label:e.label,onChange:o})]})]})}let lb="__other__";function lw({value:e,onChange:t,t:n}){let o=ef.some(t=>t.model===e),[s,l]=(0,i.useState)(!o),a=s||!o?lb:e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("select",{value:a,onChange:e=>{let n=e.target.value;n===lb?l(!0):(l(!1),t(n))},children:[ef.map(e=>(0,r.jsxs)("option",{value:e.model,children:[e.label," \xb7 ",e.model]},e.model)),(0,r.jsx)("option",{value:lb,children:n("settings.imagesOtherModel")})]}),a===lb?(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),required:!0}):null]})}let lk=null;async function lj(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(lk)return lk;let t=(async()=>{try{let t=await fetch("/api/push/config");if(!t.ok)return!1;let{publicKey:n}=await t.json();if(!n)return!1;let r=await navigator.serviceWorker.ready,i=await r.pushManager.getSubscription();return i||(i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}(n)})),(await fetch("/api/push/subscribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({subscription:i.toJSON(),locale:e})})).ok}catch{return lk=null,!1}})();return lk=t,t.then(e=>{e||lk!==t||(lk=null)}),t}let lS="pi-web-sarasa-enabled";async function lC(){let e=await fetch("/fonts/SarasaTermSC-Regular.woff2?v=1",{cache:"force-cache"});if(!e.ok)throw Error(`HTTP ${e.status}`);document.documentElement.classList.add("sarasa-term-webfont"),localStorage.setItem(lS,"1"),await document.fonts.load('14px "Sarasa Term SC Web"')}function lE({section:e,size:t=16,strokeWidth:n=1.8}){let i={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"images"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"10.5",r:"1.5"}),(0,r.jsx)("path",{d:"m21 16-5-4-4 3-3-2-5 4"})]}):"skills"===e?(0,r.jsx)("svg",{...i,children:(0,r.jsx)("path",{d:"m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3L12 3Z"})}):"agents"===e?(0,r.jsx)(X,{size:t,strokeWidth:n,className:"settings-section-icon is-agent"}):(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"m16.5 9.4-9-5.19M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"}),(0,r.jsx)("polyline",{points:"3.27 6.96 12 12.01 20.73 6.96"}),(0,r.jsx)("line",{x1:"12",y1:"22.08",x2:"12",y2:"12"})]})}function lN({preference:e}){return"light"===e?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",className:"settings-theme-icon",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.42-1.41M17.66 6.34l1.41-1.41"})]}):"dark"===e?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-theme-icon",children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-theme-icon",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}function lI({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:o}){let{locale:s,setLocale:l,supportedLocales:a,t:d}=(0,w.s)(),{preference:c,setThemePreference:u}=n2(),{width:h,setWidth:p,fontSize:f,setFontSize:g}=tn(),[m,b]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(null),[E,N]=(0,i.useState)(!1),[I,M]=(0,i.useState)(!0),[T,L]=(0,i.useState)(!1),[R,$]=(0,i.useState)(!1),[W,z]=(0,i.useState)(null),[P,A]=(0,i.useState)(!1),[D,H]=(0,i.useState)(null),[B,F]=(0,i.useState)(!1),[O,U]=(0,i.useState)(!1),[_,q]=(0,i.useState)(""),[K,V]=(0,i.useState)("available"),[J,Y]=(0,i.useState)(null);(0,i.useEffect)(()=>{N(rs()),M(oV()),L(y()),$(ts())},[]),(0,i.useEffect)(()=>{fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>F(e?.enabled===!0)).catch(()=>{})},[]),(0,i.useEffect)(()=>r1(z),[]);let Z=[{id:"light",label:d("settings.themeLight")},{id:"dark",label:d("settings.themeDark")},{id:"auto",label:d("settings.themeSystem")}];(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||b(n)}).catch(t=>{e||C(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let X=async n=>{j(!0),C(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);b(i),e&&(await r7(e,{type:"reload"}),t())}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},G=async()=>{if(!P){A(!0),H(null);try{if(!("Notification"in window))throw Error("unsupported or not permitted");let e="default"===Notification.permission?await Notification.requestPermission():Notification.permission;if("granted"!==e||!await lj(s))throw Error("unsupported or not permitted");H({kind:"ok",message:d("settings.pushRegistered")})}catch(e){H({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{A(!1)}}};(0,i.useEffect)(()=>{V("1"===localStorage.getItem(lS)?"cached":"available")},[]);let Q=async()=>{V("loading"),Y(null);try{await lC(),V("cached")}catch(e){V("error"),Y(e instanceof Error?e.message:String(e))}},ee=async()=>{U(!0),q("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{q(d("auth.logoutFailed"))}finally{U(!1)}},et=(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})}),en=(e,t,n)=>(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("span",{children:e}),(0,r.jsx)(sp,{checked:t,label:e,onChange:n})]});return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsx)("h2",{className:"settings-general-title",children:d("settings.general")}),(0,r.jsxs)("div",{className:"settings-card-grid",children:[(0,r.jsxs)("section",{className:"settings-general-section settings-card",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("span",{children:d("settings.theme")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:Z.map(e=>(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":c===e.id,onClick:()=>u(e.id),className:"settings-theme-option",children:[(0,r.jsx)(lN,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",children:e.label})]},e.id))})]}),(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("span",{children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-theme-options",children:a.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":s===e.id,onClick:()=>l(e.id),className:"settings-theme-option",children:(0,r.jsx)("span",{className:"settings-theme-option-label",children:e.label})},e.id))})]}),(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("span",{children:d("settings.typography")}),"cached"===K?(0,r.jsx)("span",{role:"status",className:"settings-chat-status",children:d("settings.fontCached")}):(0,r.jsx)(sh,{size:"small",variant:"secondary",disabled:"loading"===K,onClick:()=>void Q(),children:"loading"===K?d("settings.fontDownloadLoading"):d("settings.fontDownload")})]}),"error"===K&&(0,r.jsxs)("p",{role:"alert",className:"settings-general-error",children:[d("settings.fontDownloadFailed")," ",J]}),(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:d("settings.chatContentWidth")}),(0,r.jsxs)("div",{className:"settings-range",children:[(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:h,onChange:e=>p(Number(e.target.value))}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(sh,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>p(820),children:et})]})]}),(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:d("settings.chatContentFontSize")}),(0,r.jsxs)("div",{className:"settings-range",children:[(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:f,onChange:e=>g(Number(e.target.value))}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[f,"px"]}),(0,r.jsx)(sh,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("settings.resetChatContentFontSize"),disabled:14===f,onClick:()=>g(14),children:et})]})]}),en(d("settings.thinkingExpandedDefault"),E,e=>{window.localStorage.setItem(ri,String(e)),window.dispatchEvent(new Event(ro)),N(e)})]}),(0,r.jsxs)("div",{className:"settings-card-stack",children:[(0,r.jsxs)("section",{className:"settings-general-section settings-card",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.chat")}),en(d("settings.shiftEnterToSend"),R,e=>{window.localStorage.setItem(to,String(e)),$(e)}),en(d("settings.autoSessionTitle"),I,e=>{window.localStorage.setItem(oK,String(e)),M(e)}),en(d("settings.quoteSelection"),n,o),en(d("settings.sidebarSingleProject"),T,e=>{window.localStorage.setItem(x,String(e)),window.dispatchEvent(new Event(v)),L(e)}),m?.isWindows&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"settings-row",title:d("settings.shellToolDescription"),children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(sp,{checked:m.powerShellEnabled,loading:k,label:d("settings.usePowerShell"),onChange:e=>void X(e)})]}),S&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:S})]})]}),(0,r.jsxs)("section",{className:"settings-general-section settings-card",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.notifications")}),W&&(0,r.jsxs)("div",{className:"settings-row",children:[(0,r.jsx)("span",{children:d("settings.browserNotifications")}),"granted"===W?(0,r.jsx)("span",{className:"settings-chat-status",children:d("settings.browserNotificationsOn")}):"denied"===W?(0,r.jsx)("span",{className:"settings-chat-status",children:d("settings.browserNotificationsBlocked")}):(0,r.jsx)(sh,{size:"small",onClick:()=>void Notification.requestPermission().then(z),children:d("settings.browserNotificationsEnable")})]}),(0,r.jsxs)("div",{className:"settings-row",title:d("settings.pushPermissionDescription"),children:[(0,r.jsx)("span",{children:d("settings.pushPermission")}),(0,r.jsx)(sh,{size:"small",variant:"secondary",disabled:P,onClick:()=>void G(),children:P?d("settings.pushRegisterLoading"):d("settings.pushRegister")})]}),D&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===D.kind?{color:"var(--accent)"}:void 0,children:D.message})]})]})]}),(0,r.jsxs)("section",{className:"settings-general-footer",children:[(0,r.jsx)(iL,{showCurrentVersion:!0}),B&&(0,r.jsx)("div",{children:(0,r.jsx)(sh,{variant:"secondary",size:"small",disabled:O,onClick:()=>void ee(),children:O?d("auth.loggingOut"):d("auth.logOut")})}),_&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:_})]})]})}function lM({cwd:e,sessionId:t,initialSection:n,onClose:o,onSessionReloaded:s,onModelsChanged:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d}){let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(n),[p,f]=(0,i.useState)(()=>new Set([u])),g=[{id:"general",label:c("settings.general"),requiresProject:!1},{id:"models",label:c("common.models"),requiresProject:!1},{id:"agents",label:c("common.agents"),requiresProject:!0},{id:"images",label:c("settings.images"),requiresProject:!1},{id:"skills",label:c("common.skills"),requiresProject:!0},{id:"plugins",label:c("common.plugins"),requiresProject:!0}],m=(0,i.useRef)(!1),x=(0,i.useCallback)(e=>{m.current=e},[]),v=(0,i.useCallback)(()=>{(!m.current||window.confirm(c("models.discardConfirm")))&&o()},[o,c]);(0,i.useEffect)(()=>oU(n),[n]),(0,i.useEffect)(()=>{let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),v())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[v]),(0,i.useEffect)(()=>{e||"skills"!==u&&"agents"!==u&&"plugins"!==u||(h("general"),f(e=>new Set(e).add("general")),oU("general"))},[e,u]);let y=e=>{f(t=>new Set(t).add(e)),h(e),oU(e)},b=(e,t)=>p.has(e)?(0,r.jsx)("div",{hidden:u!==e,className:"settings-section-host",children:t},e):null;return(0,r.jsx)("div",{role:"dialog","aria-modal":"true","aria-label":c("settings.title"),onClick:e=>{e.target===e.currentTarget&&v()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:c("settings.title")}),(0,r.jsx)("select",{"aria-label":c("settings.title"),value:u,onChange:e=>y(e.target.value),className:"settings-mobile-section-picker",children:g.map(t=>(0,r.jsx)("option",{value:t.id,disabled:t.requiresProject&&!e,children:t.label},t.id))}),(0,r.jsx)("nav",{"aria-label":c("settings.title"),className:"settings-section-tabs",children:g.map(t=>{let n=u===t.id,i=t.requiresProject&&!e;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?c("settings.projectRequired"):t.label,"aria-current":n?"page":void 0,onClick:()=>y(t.id),children:[(0,r.jsx)(lE,{section:t.id}),(0,r.jsx)("span",{children:t.label})]},t.id)})}),(0,r.jsx)("button",{type:"button",onClick:v,title:c("i18n.close"),"aria-label":c("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[b("general",(0,r.jsx)(lI,{sessionId:t,onSessionReloaded:s,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),b("models",(0,r.jsx)(sq,{embedded:!0,onClose:v,cwd:e,onModelsChanged:l,onDirtyChange:x})),e&&b("agents",(0,r.jsx)(lr,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:s},e)),b("images",(0,r.jsx)(lx,{sessionId:t,onReloaded:s})),e&&b("skills",(0,r.jsx)(sQ,{embedded:!0,cwd:e,onClose:o},e)),e&&b("plugins",(0,r.jsx)(lg,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:s},e))]})]})})}function lT({cwd:e,busy:t,error:n,onCancel:o,onConfirm:s}){let{t:l}=(0,w.s)(),a=(0,i.useRef)(null),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;return d.current?.focus(),()=>{e?.isConnected?e.focus():document.querySelector('[data-dialog-focus-fallback="true"]')?.focus()}},[]),(0,i.useEffect)(()=>{t&&a.current?.focus()},[t]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||o()},children:(0,r.jsxs)("div",{ref:a,role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title",tabIndex:-1,onKeyDown:e=>{if("Escape"===e.key&&!t){e.preventDefault(),o();return}if("Tab"!==e.key)return;let n=Array.from(a.current?.querySelectorAll("button:not(:disabled)")??[]);if(0===n.length){e.preventDefault(),a.current?.focus();return}let r=n[0],i=n[n.length-1];e.shiftKey&&(document.activeElement===r||document.activeElement===a.current)?(e.preventDefault(),i.focus()):e.shiftKey||document.activeElement!==i||(e.preventDefault(),r.focus())},style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:l("trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),n&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:n})]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:d,type:"button",onClick:o,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:l("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:s,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--accent)",borderRadius:5,background:"var(--accent)",color:"white",cursor:t?"wait":"pointer",opacity:t?.7:1,fontSize:12,fontWeight:600},children:l(t?"trust.trusting":"trust.trustProject")})]})]})})}function lL(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function lR(e){let t=e,n=t.branchPreview,r=lL(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&lL(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function l$(e){if(e.length>1)return!0;let t=[...e];for(;t.length>0;){let e=t.pop();if(e.children.length>1)return!0;for(let n of e.children)t.push(n)}return!1}function lW({node:e,activePathIds:t,depth:n,isLast:i,parentLines:o,onSelect:s}){let{node:l,skipped:a,branchPreview:d,labelEntry:c}=lR(e),u=t.has(l.entry.id),h=t.has(e.entry.id)||t.has(l.entry.id),p=d?.text??function(e){if("message"===e.type&&lL(e)){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(c),f=d?d.role??null:lL(c)?c.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>s(l.entry.id),children:[o.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":h?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),f&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===f?"var(--accent)":"var(--text-dim)",background:"user"===f?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===f?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===f?"U":"A"}),a>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",a]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:p})]}),l.children.map((e,a)=>(0,r.jsx)(lW,{node:e,activePathIds:t,depth:n+1,isLast:a===l.children.length-1,parentLines:[...o,!i],onSelect:s},e.entry.id))]})}function lz({tree:e,activeLeafId:t,onLeafChange:n,inline:o,containerRef:s,open:l,onToggle:a,hasSession:d,compact:c,hideInlineButton:u,disabled:h=!1}){let{t:p}=(0,w.s)(),[f,g]=(0,i.useState)(!1),m=void 0!==l?l:f,x=(0,i.useRef)(null),[v,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!m||!o)return;let e=s?.current??x.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[m,o,s]);let b=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(e,t),[e,t]),k=(0,i.useCallback)(e=>{n(e)},[n]),j=d?l$(e)?null:p("i18n.noBranches"):p("i18n.noActiveSession"),S=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=lR(e[0]).node;return t.children.length>1?t.children:[]}(e),C=!j&&S.length>0,E=h||!C,N=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:E?"var(--text-dim)":"var(--accent)",flexShrink:0,display:"block",transform:"translateY(0.5px)"},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:m?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return o?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{className:"workspace-header-action",ref:x,disabled:E,onClick:()=>{E||(a?a():g(e=>!e))},style:{display:u?"none":"flex",alignItems:"center",justifyContent:c?"center":void 0,gap:6*!c,height:"100%",width:c?30:void 0,padding:c?0:"0 12px",background:m?"var(--bg-selected)":"none",border:"none",cursor:E?"not-allowed":"pointer",color:E?"var(--text-dim)":m?"var(--text)":"var(--text-muted)",opacity:E?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{E||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{E||(e.currentTarget.style.color=m?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=m?"var(--bg-selected)":"none")},title:E?p("i18n.noBranches",{defaultValue:"没有分支"}):p("i18n.branches"),"aria-label":p("i18n.branches"),"aria-pressed":m,children:[N,!c&&(0,r.jsx)("span",{style:{lineHeight:1},children:p("i18n.branches")})]}),m&&v&&(0,r.jsx)("div",{style:{position:"fixed",top:v.top,left:v.left,width:v.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:C?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:S.map((e,t)=>(0,r.jsx)(lW,{node:e,activePathIds:b,depth:0,isLast:t===S.length-1,parentLines:[],onSelect:k},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:j})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[N,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:p("i18n.branches")}),I]}),m&&(0,r.jsx)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:C?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:S.map((e,t)=>(0,r.jsx)(lW,{node:e,activePathIds:b,depth:0,isLast:t===S.length-1,parentLines:[],onSelect:k},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:j??p("i18n.noBranches")})})]})}function lP({mobile:e,disabled:t,menuOpen:n,exporting:o=!1,error:s,labels:l,onViewFullHistory:a,onExportMarkdown:d,onMenuOpenChange:c}){let u=(0,i.useRef)(null),[h,p]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!n)return void p(null);let e=()=>{let e=u.current?.getBoundingClientRect();e&&p({top:e.bottom,left:e.left})};e();let t=e=>{u.current?.contains(e.target)||c(!1)},r=e=>{"Escape"===e.key&&c(!1)};return window.addEventListener("resize",e),document.addEventListener("pointerdown",t,!0),document.addEventListener("keydown",r,!0),()=>{window.removeEventListener("resize",e),document.removeEventListener("pointerdown",t,!0),document.removeEventListener("keydown",r,!0)}},[n,c]);let f=t?"var(--text-dim)":"var(--text-muted)",g=(e,n)=>{t||(e.currentTarget.style.color=n?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=n?"var(--bg-hover)":"none")};return(0,r.jsxs)("div",{ref:u,style:{display:"flex",alignItems:"stretch",height:"100%",position:"relative"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{t||c(!n)},disabled:t,title:t?l.unsaved:l.menu,"aria-label":l.menu,"aria-haspopup":"menu","aria-expanded":n,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":f,cursor:t?"not-allowed":"pointer",opacity:t?.45:1,flexShrink:0,transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>g(e,!0),onMouseLeave:e=>g(e,!1),className:"workspace-header-action","data-mobile-toolbar-action":e?"history":void 0,children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:n?"var(--text)":f,flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),n&&!t&&h&&(0,r.jsxs)("div",{role:"menu","aria-label":l.menu,style:{position:"fixed",top:h.top+2,left:Math.max(8,Math.min(h.left,window.innerWidth-210)),minWidth:195,zIndex:520,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 6px 20px rgba(0,0,0,0.12)",padding:4,display:"flex",flexDirection:"column",gap:2},children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{c(!1),a()},style:lA,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),(0,r.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l.full})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",title:l.exportMarkdownTitle,disabled:o,onClick:()=>{d()},style:{...lA,opacity:o?.6:1},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),(0,r.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l.exportMarkdown}),o&&(0,r.jsxs)("svg",{className:"animate-spin",width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{marginLeft:6,flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})]}),s&&(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"#dc2626",lineHeight:1.35},children:s})]})]})}let lA={display:"flex",alignItems:"center",gap:8,width:"100%",height:28,padding:"0 8px",border:"none",borderRadius:4,background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12,fontFamily:"var(--font-ui)",transition:"background 0.12s ease",boxSizing:"border-box"};function lD({loading:e,prompt:t,translate:n}){return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":n("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:t?(0,r.jsx)("div",{className:"system-prompt-text",children:t}):(0,r.jsx)("div",{className:"system-prompt-empty",children:n(""===t?"system.empty":e?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
|
|
10
|
+
.system-prompt-panel {
|
|
11
|
+
display: flex;
|
|
12
|
+
height: min(600px, 75dvh);
|
|
13
|
+
min-height: 220px;
|
|
14
|
+
flex-direction: column;
|
|
15
|
+
background: var(--bg-panel);
|
|
16
|
+
border-bottom: 1px solid var(--border);
|
|
17
|
+
}
|
|
18
|
+
.system-prompt-scroll {
|
|
19
|
+
min-height: 0;
|
|
20
|
+
flex: 1;
|
|
21
|
+
overflow: auto;
|
|
22
|
+
padding: 12px 16px;
|
|
23
|
+
}
|
|
24
|
+
.system-prompt-text {
|
|
25
|
+
color: var(--text-muted);
|
|
26
|
+
font-family: var(--font-mono);
|
|
27
|
+
font-size: 12px;
|
|
28
|
+
line-height: 1.6;
|
|
29
|
+
overflow-wrap: anywhere;
|
|
30
|
+
white-space: pre-wrap;
|
|
31
|
+
}
|
|
32
|
+
.system-prompt-empty {
|
|
33
|
+
padding: 10px 0;
|
|
34
|
+
color: var(--text-muted);
|
|
35
|
+
font-size: 12px;
|
|
36
|
+
font-style: italic;
|
|
37
|
+
}
|
|
38
|
+
`})]})}function lH(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function lB({children:e}){return(0,r.jsx)("div",{className:"tool-definitions-empty",children:e})}function lF({loading:e,tools:t,translate:n}){let o=(0,i.useMemo)(()=>t?.filter(e=>e.active)??null,[t]),[s,l]=(0,i.useState)(null);(0,i.useEffect)(()=>{l(e=>o?.some(t=>t.name===e)?e:o?.[0]?.name??null)},[o]);let a=o?.find(e=>e.name===s)??o?.[0]??null,d=a?function(e){if(!e||!e.properties||"object"!=typeof e.properties)return[];let t=e.properties,n=new Set(Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[]);return Object.entries(t).map(([e,t])=>{let r=t&&"object"==typeof t?t:{};return{name:e,type:function e(t){let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(n)return n.map(t=>t&&"object"==typeof t?e(t):"unknown").filter((e,t,n)=>n.indexOf(e)===t).join(" | ");if(void 0!==t.const)return lH(t.const);if(Array.isArray(t.enum)&&t.enum.length>0&&void 0===t.type)return[...new Set(t.enum.map(e=>null===e?"null":typeof e))].join(" | ");let r=t.type,i=Array.isArray(r)?r.filter(e=>"string"==typeof e).join(" | "):"string"==typeof r?r:"string"==typeof t.$ref?t.$ref.split("/").pop()??"object":"unknown";if("array"===i){let n=t.items,r=n&&"object"==typeof n?e(n):"unknown";return`${r}[]`}return i}(r),description:"string"==typeof r.description?r.description:void 0,required:n.has(e),allowedValues:Array.isArray(r.enum)?r.enum.map(lH).join(", "):void 0,defaultValue:void 0===r.default?void 0:lH(r.default)}})}(a.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":n("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:o&&o.length>0?o.map(e=>{let t=e.name===a?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>l(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):o?(0,r.jsx)(lB,{children:n("tools.noTools")}):(0,r.jsx)(lB,{children:e?n("tools.loading"):n("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":n("tools.details"),children:a?(0,r.jsxs)("div",{className:"tool-definition-scroll",children:[a.description&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:n("tools.description")}),(0,r.jsx)("div",{className:"tool-definition-description",children:a.description})]}),(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsxs)("div",{className:"tool-definition-section-label",children:[(0,r.jsx)("span",{children:n("tools.parameters")}),(0,r.jsx)("span",{children:n("tools.parameterCount",{count:d.length})})]}),d.length>0?(0,r.jsx)("div",{className:"tool-definition-fields",children:d.map(e=>(0,r.jsxs)("div",{className:"tool-definition-field",children:[(0,r.jsxs)("div",{className:"tool-definition-field-name",children:[(0,r.jsx)("code",{children:e.name}),(0,r.jsx)("span",{className:e.required?"required":void 0,children:n(e.required?"tools.required":"tools.optional")})]}),(0,r.jsxs)("div",{className:"tool-definition-field-value",children:[(0,r.jsx)("code",{className:"tool-definition-type",children:e.type}),e.description&&(0,r.jsx)("div",{children:e.description}),e.allowedValues&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[n("tools.allowedValues"),": ",(0,r.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[n("tools.defaultValue"),": ",(0,r.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,r.jsx)("div",{className:"tool-definition-no-parameters",children:n("tools.noParameters")})]}),a.promptGuidelines&&a.promptGuidelines.length>0&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:n("tools.guidelines")}),(0,r.jsx)("ul",{className:"tool-definition-guidelines",children:a.promptGuidelines.map((e,t)=>(0,r.jsx)("li",{children:e},`${a.name}:${t}`))})]})]}):(0,r.jsx)(lB,{children:o?n("tools.noTools"):e?n("tools.loading"):n("tools.load")})}),(0,r.jsx)("style",{children:`
|
|
39
|
+
.tool-definitions-panel {
|
|
40
|
+
display: grid;
|
|
41
|
+
grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
|
|
42
|
+
height: min(600px, 75dvh);
|
|
43
|
+
min-height: 240px;
|
|
44
|
+
overflow: hidden;
|
|
45
|
+
background: var(--bg-panel);
|
|
46
|
+
border-bottom: 1px solid var(--border);
|
|
47
|
+
}
|
|
48
|
+
.tool-definitions-sidebar,
|
|
49
|
+
.tool-definition-detail {
|
|
50
|
+
display: flex;
|
|
51
|
+
min-width: 0;
|
|
52
|
+
min-height: 0;
|
|
53
|
+
flex-direction: column;
|
|
54
|
+
}
|
|
55
|
+
.tool-definitions-sidebar {
|
|
56
|
+
border-right: 1px solid var(--border);
|
|
57
|
+
background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
|
|
58
|
+
}
|
|
59
|
+
.tool-definitions-list,
|
|
60
|
+
.tool-definition-scroll {
|
|
61
|
+
min-height: 0;
|
|
62
|
+
flex: 1;
|
|
63
|
+
overflow: auto;
|
|
64
|
+
}
|
|
65
|
+
.tool-definitions-item {
|
|
66
|
+
display: flex;
|
|
67
|
+
width: 100%;
|
|
68
|
+
min-height: 38px;
|
|
69
|
+
align-items: center;
|
|
70
|
+
padding: 8px 12px;
|
|
71
|
+
border: none;
|
|
72
|
+
border-bottom: 1px solid var(--border);
|
|
73
|
+
background: transparent;
|
|
74
|
+
color: var(--text-muted);
|
|
75
|
+
cursor: pointer;
|
|
76
|
+
text-align: left;
|
|
77
|
+
}
|
|
78
|
+
.tool-definitions-item:hover {
|
|
79
|
+
background: var(--bg-hover);
|
|
80
|
+
color: var(--text);
|
|
81
|
+
}
|
|
82
|
+
.tool-definitions-item.selected {
|
|
83
|
+
background: var(--bg-selected);
|
|
84
|
+
box-shadow: inset 2px 0 0 var(--accent);
|
|
85
|
+
color: var(--text);
|
|
86
|
+
}
|
|
87
|
+
.tool-definitions-item code {
|
|
88
|
+
max-width: 100%;
|
|
89
|
+
color: inherit;
|
|
90
|
+
font-size: 11px;
|
|
91
|
+
font-weight: 600;
|
|
92
|
+
overflow-wrap: anywhere;
|
|
93
|
+
}
|
|
94
|
+
.tool-definition-scroll {
|
|
95
|
+
padding: 14px 16px 20px;
|
|
96
|
+
}
|
|
97
|
+
.tool-definition-section + .tool-definition-section {
|
|
98
|
+
margin-top: 18px;
|
|
99
|
+
}
|
|
100
|
+
.tool-definition-section-label {
|
|
101
|
+
display: flex;
|
|
102
|
+
align-items: center;
|
|
103
|
+
justify-content: space-between;
|
|
104
|
+
gap: 8px;
|
|
105
|
+
margin-bottom: 7px;
|
|
106
|
+
color: var(--text-dim);
|
|
107
|
+
font-size: 11px;
|
|
108
|
+
font-weight: 600;
|
|
109
|
+
}
|
|
110
|
+
.tool-definition-section-label > span:last-child {
|
|
111
|
+
font-weight: 400;
|
|
112
|
+
white-space: nowrap;
|
|
113
|
+
}
|
|
114
|
+
.tool-definition-description {
|
|
115
|
+
color: var(--text-muted);
|
|
116
|
+
font-size: 12px;
|
|
117
|
+
line-height: 1.55;
|
|
118
|
+
overflow-wrap: anywhere;
|
|
119
|
+
white-space: pre-wrap;
|
|
120
|
+
}
|
|
121
|
+
.tool-definition-fields {
|
|
122
|
+
border-top: 1px solid var(--border);
|
|
123
|
+
}
|
|
124
|
+
.tool-definition-field {
|
|
125
|
+
display: grid;
|
|
126
|
+
grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
|
|
127
|
+
gap: 12px;
|
|
128
|
+
padding: 9px 0;
|
|
129
|
+
border-bottom: 1px solid var(--border);
|
|
130
|
+
font-size: 11px;
|
|
131
|
+
line-height: 1.45;
|
|
132
|
+
}
|
|
133
|
+
.tool-definition-field-name {
|
|
134
|
+
display: flex;
|
|
135
|
+
min-width: 0;
|
|
136
|
+
flex-direction: column;
|
|
137
|
+
gap: 3px;
|
|
138
|
+
color: var(--text);
|
|
139
|
+
}
|
|
140
|
+
.tool-definition-field-name code {
|
|
141
|
+
overflow-wrap: anywhere;
|
|
142
|
+
}
|
|
143
|
+
.tool-definition-field-name span {
|
|
144
|
+
color: var(--text-dim);
|
|
145
|
+
font-size: 10px;
|
|
146
|
+
}
|
|
147
|
+
.tool-definition-field-name span.required {
|
|
148
|
+
color: var(--accent);
|
|
149
|
+
}
|
|
150
|
+
.tool-definition-field-value {
|
|
151
|
+
min-width: 0;
|
|
152
|
+
color: var(--text-muted);
|
|
153
|
+
overflow-wrap: anywhere;
|
|
154
|
+
}
|
|
155
|
+
.tool-definition-type {
|
|
156
|
+
display: block;
|
|
157
|
+
margin-bottom: 3px;
|
|
158
|
+
color: var(--text);
|
|
159
|
+
}
|
|
160
|
+
.tool-definition-meta {
|
|
161
|
+
margin-top: 4px;
|
|
162
|
+
color: var(--text-dim);
|
|
163
|
+
}
|
|
164
|
+
.tool-definition-meta code {
|
|
165
|
+
color: var(--text-muted);
|
|
166
|
+
}
|
|
167
|
+
.tool-definition-no-parameters {
|
|
168
|
+
padding: 2px 0 10px;
|
|
169
|
+
color: var(--text-dim);
|
|
170
|
+
font-size: 11px;
|
|
171
|
+
}
|
|
172
|
+
.tool-definition-guidelines {
|
|
173
|
+
margin: 0;
|
|
174
|
+
padding-left: 18px;
|
|
175
|
+
color: var(--text-muted);
|
|
176
|
+
font-size: 11px;
|
|
177
|
+
line-height: 1.5;
|
|
178
|
+
}
|
|
179
|
+
.tool-definitions-empty {
|
|
180
|
+
padding: 14px 12px;
|
|
181
|
+
color: var(--text-muted);
|
|
182
|
+
font-size: 12px;
|
|
183
|
+
font-style: italic;
|
|
184
|
+
overflow-wrap: anywhere;
|
|
185
|
+
}
|
|
186
|
+
@media (max-width: 640px) {
|
|
187
|
+
.tool-definitions-panel {
|
|
188
|
+
grid-template-columns: 112px minmax(0, 1fr);
|
|
189
|
+
}
|
|
190
|
+
.tool-definitions-item {
|
|
191
|
+
padding: 8px 10px;
|
|
192
|
+
}
|
|
193
|
+
.tool-definition-scroll {
|
|
194
|
+
padding: 12px;
|
|
195
|
+
}
|
|
196
|
+
.tool-definition-field {
|
|
197
|
+
grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
|
|
198
|
+
gap: 9px;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
`})]})}function lO(e){return e.name||e.firstMessage||e.id.slice(0,12)}function lU(e,t){return t?"running":e.relation?.kind==="subagent"?e.relation.status:"completed"}function l_(e){return"running"===e||"starting"===e?0:"queued"===e?1:2}function lq({status:e}){return"running"===e||"starting"===e?(0,r.jsx)(Z,{size:13}):"failed"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"queued"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}):"aborted"===e||"interrupted"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m8 12 3 3 5-6"})]})}function lK({session:e,main:t,selected:n,running:i,onSelect:o,onOpenInNewTab:s}){let{locale:l,t:a}=(0,w.s)(),d=e.relation?.kind==="subagent"?e.relation:null,c=lU(e,i),u=t?a("agentSwitcher.main"):d?.description||lO(e),h=t?lO(e):`${d?.profile??a("agentSwitcher.subagent")} \xb7 ${function(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let o=Math.round(r/60);if(60>Math.abs(o))return i.format(o,"minute");let s=Math.round(o/60);return 24>Math.abs(s)?i.format(s,"hour"):i.format(Math.round(s/24),"day")}(e.modified,l)}`;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,onClick:o,onAuxClick:e=>{1===e.button&&s&&(e.preventDefault(),s())},style:{width:"100%",minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",borderBottom:"1px solid var(--border)",borderLeft:n?"2px solid var(--accent)":"2px solid transparent",background:n?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="transparent")},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:t?"var(--text-muted)":"var(--accent)"},children:t?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"M3 9h18"})]}):(0,r.jsx)(X,{size:17,strokeWidth:1.8})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:n?600:500},title:u,children:u}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:h,children:h})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:t&&!i?"var(--text-dim)":"running"===c||"starting"===c?"var(--accent)":"completed"===c?"#16a34a":"failed"===c?"#dc2626":"aborted"===c?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:t&&!i?n?a("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lq,{status:c}),(0,r.jsx)("span",{children:a(`agentSwitcher.status.${c}`)})]})})]})}function lV({rootSession:e,subagents:t,selectedSessionId:n,runningSessionIds:o,onSelectSession:s,onOpenInNewTab:l}){let{t:a}=(0,w.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useMemo)(()=>[...t].sort((e,t)=>{let n=l_(lU(e,o.has(e.id)))-l_(lU(t,o.has(t.id)));return 0!==n?n:t.modified.localeCompare(e.modified)}),[o,t]),h=d.trim().toLowerCase(),p=h?u.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return[t?.description,t?.profile,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(h))}):u,f=t.filter(e=>o.has(e.id)).length;return(0,r.jsx)("div",{role:"listbox","aria-label":a("agentSwitcher.title"),style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 10px 30px rgba(0, 0, 0, 0.14)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:a("agentSwitcher.title")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:a("agentSwitcher.count",{count:t.length})}),f>0&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--accent)",fontSize:11},children:a("agentSwitcher.runningCount",{count:f})})]}),t.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",className:"agent-switcher-search-input",value:d,onChange:e=>c(e.target.value),placeholder:a("agentSwitcher.search"),"aria-label":a("agentSwitcher.search"),style:{width:"100%",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(58dvh, 480px)",overflowY:"auto"},children:[(0,r.jsx)(lK,{session:e,main:!0,selected:e.id===n,running:o.has(e.id),onSelect:()=>s(e),onOpenInNewTab:l?()=>l(e):void 0}),p.map(e=>(0,r.jsx)(lK,{session:e,selected:e.id===n,running:o.has(e.id),onSelect:()=>s(e),onOpenInNewTab:l?()=>l(e):void 0},e.id)),0===p.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:a("agentSwitcher.noMatches")})]})]})})}var lJ=n(63606),lY=n(8422);async function lZ(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(15e3)}),r=await n.json().catch(()=>{throw Error(`Terminal request failed (HTTP ${n.status}): server returned an empty or invalid JSON response. Check the pi-web server log.`)});if(!r||"object"!=typeof r)throw Error(`Terminal request failed (HTTP ${n.status}): invalid JSON response. Check the pi-web server log.`);if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}function lX({tab:e,active:t,onRestart:n,onClosed:o,onCloseError:s}){let{t:l}=(0,w.s)(),{id:a,cwd:d,restored:c}=e,u=(0,i.useRef)(null),h=(0,i.useRef)(null),p=(0,i.useRef)(Promise.resolve()),f=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:o,onCloseError:s});g.current={onClosed:o,onCloseError:s};let[m,x]=(0,i.useState)("connecting"),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(0);return(0,i.useEffect)(()=>{var e;let t,n,r,i,o,s=u.current;if(!s)return;let l=!1,g=null,m=!1,v=!1,b=!1;x("connecting"),y(null),k(null);let w=new lY.B({cursorBlink:!0,fontFamily:getComputedStyle(s).getPropertyValue("--font-mono").trim()||"monospace",fontSize:13,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:{background:"#111318",foreground:"#d7dce5",cursor:"#60a5fa",selectionBackground:"#365b8a",black:"#1d222b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e5e7eb",brightBlack:"#6b7280",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"}});h.current=w;let S=new lJ.Y;w.loadAddon(S),w.open(s),w.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&w.hasSelection())});let C=(e=e=>{l||(b=!0,w.options.disableStdin=!0,y(e.message),x("error"))},n=Promise.resolve(),r=!1,i=null,o=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await lZ(`/api/terminal/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:o(i={type:"input",data:t})},resize(e,t){i=null,o({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});f.current=C;let E=w.onData(e=>{!m||v||b||C.write(e)}),N=()=>{s.offsetWidth&&s.offsetHeight&&S.fit()},I=w.onResize(({cols:e,rows:t})=>{!m||v||b||C.resize(e,t)}),M=new ResizeObserver(N);M.observe(s);let T=()=>{l||v||!navigator.onLine||(g?.close(),(g=new EventSource(`/api/terminal/${encodeURIComponent(a)}/events${void 0===t?"":`?after=${t}`}`)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)w.reset();else if(void 0!==t&&n.offset<=t)return;w.write(n.data),t=n.offset}else v=!0,m=!1,w.options.disableStdin=!0,g?.close(),k("exit"===n.type?n.exitCode:null),x("exited")},g.onopen=()=>{m=!0,!b&&(w.options.disableStdin=!1,x("ready"),N(),C.resize(w.cols,w.rows),s.offsetWidth&&s.offsetHeight&&w.focus())},g.onerror=()=>{l||v||(m=!1,w.options.disableStdin=!0,x(g?.readyState===EventSource.CLOSED?"error":"connecting"))})};p.current=(async()=>{N(),c||j>0?await lZ(`/api/terminal/${encodeURIComponent(a)}`):await lZ("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:a,cwd:d,cols:w.cols,rows:w.rows})}),T()})().catch(e=>{l||(y(e.message),x("error"))});let L=()=>{m=!1,w.options.disableStdin=!0,g?.close(),v||b||x("connecting")},R=e=>{e.persisted&&T()};return window.addEventListener("pagehide",L),window.addEventListener("pageshow",R),window.addEventListener("offline",L),window.addEventListener("online",T),()=>{l=!0,g?.close(),C.stop(),M.disconnect(),E.dispose(),I.dispose(),window.removeEventListener("pagehide",L),window.removeEventListener("pageshow",R),window.removeEventListener("offline",L),window.removeEventListener("online",T),w.dispose(),h.current=null}},[a,d,c,j]),(0,i.useEffect)(()=>{t&&h.current?.focus()},[t]),(0,i.useEffect)(()=>{if(!e.closing)return;let t=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await p.current,await f.current?.stop(),await lZ(`/api/terminal/${encodeURIComponent(a)}`,{method:"DELETE",keepalive:!0}),t||g.current.onClosed()})().catch(e=>{t||(y(e.message),x("error"),g.current.onCloseError())}),()=>{t=!0}},[a,e.closing]),(0,r.jsxs)("section",{className:"terminal-panel","aria-label":l("terminal.title"),children:[(0,r.jsxs)("header",{className:"terminal-panel-header",children:[(0,r.jsxs)("div",{className:"terminal-panel-path",children:[(0,r.jsx)("span",{className:`terminal-status-dot is-${m}`,title:l(`terminal.${m}`)}),(0,r.jsx)("span",{title:d,children:d})]}),"error"===m&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!e.closing,title:l("terminal.reconnect"),"aria-label":l("terminal.reconnect"),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,r.jsx)("button",{type:"button",onClick:n,disabled:!!e.closing,title:l("terminal.restart"),"aria-label":l("terminal.restart"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]}),(0,r.jsxs)("div",{children:[v&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:v}),"exited"===m&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===b?l("terminal.exited"):l("terminal.exitCode",{code:b})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:u,className:"terminal-xterm-host"})})]})}let lG="pi-web:terminal-tabs";function lQ(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function l0(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function l1(e){return{min:Math.max(.2,280/e),max:Math.min(.8,(e-12-280)/e)}}function l2(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function l4(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:o,getMaxWidth:s,growthDirection:l,maxWidth:a,minWidth:d,storageKey:c,widthRef:u}=e,h=(0,i.useRef)(null),p=(0,i.useRef)(null),f=(0,i.useRef)(!1),[g,m]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1);(0,i.useEffect)(()=>{b(!0)},[]);let w=(0,i.useCallback)(()=>Math.min(a,Math.max(d,s())),[s,a,d]),k=(0,i.useCallback)(e=>l0(e,d,w()),[w,d]),j=(0,i.useCallback)(e=>{u.current=e,h.current?.style.setProperty(n,`${e}px`)},[n,u]),S=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=k(e),o=i!==u.current;return j(i),m(i),r&&(o||n)&&l2(c,i),i},[j,k,c,u]),C=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),E=(0,i.useCallback)(e=>{let t=p.current;if(t&&t.pointerId===e){p.current=null,C(t),v(!1),S(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[S,C,u]),N=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=p.current;t&&E(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),p.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[E,u]),I=(0,i.useCallback)(e=>{let t=p.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void E(e.pointerId);e.preventDefault();let n="right"===l?1:-1,r=k(t.startWidth+(e.clientX-t.startX)*n);j(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[j,k,E,l]),M=(0,i.useCallback)(e=>{E(e.pointerId)},[E]),T=(0,i.useCallback)(e=>{E(e.pointerId)},[E]),L=(0,i.useCallback)(e=>{E(e.pointerId)},[E]),R=(0,i.useCallback)(()=>{S(o?.()??r,{forcePersist:!0})},[S,r,o]),$=(0,i.useCallback)(()=>{S(u.current)},[S,u]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===l?"ArrowRight":"ArrowLeft",r="right"===l?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),S(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),S(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),S(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),S(w(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),R())},[S,w,l,d,R,u]);return(0,i.useLayoutEffect)(()=>{if(f.current)return;f.current=!0;let e=h.current,t=e?.style.transition??"";e&&(e.style.transition="none");let n=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(c),i=S(n??o?.()??r,{persist:!1});null!==n&&n!==i&&l2(c,i),e&&(e.offsetWidth,e.style.transition=t)},[S,r,o,c]),(0,i.useEffect)(()=>{if(!f.current)return;S(u.current);let e=()=>{S(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[S,u]),(0,i.useEffect)(()=>{if(!x)return;let e=()=>{let e=p.current;e&&E(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[E,x]),(0,i.useEffect)(()=>()=>{let e=p.current;e&&(p.current=null,C(e))},[C]),{isResizing:x,panelRef:h,reclampWidth:$,resetWidth:R,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":y?w():a,"aria-valuemin":d,"aria-valuenow":g,"aria-valuetext":`${g} px`,onDoubleClick:R,onKeyDown:W,onLostPointerCapture:L,onPointerCancel:T,onPointerDown:N,onPointerMove:I,onPointerUp:M,role:"separator",tabIndex:0},width:g}}let l8="pi-web:pinned-cwds";function l5(){try{return window.localStorage}catch{return null}}function l6(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if("string"!=typeof n)continue;let e=n.trim();!e||t.includes(e)||t.push(e)}return t}function l3(e,t,n){return t&&n?k(t).replace(/\/$/,"")===k(n).replace(/\/$/,"")||e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:N(t,e):e}let l7="pi-chat-draft-tabs";function l9(e){return`parked-new:${e}`}function ae({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.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,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function at(){let e,t,n,l,a,d,c,u,h,m,x,v,y,b,k,j,C=(0,o.useRouter)(),E=(0,o.useSearchParams)(),[N]=(0,i.useState)(()=>{let e;return{requestedCwd:e=E.get("cwd")?.trim()||null,sessionId:e?null:E.get("session")}}),{locale:I,t:M}=(0,w.s)(),T=eX();(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,o=.01>Math.abs(e.scale-1);i&&o&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]),n2(),(0,i.useEffect)(()=>r1(e=>{"granted"===e&&lj(I)}),[I]);let{soundEnabled:L,onSoundToggle:R,playDoneSound:$,unlockAudio:W,soundEnabledRef:z}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),o=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),s=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=o();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[o]);return{soundEnabled:e,onSoundToggle:(0,i.useCallback)(()=>{let e=!n.current;e&&s(!0),n.current=e,localStorage.setItem("pi-sound-enabled",String(e)),t(e)},[s]),playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=o();if(!e)return;let t=()=>{try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),o=e.createGain();i.connect(o),o.connect(e.destination),i.type="sine",i.frequency.value=n;let s=t+.18*r;o.gain.setValueAtTime(0,s),o.gain.linearRampToValueAtTime(.18,s+.02),o.gain.exponentialRampToValueAtTime(.001,s+.45),i.start(s),i.stop(s+.45)})}catch{}};"suspended"===e.state?e.resume().then(t).catch(()=>{}):t()},[o]),unlockAudio:s,soundEnabledRef:n}}(),[P,A]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{A("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let D=(0,i.useCallback)(e=>{A(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),H=(0,i.useRef)(new Set),B=(0,i.useCallback)(e=>{if(!z.current)return;let t=new Set(eM.current.filter(e=>"session"===e.kind&&e.session).map(e=>e.session.id));(!e||!(e.length>0)||e.some(e=>!t.has(e)))&&$()},[$,z]),[F,O]=(0,i.useState)(null),[U,_]=(0,i.useState)([]),q=(0,i.useCallback)(e=>{_(e)},[]),K=(0,i.useMemo)(()=>g(U).map(e=>e.root),[U]),[V,J]=(0,i.useState)(()=>(function(e=l5()){if(!e)return[];try{let t=e.getItem(l8);if(!t)return[];return l6(JSON.parse(t))}catch{return[]}})()),Y=(0,i.useCallback)(e=>{J(t=>{let n,r=(n=e.trim())?t.includes(n)?t.filter(e=>e!==n):[...t,n]:l6(t);return!function(e,t=l5()){if(t)try{t.setItem(l8,JSON.stringify(l6(e)))}catch{}}(r),r})},[]),[Z,G]=(0,i.useState)(""),[Q,ee]=(0,i.useState)(null),et=(0,i.useMemo)(()=>F?[...U.filter(e=>e.id!==F.id),F]:U,[F,U]),en=(0,i.useMemo)(()=>{var e;return(e=F?.id)?s(et).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[F?.id,et]),er=!!en?.subagents.length,[ei,eo]=(0,i.useState)(()=>new Set),es=(0,i.useCallback)(e=>{eo(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[el,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)("initial"),eh=(0,i.useRef)(null),[ep,ef]=(0,i.useState)(()=>N.requestedCwd?"validating":"idle"),[eg,em]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(0),[ey,eb]=(0,i.useState)(0),ew=(0,i.useRef)(new Map),ek=(0,i.useCallback)((e,t)=>{ew.current.set(e,t)},[]),[ej,eS]=(0,i.useState)([]),[eC,eE]=(0,i.useState)(!1),[eN,eI]=(0,i.useState)(!1),eM=(0,i.useRef)([]);eM.current=ej;let[eT,eL]=(0,i.useState)(null),eR=(0,i.useRef)(null);eR.current=eT;let[e$,eW]=(0,i.useState)(null),eP=(0,i.useRef)(null);eP.current=e$;let[eD,eH]=(0,i.useState)("primary"),eB=(0,i.useRef)("primary");eB.current=eD;let eO=(0,i.useRef)(!1),[eU,e_]=(0,i.useState)(.5),eK=(0,i.useRef)(null),eV=(0,i.useRef)(!1),[eJ,eY]=(0,i.useState)(600);e=(0,i.useMemo)(()=>0===ej.length?F?.id?[F.id]:[]:ej.flatMap(e=>"session"===e.kind&&e.session?[e.session.id]:[]),[ej,F?.id]).join(","),(0,i.useEffect)(()=>{if(!e)return;let t=e.split(","),n=!1,r=()=>{if(!n)for(let e of t)fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store"}).catch(()=>{})};r();let i=setInterval(r,3e4),o=()=>{"visible"===document.visibilityState&&r()};return document.addEventListener("visibilitychange",o),()=>{n=!0,clearInterval(i),document.removeEventListener("visibilitychange",o)}},[e]);let eZ=(0,i.useCallback)((e,t,n)=>{let r=!!(t.trim()||n>0),i=iZ(t,M("i18n.newSession"));eS(t=>{let n=!1,o=t.map(t=>"draft"!==t.kind||t.newSessionDraftKey!==e||t.dirty===r&&t.title===i?t:(n=!0,{...t,dirty:r,title:i}));return n?o:t})},[M]);(0,i.useEffect)(()=>{try{let e=window.sessionStorage.getItem(l7),t=(e?JSON.parse(e):[]).flatMap(e=>{if("string"!=typeof e?.draftKey||"string"!=typeof e?.title)return[];let t=ez(e.draftKey);return t?[{id:`draft:${e.draftKey}`,kind:"draft",title:iZ(t.value,e.title),session:null,newSessionCwd:"string"==typeof e.cwd?e.cwd:null,newSessionDraftKey:e.draftKey,projectKey:"string"==typeof e.cwd?e.cwd:null,dirty:!0}]:[]});if(t.length>0&&(eS(e=>[...e,...t.filter(t=>!e.some(e=>e.id===t.id))]),!N.sessionId&&!N.requestedCwd)){let e=t[0];eL(t=>t??e.id),O(null),ed(e.newSessionCwd),eh.current=e.newSessionDraftKey}}catch{}eE(!0)},[N.requestedCwd,N.sessionId]),(0,i.useEffect)(()=>{if(!eC)return;let e=ej.flatMap(e=>"draft"===e.kind&&e.dirty&&e.newSessionDraftKey?[{draftKey:e.newSessionDraftKey,cwd:e.newSessionCwd,title:e.title}]:[]);if(0===e.length){try{window.sessionStorage.removeItem(l7)}catch{}eI(!1);return}try{window.sessionStorage.setItem(l7,JSON.stringify(e)),eI(!1)}catch{eI(!0)}},[ej,eC]);let[eG,eQ]=(0,i.useState)(null),e0=(0,i.useCallback)(e=>{eQ(t=>t===e?null:t)},[]),[e1,e2]=(0,i.useState)(0),[e4,e8]=(0,i.useState)(null),[e5,e6]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(!1),[tr,to]=(0,i.useState)(null),[ts,tl]=(0,i.useState)(!0),[ta,td]=(0,i.useState)(!1),[tc,tu]=(0,i.useState)(!1),[th,tp]=(0,i.useState)(!1),tf=(0,i.useRef)(260),tg=(0,i.useRef)(560),tm=(0,i.useCallback)(()=>l0(.42*window.innerWidth,360,640),[]),tx=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:ta,rightPanelWidth:tg.current}),[ta]),tv=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:n,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(n?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:ts,sidebarWidth:tf.current}),[ts]),ty=l4({ariaLabel:M("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tx,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:tf}),tb=l4({ariaLabel:M("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:tm,getMaxWidth:tv,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:tg}),tw=ty.reclampWidth,tk=tb.reclampWidth;(0,i.useEffect)(()=>{T&&tl(!1)},[T]),(0,i.useEffect)(()=>{tp(!0)},[]),(0,i.useEffect)(()=>{ta&&(tw(),tk())},[tk,tw,ta]),(0,i.useEffect)(()=>{if(!ta)return void tu(!1);let e=tb.panelRef.current,t=!1,n=()=>{t||(t=!0,tu(!0))};if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return void n();let r=t=>{t.target===e&&("width"===t.propertyName||"min-width"===t.propertyName||"transform"===t.propertyName)&&n()};e?.addEventListener("transitionend",r);let i=window.setTimeout(n,280);return()=>{e?.removeEventListener("transitionend",r),window.clearTimeout(i)}},[ta,tb.panelRef]);let tj=(0,i.useRef)(null),[tS,tC]=(0,i.useState)(null),tE=(0,i.useCallback)(e=>{tC(t=>t?.sessionId===e?null:t)},[]),tN=(0,i.useRef)(null),[tI,tM]=(0,i.useState)([]),[tT,tL]=(0,i.useState)(null),[tR,t$]=(0,i.useState)(!1),[tW,tz]=(0,i.useState)(!1),[tP,tA]=(0,i.useState)(null),tD=(0,i.useRef)(null),tH=l$(tI),tB=(0,i.useRef)(new Map),tF=(0,i.useRef)(new Map),tO=(0,i.useRef)(new Map),tU=(0,i.useCallback)((e,t,n)=>{ne.current&&tO.current.set(ne.current,{tree:e,activeLeafId:t}),tM(e),tL(t),tD.current=n},[]),t_=(0,i.useCallback)(e=>{tD.current?.(e)},[]),[tq,tK]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(null),[tY,tZ]=(0,i.useState)(!1),tX=(0,i.useRef)(null),tG=(0,i.useRef)(0),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),t8=(0,i.useRef)(null),t5=(0,i.useCallback)(e=>{tK(e),tZ(!1)},[]),t6=(0,i.useCallback)(e=>{tJ(e)},[]),t3=(0,i.useCallback)(e=>{tG.current+=1,tX.current=e,tZ(!1)},[]),[t7,t9]=(0,i.useState)(null),ne=(0,i.useRef)(F?.id??null);ne.current=F?.id??null;let nt=(0,i.useCallback)(e=>{null!==e&&(e.sessionId&&tB.current.set(e.sessionId,e),t9(e))},[]),[nn,nr]=(0,i.useState)(null),ni=(0,i.useRef)(null),no=(0,i.useCallback)((e,t)=>{n4(t).then(()=>{ni.current&&clearTimeout(ni.current),nr(e),ni.current=setTimeout(()=>nr(null),1400)})},[]);(0,i.useEffect)(()=>()=>{ni.current&&clearTimeout(ni.current)},[]);let[ns,nl]=(0,i.useState)(null),na=(0,i.useCallback)(e=>{null!==e&&(ne.current&&tF.current.set(ne.current,e),nl(e))},[]),nd=(0,i.useCallback)(e=>{t9(tB.current.get(e)??null),nl(tF.current.get(e)??null);let t=tO.current.get(e);tM(t?.tree??[]),tL(t?.activeLeafId??null)},[]);(0,i.useEffect)(()=>{if(!F){t9(null),nl(null);return}nd(F.id)},[F,nd]);let[nc,nu]=(0,i.useState)(null),[nh,np]=(0,i.useState)(null),nf=(0,i.useCallback)((e=!1)=>{nu(null),e&&nc&&requestAnimationFrame(()=>{let e=document.querySelector(`[data-top-panel-trigger="${nc}"]`)??t0.current;e?.focus()})},[nc]);(0,i.useEffect)(()=>{tH||nu(e=>"branches"===e?null:e)},[tH]),(0,i.useEffect)(()=>{er||nu(e=>"agents"===e?null:e)},[er]);let ng=(0,i.useCallback)(e=>{T&&tl(!1),nu(t=>t===e?null:e)},[T]),nm=(0,i.useCallback)(e=>{let t=nc!==e;if(ng(e),!t||tY)return;let n=tX.current;if(!n)return;let r=++tG.current;tZ(!0),n().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tG.current===r&&tZ(!1)})},[nc,tY,ng]),nx=(0,i.useCallback)(()=>{T&&tl(!1),nu(e=>"session"===e?null:"session")},[T]),nv=(0,i.useCallback)(()=>{T&&nu(null),tl(e=>!e)},[T]),ny=(0,i.useCallback)(()=>{tl(!1),requestAnimationFrame(()=>t0.current?.focus())},[]);(0,i.useEffect)(()=>{if(!T||!ts||!th)return;let e=requestAnimationFrame(()=>{let e=ty.panelRef.current;e?.querySelector('[aria-current="page"], button:not(:disabled)')?.focus()}),t=e=>{"Escape"===e.key&&(e.preventDefault(),ny())};return document.addEventListener("keydown",t),()=>{cancelAnimationFrame(e),document.removeEventListener("keydown",t)}},[ny,T,th,ts,ty.panelRef]);let nb=(0,i.useCallback)(()=>{T&&(tl(!1),nu(null)),td(e=>!e)},[T]),nw=(0,i.useCallback)((e=!1)=>{td(!1),e&&requestAnimationFrame(()=>t1.current?.focus())},[]);(0,i.useEffect)(()=>{if(!ta)return;let e=requestAnimationFrame(()=>{(T||!(window.innerWidth>=960))&&tb.panelRef.current?.querySelector('[role="tab"][aria-selected="true"]')?.focus()}),t=e=>{"Escape"===e.key&&(T||!(window.innerWidth>=960))&&(e.preventDefault(),e.stopPropagation(),nw(!0))};return document.addEventListener("keydown",t,!0),()=>{cancelAnimationFrame(e),document.removeEventListener("keydown",t,!0)}},[nw,T,ta,tb.panelRef]),(0,i.useEffect)(()=>{t$(!1),tA(null)},[T,F?.id,ec]),(0,i.useEffect)(()=>{nc&&t$(!1)},[nc]),(0,i.useEffect)(()=>{if(!nc||!tN.current)return;let e=()=>{let e=tN.current.getBoundingClientRect();if("agents"===nc){let t=t4.current??t2.current,n=Math.min(420,window.innerWidth-16);if(t){let e=t.getBoundingClientRect(),r=Math.max(8,Math.min(e.right-n,window.innerWidth-n-8));np({top:e.bottom+4,left:r,width:n});return}let r=Math.max(8,Math.min(e.right-n-8,window.innerWidth-n-8));np({top:e.bottom+4,left:r,width:n});return}np({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tN.current),window.addEventListener("resize",e),()=>{t.disconnect(),window.removeEventListener("resize",e)}},[nc,T]),(0,i.useEffect)(()=>{if(!nc||"branches"===nc||"language"===nc)return;let e=e=>{let t=e.target;!t||t8.current?.contains(t)||t instanceof Element&&t.closest(`[data-top-panel-trigger="${nc}"]`)||nf()},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),nf(!0))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[nc,nf]);let[nk,nj]=(0,i.useState)([]),[nS,nC]=(0,i.useState)(null),[nE,nN]=(0,i.useState)([]),[nI,nM]=(0,i.useState)(!1),nT=(0,i.useMemo)(()=>[...nk,...nE.map(e=>({id:e.id,label:S(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing}))],[nk,nE]);(0,i.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(lG));nN(e.tabs),e.activeId&&(nC(e.activeId),td(e.open))}catch{}nM(!0)},[]),(0,i.useEffect)(()=>{if(nI)try{window.sessionStorage.setItem(lG,JSON.stringify({tabs:nE.map(({id:e,cwd:t})=>({id:e,cwd:t})),activeId:nS,open:ta}))}catch{}},[nE,nS,ta,nI]);let nL=(0,i.useCallback)((e,t,n)=>{nj(r=>(function(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let o=[...e];return o[i]={...o[i],viewerState:r},o})(r,e,t,n))},[]),[nR,n$]=(0,i.useState)(null),nW=(0,i.useCallback)(()=>{let e=eO.current&&"secondary"===eB.current?eP.current:eR.current,t=eM.current.find(t=>t.id===e);return t?.kind==="session"?t.session?.cwd??null:t?.kind==="draft"?t.newSessionCwd:F?.cwd??el??nR},[nR,el,F?.cwd]),nz=(0,i.useCallback)((e,t,n)=>{let r=l3(e,n,nW());tj.current?.insertText(eq(r,t)),T&&(td(!1),tl(!1))},[nW,T]),nP=(0,i.useCallback)((e,t)=>{let n=nW(),r=e.map(e=>l3(e,t,n)).map(e=>eq(e,!1)).join("");r&&tj.current?.insertText(r),T&&(td(!1),tl(!1))},[nW,T]),nA=(0,i.useCallback)((e,t,n,r)=>{let i,o,s,l,a,d,c,u=l3(e,r,nW());tj.current?.insertText((o=(i=e=>Number.isFinite(e)&&Number.isInteger(e)&&e>=1?e:1)(t),l=Math.min(o,s=i(n)),a=Math.max(o,s),d=u.includes(" ")?`@"${u}"`:`@${u}`,c=l===a?`:${l}`:`:${l}-${a}`,`${d}${c} `)),T&&(td(!1),tl(!1))},[nW,T]),nD=N.sessionId,nH=(0,i.useRef)(null),nB=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=N.requestedCwd;if(!e)return;let t=new AbortController;return ef("validating"),em(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);nB.current=!0;let r=`initial:${e}`;eu(r),eh.current=`new:${r}:${n.cwd}`,ed(n.cwd),ef("ready")}).catch(e=>{t.signal.aborted||(em(e instanceof Error?e.message:String(e)),ef("error"))}),()=>t.abort()},[N]);let nF=(0,i.useCallback)((e,t,n)=>{let r=el??nR;if(n$(e),!e)return;let i=n??t??e,o=nH.current??(F?f(F):null);if(nH.current=i,nB.current){nB.current=!1;return}if(r===e&&o!==i||void 0!==eM&&eM.current?.length>0||o===i&&(null!==F||r===e))return;let s=eh.current;s&&r&&eF(s,l9(r));let l="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${l}:${e}`;eF(l9(e),a),eu(l),eh.current=a,O(null),ed(t=>t&&t!==e?null:t),eb(e=>e+1),tM([]),tL(null),tK(null),tJ(null),tZ(!1),nu(null),o!==i&&(nj([]),(!nS||nS.startsWith("file:"))&&(nC(null),td(!1))),C.replace(window.location.pathname,{scroll:!1})},[nR,nS,el,C,F]),nO=(0,i.useCallback)((e,t=!1,n,r,i=!1,o=!1)=>{var s,l;let a,d;eQ(n?{sessionId:e.id,entryId:n,blockIndex:r}:null);let c=eh.current,u=el??(null===F?nR:null);if(c&&u&&!eM.current.some(e=>e.id===`draft:${c}`)&&eF(c,l9(u)),eh.current=null,e.projectKey&&(nH.current=e.projectKey),!t&&F){let t=f(F)===f(e);if(F.id===e.id&&t){i&&eS(t=>i0(t,e.id)),T&&tl(!1);return}}ed(null),"function"==typeof nd&&nd(e.id),O(e);let h=eO.current?eB.current:"primary",g=(s=eM.current,l=e.id,"secondary"===(d=(a=s.find(e=>e.id===l))?iX(a):h)?{splitChatTabId:l,pane:d}:{activeChatTabId:l,pane:d});eS(n=>!o||t||i?(t||i?i2(n,e,h):iQ(n,e,h)).tabs:function(e,t,n,r="primary"){let i=e.findIndex(e=>e.id===n.id),o=p(n);if(i>=0){let t=[...e];return t[i]={...t[i],session:n,title:o,projectKey:n.projectKey??n.cwd},{tabs:t,tabId:n.id}}let s=t?e.findIndex(e=>e.id===t):-1,l=s>=0?e[s]:void 0;if(!l||"session"!==l.kind)return iQ(e,n,r);let a=[...e];return a[s]={...l,id:n.id,title:o,session:n,newSessionCwd:null,newSessionDraftKey:null,projectKey:n.projectKey??n.cwd,mountKey:void 0},{tabs:a,tabId:n.id}}(n,"secondary"===h?eP.current:eR.current,e,h).tabs),void 0!==g.activeChatTabId&&eL(g.activeChatTabId),void 0!==g.splitChatTabId&&eW(g.splitChatTabId),eH(g.pane),eb(e=>e+1),tM([]),tL(null),tD.current=null,tK(null),tJ(null),tZ(!1),T&&!t&&tl(!1),t&&(nB.current=!0),t||C.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nR,C,T,el,F,nd]),nU=(0,i.useCallback)((e,t)=>{let n=`new:${e}:${t}`;eF(l9(t),n),eh.current=n,eu(e),O(null),ed(t);{let e=eO.current&&"secondary"===eB.current,r=`draft:${n}`;eS(r=>i4(r,t,n,M("i18n.newSession"),e?"secondary":"primary").tabs),e?eW(r):eL(r)}eb(e=>e+1),tM([]),tL(null),tK(null),tJ(null),tZ(!1),nu(null),T&&tl(!1),C.replace(window.location.pathname,{scroll:!1})},[C,T,M]),n_=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&(O(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t),eS(t=>t.map(t=>t.id===e&&"session"===t.kind?{...t,title:p(n),session:{...t.session,...n}}:t)))}).catch(()=>{})},[]),nq=(0,i.useCallback)(e=>{nO(e,!1,void 0,void 0,!0)},[nO]),nK=(0,i.useCallback)(e=>{nO(e,!1,void 0,void 0,!1,!0)},[nO]),nV=(0,i.useCallback)(async e=>{try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||!n.info)throw Error(n.error??`HTTP ${t.status}`);nq(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[nq]),nJ=(0,i.useCallback)((e,t)=>{ev(e=>e+1),eS(n=>{var r;let i,{tabs:o,newTabId:s}=(r=`draft:${t}`,i=p(e),{tabs:n.map(t=>t.id===r?{...t,id:e.id,kind:"session",title:i,session:e,newSessionCwd:null,newSessionDraftKey:null,projectKey:e.projectKey??e.cwd,mountKey:t.mountKey??t.id}:t),newTabId:e.id});return eL(e=>e===`draft:${t}`?s:e),eW(e=>e===`draft:${t}`?s:e),o}),eh.current===t&&(eh.current=null,ed(null),O(e),n_(e.id),C.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[C,n_]),nY=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&r4({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&nq(e)}})},[nq]),nZ=(0,i.useCallback)((e,t)=>{ev(e=>e+1),O(n=>n?.id===e?{...n,name:t}:n),eS(n=>n.map(n=>n.id===e&&"session"===n.kind?{...n,title:t,session:n.session?{...n.session,name:t}:n.session}:n)),t9(n=>n?.sessionId===e?{...n,sessionName:t}:n)},[]),nX=(0,i.useRef)(void 0),nG=(0,i.useRef)(new Set),nQ=(0,i.useCallback)(e=>{ev(e=>e+1),e2(e=>e+1),F&&n_(F.id);let t=e??F;if(oV()&&t&&t.id&&!t.name&&t.relation?.kind!=="subagent"&&!nG.current.has(t.id)){let e=t.id;setTimeout(()=>{nX.current?.({sessionId:e})},350)}t?.relation?.kind==="subagent"||r0()&&nY({targetSession:t,title:t?.name??M("i18n.sessionComplete"),body:M("i18n.taskFinished"),tag:t?`pi-session-complete:${t.id}`:"pi-session-complete"})},[nY,n_,F,M]),n0=(0,i.useCallback)((e,t)=>{var n;t?.relation?.kind!=="subagent"&&r0()&&(n=H.current,!(!r2(e)||n.has(e.id))&&(n.add(e.id),1)&&nY({targetSession:t,title:M("i18n.attentionNeeded"),body:"custom"===e.method?M("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nY,M]);nX.current=(0,i.useCallback)(async e=>{let t=e?.sessionId;if(t&&!nG.current.has(t)){nG.current.add(t);try{let e=await fetch(`/api/sessions/${encodeURIComponent(t)}/auto-name`,{method:"POST"}),n=await e.json().catch(()=>({}));if(!e.ok||!n.title)throw Error(n.error||`HTTP ${e.status}`);nZ(t,n.title.trim())}catch(e){console.warn("[pi-web] silent auto-name failed:",e instanceof Error?e.message:e)}finally{nG.current.delete(t)}}},[nZ]);let n1=(0,i.useCallback)(()=>{e2(e=>e+1)},[]),n8=(0,i.useCallback)((e,t)=>{let n=eM.current.find(e=>e.id===(t??F?.id)),r=t?n?.session:F,i=eO.current&&n?iX(n):"primary",o={...r??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1},s=!t||ne.current===t;ev(e=>e+1),eS(e=>i2(e,o,i).tabs),n_(e),s&&(eh.current=null,eb(e=>e+1),ed(null),O(o),"secondary"===i?eW(e):eL(e),eH(i),C.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1}))},[n_,C,F]),n5=(0,i.useCallback)(async(e,t,n)=>{eS(e=>i0(e,t));let r=await r7(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(M("chat.quoteForkFailed"));tC({sessionId:r.newSessionId,text:e}),n8(r.newSessionId,t)},[n8,M]),n6=(0,i.useCallback)(e=>{ev(e=>e+1),eS(t=>{if(!t.some(t=>t.id===e))return t;let{tabs:n,nextActiveTabId:r,nextSplitTabId:i}=i8(t,e,eR.current??"",eP.current);if(0===n.length){let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,t=nR?`new:${e}:${nR}`:`draft:${e}`,n=i4([],nR??null,t,M("i18n.newSession"));return eL(n.tabId),eW(null),eH("primary"),O(null),ed(nR??null),C.replace(window.location.pathname,{scroll:!1}),n.tabs}eL(r),eW(i),i||"secondary"!==eB.current||eH("primary");let o="secondary"===eB.current&&i?i:r,s=n.find(e=>e.id===o);return s?.kind==="session"&&s.session?(O(s.session),ed(null),C.replace(`?session=${encodeURIComponent(s.session.id)}`,{scroll:!1})):s?.kind==="draft"&&(O(null),ed(s.newSessionCwd),C.replace(window.location.pathname,{scroll:!1})),n}),ne.current===e&&(tM([]),tL(null),tK(null),tJ(null),tZ(!1),nu(null))},[nR,C,M]),n3=(0,i.useCallback)(e=>{let t=eK.current;if(!t)return;let n=t.getBoundingClientRect();if(n.width<=0)return;let r=l1(n.width);e_(Math.max(r.min,Math.min(r.max,(e-n.left)/n.width)))},[]),n7=(0,i.useCallback)(e=>{e.preventDefault(),eV.current=!0,e.currentTarget.setPointerCapture(e.pointerId),n3(e.clientX)},[n3]),n9=(0,i.useCallback)(e=>{eV.current&&n3(e.clientX)},[n3]),re=(0,i.useCallback)(()=>{eV.current=!1},[]),rt=(0,i.useCallback)(e=>{let t=l1(eJ);if("ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let n="ArrowLeft"===e.key?-1:1;e_(e=>Math.max(t.min,Math.min(t.max,e+.05*n)))}else("Home"===e.key||"End"===e.key)&&(e.preventDefault(),e_("Home"===e.key?t.min:t.max))},[eJ]),rn=(0,i.useMemo)(()=>iG(ej,"primary"),[ej]),rr=(0,i.useMemo)(()=>iG(ej,"secondary"),[ej]),ri=(0,i.useMemo)(()=>rn.find(e=>e.id===eT)??rn[0]??null,[rn,eT]),ro=(0,i.useMemo)(()=>e$?ej.find(e=>e.id===e$)??null:null,[ej,e$]),rs=!T&&eJ>=600,rl=!!(rs&&e$&&ro&&eT!==e$);eO.current=rl;let ra=!rl||"primary"===eD,rd=(0,i.useCallback)((e,t)=>{if(eH(t),"session"===e.kind&&e.session){eh.current=null,ne.current!==e.session.id&&(tD.current=null,nd(e.session.id),tK(null),tJ(null),tZ(!1),nu(null)),O(e.session),ed(null),C.replace(`?session=${encodeURIComponent(e.session.id)}`,{scroll:!1});return}eh.current=e.newSessionDraftKey,O(null),ed(e.newSessionCwd),t9(null),nl(null),tM([]),tL(null),tD.current=null,tK(null),tJ(null),tZ(!1),nu(null),C.replace(window.location.pathname,{scroll:!1})},[C,nd]),rc=(0,i.useCallback)(e=>{let t="secondary"===e?ro:ri;t&&rd(t,e)},[rd,ri,ro]);(0,i.useLayoutEffect)(()=>{let e=eK.current;if(!e)return;let t=e=>{if(eY(e),e<600)return;let t=l1(e);e_(e=>Math.max(t.min,Math.min(t.max,e)))};t(e.getBoundingClientRect().width);let n=new ResizeObserver(([e])=>t(e.contentRect.width));return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>{if(!e$||rs)return;let e="secondary"===eD?ro:ri;(eS(t=>i1(t,e?.id??null)),eW(null),e)?(eL(e.id),rd(e,"primary")):eH("primary")},[eD,rs,rd,ri,ro,e$]);let ru=(0,i.useCallback)(e=>{let t=ej.find(t=>t.id===e);t&&(eL(e),rd(t,"primary"))},[ej,rd]),rh=(0,i.useCallback)(e=>{let t=ej.find(t=>t.id===e);t&&(eW(e),rd(t,"secondary"))},[ej,rd]),rp=(0,i.useCallback)(e=>{let t=ej.find(t=>t.id===e);if(!t)return;let n=rl?iX(t):"primary";"secondary"===n?eW(e):eL(e),rd(t,n)},[ej,rd,rl]),rf=(0,i.useCallback)(e=>{let t=eM.current.find(t=>t.id===e);if(t?.kind==="draft"&&t.newSessionDraftKey){let e=ez(t.newSessionDraftKey);if((t.dirty||e&&(e.value.trim()||e.images.length>0))&&!window.confirm(M("chatTabs.discardDraft")))return!1;eA(t.newSessionDraftKey)}return eS(t=>{let{tabs:n,nextActiveTabId:r,nextSplitTabId:i}=i8(t,e,eT??"",e$);if(0===n.length){let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,t=`new:${e}:${nR??""}`;eF(l9(nR??""),t),eh.current=t,eu(e);let n=i4([],nR,t,M("i18n.newSession"));return eL(n.tabId),eW(null),eH("primary"),O(null),ed(nR),C.replace(window.location.pathname,{scroll:!1}),n.tabs}eL(r),eW(i),i||"secondary"!==eD||eH("primary");let o="secondary"===eD&&i?i:r,s=n.find(e=>e.id===o)??n.find(e=>e.id===r);return s?.kind==="session"&&s.session?(O(s.session),ed(null),C.replace(`?session=${encodeURIComponent(s.session.id)}`,{scroll:!1})):s?.kind==="draft"&&(O(null),ed(s.newSessionCwd),C.replace(window.location.pathname,{scroll:!1})),n}),!0},[eD,eT,nR,C,e$,M]),rg=(0,i.useCallback)(e=>{var t;let n=rl&&("secondary"===e||"primary"!==e&&"secondary"===eD),r=((t=n?ro:ri)?"session"===t.kind?t.session?.cwd??null:t.newSessionCwd:null)??nR,i="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,o=`new:${i}:${r??""}`;eF(l9(r??""),o),eh.current=o,eu(i);let{tabs:s,tabId:l}=i4(ej,r,o,M("i18n.newSession"),n?"secondary":"primary");eS(s),n?(eW(l),eH("secondary")):(eL(l),eH("primary")),O(null),ed(r),C.replace(window.location.pathname,{scroll:!1})},[eD,nR,ej,rl,ri,C,ro,M]),rm=(0,i.useCallback)(async(e,t)=>{let n=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await n.json();if(!n.ok||!r.cwd)throw Error(r.error??`HTTP ${n.status}`);let i=r.cwd;e&&eS(t=>t.map(t=>"draft"===t.kind&&t.newSessionDraftKey===e?{...t,newSessionCwd:i,projectKey:i}:t)),e&&eh.current!==e||ed(i),n$(i)},[]),rx=(0,i.useCallback)(()=>{if(e$){let e="secondary"===eD?ro:ri;eS(t=>i1(t,e?.id??null)),eW(null),eH("primary"),e&&(eL(e.id),rd(e,"primary"))}else if(rs){let e=ej.findIndex(e=>e.id===eT),t=ej[e+1]??ej[e-1];if(t)eS(e=>e.map(e=>e.id===t.id?{...e,pane:"secondary"}:e)),eW(t.id),eH("secondary"),"session"===t.kind&&t.session?(O(t.session),ed(null),C.replace(`?session=${encodeURIComponent(t.session.id)}`,{scroll:!1})):"draft"===t.kind&&(O(null),ed(t.newSessionCwd),C.replace(window.location.pathname,{scroll:!1}));else{let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,t=`new:${e}:${nR??""}`;eF(l9(nR??""),t),eh.current=t,eu(e);let{tabs:n,tabId:r}=i4(ej,nR,t,M("i18n.newSession"),"secondary");eS(n),eW(r),eH("secondary"),O(null),ed(nR),C.replace(window.location.pathname,{scroll:!1})}}},[eD,eT,nR,rs,ej,rd,ri,C,ro,e$,M]),rv=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,o=`file:${e}`;nj(s=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,cwd:t.cwd,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,...void 0!==t.page?{pdfPage:t.page}:{},viewerState:t.modeHint?{displayMode:t.modeHint,wrapLines:!1,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=!!(t.cwd&&n.cwd!==t.cwd),o=(t.page??void 0)!==n.pdfPage;return r||i||t.modeHint||o?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e};return r&&(n.sourceSessionId=t.sourceSessionId),i&&(n.cwd=t.cwd),o&&(n.pdfPage=t.page,n.viewerRevision=(e.viewerRevision??0)+1),t.modeHint?(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines??!1,scrollTop:0,scrollLeft:0,loadedBytes:e.viewerState?.loadedBytes,scrollByMode:{...e.viewerState?.scrollByMode,diff:{scrollTop:0,scrollLeft:0}}},n.viewerRevision=(e.viewerRevision??0)+1):(r||i)&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(s,{fileName:t,filePath:e,cwd:n?.cwd??nR??void 0,modeHint:i,sourceSessionId:r,...n?.page!==void 0?{page:n.page}:{},tabId:o})),nC(o),td(!0),T&&tl(!1)},[nR,T]),ry=(0,i.useCallback)((e,t,n)=>{let r=t?eM.current.find(e=>e.id===t)?.session?.cwd:void 0;rv(e,S(e),{sourceSessionId:t,cwd:r,...void 0!==n?{page:n}:{}})},[rv]),rb=(0,i.useCallback)(e=>{let t=nE.find(t=>t.cwd===e),n=t??lQ(e);t||nN(e=>[...e,n]),nC(n.id),td(!0),T&&tl(!1)},[nE,T]),rw=(0,i.useCallback)(e=>{if(nE.some(t=>t.id===e))return void nN(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));let t=oP(nT,e);nj(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nE.length&&td(!1),n}),nC(n=>n!==e?n:t)},[nT,nE]),rk=(0,i.useCallback)(()=>{F&&window.open(`/api/sessions/${encodeURIComponent(F.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[F]);(0,i.useEffect)(()=>{if(F)eS(e=>e.some(e=>e.id===F.id)?e:i2(e,F).tabs),eL(e=>e??F.id);else if(el){let e=eh.current??ec;eS(t=>{let n=`draft:${e}`;return t.some(e=>e.id===n)?t:i4(t,el,e,M("i18n.newSession")).tabs}),eL(e=>e??`draft:${eh.current??ec}`)}},[el,ec,F,M]);let rj=(0,i.useCallback)(e=>{eS(t=>i0(t,e))},[]),rS=(e,t,n,i,o,s)=>{let l=e?ei.has(e.id):!!(F&&ei.has(F.id));return(0,r.jsx)(i_,{session:e,searchTarget:i&&eG?.sessionId===e?.id?eG:null,onSearchTargetHandled:e0,initialScrollPosition:e?ew.current.get(e.id)??null:null,onScrollPositionChange:ek,sessionRunning:l,newSessionCwd:t,newSessionDraftKey:n,onDraftChange:eZ,onKeepTabOpen:rj,onNewSessionCwdChange:!e&&t?e=>rm(n,e):void 0,recentProjectPaths:K,pinnedCwds:V,onTogglePinnedCwd:Y,homeDir:Z,worktreeInfo:Q,draftPersistenceWarning:eN,onAgentEnd:nQ,onAttentionNeeded:n0,onSessionCreated:nJ,onSessionForked:n8,modelsRefreshKey:e5,chatInputRef:i?tj:void 0,isFocusedPane:i,isVisiblePane:s,onBranchDataChange:i?tU:void 0,onSystemPromptChange:i?t5:void 0,onSystemToolsChange:i?t6:void 0,onSystemInfoLoaderChange:i?t3:void 0,onSessionStatsChange:i?nt:void 0,onSessionStatsPanelOpen:nx,onContextUsageChange:i?na:void 0,onOpenFile:ry,onOpenSession:nV,onAskInNewChat:n5,quoteSelectionEnabled:P,initialPrompt:tS?.sessionId===e?.id?tS?.text:void 0,onInitialPromptConsumed:tE,soundEnabled:L,onSoundToggle:R,playDoneSound:$,unlockAudio:W},o??ey)},rC=(0,i.useCallback)(e=>{e&&nu(null),t$(e),e||tA(null)},[]),rE=(0,i.useCallback)(async()=>{if(F){tA(null),tz(!0);try{let e=new URLSearchParams({format:"md"});tT&&e.set("leafId",tT),e.set("tz",String(-new Date().getTimezoneOffset()));let t=await fetch(`/api/sessions/${encodeURIComponent(F.id)}/export?${e}`);if(!t.ok){let e=await t.json().catch(()=>null);tA(e?.error==="empty"?M("history.exportEmpty"):M("history.exportFailed"));return}let n=await t.blob(),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=function(e){if(!e)return null;let t=/filename\*=UTF-8''([^;]+)/i.exec(e);if(t?.[1])try{return decodeURIComponent(t[1])}catch{return t[1]}return/filename="([^"]+)"/i.exec(e)?.[1]??null}(t.headers.get("Content-Disposition"))??"session.md",document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r),t$(!1)}catch{tA(M("history.exportFailed"))}finally{tz(!1)}}},[tT,F,M]),rN=el??(null===F&&nR?nR:null),rI=null===F&&rN?`new:${ec}:${rN}`:null,rM=rl&&"secondary"===eD?ro:ri,rT=rM?.kind==="draft"?rM.newSessionDraftKey:0===ej.length?rI:null;(0,i.useLayoutEffect)(()=>{eh.current=rT},[rT]);let rL=null!==F||null!==rN,rR=!!(F&&t7?.sessionId===F.id),r$=F?.cwd??rN;(0,i.useEffect)(()=>{if(e7(null),te(!1),to(null),!r$)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(r$)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e7(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[r$]);let rW=(0,i.useCallback)(async()=>{if(r$&&!tt){tn(!0),to(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r$})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e7(t),te(!1),e6(e=>e+1),eb(e=>e+1)}catch(e){to(e instanceof Error?e.message:String(e))}finally{tn(!1)}}},[tt,r$]),rz=nk.find(e=>e.id===nS)??null,rP=nR?S(nR)||nR:null,rA=rP?`${rP} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rA&&(document.title=rA)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rA]);let rD=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ea,{selectedSessionId:F?.id??null,onPinSession:nq,onSelectSession:nO,onOpenSessionInNewTab:nq,onNewSession:nU,initialSessionId:nD,skipInitialProjectSelection:null!==N.requestedCwd,refreshKey:ex,onSessionDeleted:n6,selectedCwd:nR??F?.cwd??el??null,onCwdChange:nF,onOpenFile:rv,onOpenTerminal:rb,explorerRefreshKey:e1,onExplorerRefresh:n1,onAtMention:nz,onAtMentions:nP,onBackgroundTaskDone:B,onRunningSessionIdsChange:es,onSessionsChange:q,pinnedCwds:V,onTogglePinnedCwd:Y,onHomeDirChange:G,onWorktreeInfoChange:ee}),(0,r.jsx)("div",{className:"sidebar-footer",children:(0,r.jsxs)("button",{type:"button",onClick:()=>e8(function(e,t=oB()){if(!t)return"general";try{let n=oF(t).section;if(!("string"==typeof n&&oA.includes(n)))return"general";return oH.has(n)&&!e?"general":n}catch{return"general"}}(r$)),title:M("common.settings"),"aria-label":M("common.settings"),className:"sidebar-footer-item",children:[(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(ae,{size:13})}),(0,r.jsx)("span",{children:M("common.settings")})]})})]}),rH=e=>rL&&e3?.requiresTrust&&!e3.trusted?(0,r.jsxs)("button",{type:"button",onClick:()=>{to(null),te(!0)},title:M("trust.resourcesNotLoaded"),"aria-label":M("trust.resourcesNotLoaded"),style:{display:"flex",alignItems:"center",justifyContent:e?"flex-start":"center",gap:6,width:e?"100%":void 0,minHeight:e?32:void 0,height:e?void 0:"100%",padding:e?"6px 12px":"0 12px",background:e?"color-mix(in srgb, #d97706 8%, var(--bg-panel))":"none",border:"none",borderRight:e?"none":"1px solid var(--border)",borderBottom:e?"1px solid var(--border)":"none",color:"#d97706",cursor:"pointer",flexShrink:0,fontSize:11,lineHeight:e?1.35:void 0,textAlign:"left"},className:e?void 0:"workspace-header-action","data-mobile-trust-banner":e?"true":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:M("trust.resourcesNotLoaded")})]}):null,rB=(e,t)=>{let n=t?.sessionTools??!0;return(e||rL)&&(e||n||er)?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[er&&F?.relation?.kind==="subagent"&&(0,r.jsx)("button",{type:"button",onClick:()=>nK(en.root),title:M("agentSwitcher.backToMain"),"aria-label":M("agentSwitcher.backToMain"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M19 12H5"}),(0,r.jsx)("path",{d:"m12 19-7-7 7-7"})]})}),er&&(0,r.jsxs)("button",{ref:e?void 0:t2,type:"button",onClick:e=>{t4.current=e.currentTarget,ng("agents")},title:M("agentSwitcher.title"),"aria-label":M("agentSwitcher.title"),"aria-pressed":"agents"===nc,"aria-expanded":"agents"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"agents",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"agents"===nc?"var(--bg-selected)":"none",border:"none",color:"agents"===nc?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},className:"workspace-header-action","data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsx)(X,{size:13,strokeWidth:1.9}),(0,r.jsx)("span",{"aria-hidden":"true",style:{position:"absolute",top:2,right:2,minWidth:13,height:13,padding:"0 3px",display:"grid",placeItems:"center",borderRadius:4,background:"var(--bg-selected)",color:"var(--accent)",fontSize:9,lineHeight:1,fontVariantNumeric:"tabular-nums"},children:en.subagents.length})]}),n&&(e?tH&&(0,r.jsx)("button",{type:"button",onClick:()=>ng("branches"),title:M("i18n.branches"),"aria-label":M("i18n.branches"),"aria-pressed":"branches"===nc,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"branches"===nc?"var(--bg-selected)":"none",border:"none",color:"branches"===nc?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action","data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tI.length>0?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}):(0,r.jsx)(lz,{tree:tI,activeLeafId:tT,onLeafChange:t_,inline:!0,compact:!0,containerRef:tN,open:"branches"===nc,onToggle:()=>ng("branches"),disabled:!tH,hasSession:!0})),n&&(0,r.jsx)(lP,{mobile:e,disabled:!F,menuOpen:tR,exporting:tW,error:tP,labels:{full:M("history.full"),unsaved:M("history.unsaved"),menu:M("history.menu"),exportMarkdown:M("history.exportMarkdown"),exportMarkdownTitle:M("history.exportMarkdownTitle")},onMenuOpenChange:e=>{rC(e)},onViewFullHistory:()=>{rk()},onExportMarkdown:()=>{rE()}}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:tQ,type:"button",onClick:()=>nm("system"),disabled:e&&!rL,title:M("system.prompt"),"aria-label":M("system.prompt"),"aria-pressed":"system"===nc,"aria-expanded":"system"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"system",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"system"===nc?"var(--bg-selected)":"none",border:"none",cursor:e&&!rL?"not-allowed":"pointer",color:"system"===nc?"var(--text)":"var(--text-muted)",opacity:e&&!rL?.45:1,transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rL)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===nc?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":e?"system":void 0,children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,r.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>nm("tools"),disabled:e&&!rL,title:M("tools.title"),"aria-label":M("tools.title"),"aria-pressed":"tools"===nc,"aria-expanded":"tools"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"tools",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"tools"===nc?"var(--bg-selected)":"none",border:"none",cursor:e&&!rL?"not-allowed":"pointer",color:"tools"===nc?"var(--text)":"var(--text-muted)",opacity:e&&!rL?.45:1,transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rL)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===nc?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":e?"tools":void 0,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"})})}),n&&e&&(0,r.jsx)("button",{type:"button",onClick:()=>window.dispatchEvent(new CustomEvent("pi-toggle-outline")),title:M("chatMinimap.userOutline")||"Outline","aria-label":M("chatMinimap.userOutline")||"Outline",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action","data-mobile-toolbar-action":"outline",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),(0,r.jsx)("line",{x1:"4",y1:"12",x2:"14",y2:"12"}),(0,r.jsx)("line",{x1:"4",y1:"18",x2:"17",y2:"18"})]})})]})]}):null},rF=F?p(F):M("i18n.newSession"),rO=e=>{if(!e&&(!rL||!rR))return null;let t=ns??t7?.contextUsage;if(!t7&&(!e||!t))return null;let n=t7?.tokens,i=t7?.cost??0,o=i>=.01?`$${i.toFixed(2)}`:i>0?"<$0.01":"$0.00",s=(n?.cacheRead??0)+(n?.cacheWrite??0)+(n?.input??0),l=s>0?(n?.cacheRead??0)/s*100:null,a=[];if(n&&(a.push(`in: ${n.input.toLocaleString(I)}`),a.push(`out: ${n.output.toLocaleString(I)}`),a.push(`cache read: ${n.cacheRead.toLocaleString(I)}`),a.push(`cache write: ${n.cacheWrite.toLocaleString(I)}`),null!==l&&a.push(`${M("session.cacheHitRate")}: ${l.toFixed(1)}%`),i>0&&a.push(`cost: $${i.toFixed(4)}`)),t?.contextWindow){let e=t.percent;a.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${t.contextWindow.toLocaleString()} tokens`)}let d=a.join(" | ");return(0,r.jsx)("button",{type:"button",onClick:()=>ng("session"),disabled:!rL,title:d||M("session.title"),"aria-label":d||M("session.title"),"aria-pressed":"session"===nc,"aria-expanded":"session"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"session",className:"workspace-header-action","data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:"auto",display:"flex",alignItems:"center",justifyContent:"flex-end",minWidth:0,gap:e?8:10,paddingLeft:e?6:8,paddingRight:e?6:8,height:"100%",overflow:"hidden",background:"session"===nc?"var(--bg-selected)":"none",border:"none",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rL?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rL&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===nc?"var(--text)":"var(--text-muted)"},children:o&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text-muted)",fontWeight:400,flexShrink:0,lineHeight:1},children:o})})},rU=e=>(0,r.jsx)("button",{ref:t1,type:"button",onClick:nb,"aria-controls":"file-panel","aria-expanded":ta,title:ta?M("files.hidePanel"):M("files.showPanel"),"aria-label":ta?M("files.hidePanel"):M("files.showPanel"),className:"workspace-header-action","data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:t7||ns?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:ta?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]}):(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
|
|
202
|
+
@keyframes session-info-pop {
|
|
203
|
+
0% {
|
|
204
|
+
opacity: 0;
|
|
205
|
+
transform: translateY(-8px);
|
|
206
|
+
}
|
|
207
|
+
100% {
|
|
208
|
+
opacity: 1;
|
|
209
|
+
transform: translateY(0);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
.session-info-popover {
|
|
213
|
+
position: relative;
|
|
214
|
+
overflow: hidden;
|
|
215
|
+
animation: session-info-pop 180ms cubic-bezier(0.16, 1, 0.3, 1) both;
|
|
216
|
+
}
|
|
217
|
+
@media (prefers-reduced-motion: reduce) {
|
|
218
|
+
.session-info-popover {
|
|
219
|
+
animation: none;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
@media (max-width: 640px) {
|
|
223
|
+
.sidebar-overlay-backdrop.sidebar-mobile-pending {
|
|
224
|
+
opacity: 0 !important;
|
|
225
|
+
pointer-events: none !important;
|
|
226
|
+
}
|
|
227
|
+
.sidebar-container.sidebar-mobile-pending.sidebar-open {
|
|
228
|
+
transform: translateX(calc(-100% - env(safe-area-inset-left)));
|
|
229
|
+
box-shadow: none;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
`}),(0,r.jsxs)("div",{style:{display:"flex",width:"100%",height:"var(--app-viewport-height, 100dvh)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{className:`sidebar-overlay-backdrop${th?"":" sidebar-mobile-pending"}`,"aria-hidden":"true",onClick:ny,style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!ts,pointerEvents:ts?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:ty.panelRef,id:"session-sidebar",role:"navigation","aria-label":"Pi Web","aria-hidden":!!T&&!ts||void 0,inert:!!T&&!ts||void 0,className:`sidebar-container${ts?" sidebar-open":" sidebar-closed"}${th?"":" sidebar-mobile-pending"}${ty.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${ty.width}px`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)",zIndex:200},children:rD}),ts&&(0,r.jsx)("div",{...ty.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${ty.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${M("layout.resizeSidebar")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tN,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{position:"relative"},children:[(0,r.jsx)("button",{ref:t0,"data-dialog-focus-fallback":"true",className:"workspace-header-action",onClick:nv,title:ts?M("sidebar.hide"):M("sidebar.show"),"aria-label":ts?M("sidebar.hide"):M("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:ts?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),T&&(0,r.jsxs)("div",{"data-mobile-toolbar":"true",style:{display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[rB(!0),rO(!0),rU(!0)]}),!T&&(0,r.jsxs)(r.Fragment,{children:[!rl&&rL&&ej.length>0&&(0,r.jsx)("div",{style:{flex:"0 1 auto",minWidth:0,height:"100%",overflow:"hidden",display:"flex",alignItems:"stretch"},children:(0,r.jsx)(iY,{tabs:ej,activeTabId:eT??"",activePane:"primary",runningSessionIds:ei,onSelectTab:rp,onCloseTab:rf,onPinTab:rj,onNewTab:rg,onToggleSplit:rx,canSplit:rs,unifiedHeader:!0})}),ts||!rL||ej.length>0?null:(0,r.jsx)("button",{type:"button",onClick:()=>ng("session"),title:rF,"aria-label":rF,"aria-pressed":"session"===nc,"aria-expanded":"session"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"session",className:"workspace-header-action","data-collapsed-session-title":"true",style:{display:"flex",alignItems:"center",minWidth:0,flex:1,height:"100%",padding:"0 12px",border:"none",borderRight:"1px solid var(--border)",background:"session"===nc?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",fontSize:12,fontWeight:500,textAlign:"left"},children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:rF})}),(0,r.jsxs)("div",{"data-desktop-header-actions":"true",style:{marginLeft:"auto",display:"flex",alignItems:"stretch",height:"100%",flexShrink:0},children:[rH(!1),rO(!1),rB(!1,{sessionTools:rR})]})]}),!T&&rU(!1),T&&tH&&(0,r.jsx)(lz,{tree:tI,activeLeafId:tT,onLeafChange:t_,inline:!0,compact:!0,containerRef:tN,open:"branches"===nc,onToggle:()=>ng("branches"),hasSession:rL,hideInlineButton:!0}),nc&&nh&&(0,r.jsxs)("div",{ref:t8,id:"workspace-top-panel",role:"region","aria-label":"agents"===nc?M("agentSwitcher.title"):"system"===nc?M("system.prompt"):"tools"===nc?M("tools.title"):M("session.title"),style:{position:"fixed",top:nh.top,left:nh.left,width:nh.width,maxHeight:`calc(100dvh - ${nh.top}px - 16px)`,overflowY:"agents"===nc?"visible":"auto",zIndex:520},children:["agents"===nc&&en&&F&&(0,r.jsx)(lV,{rootSession:en.root,subagents:en.subagents,selectedSessionId:F.id,runningSessionIds:ei,onSelectSession:nK,onOpenInNewTab:nq}),"system"===nc&&(0,r.jsx)(lD,{loading:tY,prompt:tq,translate:M}),"tools"===nc&&(0,r.jsx)(lF,{loading:tY,tools:tV,translate:M}),"session"===nc&&(0,r.jsxs)("div",{className:"session-info-popover",style:{position:"relative",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 8px 24px rgba(0,0,0,0.08)",padding:T?"12px 14px":"14px 20px"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:10,right:12,zIndex:2},children:(0,r.jsx)("button",{type:"button",onClick:()=>nf(!0),title:M("i18n.close"),"aria-label":M("i18n.close"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:"transparent",border:"none",borderRadius:4,color:"var(--text-dim)",cursor:"pointer",transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="transparent"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}),t7?(t=t7.totalActiveMs??0,n={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},l=(e,t)=>{let i=nn===e;return(0,r.jsx)("button",{type:"button",title:i?M("session.copied"):M(n[e]),onClick:()=>no(e,t),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:20,height:20,color:i?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=i?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:i?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})},a=ns??t7.contextUsage,c=null!==(d=a?.percent??(a?.tokens!==null&&a?.contextWindow?a.tokens/a.contextWindow*100:null))?Math.min(100,Math.max(0,d)):0,u=null!==d&&d>=85,h=null!==d&&d>=70&&d<85,m=a?.tokens!==null&&a?.contextWindow?Math.max(0,a.contextWindow-a.tokens):null,x=a?.contextWindow?(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)("span",{children:M("session.activeContext")}),null!==d&&(0,r.jsxs)("span",{style:{fontSize:11,fontWeight:650,color:u?"#ef4444":h?"rgba(234,179,8,0.95)":"var(--accent)"},children:[d.toFixed(1),"%"]})]}),(0,r.jsx)("div",{style:{width:"100%",height:5,borderRadius:3,background:"var(--border)",overflow:"hidden",marginBottom:8},children:(0,r.jsx)("div",{style:{width:`${c}%`,height:"100%",background:u?"#ef4444":h?"#eab308":"var(--accent)",borderRadius:3,transition:"width 0.3s ease"}})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"max-content max-content",columnGap:14,rowGap:4,justifyContent:"start",fontSize:11.5},children:[null!==a.tokens&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.contextUsed")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:ti(a.tokens,I)})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.contextWindow")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:ti(a.contextWindow,I)}),null!==m&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.contextRemaining")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:ti(m,I)})]})]}),u&&(0,r.jsxs)("div",{style:{marginTop:6,fontSize:11,color:"#ef4444",display:"flex",alignItems:"center",gap:4},children:[(0,r.jsx)("span",{children:"⚠️"}),(0,r.jsx)("span",{children:M("chat.contextHighWarning")})]})]}):null,y=(v=t7.tokens.cacheRead+t7.tokens.cacheWrite)+t7.tokens.input>0?`${(t7.tokens.cacheRead/(v+t7.tokens.input)*100).toFixed(1)}%`:null,b=(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)("span",{children:M("session.cumulativeTokens")}),t7.cost>0&&(0,r.jsxs)("span",{style:{fontSize:11,fontWeight:650,color:"var(--text)"},children:["$",t7.cost.toFixed(4)]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"max-content max-content",columnGap:14,rowGap:4,justifyContent:"start",fontSize:11.5},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.total")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:ti(t7.tokens.total,I)}),(0,r.jsxs)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:[M("session.input")," / ",M("session.output")]}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:[ti(t7.tokens.input,I)," / ",ti(t7.tokens.output,I)]}),t7.tokens.cacheRead>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.cacheRead")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:ti(t7.tokens.cacheRead,I)})]}),y&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.cacheHitRate")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:y})]})]})]}),j=(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:"column"},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:M("session.infoSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5,fontSize:11.5},children:[t7.sessionName&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.name"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text)",fontWeight:550,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t7.sessionName})]}),F&&(k=Z&&F.cwd.startsWith(Z)?`~${F.cwd.slice(Z.length)}`:F.cwd,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.directory"),":"]}),(0,r.jsx)("span",{title:F.cwd,style:{color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:k})}),F.branch&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:["\xb7 ",F.branch]}),l(F.isWorktree?"gitWorktree":"projectDir",F.cwd)]})),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.messages"),":"]}),(0,r.jsxs)("span",{style:{color:"var(--text-muted)",whiteSpace:"nowrap"},children:[t7.userMessages," ",M("session.user").toLowerCase()," \xb7 ",t7.assistantMessages," ",M("session.assistant").toLowerCase()," \xb7 ",t7.toolCalls," ",M("session.toolCalls").toLowerCase(),t>0?` (${(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`})(t)})`:""]})]}),t7.sessionFile&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.file"),":"]}),(0,r.jsx)("span",{title:t7.sessionFile,style:{color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:t7.sessionFile})}),l("file",t7.sessionFile)]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.id"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:t7.sessionId?`${t7.sessionId.slice(0,8)}...${t7.sessionId.slice(-6)}`:"?"}),t7.sessionId&&l("id",t7.sessionId)]})]})]}),(0,r.jsxs)("div",{className:"session-stats-grid",style:{fontFamily:"var(--font-mono)",lineHeight:1.45},children:[x,b,j]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:M("session.load")})]})]})]}),T&&rL&&ej.length>1&&(0,r.jsx)("div",{"data-mobile-chat-tabs":"true",style:{borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",height:"var(--workspace-header-height, 30px)",minHeight:"var(--workspace-header-height, 30px)",width:"100%",maxWidth:"100%",minWidth:0,overflow:"hidden",display:"flex",alignItems:"stretch"},children:(0,r.jsx)(iY,{tabs:ej,activeTabId:eT??"",activePane:"primary",runningSessionIds:ei,onSelectTab:rp,onCloseTab:rf,onPinTab:rj,onNewTab:rg,canSplit:!1,isMobile:!0})}),T&&rH(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative",display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{ref:eK,style:{flex:1,overflow:"hidden",position:"relative",display:"grid",minHeight:0,gridTemplateColumns:rl?`${100*eU}% 0 minmax(0, 1fr)`:"minmax(0, 1fr)",gridTemplateRows:rl?"auto minmax(0, 1fr)":"minmax(0, 1fr)"},children:rL?(0,r.jsxs)(r.Fragment,{children:[rl&&(0,r.jsx)("div",{style:{gridColumn:1,gridRow:1,minWidth:0,overflow:"hidden"},onPointerDownCapture:()=>rc("primary"),children:(0,r.jsx)(iY,{tabs:rn,activeTabId:eT??"",activePane:"primary"===eD?"primary":"secondary",runningSessionIds:ei,onSelectTab:ru,onCloseTab:rf,onPinTab:rj,onNewTab:()=>rg("primary"),onToggleSplit:rx,canSplit:!1})}),ej.length>0?ej.map(e=>{let t=rl?iX(e):"primary",n=e.id===("secondary"===t?e$:eT),i="secondary"===t?"secondary"===eD:ra,o=e.mountKey??e.id;return(0,r.jsx)("div",{"data-chat-pane":t,onPointerDownCapture:()=>{n&&rl&&rc(t)},style:{gridColumn:"secondary"===t?3:1,gridRow:rl?2:1,display:n?"flex":"none",flexDirection:"column",minWidth:0,minHeight:0,overflow:"hidden",position:"relative",borderLeft:"secondary"===t?"1px solid var(--border)":void 0},children:rS("session"===e.kind?e.session:null,"draft"===e.kind?e.newSessionCwd:null,"draft"===e.kind?e.newSessionDraftKey:null,n&&i,o,n)},o)}):(0,r.jsx)("div",{style:{gridColumn:1,gridRow:rl?2:1,minHeight:0,display:"flex",flexDirection:"column"},children:rS(F,rN,rI,ra,void 0,!0)}),rl&&(0,r.jsx)("div",{className:"split-chat-resize-handle",style:{gridColumn:2,gridRow:"1 / 3"},role:"separator","aria-orientation":"vertical","aria-valuemin":Math.round(100*l1(eJ).min),"aria-valuemax":Math.round(100*l1(eJ).max),"aria-valuenow":Math.round(100*eU),tabIndex:0,title:M("chatTabs.splitView",{defaultValue:"调整分屏大小"}),onPointerDown:n7,onPointerMove:n9,onPointerUp:re,onPointerCancel:re,onKeyDown:rt,onDoubleClick:()=>e_(.5)}),rl&&ro&&(0,r.jsx)("div",{style:{gridColumn:3,gridRow:1,minWidth:0,overflow:"hidden",borderLeft:"1px solid var(--border)"},onPointerDownCapture:()=>rc("secondary"),children:(0,r.jsx)(iY,{tabs:rr,activeTabId:e$??"",activePane:"secondary"===eD?"primary":"secondary",runningSessionIds:ei,onSelectTab:rh,onCloseTab:rf,onPinTab:rj,onNewTab:()=>rg("secondary"),onClosePane:rx,isSecondaryPane:!0})})]}):"validating"===ep?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:M("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:N.requestedCwd})]}):"error"===ep?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"#dc2626"},children:M("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:N.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eg})]}):null})})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${ta?" is-open":""}`,onClick:()=>nw(!0)}),ta&&(0,r.jsx)("div",{...tb.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tb.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${M("layout.resizeFilePanel")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tb.panelRef,id:"file-panel","aria-hidden":!ta,inert:!ta||void 0,className:`right-panel-container${ta?" right-panel-open":" right-panel-closed"}${tb.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tb.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,height:"100%",overflow:"hidden"},children:(0,r.jsx)(oz,{tabs:nT,activeTabId:nS??"",onSelectTab:nC,onCloseTab:rw})}),(0,r.jsx)("button",{type:"button",onClick:()=>nw(!0),className:"workspace-header-action right-panel-header-close","aria-controls":"file-panel",title:M("files.hidePanel"),"aria-label":M("files.hidePanel"),style:{alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflow:"hidden",paddingBottom:"env(safe-area-inset-bottom)"},children:[rz?.filePath?(0,r.jsx)(oT,{filePath:rz.filePath,cwd:rz.cwd??nR??void 0,sourceSessionId:rz.sourceSessionId,gitRefreshKey:e1,initialDisplayMode:rz.initialDisplayMode,initialState:rz.viewerState,watchEnabled:tc,pdfPage:rz.pdfPage,onStateChange:e=>nL(rz.id,rz.viewerRevision??0,e),onMentionLines:ta?nA:void 0,onAtMention:nz,onOpenFile:e=>rv(e,S(e),{sourceSessionId:rz.sourceSessionId,cwd:rz.cwd})},`${rz.id}:${rz.viewerRevision??0}`):nE.some(e=>e.id===nS)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:M("files.noneOpen")}),nE.map(e=>(0,r.jsx)("div",{hidden:e.id!==nS,style:{width:"100%",height:"100%"},children:(0,r.jsx)(lX,{tab:e,active:ta&&e.id===nS,onRestart:()=>nN(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n,r;return t="restart"===e.closing?lQ(e.cwd):null,n=nE.filter(t=>t.id!==e.id),r=oP(nT,e.id),void(nN(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nC(n=>n!==e.id?n:t?.id??r),!t&&!n.length&&!nk.length&&td(!1))},onCloseError:()=>nN(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),e4&&(0,r.jsx)(lM,{cwd:r$,sessionId:F?.id??null,initialSection:e4,quoteSelectionEnabled:P,onQuoteSelectionChange:D,onClose:()=>{e8(null),e6(e=>e+1)},onSessionReloaded:()=>eb(e=>e+1),onModelsChanged:()=>e6(e=>e+1)}),e9&&r$&&(0,r.jsx)(lT,{cwd:r$,busy:tt,error:tr,onCancel:()=>{tt||te(!1)},onConfirm:()=>void rW()})]})}},78709:(e,t,n)=>{Promise.resolve().then(n.bind(n,61795)),Promise.resolve().then(n.bind(n,21278))},88576:e=>{e.exports={minimap:"ChatMinimap_minimap__gDaeY",trigger:"ChatMinimap_trigger__Wb5KU",marker:"ChatMinimap_marker__NEjJc",panel:"ChatMinimap_panel__bAkor",menu:"ChatMinimap_menu__7Cur1",minimapFadeIn:"ChatMinimap_minimapFadeIn__XXu75",list:"ChatMinimap_list__g9HUb",track:"ChatMinimap_track__ZlbIX",row:"ChatMinimap_row__LGVWw",rowText:"ChatMinimap_rowText__bagDa",status:"ChatMinimap_status__U2inN"}}},e=>{e.O(0,[7523,7330,3888,5931,1278,8441,3794,7358],()=>e(e.s=78709)),_N_E=e.O()}]);
|