@calmabacus/pi-web 1.1.3 → 1.1.4
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 +8 -8
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- 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 +3 -3
- package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- 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 +1 -1
- 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 +1 -1
- 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/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 +3 -3
- 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 +2 -2
- 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 +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- 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 +4 -4
- package/.next/server/app/login.segments/_full.segment.rsc +4 -4
- package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +4 -4
- 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 +3 -3
- 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 +8 -8
- package/.next/server/chunks/2243.js +1 -1
- package/.next/server/chunks/2265.js +1 -0
- package/.next/server/chunks/2430.js +4 -4
- package/.next/server/chunks/3379.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/middleware.js +3 -3
- 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-12a09a53f2579278.js +1 -0
- package/.next/static/chunks/app/_not-found/page-4bc1de1a9457bf3c.js +1 -0
- package/.next/static/chunks/app/layout-49ccb92d50b20d78.js +1 -0
- package/.next/static/chunks/app/login/{page-4d08a41789f24789.js → page-6d2b7e6521b5b45c.js} +1 -1
- package/.next/static/chunks/app/{page-b56928790db1e7a3.js → page-a41100e64e8c078a.js} +3 -3
- package/.next/static/chunks/main-app-7931444f130b8836.js +1 -0
- package/.next/static/chunks/next/dist/client/components/builtin/global-error-db9c7b142e888d0c.js +1 -0
- package/.next/static/css/0629994cc558abc1.css +1 -0
- package/.next/trace +41 -7
- 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/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/5.js +0 -1
- package/.next/static/chunks/1278-a8c310b2fef0b809.js +0 -1
- package/.next/static/chunks/app/_not-found/page-d1e0360401438077.js +0 -1
- package/.next/static/chunks/app/layout-7ce32d5d7fe19126.js +0 -1
- package/.next/static/chunks/main-app-5f091d229b1e5a0e.js +0 -1
- package/.next/static/chunks/next/dist/client/components/builtin/global-error-ae6c57598b75d8bb.js +0 -1
- package/.next/static/css/a20cec158a3c092e.css +0 -1
- /package/.next/static/{mU_TOmR1S_u5NY5pz8Yvi → l8w6fw-pBYxXr7YG4khwB}/_buildManifest.js +0 -0
- /package/.next/static/{mU_TOmR1S_u5NY5pz8Yvi → l8w6fw-pBYxXr7YG4khwB}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
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?[...l]:"read-only"===e?[...s]:"full"===e?[...d]:[...a]}let l=[],s=["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===[...s].sort().join(",")?"read-only":t===[...a].sort().join(",")?"default":t===[...d].sort().join(",")?"full":"default"}},66582:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>s0});var r=n(95155),i=n(12115),o=n(73321);function l(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,l=null;for(;;){if(n.has(o)){l=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"){l=r.id;break}o=r.relation.parentSessionId}for(let t of e)n.set(t,l)}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 s="pi-web:file-explorer:open";function a(){try{return window.localStorage}catch{return null}}function d(e,t=a()){if(t)try{t.setItem(s,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}))}var x=n(2730),m=n(21278);function y(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function v(e){return y(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function b(e){let t=y(e).replace(/\/+$/,"");return t.split("/").pop()??t}function w(e){let t=y(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 k(e,t){if(!t)return e;let n=y(e),r=y(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function j(e,t){return`${y(e).replace(/\/$/,"")}/${t}`}var S=n(47650);async function C(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 I(){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 E(){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 M({onCancel:e,onSelect:t,initialPath:n,busy:o=!1,error:l}){let{t:s}=(0,m.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(n??""),[x,y]=(0,i.useState)([]),[v,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,T]=(0,i.useState)(!0),L=(0,i.useCallback)(async e=>{T(!0),k(null);try{let t=await C(e),n=t.path??e??"/";u(n),p(t.parentPath??null),g(n),y(t.directories??[]),b(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{T(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),L(n||void 0)},[n,L]);let R=f.trim()!==c,N=!!c&&!R&&!o,$=!!h||/^[a-zA-Z]:[\\/]?$/.test(c);return a?(0,S.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("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:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:o,title:s("i18n.close"),"aria-label":s("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&&L(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 L(h??void 0),disabled:j||!$,title:s("directoryPicker.goToParent"),"aria-label":s("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:s("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:s("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:s("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:s("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 L(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)(E,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void L(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)(I,{}),(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:s("directoryPicker.noSubdirectories")}),(w||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??l})]}),(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:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!N,title:s(R?"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:s(o?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),a):null}function T({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 L({size:e=14,open:t=!1}){return(0,r.jsx)(T,{name:t?"_folder_open":"_folder",size:e})}function R({size:e=14}){return(0,r.jsx)(T,{name:"_file",size:e})}let N={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 $(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)(T,{name:i,size:t});let o=N[n.split(".").pop()??""];return o?(0,r.jsx)(T,{name:o,size:t}):(0,r.jsx)(R,{size:t})}function W({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 z(e){let t=v(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:j(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function P(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 A={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},D={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function H({status:e,t}){return(0,r.jsx)("span",{title:t(A[e.status]),"aria-label":t(A[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:D[e.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:e.code})}function B({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 F({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 O({node:e,depth:t,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p}){let f=s.has(e.fullPath),g=c.has(e.fullPath),x=y(e.fullPath),m=u.get(x),b=e.isDir&&(void 0!==m||h.has(x)),[w,j]=(0,i.useState)(e.children??[]),[S,C]=(0,i.useState)(e.loaded??!1),[I,E]=(0,i.useState)(!1),[M,T]=(0,i.useState)(null),[R,N]=(0,i.useState)(!1),P=(0,i.useCallback)(async(t=!1)=>{if(!S||t){E(!0),T(null);try{let t=await z(e.fullPath);j(t),C(!0)}catch(e){T(e instanceof Error?e.message:String(e))}finally{E(!1)}}},[S,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&f&&S&&P(!0)},[d]);let A=(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&&!S&&P()},[P,S,f]),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:A,onMouseEnter:()=>N(!0),onMouseLeave:()=>N(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:2,paddingLeft:2+14*t,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:R?"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)(W,{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)(L,{size:14,open:f}):$(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"}})}),!R&&!e.isDir&&m&&(0,r.jsx)(H,{status:m,t:p}),!R&&b&&(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"}})}),I&&(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"})}),l&&R&&(0,r.jsxs)("button",{onClick:t=>{t.stopPropagation(),l(k(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)(B,{}),p("files.mention")]}),R&&!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${v(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:[w.map(e=>(0,r.jsx)(O,{node:e,depth:t+1,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p},e.fullPath)),0===w.length&&S&&(0,r.jsx)("div",{style:{paddingLeft:2+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),M&&(0,r.jsx)("button",{type:"button",onClick:()=>void P(!0),title:M,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 U({status:e,cwd:t,onOpenFile:n,t:o}){let[l,s]=(0,i.useState)(!1),a=b(e.filePath),d=k(e.filePath,t);return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,a,{modeHint:"diff",cwd:t}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:l?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)(H,{status:e,t:o}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",opacity:.85,transform:"translateY(0.5px)"},children:$(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 _=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:o,onAtMentions:l,onUploadBusyChange:s,changesCollapsed:a,onChangesCountChange:d,fileSearchOpen:c=!1,onFileSearchOpenChange:u},h){let{t:p}=(0,m.s)(),[f,g]=(0,i.useState)([]),[x,b]=(0,i.useState)(!0),[S,C]=(0,i.useState)(null),[I,E]=(0,i.useState)(new Set),[M,T]=(0,i.useState)(0),[L,R]=(0,i.useState)(new Set),[N,$]=(0,i.useState)([]),[W,A]=(0,i.useState)({additions:0,deletions:0}),[H,_]=(0,i.useState)(null),[q,K]=(0,i.useState)(null),[V,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,el]=(0,i.useState)([]),[es,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),ex=(0,i.useRef)(null),em=`${n??0}:${M}`,ey="idle"!==V,ev=er.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=er.trim();if(!t){el([]),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(em)}`,{signal:n.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>el((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{n.signal.aborted||(el([]),ec(!0))}).finally(()=>{n.signal.aborted||ea(!1)})},150);return()=>{clearTimeout(r),n.abort()}},[e,c,em,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(j(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:j(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(N.map(e=>[y(e.filePath),e])),[N]),ek=(0,i.useMemo)(()=>{let t=new Set,n=y(e).replace(/\/$/,"");for(let e of N){let r=w(y(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=w(r);if(e===r)break;r=e}}return t},[e,N]),ej=(0,i.useCallback)((e,t)=>{E(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&&(R(new Set(n.map(t=>j(e,t)))),T(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 l=new XMLHttpRequest;l.open("POST",`/api/files/${v(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&Z(Math.round(e.loaded/e.total*100))},l.onerror=()=>i(Error("Network error while uploading files")),l.onabort=()=>i(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}r({status:l.status,data:e})},l.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]),eI=(0,i.useCallback)(async t=>{if(0!==t.length&&!ey){ee(null),R(new Set),en(null),G(null),Z(0),J("checking");try{let n=await fetch(`/api/files/${v(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,ey]),eE=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eI(t)},[eI]);(0,i.useImperativeHandle)(h,()=>({openUploadPicker(){ey||ex.current?.click()}}),[ey]),(0,i.useEffect)(()=>{s?.(ey)},[s,ey]),(0,i.useEffect)(()=>()=>s?.(!1),[s]),(0,i.useEffect)(()=>{let t=ef.current!==e;ef.current=e,t&&(E(new Set),R(new Set),ee(null),en(null),G(null)),b(t),C(null);let n=!1;return z(e).then(e=>{n||g(e)}).catch(e=>{n||C(e instanceof Error?e.message:String(e))}).finally(()=>{n||b(!1)}),()=>{n=!0}},[e,n,M]),(0,i.useEffect)(()=>{let t=!1;return eg.current!==e&&(_(null),$([]),A({additions:0,deletions:0})),K(null),P(e).then(n=>{t||($(n.isGitRepository?n.files:[]),A(n.isGitRepository?{additions:n.additions,deletions:n.deletions}:{additions:0,deletions:0}),eg.current=e,_(e))}).catch(e=>{t||K(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e,n,M]),(0,i.useEffect)(()=>{d?.(H===e?N.length:0)},[e,N,H,d]);let eM=ey||null!==et||null!==X||null!==Q,eT=(0,i.useCallback)(()=>{Q&&0!==Q.uploaded.length&&l?.(Q.uploaded.map(t=>k(j(e,t),e)),e)},[e,l,Q]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:ex,type:"file",multiple:!0,hidden:!0,onChange:eE}),eM&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ey&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===V?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"===V?(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"===V&&(0,r.jsxs)("span",{style:{fontSize:10},children:[Y,"%"]})]}),"uploading"===V&&(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)(F,{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&&l&&(0,r.jsxs)("button",{type:"button",onClick:eT,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)(B,{}),p("files.mention")]}),(0,r.jsx)(F,{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"})]})})]}),ev&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[es&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:p("sidebar.searchingFiles")}),!es&&ed&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:p("i18n.networkError")}),!es&&!ed&&0===eo.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:p("sidebar.noMatchingFiles")}),!es&&!ed&&eo.length>0&&(0,r.jsx)("div",{children:eb.map(n=>(0,r.jsx)(O,{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:L,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},`${er}:${n.fullPath}`))})]})]}),q&&(0,r.jsx)("div",{role:"alert",title:q,style:{padding:"6px 12px",fontSize:11,color:"#f87171"},children:p("files.gitStatusFailed")}),!a&&H===e&&N.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":p("files.changeStats",{count:N.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:N.length})}),(0,r.jsxs)("span",{style:{color:D.added,fontFamily:"var(--font-mono)"},children:["+",W.additions]}),(0,r.jsxs)("span",{style:{color:D.deleted,fontFamily:"var(--font-mono)"},children:["-",W.deletions]})]}),N.map(n=>(0,r.jsx)(U,{status:n,cwd:e,onOpenFile:t,t:p},n.filePath))]}),(a||H!==e||0===N.length)&&(!c||!ev)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[x?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):S?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:S}):f.map(n=>(0,r.jsx)(O,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:I,onToggleExpanded:ej,refreshToken:em,highlightedPaths:L,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},n.fullPath)),!x&&!S&&0===f.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:p("files.noFiles")})]})]})});function q({open:e,query:t,refreshKey:n,children:o,selectedSessionId:l,onSelectSession:s}){let{t:a,locale:d}=(0,m.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:()=>s(e,t,n),"aria-current":e.id===l?"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===l?"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,x.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 K({size:e=14,title:t,ariaLabel:n,className:i,style:o}){let l=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:l,height:l},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"live-pulse-beacon-core",style:{width:l,height:l},"aria-hidden":"true"})]})}function V({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 J({onClick:e,title:t,disabled:n,skipHover:i,color:o,background:l="none",marginRight:s,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:s,background:l,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=l)},children:c})}function Y({open:e}){return(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(W,{open:e})})}let Z="pi-web:unread-session-ids",X="pi-web:last-custom-cwd",G="pi-web:workspace-expansion";function Q(){try{let e=window.localStorage.getItem(G);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 ee(){try{return window.localStorage.getItem(X)??""}catch{return""}}function et(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function en({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 er({open:e,children:t,style:n}){let[o,l]=(0,i.useState)(e),[s,a]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(l(!0),a(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>a(!0))})):(a(!1),n=setTimeout(()=>l(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),o)?(0,r.jsx)("div",{style:{...n,opacity:+!!s,transform:s?"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 ei({selectedSessionId:e,onSelectSession:t,onOpenSessionInNewTab:n,onPinSession:o,onNewSession:c,initialSessionId:u,skipInitialProjectSelection:h,refreshKey:p,onSessionDeleted:x,selectedCwd:y,onCwdChange:v,onOpenFile:w,onOpenTerminal:k,explorerRefreshKey:j,onExplorerRefresh:S,onAtMention:C,onAtMentions:I,onBackgroundTaskDone:E,onRunningSessionIdsChange:T,onSessionsChange:L,pinnedCwds:R,onTogglePinnedCwd:N,onHomeDirChange:$,onWorktreeInfoChange:W}){let z,P,A,{t:D}=(0,m.s)(),[H,B]=(0,i.useState)([]),[F,O]=(0,i.useState)(null),U=(0,i.useRef)(null),V=(0,i.useRef)(0),[eo,el]=(0,i.useState)(!0),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[eh,ep]=(0,i.useState)(""),[ef,eg]=(0,i.useState)(!1),[ex,em]=(0,i.useState)(""),[ey,ev]=(0,i.useState)(!1),[eb,ew]=(0,i.useState)(ee),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(!1),[eI,eE]=(0,i.useState)(null),eM=(0,i.useRef)(null),[eT,eL]=(0,i.useState)(null),[eR,eN]=(0,i.useState)(!1),[e$,eW]=(0,i.useState)(!1),[ez,eP]=(0,i.useState)(""),[eA,eD]=(0,i.useState)(null),[eH,eB]=(0,i.useState)(!1),[eF,eO]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(null),eq=(0,i.useRef)(null),eK=(0,i.useRef)(null),[eV,eJ]=(0,i.useState)(!0),[eY,eZ]=(0,i.useState)(!0),[eX,eG]=(0,i.useState)(Q),[eQ,e0]=(0,i.useState)({}),[e1,e2]=(0,i.useState)(0),[e4,e8]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(""),tt=e3&&!!e9.trim(),[tn,tr]=(0,i.useState)(0),[ti,to]=(0,i.useState)(!0),[tl,ts]=(0,i.useState)(()=>new Set),[ta,td]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(Z);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}})()),tc=(0,i.useRef)(new Set),tu=(0,i.useRef)(new Set),th=(0,i.useRef)(new Set),tp=(0,i.useRef)(!1),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),[tx,tm]=(0,i.useState)(0),[ty,tv]=(0,i.useState)(0),[tb,tw]=(0,i.useState)(null),[tk,tj]=(0,i.useState)(null),[tS,tC]=(0,i.useState)(null),tI=(0,i.useRef)(null),tE=(0,i.useRef)(null),tM=(0,i.useRef)(!1),tT=(0,i.useRef)(null),tL=(0,i.useCallback)(e=>{tj(null),tC(null);let t=e.currentTarget.scrollTop;null==tT.current&&(tT.current=requestAnimationFrame(()=>{tT.current=null,tv(t)}))},[]);(0,i.useEffect)(()=>{if(!tk&&!tS)return;let e=e=>{let t=e.target;t?.closest(".session-row-actions, .workspace-row-action")||(tj(null),tC(null))};return window.addEventListener("pointerdown",e,!0),()=>window.removeEventListener("pointerdown",e,!0)},[tk,tS]);let tR=(0,i.useCallback)((e,t)=>{if(t.target?.closest(".workspace-row-action"))return;let n=t.touches[0];tE.current={x:n.clientX,y:n.clientY},tM.current=!1,tI.current=setTimeout(()=>{tM.current=!0,tC(e),navigator.vibrate?.(15)},400)},[]),tN=(0,i.useCallback)(e=>{if(!tE.current||!tI.current)return;let t=e.touches[0];(Math.abs(t.clientX-tE.current.x)>10||Math.abs(t.clientY-tE.current.y)>10)&&(clearTimeout(tI.current),tI.current=null)},[]),t$=(0,i.useCallback)(()=>{tI.current&&clearTimeout(tI.current),tI.current=null,tE.current=null},[]);(0,i.useLayoutEffect)(()=>{let e=tg.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)tm(t.contentRect.height)});return t.observe(e),tm(e.clientHeight),tv(e.scrollTop),()=>t.disconnect()},[tt]);let tW=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++V.current;try{e&&el(!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;U.current=i.sessionListVersion,O(i.sessionListVersion),B(i.sessions),tp.current||(tu.current=new Set(i.completionNotificationSuppressedSessionIds??[]),ts(new Set(i.runningSessionIds??[])));let o=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));td(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),ed(null)}catch(e){n===V.current&&ed(String(e))}finally{n===V.current&&el(!1)}},[]),tz=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tz.current;tz.current=!0,tW(e,!e)},[tW,p]),(0,i.useEffect)(()=>{eJ(function(e=a()){if(!e)return!0;try{return"false"!==e.getItem(s)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===ta.size?window.localStorage.removeItem(Z):window.localStorage.setItem(Z,JSON.stringify([...ta]))}catch{}},[ta]),(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;tp.current=!0,tu.current=new Set(r.completionNotificationSuppressedSessionIds??[]),ts(new Set(r.runningSessionIds??[])),r.sessionListVersion!==U.current&&await tW()}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)}},[tW]),(0,i.useEffect)(()=>{T?.(tl)},[T,tl]),(0,i.useEffect)(()=>{L?.(H)},[H,L]),(0,i.useEffect)(()=>{let t=tc.current,n=[...t].filter(t=>!tl.has(t)&&t!==e),r=new Set(H.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!th.current.has(e)&&!r.has(e)),o=[...tl].filter(e=>!t.has(e));(i.length>0||o.length>0)&&td(e=>{let t=new Set(e);return tl.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let l=o.some(e=>!H.some(t=>t.id===e));(n.length>0||l)&&tW(!1,!0),i.length>0&&E?.(i),tc.current=tl,th.current=new Set([...tl].filter(e=>tu.current.has(e)||r.has(e)))},[tl,e,H,tW,E]),(0,i.useEffect)(()=>{e&&td(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==j&&e2(e=>e+1)},[j]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&ep(e.home)}).catch(()=>{})},[]),(0,i.useEffect)(()=>{eh&&$?.(eh)},[eh,$]);let tP=(0,i.useRef)(!1),tA=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tD=(0,i.useCallback)(e=>{if(!e)return null;if(eI?.cwd===e)return tA(eI.root,eI.key);if(eT&&eT.forCwd===e||eT?.worktrees.some(t=>t.path===e))return tA(eT.projectRoot,eT.projectKey);let t=H.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tA(t.projectRoot??t.cwd,f(t)):tA(e,e)},[eI,eT,H,tA]),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tD(ec),t=tH.current;(t?.cwd!==ec||t.key!==(e?.key??null))&&(tH.current={cwd:ec,key:e?.key??null},v?.(ec,e?.root??null,e?.key??null))},[ec,v,tD]);let tB=(0,i.useRef)(null);(0,i.useEffect)(()=>{y&&y!==tB.current&&(tB.current=y,eu(y))},[y]);let[tF,tO]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!ec){eL(null),e_(null);return}let e=!1;return e_(ec),fetch(`/api/worktrees?cwd=${encodeURIComponent(ec)}`).then(e=>e.json()).then(t=>{if(!e){if(e_(null),t.error||!t.projectRoot)return void eL(null);eL({forCwd:ec,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||(e_(null),eL(null))}),()=>{e=!0}},[ec,tF,p]),(0,i.useEffect)(()=>{if(W){if(!eT?.isGit)return void W(null);W({forCwd:eT.forCwd,projectRoot:eT.projectRoot,currentWorktreePath:eT.currentWorktreePath,worktrees:eT.worktrees})}},[eT,W]),(0,i.useEffect)(()=>{if(0!==H.length&&!h&&null===ec){if(u&&!tP.current){tP.current=!0;let e=H.find(e=>e.id===u);if(e){eu(e.cwd),t(e,!0);return}}let e=g(H);e.length>0&&eu(e[0].root)}},[H,ec,u,h,t]);let tU=eT?eT.worktrees.find(e=>e.path===ec)??(eT.forCwd===ec&&eT.currentWorktreePath?eT.worktrees.find(e=>e.path===eT.currentWorktreePath):void 0)??eT.worktrees.find(e=>e.isMain):void 0,t_=tU?.path??null,tq=(0,i.useCallback)(async e=>{let t=(e??eb).trim();if(t&&!eS){eC(!0),ej(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 ej(r.error??`HTTP ${e.status}`);eE({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(X,n)}catch{}ew(r.cwd),R.includes(r.projectRoot)||N(r.projectRoot),eG(e=>new Set([...e??[],r.projectKey])),eu(r.cwd),ev(!1),eg(!1)}catch(e){ej(e instanceof Error?e.message:String(e))}finally{eC(!1)}}},[eb,eS,N,R]),tK=(0,i.useCallback)(()=>{ev(!0),ej(null),eg(!1)},[]),tV=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(R.includes(t.cwd)||N(t.cwd),eG(e=>new Set([...e??[],t.cwd])),eu(t.cwd),ev(!1),ej(null),eg(!1))}catch{}},[N,R]),tJ=(0,i.useCallback)(async()=>{let e=ez.trim();if(e&&!eH&&eT){eB(!0),eD(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eT.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eD(n.error??`HTTP ${t.status}`);eW(!1),eP(""),eN(!1),eL(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),eu(n.path),tO(e=>e+1)}catch(e){eD(e instanceof Error?e.message:String(e))}finally{eB(!1)}}},[ez,eH,eT]),tY=(0,i.useCallback)(async(e,t)=>{if(eT&&!eH){eB(!0),eD(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eT.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eO(e);eD(r.error??`HTTP ${n.status}`);return}eO(null),t_===e&&eu(eT.projectRoot),tO(e=>e+1)}catch(e){eD(e instanceof Error?e.message:String(e))}finally{eB(!1)}}},[eT,eH,t_]);(0,i.useEffect)(()=>{let e=e=>{eM.current&&!eM.current.contains(e.target)&&eg(!1),eq.current&&!eq.current.contains(e.target)&&(eN(!1),eW(!1),eP(""),eD(null),eO(null),em(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tZ=(0,i.useCallback)((e,n,r)=>{B(t=>t.some(t=>t.id===e.id)?t:[e,...t]),eG(t=>{let n=new Set(t??[]);return n.add(f(e)),n});let i=tD(ec)?.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:ec,sessionProjectKey:f(e),selectedProjectKey:i,worktrees:eT?.worktrees})&&eu(e.cwd),t(e,!1,n,r)},[t,tD,ec,eT]),tX=(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]),tG=(0,i.useMemo)(()=>g(H),[H]),tQ=!ec&&!eo&&!ea&&0===tG.length,t0=(0,i.useMemo)(()=>tD(ec),[tD,ec]),t1=(0,i.useMemo)(()=>{let e=[],t=new Set,n=n=>{!n||t.has(n.key)||(t.add(n.key),e.push(n))};return R.forEach(e=>n(tD(e))),tG.forEach(n),n(t0),e},[R,tD,tG,t0]),t2=(0,i.useMemo)(()=>{let t;return e?t=t0?.key:1===t1.length&&(t=t1[0]?.key),new Set(t?[t]:[])},[t0?.key,e,t1]);(0,i.useEffect)(()=>{null===eX&&0!==t1.length&&eG(t2)},[t2,eX,t1.length]),(0,i.useEffect)(()=>{null!==eX&&function(e){try{window.localStorage.setItem(G,JSON.stringify([...e]))}catch{}}(eX)},[eX]);let t4=(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})(H,tl,ta),[H,tl,ta]),t8=!!(eT?.isGit&&eT.isTopLevel&&ec&&t0?.key===eT.projectKey),t5=(0,i.useMemo)(()=>{let t=[],n=eX??t2;for(let r of t1){let i=l(function(e,t){return e.filter(e=>f(e)===t)}(H,r.key));if(t.push({kind:"workspace",project:r,cwd:i[0]?.root.cwd??r.root}),n.has(r.key)){let n=eQ[r.key]??6,o=i.slice(0,n),l=i.find(t=>t.root.id===e||t.subagents.some(t=>t.id===e));l&&!o.includes(l)&&(o=[...o.slice(0,Math.max(0,n-1)),l]),t.push(...o.map(e=>({kind:"session",family:e})));let s=i.length-o.length;s>0&&t.push({kind:"showMore",projectKey:r.key,remaining:s})}}return t},[H,t2,eX,e,t1,eQ]),t6=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)),l=Math.min(e,o+i),s=Array.from({length:l-o},(e,t)=>o+t);return r>=0&&r<o&&s.unshift(r),r>=l&&r<e&&s.push(r),s}(t5.length,ty,tx,t5.findIndex(e=>"session"===e.kind&&e.family.root.id===tb)),t3=t8&&eT?(P=(z=eT.worktrees.length>=8)&&ex.trim()?eT.worktrees.filter(e=>(e.branch??et(e.path,eh)).toLowerCase().includes(ex.trim().toLowerCase())):eT.worktrees,A=tU?tU.branch??et(tU.path,eh):"…",(0,r.jsxs)("div",{ref:eq,className:"workspace-worktree-switcher",style:{minWidth:0,flex:"0 1 auto"},children:[(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),eN(e=>!e),eg(!1)},onTouchStart:e=>e.stopPropagation(),title:tU?D("sidebar.switchWorktreeTitle",{path:tU.path}):D("sidebar.switchWorktree"),"aria-expanded":eR,"aria-haspopup":"listbox",style:{display:"flex",alignItems:"center",gap:4,height:22,maxWidth:96,minWidth:0,padding:"0 4px",background:eR?"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=>{eR||(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:A})]}),(0,r.jsxs)(er,{open:eR,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:[z&&(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:ex,onChange:e=>em(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(em(""),eN(!1))},placeholder:D("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)"}}),ex&&(0,r.jsx)("button",{type:"button",onClick:()=>em(""),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:D("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:[P.map(e=>{let t=e.path===t_;return eF===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:D("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tY(e.path,!0),disabled:eH,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:D("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eO(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:D("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:()=>{eu(e.path),eN(!1),eD(null),em("")},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)(en,{text:e.branch??et(e.path,eh),style:{flex:1}}),e.isMain&&(e.branch??"").toLowerCase()!==D("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:D("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tY(e.path,!1),disabled:eH,title:D("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)}),z&&0===P.length&&ex.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:D("sidebar.noMatchingWorktrees")})]}),e$?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eK,className:"sidebar-dropdown-filter-input",value:ez,onChange:e=>{eP(e.target.value),eD(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tJ()),"Escape"===e.key&&(eW(!1),eP(""),eD(null))},placeholder:D("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 tJ(),disabled:eH||!ez.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",fontSize:11,fontWeight:600,cursor:eH||!ez.trim()?"not-allowed":"pointer",opacity:eH||!ez.trim()?.65:1},children:eH?D("sidebar.creating"):D("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eW(!1),eP(""),eD(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:D("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eW(!0),eD(null),setTimeout(()=>eK.current?.focus(),0)},title:D("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:D("sidebar.newWorktree")})]}),eA&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eA})]})]})):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[ey&&(0,r.jsx)(M,{initialPath:eb,busy:eS,error:ek,onCancel:()=>{ev(!1),ej(null)},onSelect:e=>void tq(e)}),(0,r.jsxs)("div",{ref:eM,className:"sidebar-section-row",style:{position:"relative"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eZ(e=>!e),className:"sidebar-section-label",children:[(0,r.jsx)(Y,{open:eY}),(0,r.jsx)("span",{children:D("sidebar.projects")}),t1.length>0&&(0,r.jsx)("span",{className:"sidebar-header-count",children:t1.length})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[(0,r.jsx)("div",{children:(0,r.jsx)(J,{onClick:()=>{eg(e=>!e),eN(!1)},title:D("sidebar.addProject"),ariaPressed:ef,color:ef?"var(--accent)":"var(--text-dim)",background:ef?"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)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})}),(0,r.jsx)(J,{onClick:()=>{e7(e=>{let t=!e;return t&&eZ(!0),t}),eN(!1),eg(!1)},title:D("sidebar.toggleSessionSearch"),ariaPressed:e3,color:e3?"var(--accent)":"var(--text-dim)",background:e3?"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)(er,{open:ef,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:[(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),tV()},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:D("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),tK()},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:D("sidebar.customPath")})]})]})]}),e3&&eY&&(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:e9,maxLength:200,"aria-label":D("sidebar.searchSessions"),placeholder:D("sidebar.searchSessions"),onChange:e=>te(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),te(""))},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"})}),(0,r.jsx)(q,{open:e3&&eY,query:e9,refreshKey:F,selectedSessionId:e,onSelectSession:tZ,children:eY&&(0,r.jsxs)("div",{ref:tg,onScroll:tL,style:{flex:eV&&(y||ec)?"1 1 0":"1 1 auto",overflowY:"auto",padding:"0",minHeight:80},children:[ea&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:ea}),!eo&&!ea&&!tQ&&0===t1.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:D("sidebar.noSessions")}),t5.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:28*t5.length},children:t6.map(t=>{let i=t5[t];if("workspace"===i.kind){let e=(eX??t2).has(i.project.key),n=i.project.key===t0?.key,o=t4.get(i.project.key),l=n&&ec?ec:i.cwd,s=R.includes(i.project.root),a=tS===i.project.key;return(0,r.jsxs)("div",{className:`workspace-list-row${a?" is-actions-revealed":""}`,"data-active":n?"true":"false",onTouchStart:e=>tR(i.project.key,e),onTouchMove:tN,onTouchEnd:t$,onTouchCancel:t$,onContextMenu:e=>{tM.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":e,onClick:()=>{if(tM.current){tM.current=!1;return}e&&e0(e=>{if(!(i.project.key in e))return e;let t={...e};return delete t[i.project.key],t}),eG(e=>{let t=new Set(e??t2);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)(Y,{open:e}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:b(i.project.root)}),o?.running?(0,r.jsx)("span",{role:"status","aria-label":`${D("sidebar.agentRunning")} (${o.running})`,children:(0,r.jsx)(K,{size:11})}):null,o?.unread?(0,r.jsx)("span",{"aria-label":`${D("sidebar.newSessionActivity")} (${o.unread})`,style:{color:"#10b981",fontSize:10},children:o.unread}):null]}),n?t3:null,(0,r.jsxs)("span",{className:"workspace-row-action",children:[(0,r.jsx)(J,{onClick:()=>{tC(null),eu(l),eJ(!0),d(!0)},title:D("sidebar.openProjectExplorer",{path:l}),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)(J,{onClick:()=>{tC(null),N(i.project.root)},title:D(s?"sidebar.unpinDirectory":"sidebar.pinDirectory"),ariaPressed:s,color:s?"var(--text-muted)":"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:s?"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)(J,{onClick:()=>{tM.current=!1,tC(null),eu(l),eG(e=>new Set([...e??t2,i.project.key])),tX(l)},title:D("sidebar.newSessionTitle",{path:l}),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":D("sidebar.showMoreSessionsLabel",{count:i.remaining}),onClick:()=>e0(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:D("sidebar.showMoreSessions")}),(0,r.jsx)("span",{className:"workspace-show-more-count",children:i.remaining})]},`more:${i.projectKey}`);let l=i.family,s=[l.root,...l.subagents],a=l.latestModified===l.root.modified?l.root:{...l.root,modified:l.latestModified};return(0,r.jsx)("div",{onFocus:()=>tw(l.root.id),onBlur:()=>tw(null),style:{position:"absolute",top:28*t,left:4,right:4},children:(0,r.jsx)(es,{session:a,indent:14,isSelected:s.some(t=>t.id===e),isRunning:s.some(e=>tl.has(e.id)),isUnread:s.some(e=>ta.has(e.id)),isActionsRevealed:tk===l.root.id,onRevealActions:()=>tj(l.root.id),onDismissActions:()=>tj(e=>e===l.root.id?null:e),onClick:()=>{tj(null),tZ(l.root)},onRenamed:tW,onOpenInNewTab:n?()=>{tj(null),n(l.root)}:void 0,onPin:o?()=>{tj(null),o(l.root)}:void 0,onDeleted:e=>{tj(null),x?.(e),tW()}})},l.root.id)})})]})}),(y||ec)&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:eV?"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:()=>eJ(e=>{let t=!e;return d(t),t}),className:"sidebar-section-label",children:[(0,r.jsx)(Y,{open:eV}),(0,r.jsx)("span",{children:D("files.explorer")})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[k&&(0,r.jsx)(J,{onClick:()=>k(ec??y),title:D("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"})]})}),eV&&tn>0&&(0,r.jsx)(J,{onClick:()=>to(e=>!e),title:D("sidebar.changedFiles",{count:tn}),ariaPressed:!ti,color:ti?"var(--text-dim)":"var(--accent)",background:ti?"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"})]})}),eV&&(0,r.jsx)(J,{onClick:()=>{e6(e=>!e)},title:D("sidebar.searchFiles"),ariaPressed:e5,color:e5?"var(--accent)":"var(--text-dim)",background:e5?"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"})]})}),eV&&(0,r.jsx)(J,{onClick:()=>tf.current?.openUploadPicker(),disabled:e4,title:D("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)(J,{onClick:()=>{S?S():e2(e=>e+1)},title:D("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"})]})})]})]}),eV&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(_,{ref:tf,cwd:ec??y,onOpenFile:w??(()=>{}),refreshKey:e1,onAtMention:C,onAtMentions:I,onUploadBusyChange:e8,changesCollapsed:ti,onChangesCountChange:tr,fileSearchOpen:e5,onFileSearchOpenChange:e6})})]})]})}function eo(){let{t:e}=(0,m.s)();return(0,r.jsx)(K,{size:14,title:e("sidebar.agentRunning"),ariaLabel:e("sidebar.agentRunning")})}function el(){let{t:e}=(0,m.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 es({session:e,isSelected:t,isRunning:n,isUnread:o,isActionsRevealed:l=!1,onRevealActions:s,onDismissActions:a,onClick:d,onRenamed:c,onOpenInNewTab:h,onPin:f,onDeleted:g,indent:y=0,depth:v=0,hasChildren:b=!1,collapsed:w=!1,onToggleCollapse:k}){let{locale:j,t:S}=(0,m.s)(),[C,I]=(0,i.useState)(!1),[E,M]=(0,i.useState)(!1),[T,L]=(0,i.useState)(""),[R,N]=(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(R||E||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{}s?.()},400)},[R,s,E,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(E){let e=requestAnimationFrame(()=>z.current?.select());return()=>cancelAnimationFrame(e)}},[E]);let O=u(e.firstMessage)??e.firstMessage,U=p(e),_=(0,i.useCallback)(t=>{t?.stopPropagation(),e.transient||(L(p(e)),M(!0))},[e]),q=(0,i.useCallback)(async()=>{let t=T.trim();if(M(!1),T!==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{}},[T,e.id,e.name,c,U]),K=(0,i.useCallback)(async()=>{if(!e.transient){N(!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]),J=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?K():N(!0)},[K]),Y=(0,i.useCallback)(e=>{e.stopPropagation(),K()},[K]),Z=(0,i.useCallback)(e=>{e.stopPropagation(),N(!1)},[]),X=(0,i.useCallback)(t=>{if(D.current||l){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())},[l,c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`session-list-row${l?" is-actions-revealed":""}`,onClick:e=>{if(D.current){D.current=!1,e.preventDefault(),e.stopPropagation();return}l?a?.():R||E||d()},onDoubleClick:()=>{R||E||l||e.transient||f?.()},onTouchStart:H,onTouchMove:B,onTouchEnd:F,onTouchCancel:F,onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1!==e.button||!h||R||E||(e.preventDefault(),e.stopPropagation(),h())},onContextMenu:R||E?void 0:X,onMouseEnter:()=>I(!0),onMouseLeave:()=>{I(!1)},style:{height:28,position:"relative",display:"flex",alignItems:"center",paddingLeft:10+y+14*v,paddingRight:8,cursor:R||E?"default":"pointer",background:R?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":C?"var(--bg-hover)":"transparent",borderLeft:R?"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:R?(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:Y,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:Z,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")})]})]}):E?(0,r.jsx)("input",{ref:z,value:T,onChange:e=>L(e.target.value),onBlur:q,onKeyDown:e=>{"Enter"===e.key&&q(),"Escape"===e.key&&M(!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:[v>0&&(0,r.jsx)(V,{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}
|
|
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?[...l]:"read-only"===e?[...s]:"full"===e?[...d]:[...a]}let l=[],s=["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===[...s].sort().join(",")?"read-only":t===[...a].sort().join(",")?"default":t===[...d].sort().join(",")?"full":"default"}},64873:(e,t,n)=>{Promise.resolve().then(n.bind(n,66582)),Promise.resolve().then(n.bind(n,21278))},66582:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>s0});var r=n(95155),i=n(12115),o=n(73321);function l(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,l=null;for(;;){if(n.has(o)){l=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"){l=r.id;break}o=r.relation.parentSessionId}for(let t of e)n.set(t,l)}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 s="pi-web:file-explorer:open";function a(){try{return window.localStorage}catch{return null}}function d(e,t=a()){if(t)try{t.setItem(s,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}))}var x=n(2730),m=n(21278);function y(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function v(e){return y(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function b(e){let t=y(e).replace(/\/+$/,"");return t.split("/").pop()??t}function w(e){let t=y(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 k(e,t){if(!t)return e;let n=y(e),r=y(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function j(e,t){return`${y(e).replace(/\/$/,"")}/${t}`}var S=n(47650);async function C(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 I(){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 E(){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 M({onCancel:e,onSelect:t,initialPath:n,busy:o=!1,error:l}){let{t:s}=(0,m.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(n??""),[x,y]=(0,i.useState)([]),[v,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,T]=(0,i.useState)(!0),L=(0,i.useCallback)(async e=>{T(!0),k(null);try{let t=await C(e),n=t.path??e??"/";u(n),p(t.parentPath??null),g(n),y(t.directories??[]),b(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{T(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),L(n||void 0)},[n,L]);let R=f.trim()!==c,N=!!c&&!R&&!o,$=!!h||/^[a-zA-Z]:[\\/]?$/.test(c);return a?(0,S.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("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:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:o,title:s("i18n.close"),"aria-label":s("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&&L(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 L(h??void 0),disabled:j||!$,title:s("directoryPicker.goToParent"),"aria-label":s("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:s("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:s("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:s("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:s("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 L(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)(E,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void L(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)(I,{}),(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:s("directoryPicker.noSubdirectories")}),(w||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??l})]}),(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:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!N,title:s(R?"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:s(o?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),a):null}function T({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 L({size:e=14,open:t=!1}){return(0,r.jsx)(T,{name:t?"_folder_open":"_folder",size:e})}function R({size:e=14}){return(0,r.jsx)(T,{name:"_file",size:e})}let N={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 $(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)(T,{name:i,size:t});let o=N[n.split(".").pop()??""];return o?(0,r.jsx)(T,{name:o,size:t}):(0,r.jsx)(R,{size:t})}function W({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 z(e){let t=v(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:j(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function P(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 A={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},D={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function H({status:e,t}){return(0,r.jsx)("span",{title:t(A[e.status]),"aria-label":t(A[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:D[e.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:e.code})}function B({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 F({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 O({node:e,depth:t,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p}){let f=s.has(e.fullPath),g=c.has(e.fullPath),x=y(e.fullPath),m=u.get(x),b=e.isDir&&(void 0!==m||h.has(x)),[w,j]=(0,i.useState)(e.children??[]),[S,C]=(0,i.useState)(e.loaded??!1),[I,E]=(0,i.useState)(!1),[M,T]=(0,i.useState)(null),[R,N]=(0,i.useState)(!1),P=(0,i.useCallback)(async(t=!1)=>{if(!S||t){E(!0),T(null);try{let t=await z(e.fullPath);j(t),C(!0)}catch(e){T(e instanceof Error?e.message:String(e))}finally{E(!1)}}},[S,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&f&&S&&P(!0)},[d]);let A=(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&&!S&&P()},[P,S,f]),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:A,onMouseEnter:()=>N(!0),onMouseLeave:()=>N(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:2,paddingLeft:2+14*t,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:R?"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)(W,{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)(L,{size:14,open:f}):$(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"}})}),!R&&!e.isDir&&m&&(0,r.jsx)(H,{status:m,t:p}),!R&&b&&(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"}})}),I&&(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"})}),l&&R&&(0,r.jsxs)("button",{onClick:t=>{t.stopPropagation(),l(k(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)(B,{}),p("files.mention")]}),R&&!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${v(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:[w.map(e=>(0,r.jsx)(O,{node:e,depth:t+1,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p},e.fullPath)),0===w.length&&S&&(0,r.jsx)("div",{style:{paddingLeft:2+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),M&&(0,r.jsx)("button",{type:"button",onClick:()=>void P(!0),title:M,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 U({status:e,cwd:t,onOpenFile:n,t:o}){let[l,s]=(0,i.useState)(!1),a=b(e.filePath),d=k(e.filePath,t);return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,a,{modeHint:"diff",cwd:t}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:l?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)(H,{status:e,t:o}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",opacity:.85,transform:"translateY(0.5px)"},children:$(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 _=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:o,onAtMentions:l,onUploadBusyChange:s,changesCollapsed:a,onChangesCountChange:d,fileSearchOpen:c=!1,onFileSearchOpenChange:u},h){let{t:p}=(0,m.s)(),[f,g]=(0,i.useState)([]),[x,b]=(0,i.useState)(!0),[S,C]=(0,i.useState)(null),[I,E]=(0,i.useState)(new Set),[M,T]=(0,i.useState)(0),[L,R]=(0,i.useState)(new Set),[N,$]=(0,i.useState)([]),[W,A]=(0,i.useState)({additions:0,deletions:0}),[H,_]=(0,i.useState)(null),[q,K]=(0,i.useState)(null),[V,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,el]=(0,i.useState)([]),[es,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),ex=(0,i.useRef)(null),em=`${n??0}:${M}`,ey="idle"!==V,ev=er.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=er.trim();if(!t){el([]),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(em)}`,{signal:n.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>el((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{n.signal.aborted||(el([]),ec(!0))}).finally(()=>{n.signal.aborted||ea(!1)})},150);return()=>{clearTimeout(r),n.abort()}},[e,c,em,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(j(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:j(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(N.map(e=>[y(e.filePath),e])),[N]),ek=(0,i.useMemo)(()=>{let t=new Set,n=y(e).replace(/\/$/,"");for(let e of N){let r=w(y(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=w(r);if(e===r)break;r=e}}return t},[e,N]),ej=(0,i.useCallback)((e,t)=>{E(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&&(R(new Set(n.map(t=>j(e,t)))),T(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 l=new XMLHttpRequest;l.open("POST",`/api/files/${v(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&Z(Math.round(e.loaded/e.total*100))},l.onerror=()=>i(Error("Network error while uploading files")),l.onabort=()=>i(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}r({status:l.status,data:e})},l.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]),eI=(0,i.useCallback)(async t=>{if(0!==t.length&&!ey){ee(null),R(new Set),en(null),G(null),Z(0),J("checking");try{let n=await fetch(`/api/files/${v(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,ey]),eE=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eI(t)},[eI]);(0,i.useImperativeHandle)(h,()=>({openUploadPicker(){ey||ex.current?.click()}}),[ey]),(0,i.useEffect)(()=>{s?.(ey)},[s,ey]),(0,i.useEffect)(()=>()=>s?.(!1),[s]),(0,i.useEffect)(()=>{let t=ef.current!==e;ef.current=e,t&&(E(new Set),R(new Set),ee(null),en(null),G(null)),b(t),C(null);let n=!1;return z(e).then(e=>{n||g(e)}).catch(e=>{n||C(e instanceof Error?e.message:String(e))}).finally(()=>{n||b(!1)}),()=>{n=!0}},[e,n,M]),(0,i.useEffect)(()=>{let t=!1;return eg.current!==e&&(_(null),$([]),A({additions:0,deletions:0})),K(null),P(e).then(n=>{t||($(n.isGitRepository?n.files:[]),A(n.isGitRepository?{additions:n.additions,deletions:n.deletions}:{additions:0,deletions:0}),eg.current=e,_(e))}).catch(e=>{t||K(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e,n,M]),(0,i.useEffect)(()=>{d?.(H===e?N.length:0)},[e,N,H,d]);let eM=ey||null!==et||null!==X||null!==Q,eT=(0,i.useCallback)(()=>{Q&&0!==Q.uploaded.length&&l?.(Q.uploaded.map(t=>k(j(e,t),e)),e)},[e,l,Q]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:ex,type:"file",multiple:!0,hidden:!0,onChange:eE}),eM&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ey&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===V?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"===V?(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"===V&&(0,r.jsxs)("span",{style:{fontSize:10},children:[Y,"%"]})]}),"uploading"===V&&(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)(F,{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&&l&&(0,r.jsxs)("button",{type:"button",onClick:eT,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)(B,{}),p("files.mention")]}),(0,r.jsx)(F,{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"})]})})]}),ev&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[es&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:p("sidebar.searchingFiles")}),!es&&ed&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:p("i18n.networkError")}),!es&&!ed&&0===eo.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:p("sidebar.noMatchingFiles")}),!es&&!ed&&eo.length>0&&(0,r.jsx)("div",{children:eb.map(n=>(0,r.jsx)(O,{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:L,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},`${er}:${n.fullPath}`))})]})]}),q&&(0,r.jsx)("div",{role:"alert",title:q,style:{padding:"6px 12px",fontSize:11,color:"#f87171"},children:p("files.gitStatusFailed")}),!a&&H===e&&N.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":p("files.changeStats",{count:N.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:N.length})}),(0,r.jsxs)("span",{style:{color:D.added,fontFamily:"var(--font-mono)"},children:["+",W.additions]}),(0,r.jsxs)("span",{style:{color:D.deleted,fontFamily:"var(--font-mono)"},children:["-",W.deletions]})]}),N.map(n=>(0,r.jsx)(U,{status:n,cwd:e,onOpenFile:t,t:p},n.filePath))]}),(a||H!==e||0===N.length)&&(!c||!ev)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[x?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):S?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:S}):f.map(n=>(0,r.jsx)(O,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:I,onToggleExpanded:ej,refreshToken:em,highlightedPaths:L,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},n.fullPath)),!x&&!S&&0===f.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:p("files.noFiles")})]})]})});function q({open:e,query:t,refreshKey:n,children:o,selectedSessionId:l,onSelectSession:s}){let{t:a,locale:d}=(0,m.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:()=>s(e,t,n),"aria-current":e.id===l?"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===l?"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,x.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 K({size:e=14,title:t,ariaLabel:n,className:i,style:o}){let l=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:l,height:l},"aria-hidden":"true"}),(0,r.jsx)("span",{className:"live-pulse-beacon-core",style:{width:l,height:l},"aria-hidden":"true"})]})}function V({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 J({onClick:e,title:t,disabled:n,skipHover:i,color:o,background:l="none",marginRight:s,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:s,background:l,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=l)},children:c})}function Y({open:e}){return(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(W,{open:e})})}let Z="pi-web:unread-session-ids",X="pi-web:last-custom-cwd",G="pi-web:workspace-expansion";function Q(){try{let e=window.localStorage.getItem(G);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 ee(){try{return window.localStorage.getItem(X)??""}catch{return""}}function et(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function en({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 er({open:e,children:t,style:n}){let[o,l]=(0,i.useState)(e),[s,a]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(l(!0),a(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>a(!0))})):(a(!1),n=setTimeout(()=>l(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),o)?(0,r.jsx)("div",{style:{...n,opacity:+!!s,transform:s?"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 ei({selectedSessionId:e,onSelectSession:t,onOpenSessionInNewTab:n,onPinSession:o,onNewSession:c,initialSessionId:u,skipInitialProjectSelection:h,refreshKey:p,onSessionDeleted:x,selectedCwd:y,onCwdChange:v,onOpenFile:w,onOpenTerminal:k,explorerRefreshKey:j,onExplorerRefresh:S,onAtMention:C,onAtMentions:I,onBackgroundTaskDone:E,onRunningSessionIdsChange:T,onSessionsChange:L,pinnedCwds:R,onTogglePinnedCwd:N,onHomeDirChange:$,onWorktreeInfoChange:W}){let z,P,A,{t:D}=(0,m.s)(),[H,B]=(0,i.useState)([]),[F,O]=(0,i.useState)(null),U=(0,i.useRef)(null),V=(0,i.useRef)(0),[eo,el]=(0,i.useState)(!0),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[eh,ep]=(0,i.useState)(""),[ef,eg]=(0,i.useState)(!1),[ex,em]=(0,i.useState)(""),[ey,ev]=(0,i.useState)(!1),[eb,ew]=(0,i.useState)(ee),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(!1),[eI,eE]=(0,i.useState)(null),eM=(0,i.useRef)(null),[eT,eL]=(0,i.useState)(null),[eR,eN]=(0,i.useState)(!1),[e$,eW]=(0,i.useState)(!1),[ez,eP]=(0,i.useState)(""),[eA,eD]=(0,i.useState)(null),[eH,eB]=(0,i.useState)(!1),[eF,eO]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(null),eq=(0,i.useRef)(null),eK=(0,i.useRef)(null),[eV,eJ]=(0,i.useState)(!0),[eY,eZ]=(0,i.useState)(!0),[eX,eG]=(0,i.useState)(Q),[eQ,e0]=(0,i.useState)({}),[e1,e2]=(0,i.useState)(0),[e4,e8]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(!1),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(""),tt=e3&&!!e9.trim(),[tn,tr]=(0,i.useState)(0),[ti,to]=(0,i.useState)(!0),[tl,ts]=(0,i.useState)(()=>new Set),[ta,td]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(Z);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}})()),tc=(0,i.useRef)(new Set),tu=(0,i.useRef)(new Set),th=(0,i.useRef)(new Set),tp=(0,i.useRef)(!1),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),[tx,tm]=(0,i.useState)(0),[ty,tv]=(0,i.useState)(0),[tb,tw]=(0,i.useState)(null),[tk,tj]=(0,i.useState)(null),[tS,tC]=(0,i.useState)(null),tI=(0,i.useRef)(null),tE=(0,i.useRef)(null),tM=(0,i.useRef)(!1),tT=(0,i.useRef)(null),tL=(0,i.useCallback)(e=>{tj(null),tC(null);let t=e.currentTarget.scrollTop;null==tT.current&&(tT.current=requestAnimationFrame(()=>{tT.current=null,tv(t)}))},[]);(0,i.useEffect)(()=>{if(!tk&&!tS)return;let e=e=>{let t=e.target;t?.closest(".session-row-actions, .workspace-row-action")||(tj(null),tC(null))};return window.addEventListener("pointerdown",e,!0),()=>window.removeEventListener("pointerdown",e,!0)},[tk,tS]);let tR=(0,i.useCallback)((e,t)=>{if(t.target?.closest(".workspace-row-action"))return;let n=t.touches[0];tE.current={x:n.clientX,y:n.clientY},tM.current=!1,tI.current=setTimeout(()=>{tM.current=!0,tC(e),navigator.vibrate?.(15)},400)},[]),tN=(0,i.useCallback)(e=>{if(!tE.current||!tI.current)return;let t=e.touches[0];(Math.abs(t.clientX-tE.current.x)>10||Math.abs(t.clientY-tE.current.y)>10)&&(clearTimeout(tI.current),tI.current=null)},[]),t$=(0,i.useCallback)(()=>{tI.current&&clearTimeout(tI.current),tI.current=null,tE.current=null},[]);(0,i.useLayoutEffect)(()=>{let e=tg.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)tm(t.contentRect.height)});return t.observe(e),tm(e.clientHeight),tv(e.scrollTop),()=>t.disconnect()},[tt]);let tW=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++V.current;try{e&&el(!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;U.current=i.sessionListVersion,O(i.sessionListVersion),B(i.sessions),tp.current||(tu.current=new Set(i.completionNotificationSuppressedSessionIds??[]),ts(new Set(i.runningSessionIds??[])));let o=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));td(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),ed(null)}catch(e){n===V.current&&ed(String(e))}finally{n===V.current&&el(!1)}},[]),tz=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tz.current;tz.current=!0,tW(e,!e)},[tW,p]),(0,i.useEffect)(()=>{eJ(function(e=a()){if(!e)return!0;try{return"false"!==e.getItem(s)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===ta.size?window.localStorage.removeItem(Z):window.localStorage.setItem(Z,JSON.stringify([...ta]))}catch{}},[ta]),(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;tp.current=!0,tu.current=new Set(r.completionNotificationSuppressedSessionIds??[]),ts(new Set(r.runningSessionIds??[])),r.sessionListVersion!==U.current&&await tW()}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)}},[tW]),(0,i.useEffect)(()=>{T?.(tl)},[T,tl]),(0,i.useEffect)(()=>{L?.(H)},[H,L]),(0,i.useEffect)(()=>{let t=tc.current,n=[...t].filter(t=>!tl.has(t)&&t!==e),r=new Set(H.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!th.current.has(e)&&!r.has(e)),o=[...tl].filter(e=>!t.has(e));(i.length>0||o.length>0)&&td(e=>{let t=new Set(e);return tl.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let l=o.some(e=>!H.some(t=>t.id===e));(n.length>0||l)&&tW(!1,!0),i.length>0&&E?.(i),tc.current=tl,th.current=new Set([...tl].filter(e=>tu.current.has(e)||r.has(e)))},[tl,e,H,tW,E]),(0,i.useEffect)(()=>{e&&td(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==j&&e2(e=>e+1)},[j]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&ep(e.home)}).catch(()=>{})},[]),(0,i.useEffect)(()=>{eh&&$?.(eh)},[eh,$]);let tP=(0,i.useRef)(!1),tA=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tD=(0,i.useCallback)(e=>{if(!e)return null;if(eI?.cwd===e)return tA(eI.root,eI.key);if(eT&&eT.forCwd===e||eT?.worktrees.some(t=>t.path===e))return tA(eT.projectRoot,eT.projectKey);let t=H.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tA(t.projectRoot??t.cwd,f(t)):tA(e,e)},[eI,eT,H,tA]),tH=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tD(ec),t=tH.current;(t?.cwd!==ec||t.key!==(e?.key??null))&&(tH.current={cwd:ec,key:e?.key??null},v?.(ec,e?.root??null,e?.key??null))},[ec,v,tD]);let tB=(0,i.useRef)(null);(0,i.useEffect)(()=>{y&&y!==tB.current&&(tB.current=y,eu(y))},[y]);let[tF,tO]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!ec){eL(null),e_(null);return}let e=!1;return e_(ec),fetch(`/api/worktrees?cwd=${encodeURIComponent(ec)}`).then(e=>e.json()).then(t=>{if(!e){if(e_(null),t.error||!t.projectRoot)return void eL(null);eL({forCwd:ec,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||(e_(null),eL(null))}),()=>{e=!0}},[ec,tF,p]),(0,i.useEffect)(()=>{if(W){if(!eT?.isGit)return void W(null);W({forCwd:eT.forCwd,projectRoot:eT.projectRoot,currentWorktreePath:eT.currentWorktreePath,worktrees:eT.worktrees})}},[eT,W]),(0,i.useEffect)(()=>{if(0!==H.length&&!h&&null===ec){if(u&&!tP.current){tP.current=!0;let e=H.find(e=>e.id===u);if(e){eu(e.cwd),t(e,!0);return}}let e=g(H);e.length>0&&eu(e[0].root)}},[H,ec,u,h,t]);let tU=eT?eT.worktrees.find(e=>e.path===ec)??(eT.forCwd===ec&&eT.currentWorktreePath?eT.worktrees.find(e=>e.path===eT.currentWorktreePath):void 0)??eT.worktrees.find(e=>e.isMain):void 0,t_=tU?.path??null,tq=(0,i.useCallback)(async e=>{let t=(e??eb).trim();if(t&&!eS){eC(!0),ej(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 ej(r.error??`HTTP ${e.status}`);eE({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(X,n)}catch{}ew(r.cwd),R.includes(r.projectRoot)||N(r.projectRoot),eG(e=>new Set([...e??[],r.projectKey])),eu(r.cwd),ev(!1),eg(!1)}catch(e){ej(e instanceof Error?e.message:String(e))}finally{eC(!1)}}},[eb,eS,N,R]),tK=(0,i.useCallback)(()=>{ev(!0),ej(null),eg(!1)},[]),tV=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(R.includes(t.cwd)||N(t.cwd),eG(e=>new Set([...e??[],t.cwd])),eu(t.cwd),ev(!1),ej(null),eg(!1))}catch{}},[N,R]),tJ=(0,i.useCallback)(async()=>{let e=ez.trim();if(e&&!eH&&eT){eB(!0),eD(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eT.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eD(n.error??`HTTP ${t.status}`);eW(!1),eP(""),eN(!1),eL(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),eu(n.path),tO(e=>e+1)}catch(e){eD(e instanceof Error?e.message:String(e))}finally{eB(!1)}}},[ez,eH,eT]),tY=(0,i.useCallback)(async(e,t)=>{if(eT&&!eH){eB(!0),eD(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eT.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eO(e);eD(r.error??`HTTP ${n.status}`);return}eO(null),t_===e&&eu(eT.projectRoot),tO(e=>e+1)}catch(e){eD(e instanceof Error?e.message:String(e))}finally{eB(!1)}}},[eT,eH,t_]);(0,i.useEffect)(()=>{let e=e=>{eM.current&&!eM.current.contains(e.target)&&eg(!1),eq.current&&!eq.current.contains(e.target)&&(eN(!1),eW(!1),eP(""),eD(null),eO(null),em(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tZ=(0,i.useCallback)((e,n,r)=>{B(t=>t.some(t=>t.id===e.id)?t:[e,...t]),eG(t=>{let n=new Set(t??[]);return n.add(f(e)),n});let i=tD(ec)?.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:ec,sessionProjectKey:f(e),selectedProjectKey:i,worktrees:eT?.worktrees})&&eu(e.cwd),t(e,!1,n,r)},[t,tD,ec,eT]),tX=(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]),tG=(0,i.useMemo)(()=>g(H),[H]),tQ=!ec&&!eo&&!ea&&0===tG.length,t0=(0,i.useMemo)(()=>tD(ec),[tD,ec]),t1=(0,i.useMemo)(()=>{let e=[],t=new Set,n=n=>{!n||t.has(n.key)||(t.add(n.key),e.push(n))};return R.forEach(e=>n(tD(e))),tG.forEach(n),n(t0),e},[R,tD,tG,t0]),t2=(0,i.useMemo)(()=>{let t;return e?t=t0?.key:1===t1.length&&(t=t1[0]?.key),new Set(t?[t]:[])},[t0?.key,e,t1]);(0,i.useEffect)(()=>{null===eX&&0!==t1.length&&eG(t2)},[t2,eX,t1.length]),(0,i.useEffect)(()=>{null!==eX&&function(e){try{window.localStorage.setItem(G,JSON.stringify([...e]))}catch{}}(eX)},[eX]);let t4=(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})(H,tl,ta),[H,tl,ta]),t8=!!(eT?.isGit&&eT.isTopLevel&&ec&&t0?.key===eT.projectKey),t5=(0,i.useMemo)(()=>{let t=[],n=eX??t2;for(let r of t1){let i=l(function(e,t){return e.filter(e=>f(e)===t)}(H,r.key));if(t.push({kind:"workspace",project:r,cwd:i[0]?.root.cwd??r.root}),n.has(r.key)){let n=eQ[r.key]??6,o=i.slice(0,n),l=i.find(t=>t.root.id===e||t.subagents.some(t=>t.id===e));l&&!o.includes(l)&&(o=[...o.slice(0,Math.max(0,n-1)),l]),t.push(...o.map(e=>({kind:"session",family:e})));let s=i.length-o.length;s>0&&t.push({kind:"showMore",projectKey:r.key,remaining:s})}}return t},[H,t2,eX,e,t1,eQ]),t6=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)),l=Math.min(e,o+i),s=Array.from({length:l-o},(e,t)=>o+t);return r>=0&&r<o&&s.unshift(r),r>=l&&r<e&&s.push(r),s}(t5.length,ty,tx,t5.findIndex(e=>"session"===e.kind&&e.family.root.id===tb)),t3=t8&&eT?(P=(z=eT.worktrees.length>=8)&&ex.trim()?eT.worktrees.filter(e=>(e.branch??et(e.path,eh)).toLowerCase().includes(ex.trim().toLowerCase())):eT.worktrees,A=tU?tU.branch??et(tU.path,eh):"…",(0,r.jsxs)("div",{ref:eq,className:"workspace-worktree-switcher",style:{minWidth:0,flex:"0 1 auto"},children:[(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),eN(e=>!e),eg(!1)},onTouchStart:e=>e.stopPropagation(),title:tU?D("sidebar.switchWorktreeTitle",{path:tU.path}):D("sidebar.switchWorktree"),"aria-expanded":eR,"aria-haspopup":"listbox",style:{display:"flex",alignItems:"center",gap:4,height:22,maxWidth:96,minWidth:0,padding:"0 4px",background:eR?"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=>{eR||(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:A})]}),(0,r.jsxs)(er,{open:eR,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:[z&&(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:ex,onChange:e=>em(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(em(""),eN(!1))},placeholder:D("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)"}}),ex&&(0,r.jsx)("button",{type:"button",onClick:()=>em(""),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:D("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:[P.map(e=>{let t=e.path===t_;return eF===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:D("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tY(e.path,!0),disabled:eH,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:D("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eO(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:D("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:()=>{eu(e.path),eN(!1),eD(null),em("")},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)(en,{text:e.branch??et(e.path,eh),style:{flex:1}}),e.isMain&&(e.branch??"").toLowerCase()!==D("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:D("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tY(e.path,!1),disabled:eH,title:D("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)}),z&&0===P.length&&ex.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:D("sidebar.noMatchingWorktrees")})]}),e$?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eK,className:"sidebar-dropdown-filter-input",value:ez,onChange:e=>{eP(e.target.value),eD(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tJ()),"Escape"===e.key&&(eW(!1),eP(""),eD(null))},placeholder:D("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 tJ(),disabled:eH||!ez.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",fontSize:11,fontWeight:600,cursor:eH||!ez.trim()?"not-allowed":"pointer",opacity:eH||!ez.trim()?.65:1},children:eH?D("sidebar.creating"):D("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eW(!1),eP(""),eD(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:D("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eW(!0),eD(null),setTimeout(()=>eK.current?.focus(),0)},title:D("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:D("sidebar.newWorktree")})]}),eA&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eA})]})]})):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[ey&&(0,r.jsx)(M,{initialPath:eb,busy:eS,error:ek,onCancel:()=>{ev(!1),ej(null)},onSelect:e=>void tq(e)}),(0,r.jsxs)("div",{ref:eM,className:"sidebar-section-row",style:{position:"relative"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eZ(e=>!e),className:"sidebar-section-label",children:[(0,r.jsx)(Y,{open:eY}),(0,r.jsx)("span",{children:D("sidebar.projects")}),t1.length>0&&(0,r.jsx)("span",{className:"sidebar-header-count",children:t1.length})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[(0,r.jsx)("div",{children:(0,r.jsx)(J,{onClick:()=>{eg(e=>!e),eN(!1)},title:D("sidebar.addProject"),ariaPressed:ef,color:ef?"var(--accent)":"var(--text-dim)",background:ef?"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)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})}),(0,r.jsx)(J,{onClick:()=>{e7(e=>{let t=!e;return t&&eZ(!0),t}),eN(!1),eg(!1)},title:D("sidebar.toggleSessionSearch"),ariaPressed:e3,color:e3?"var(--accent)":"var(--text-dim)",background:e3?"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)(er,{open:ef,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:[(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),tV()},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:D("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),tK()},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:D("sidebar.customPath")})]})]})]}),e3&&eY&&(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:e9,maxLength:200,"aria-label":D("sidebar.searchSessions"),placeholder:D("sidebar.searchSessions"),onChange:e=>te(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),te(""))},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"})}),(0,r.jsx)(q,{open:e3&&eY,query:e9,refreshKey:F,selectedSessionId:e,onSelectSession:tZ,children:eY&&(0,r.jsxs)("div",{ref:tg,onScroll:tL,style:{flex:eV&&(y||ec)?"1 1 0":"1 1 auto",overflowY:"auto",padding:"0",minHeight:80},children:[ea&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:ea}),!eo&&!ea&&!tQ&&0===t1.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:D("sidebar.noSessions")}),t5.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:28*t5.length},children:t6.map(t=>{let i=t5[t];if("workspace"===i.kind){let e=(eX??t2).has(i.project.key),n=i.project.key===t0?.key,o=t4.get(i.project.key),l=n&&ec?ec:i.cwd,s=R.includes(i.project.root),a=tS===i.project.key;return(0,r.jsxs)("div",{className:`workspace-list-row${a?" is-actions-revealed":""}`,"data-active":n?"true":"false",onTouchStart:e=>tR(i.project.key,e),onTouchMove:tN,onTouchEnd:t$,onTouchCancel:t$,onContextMenu:e=>{tM.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":e,onClick:()=>{if(tM.current){tM.current=!1;return}e&&e0(e=>{if(!(i.project.key in e))return e;let t={...e};return delete t[i.project.key],t}),eG(e=>{let t=new Set(e??t2);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)(Y,{open:e}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:b(i.project.root)}),o?.running?(0,r.jsx)("span",{role:"status","aria-label":`${D("sidebar.agentRunning")} (${o.running})`,children:(0,r.jsx)(K,{size:11})}):null,o?.unread?(0,r.jsx)("span",{"aria-label":`${D("sidebar.newSessionActivity")} (${o.unread})`,style:{color:"#10b981",fontSize:10},children:o.unread}):null]}),n?t3:null,(0,r.jsxs)("span",{className:"workspace-row-action",children:[(0,r.jsx)(J,{onClick:()=>{tC(null),eu(l),eJ(!0),d(!0)},title:D("sidebar.openProjectExplorer",{path:l}),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)(J,{onClick:()=>{tC(null),N(i.project.root)},title:D(s?"sidebar.unpinDirectory":"sidebar.pinDirectory"),ariaPressed:s,color:s?"var(--text-muted)":"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:s?"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)(J,{onClick:()=>{tM.current=!1,tC(null),eu(l),eG(e=>new Set([...e??t2,i.project.key])),tX(l)},title:D("sidebar.newSessionTitle",{path:l}),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":D("sidebar.showMoreSessionsLabel",{count:i.remaining}),onClick:()=>e0(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:D("sidebar.showMoreSessions")}),(0,r.jsx)("span",{className:"workspace-show-more-count",children:i.remaining})]},`more:${i.projectKey}`);let l=i.family,s=[l.root,...l.subagents],a=l.latestModified===l.root.modified?l.root:{...l.root,modified:l.latestModified};return(0,r.jsx)("div",{onFocus:()=>tw(l.root.id),onBlur:()=>tw(null),style:{position:"absolute",top:28*t,left:4,right:4},children:(0,r.jsx)(es,{session:a,indent:14,isSelected:s.some(t=>t.id===e),isRunning:s.some(e=>tl.has(e.id)),isUnread:s.some(e=>ta.has(e.id)),isActionsRevealed:tk===l.root.id,onRevealActions:()=>tj(l.root.id),onDismissActions:()=>tj(e=>e===l.root.id?null:e),onClick:()=>{tj(null),tZ(l.root)},onRenamed:tW,onOpenInNewTab:n?()=>{tj(null),n(l.root)}:void 0,onPin:o?()=>{tj(null),o(l.root)}:void 0,onDeleted:e=>{tj(null),x?.(e),tW()}})},l.root.id)})})]})}),(y||ec)&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:eV?"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:()=>eJ(e=>{let t=!e;return d(t),t}),className:"sidebar-section-label",children:[(0,r.jsx)(Y,{open:eV}),(0,r.jsx)("span",{children:D("files.explorer")})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[k&&(0,r.jsx)(J,{onClick:()=>k(ec??y),title:D("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"})]})}),eV&&tn>0&&(0,r.jsx)(J,{onClick:()=>to(e=>!e),title:D("sidebar.changedFiles",{count:tn}),ariaPressed:!ti,color:ti?"var(--text-dim)":"var(--accent)",background:ti?"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"})]})}),eV&&(0,r.jsx)(J,{onClick:()=>{e6(e=>!e)},title:D("sidebar.searchFiles"),ariaPressed:e5,color:e5?"var(--accent)":"var(--text-dim)",background:e5?"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"})]})}),eV&&(0,r.jsx)(J,{onClick:()=>tf.current?.openUploadPicker(),disabled:e4,title:D("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)(J,{onClick:()=>{S?S():e2(e=>e+1)},title:D("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"})]})})]})]}),eV&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(_,{ref:tf,cwd:ec??y,onOpenFile:w??(()=>{}),refreshKey:e1,onAtMention:C,onAtMentions:I,onUploadBusyChange:e8,changesCollapsed:ti,onChangesCountChange:tr,fileSearchOpen:e5,onFileSearchOpenChange:e6})})]})]})}function eo(){let{t:e}=(0,m.s)();return(0,r.jsx)(K,{size:14,title:e("sidebar.agentRunning"),ariaLabel:e("sidebar.agentRunning")})}function el(){let{t:e}=(0,m.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 es({session:e,isSelected:t,isRunning:n,isUnread:o,isActionsRevealed:l=!1,onRevealActions:s,onDismissActions:a,onClick:d,onRenamed:c,onOpenInNewTab:h,onPin:f,onDeleted:g,indent:y=0,depth:v=0,hasChildren:b=!1,collapsed:w=!1,onToggleCollapse:k}){let{locale:j,t:S}=(0,m.s)(),[C,I]=(0,i.useState)(!1),[E,M]=(0,i.useState)(!1),[T,L]=(0,i.useState)(""),[R,N]=(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(R||E||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{}s?.()},400)},[R,s,E,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(E){let e=requestAnimationFrame(()=>z.current?.select());return()=>cancelAnimationFrame(e)}},[E]);let O=u(e.firstMessage)??e.firstMessage,U=p(e),_=(0,i.useCallback)(t=>{t?.stopPropagation(),e.transient||(L(p(e)),M(!0))},[e]),q=(0,i.useCallback)(async()=>{let t=T.trim();if(M(!1),T!==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{}},[T,e.id,e.name,c,U]),K=(0,i.useCallback)(async()=>{if(!e.transient){N(!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]),J=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?K():N(!0)},[K]),Y=(0,i.useCallback)(e=>{e.stopPropagation(),K()},[K]),Z=(0,i.useCallback)(e=>{e.stopPropagation(),N(!1)},[]),X=(0,i.useCallback)(t=>{if(D.current||l){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())},[l,c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`session-list-row${l?" is-actions-revealed":""}`,onClick:e=>{if(D.current){D.current=!1,e.preventDefault(),e.stopPropagation();return}l?a?.():R||E||d()},onDoubleClick:()=>{R||E||l||e.transient||f?.()},onTouchStart:H,onTouchMove:B,onTouchEnd:F,onTouchCancel:F,onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1!==e.button||!h||R||E||(e.preventDefault(),e.stopPropagation(),h())},onContextMenu:R||E?void 0:X,onMouseEnter:()=>I(!0),onMouseLeave:()=>{I(!1)},style:{height:28,position:"relative",display:"flex",alignItems:"center",paddingLeft:10+y+14*v,paddingRight:8,cursor:R||E?"default":"pointer",background:R?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":C?"var(--bg-hover)":"transparent",borderLeft:R?"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:R?(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:Y,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:Z,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")})]})]}):E?(0,r.jsx)("input",{ref:z,value:T,onChange:e=>L(e.target.value),onBlur:q,onKeyDown:e=>{"Enter"===e.key&&q(),"Escape"===e.key&&M(!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:[v>0&&(0,r.jsx)(V,{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
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})]}),b&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),k?.()},title:S(w?"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:w?"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)(eo,{}):o?(0,r.jsx)(el,{}):(0,r.jsx)("span",{title:e.modified,children:(0,x.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?.(),J(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 ea({src:e,alt:t="",children:n,className:o,style:l}){let{t:s}=(0,m.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",...l},onClick:()=>d(!0),"aria-label":s("chat.previewImage"),"aria-haspopup":"dialog","aria-expanded":a,title:s("chat.previewImage"),children:n}),a&&(0,r.jsxs)("dialog",{ref:u,className:"image-preview-dialog","aria-label":s("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":s("chat.close"),title:s("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 ed="pi-image-result",ec=[{model:"gpt-image-2.5-flare",label:"Flare"},{model:"gpt-image-2.5-sunburst",label:"Sunburst"},{model:"grok-imagine-image-2.0",label:"Grok"}],eu=["1:1","16:9","9:16","4:3","3:4","3:2","2:3"];function eh(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 ep=/@"([^"]+)"|@([^\s"]+)/g,ef=/\.(?:png|jpe?g|webp)$/i;function eg(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ex(e){if(!eg(e)||![ed,"pi-web:image"].includes(e.type)||1!==e.version)return null;let t=e.type===ed;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:ed}:null}function em(e,t,n){if("generate_image"!==e)return null;let r=ex(n);return r?r.source?"edit":"generate":eg(t)&&!0===t.new_image?"generate":eg(t)&&("string"==typeof t.target&&t.target||!0===t.use_last_attachment)?"edit":null}function ey(e,t){return`/api/files/${v(e)}?type=${t}`}function ev(e,t){return e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:t?j(t,e):e}function eb({path:e,cwd:t,onRemove:n}){let{t:i}=(0,m.s)(),o=ey(ev(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 ew(e,t){return{aspectRatio:`${e} / ${t}`,width:`min(100%, calc(28rem * ${e/t}))`}}function ek({value:e,cwd:t,onEdit:n,onMention:o,showPrompt:l=!1,createdAt:s}){let a,d,c,u,{t:h,locale:p}=(0,m.s)(),f=ex(e),[g,x]=(0,i.useState)(!1);if(!f)return null;let y=ev(f.path,t),v=ey(y,"read"),b=(c=[(a=function(e,t){if(e<=0||t<=0)return eh(e,t);let n=e/t,r=eu[0],i=1/0;for(let e of eu){let[t,o]=e.split(":").map(Number),l=Math.abs(n-t/o)/(t/o);l<i&&(r=e,i=l)}return i<=.03?r:eh(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 ")),w=[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,s?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}`}(s,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:ew(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)(ea,{src:v,alt:f.prompt,className:"block h-full w-full",children:(0,r.jsx)("img",{src:v,alt:f.prompt,loading:"lazy",onError:()=>x(!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:ey(y,"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"})]})})]})})]}),l&&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,b||w?(0,r.jsxs)("div",{className:`${l&&f.prompt?"mt-1":"mt-1.5"} max-w-full text-[11px] leading-snug tracking-wide text-text-muted`,title:f.model,children:[b,b&&w?" \xb7 ":null,w]}):null]})}function ej({prompt:e,size:t,width:n,height:i,previewUrl:o}){let{t:l}=(0,m.s)(),{w:s,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":l("image.generating"),className:"relative max-w-full overflow-hidden rounded-[10px] border border-border/80 bg-bg-panel",style:ew(s,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]})}function eS(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 eC({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 eI({config:e,edit:t,editPreviewUrl:n,onClose:o,onSubmit:l}){let{t:s}=(0,m.s)(),a=(0,i.useRef)(null),d=(0,i.useRef)(null),[c,u]=(0,i.useState)(""),[h,p]=(0,i.useState)(()=>t?.connection&&e.connections.some(e=>e.id===t.connection)?t.connection:e.defaultConnection);(0,i.useEffect)(()=>{e.connections.some(e=>e.id===h)||p(e.defaultConnection||e.connections[0]?.id||"")},[e,h]);let f=e.connections.find(e=>e.id===h)??e.connections[0],[g,x]=(0,i.useState)(()=>eS(f,"sizes","size",t?.size)),[y,v]=(0,i.useState)(()=>eS(f,"resolutions","resolution",t?.resolution)),[b,w]=(0,i.useState)(()=>eS(f,"qualities","quality",t?.quality)),k=f?.capabilities.sizes??[],j=f?.capabilities.resolutions??[],S=f?.capabilities.qualities??[],C=!!t,I=e.connections.length>1;(0,i.useLayoutEffect)(()=>{let e=d.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`)},[c]),(0,i.useEffect)(()=>{let e=document.activeElement;return window.matchMedia("(max-width: 640px)").matches||d.current?.focus(),()=>{e?.isConnected&&e.focus()}},[]),(0,i.useEffect)(()=>{let e=t&&f?.id===t.connection?t:void 0;x(eS(f,"sizes","size",e?.size)),v(eS(f,"resolutions","resolution",e?.resolution)),w(eS(f,"qualities","quality",e?.quality))},[f,t]);let E=()=>{if(!c.trim()||!f)return;let e={prompt:c.trim(),connection:f.id,...g?{size:g}:{},...y?{resolution:y}:{},...b?{quality:b}:{},...t?{target:t.path}:{new_image:!0}};o(),l(e)};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&&o()},children:(0,r.jsxs)("div",{ref:a,role:"dialog","aria-modal":"true","aria-labelledby":"image-generation-title",tabIndex:-1,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(),o();return}if((e.metaKey||e.ctrlKey)&&"Enter"===e.key){e.preventDefault(),E();return}if("Tab"!==e.key)return;let t=Array.from(a.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:C?s("image.editTitle"):s("image.title")}),(0,r.jsx)("button",{type:"button",onClick:o,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:s("trust.cancel"),"aria-label":s("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:C&&n?"flex flex-col gap-3 sm:flex-row sm:items-start":void 0,children:[C&&n?(0,r.jsx)("div",{className:"overflow-hidden rounded-[10px] sm:shrink-0",children:(0,r.jsx)("img",{src:n,alt:t?.prompt??s("image.editSource"),className:"block h-auto w-full sm:h-28 sm:w-auto sm:max-w-[7.5rem]"})}):null,(0,r.jsx)("textarea",{ref:d,id:"image-prompt",rows:2,value:c,maxLength:32e3,"aria-label":s("image.prompt"),onChange:e=>u(e.target.value),placeholder:C?s("image.editPromptPlaceholder"):s("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 ${C&&n?"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:[I?(0,r.jsx)(eC,{value:h,label:s("image.connection"),onChange:p,children:e.connections.map(e=>(0,r.jsx)("option",{value:e.id,children:e.label},e.id))}):null,k.length?(0,r.jsx)(eC,{value:g,label:s("image.aspect"),onChange:x,children:k.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)?s("image.aspectAuto"):"square"===t?`${s("image.aspectSquare")} ${e}`:"portrait"===t?`${s("image.aspectPortrait")} ${e}`:"landscape"===t?`${s("image.aspectLandscape")} ${e}`:e},e)})}):null,j.length?(0,r.jsx)(eC,{value:y,label:s("image.resolution"),onChange:v,children:j.map(e=>(0,r.jsx)("option",{value:e,children:e.toUpperCase()},e))}):null,S.length?(0,r.jsx)(eC,{value:b,label:s("image.quality"),onChange:w,children:S.map(e=>(0,r.jsx)("option",{value:e,children:"auto"===e?s("image.qualityAuto"):"low"===e?s("image.qualityLow"):"medium"===e?s("image.qualityMedium"):"high"===e?s("image.qualityHigh"):e},e))}):null]}),(0,r.jsx)("button",{type:"button",disabled:!c.trim(),onClick:E,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:C?s("image.edit"):s("image.generate")})]})]})})}let eE=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eM=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eT=/\x1B_pi:c\x07/g;function eL(e){return e.replace(eT,"").replace(eE,"")}function eR(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eM);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 eN(e,t){let n=eR(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function e$(e){return eR(e)[0]?.char}let eW={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:""},ez={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function eP(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function eA(e){return"custom"===e.role&&"pi-web:subagent-notification"===e.customType}function eD(e){return eP(e)||eA(e)}function eH(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function eB(e,t={}){return(e.content??[]).filter(e=>!eH(e,t)&&!function(e,t={}){return"text"===e.type&&!t.isStreaming&&""===e.text.trim()}(e,t))}function eF(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eO(e,t={}){return"image"===e.type||"text"===e.type&&(t.isStreaming?e.text.length>0:e.text.trim().length>0)}function eU(e,t={}){let n=eB(e,t),r=n.findLastIndex(e=>!eO(e,t));return -1===r?{answerBlocks:n,processBlocks:[]}:{processBlocks:n.slice(0,r+1),answerBlocks:n.slice(r+1)}}function e_(e,t={}){return eU(e,t).answerBlocks.some(e=>eO(e,t))}function eq(e){return e.filter(e=>"toolCall"===e.type).length}function eK(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 eV(e,t={}){let n=function(e,t={}){let{processBlocks:n,answerBlocks:r}=eU(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=e_(e,t),i=!!eF(e,t),o=n.answerBlocks.length>0?eK(e,n.answerBlocks,{omitError:!r}):null;return{processMessage:eB({...e,content:n.processBlocks},t).length>0||i&&!r?eK(e,n.processBlocks,{omitUsage:!!o&&!t.isStreaming,omitError:r}):null,answerMessage:o}}let eJ=/^\*\*\* (Add|Update|Delete) File: (.+)$/,eY=/^\*\*\* Move to: (.+)$/;function eZ(){return{lineNo:null,text:"",type:"empty"}}function eX(e){if(!e.includes("*** Begin Patch"))return null;let t=[],n=null,r=!1,i=[],o=[],l=()=>{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"}:eZ(),r=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"added"}:eZ();n.rows.push({type:"line",left:e,right:r})}i=[],o=[]};for(let s of e.split(/\r?\n/)){if(s.startsWith("*** Begin Patch")||s.startsWith("*** End Patch")){l(),r=!1;continue}let e=s.match(eJ);if(e){l(),r=!1;let i=e[1].toLowerCase();n={path:e[2].trim(),operation:i,rows:[]},t.push(n);continue}if(!n)continue;let a=s.match(eY);if(a){n.moveTo=a[1].trim();continue}if(s.startsWith("@@")){l(),r=!0,n.rows.push({type:"hunk",text:s});continue}if(s.startsWith("*** "))return null;if(""===s){l();continue}if(!r&&"update"===n.operation)continue;let d=s[0]??"",c=s.slice(1);"+"===d?o.push({lineNo:null,text:c}):"-"===d?i.push({lineNo:null,text:c}):" "===d&&(l(),n.rows.push({type:"line",left:{lineNo:null,text:c,type:"context"},right:{lineNo:null,text:c,type:"context"}}))}return l(),t.length>0?t:null}function eG(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function eQ(e){try{return decodeURIComponent(e)}catch{return e}}function e0(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e1(e){let t=e0(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 l=o.join("/");return n?l:r?`//${l}`:i?`/${l}`:l}function e2(e,t,n=t){let r,i,o,l,s;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=eQ(a),h=u.startsWith("\\\\"),p=e0(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=eQ(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=`${e0(t).replace(/\/+$/,"")}/${p}`,c="relative"),!d)return null;let g=e1(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=e1(g).replace(/\/+$/,""),i=e1(n).replace(/\/+$/,""),l=(o=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(l===(s=o?i.toLowerCase():i)||l.startsWith(`${s}/`)))?null:g}function e4(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 e8(e){let t=e.toLowerCase();return"apply_patch"===t||t.endsWith(".apply_patch")||t.endsWith("/apply_patch")||t.endsWith("_apply_patch")}function e5(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
3
3
|
|
|
4
4
|
${r}
|
|
@@ -6,7 +6,7 @@ ${r}
|
|
|
6
6
|
${n}`}function e6(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 e3(e,t,n,r=8){return e+t>=n-r}class e7 extends Error{constructor(e,t){super(t),this.name="OutlineLocateError",this.reason=e}}function e9(e,t){return e.entry.id===t||!!e.compressedEntryIds?.includes(t)}function te(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(e9(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 tt(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 e7("exhausted","Question is no longer in this branch. Refresh the outline and try again.");if(o.has(t))throw new e7("stalled","History did not advance. Please try again.");o.add(t);let l=await n(t);if(r.throwIfAborted(),!l)throw new e7("load_failed","Could not load this question. Please try again.");if(l.entryIds.includes(e))return;if(l.oldestEntryId===t||null!==l.oldestEntryId&&o.has(l.oldestEntryId))throw new e7("stalled","History did not advance. Please try again.");i=l}}function tn(e,t){return t.aborted||e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&"AbortError"===e.name}var tr=n(32316),ti=n(88374),to=n(5924),tl=n(94764),ts=n(63835),ta=n(23135),td=n(54152),tc=n(84678),tu=n(98164);let th={...tl.j,attributes:{...tl.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...tl.j.protocols,href:[...tl.j.protocols?.href??[],"file"]},strip:[...tl.j.strip||[],"iframe","object","style","form"]};function tp(e){return/^file:/i.test(e)?e:(0,tr.Lv)(e)}let tf=/(?<![\\`])`((?:[^`\n]|\\`)+?)(?<![\\`])`(?!`)/g;function tg(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,o=0,l=null,s=new Map,a=new Set;for(let e=0;e<n.length;e++){var d,c;let t=n[e];if(l){r.push(t),RegExp(`</${l}\\s*>`,"i").test(t)&&(l=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)||(l=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(tf,(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=>tv(e,g[1])),`${g[1]}$$`),e=t;continue}}let x=t.match(/^([ \t]*)\$\$(.+)\$\$[ \t]*$/);if(x){let e=x[2].trim();if(e){r.push(`${x[1]}$$`,`${x[1]}${e}`,`${x[1]}$$`);continue}}let m=t.match(/^([ \t]*)\$\$(.+)$/);if(m){let i=m[1],o=m[2].trimEnd();if(o&&!o.includes("$$")){let l=tx(n,e+1,i,s);if(l){r.push(`${i}$$`,`${i}${o}`);for(let t=e+1;t<l.index;t++)r.push(tv(n[t],i));l.content&&r.push(`${i}${l.content}`),r.push(`${i}$$`),e=l.index;continue}r.push(tm(t));continue}}let y=t.match(/^([ \t]*)\$\$\s*$/);if(y){let i=y[1],o=tx(n,e+1,i,s);if(o&&(o.glued||""!==i)){r.push(`${i}$$`);for(let t=e+1;t<o.index;t++)r.push(tv(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(tm(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 tx(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,l;let t=e[i];if(function(e,t){if(""===t)return/^ {0,3}\$\$\s*$/.test(e);let n=ty(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)||(l=t,/^[ \t]*\$\$(?:\S|[ \t]+\S)/.test(l)))return r.set(n,i),null;let s=function(e,t){let n=ty(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!==s)return{index:i,content:s,glued:!0}}return r.set(n,e.length),null}function tm(e){return e.replace(/^([ \t]*)\$\$/,(e,t)=>`${t}\\$\\$`)}function ty(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 tv(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 tb={singleTilde:!1},tw=[[td.A,["yaml"]],[tc.A,tb],tu.A,ta.A],tk=[[td.A,["yaml"]],[tc.A,tb],tu.A,ta.A],tj=[to.A,[ts.A,th],[ti.A,{throwOnError:!1,strict:!1}]],tS=[to.A,[ts.A,th],[ti.A,{throwOnError:!1,strict:!1}]];var tC=n(7644);let tI="pi-theme",tE=["light","dark","auto"],tM={preference:"auto",theme:"light"},tT=new Set,tL=null,tR=!1;function tN(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function t$(e){return"auto"===e?tN():e}let tW={light:"#f5f5f5",dark:"#242424"};function tz(e){"u">typeof document&&(document.documentElement.classList.toggle("dark","dark"===e),function(e){if("u"<typeof document)return;let t=tW[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 tP(){if(tL)return tL;let e=function(){try{let e=localStorage.getItem(tI);if("light"===e||"dark"===e||"auto"===e)return e}catch{}return"auto"}(),t=t$(e);return tz(t),tL={preference:e,theme:t}}function tA(e,t,n){if(tz(t),n)try{localStorage.setItem(tI,e)}catch{}tL={preference:e,theme:t},tT.forEach(e=>e())}function tD(){let e=tP();if("auto"!==e.preference)return;let t=tN();t!==e.theme&&tA("auto",t,!1)}function tH(e){return tT.add(e),tP(),tR||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tD),window.addEventListener("focus",tD),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tD()}),tR=!0),tD(),()=>{tT.delete(e)}}function tB(){return tP()}function tF(){return tM}function tO(){let e=(0,i.useSyncExternalStore)(tH,tB,tF),t=(0,i.useCallback)((e,t)=>{if(tP().preference===e)return;let n=t$(e),r=()=>{tA(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,l=t?.y??window.innerHeight/2,s=Math.hypot(Math.max(o,window.innerWidth-o),Math.max(l,window.innerHeight-l));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${o}px ${l}px)`,`circle(${s}px at ${o}px ${l}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=tP().preference,r=tE.indexOf(n),tE[(r+1)%tE.length]),e)},[t]);return{theme:e.theme,preference:e.preference,setThemePreference:t,toggleTheme:n,isDark:"dark"===e.theme}}function tU(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 t_=n(65063);function tq({code:e,isStreaming:t,defaultPreview:o=!1}){let{isDark:l}=tO(),{t:s}=(0,m.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=`${l?"dark":"light"}
|
|
7
7
|
${e}`,x=a&&!t;(0,i.useEffect)(()=>{if(!x)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:l?"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,l,x]);let y=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):x?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",x?"is-active":""].filter(Boolean).join(" "),children:x?s("i18n.source"):s("i18n.preview")}),[t,x,s]);if(!x)return(0,r.jsx)(tV,{code:e,lang:"mermaid",headerAction:y,isStreaming:t});let v=c?.key===g&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==g||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!h&&(0,r.jsx)("button",{ref:f,type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),h&&(0,r.jsx)(tK,{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:`${s("i18n.downloadFile")} (SVG)`,"aria-label":`${s("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"}),y]})]}),v]})}function tK({svg:e,onClose:t}){let{t:n}=(0,m.s)(),o=(0,i.useRef)(null),[l,s]=(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:()=>s(e=>Math.max(.5,e-.25)),disabled:l<=.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*l),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>s(e=>Math.min(3,e+.25)),disabled:l>=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:()=>s(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*l}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tV=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:o}){let{isDark:l}=tO(),{t:s}=(0,m.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:()=>{tU(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",title:s(a?"i18n.copied":"i18n.copy"),"aria-label":s(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:s(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)(t_.A,{language:t||"text",style:l?tC.xJ:tC.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 tJ({children:e,className:t,isStreaming:n,cwd:o,onOpenFile:l}){let s=(0,i.useMemo)(()=>tg(e),[e]),a=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let o=e?.replace("language-","").toLowerCase()??"",l=String(t);return e?.includes("language-")||l.includes("\n")?"mermaid"===o?(0,r.jsx)(tq,{code:l.replace(/\n$/,""),isStreaming:n,defaultPreview:!0}):(0,r.jsx)(tV,{code:l.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=l?e2(e,o):null;if(!i||!l)return(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t});let s=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(!eG(e))return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),l(i,s??void 0))},children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?e2(e,o):null,l=i?`/api/files/${v(i)}?type=read`:e;return(0,r.jsx)("img",{src:l,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,l]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(tr.oz,{remarkPlugins:tw,rehypePlugins:tj,urlTransform:l?tp:void 0,components:a,children:s})})}function tY({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"})]})}function tZ({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)(V,{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 tX=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tG=/(?:\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 tQ(e){let t,n=[],r=null,i=0,o=0,l=0,s=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(!(l>0||s>0)){if(c.startsWith("--- ")){u(),t=t0(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:t0(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]),l=void 0===e[2]?1:Number(e[2]),s=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"}}),l>0&&l--,s>0&&s--):"-"===h?(a.push({lineNo:i++,text:p}),l>0&&l--):"+"===h?(d.push({lineNo:o++,text:p}),s>0&&s--):""!==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 t0(e){return e.split(" ")[0].trim()}let t1="pi-thinking-expanded",t2="pi-thinking-expanded-changed";function t4(){return"true"===window.localStorage.getItem(t1)}function t8({files:e,onOpenFile:t}){let{t:n}=(0,m.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=b(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:$(i,12)}),(0,r.jsx)("span",{style:{lineHeight:1},children:i})]},e)})})}let t5=new Map;function t6({children:e,className:t,...n}){let{t:o}=(0,m.s)(),[l,s]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(tJ,{className:t,...n,children:e});if(!l){var a;return(0,r.jsxs)("button",{onClick:()=>s(!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 t3(e,t){if("number"!=typeof e||"number"!=typeof t)return;let n=Math.round((t-e)/1e3);return n>0?n:void 0}function t7(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 t9=(0,i.memo)(function({message:e,modelName:t,isStreaming:n,toolResults:i,cwd:o,onOpenFile:l,onOpenSession:s,entryId:a,searchBlock:d,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:f,isTurnEnd:g,sessionId:x,writtenFiles:m,isProcess:y}){return"user"===e.role?(0,r.jsx)(nt,{message:e,cwd:o,onOpenFile:l,entryId:a,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:f}):"assistant"===e.role?(0,r.jsx)(nn,{message:e,modelName:t,isStreaming:n,toolResults:i,cwd:o,onOpenFile:l,onOpenSession:s,isTurnEnd:g,sessionId:x,entryId:a,searchBlock:d,writtenFiles:m,isProcess:y}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(ny,{message:e}):eA(e)?(0,r.jsx)(nw,{message:e,cwd:o,onOpenFile:l}):(0,r.jsx)(nk,{message:e,cwd:o,onOpenFile:l}):"bashExecution"===e.role?(0,r.jsx)(nI,{message:e,sessionId:x}):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 ne({text:e,cwd:t,onOpenFile:n}){let i=function(e){let t=[],n=0;for(let r of e.matchAll(ep)){let i=function(e){let t=(e[1]??e[2]??"").replace(/[),.;]+$/,"");if(!(!ef.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),l=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*!!l},children:o.map(e=>(0,r.jsx)(eb,{path:e.path,cwd:t},e.path))}),l?(0,r.jsx)(t6,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:l}):null]}):(0,r.jsx)(t6,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:e})}function nt({message:e,cwd:t,onOpenFile:n,entryId:o,onFork:l,forking:s,onNavigate:a,prevAssistantEntryId:d,onEditContent:c}){let{t:h}=(0,m.s)(),[p,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(!1),[y,v]=(0,i.useState)(!1),b="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),w="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),k=u(b),j=k?.search(/\s/)??-1,S=k?-1===j?k:k.slice(0,j):"",C=k&&-1!==j?k.slice(j+1):"",I=t7(e.timestamp),E=!!o&&!!l,M=k??b,T=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,L=w.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!b},children:w.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)(ea,{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)})}),R=!!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:[L,(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(y?"i18n.collapse":"i18n.expand"),"aria-expanded":y,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:y?"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})]}),y&&(0,r.jsx)(tJ,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:b})]}):(0,r.jsxs)(r.Fragment,{children:[L,b&&(0,r.jsx)(ne,{text:b,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:()=>{tU(M).then(()=>{x(!0),setTimeout(()=>x(!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"})]})})}),(E||R)&&(0,r.jsxs)("div",{className:"message-action-group",style:{opacity:p||s?1:0,pointerEvents:p||s?"auto":"none"},children:[R&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{a(d),c?.(T)},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"})]})}),E&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{l(o)},disabled:s,title:h(s?"i18n.creatingSession":"i18n.newSessionTitle"),"aria-label":h(s?"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"})]})})]}),I&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",userSelect:"none"},children:I})]})]})}function nn({message:e,modelName:t,isStreaming:n,toolResults:o,cwd:l,onOpenFile:s,onOpenSession:a,isTurnEnd:d,sessionId:c,entryId:u,searchBlock:h,writtenFiles:p,isProcess:f}){let{t:g}=(0,m.s)(),[x,y]=(0,i.useState)(!1),v=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!eH(e,{isStreaming:n})),[e.content,n]),b=(0,i.useMemo)(()=>v.map(({block:e})=>e),[v]),w=e.completedAt??e.timestamp,k=(0,i.useMemo)(()=>{let t=new Map;if(!o||void 0===w)return t;for(let n of e.content){if("toolCall"!==n.type)continue;let e=o.get(n.toolCallId),r=t3(w,e?.timestamp);void 0!==r&&t.set(n.toolCallId,r)}return t},[e.content,o,w]),j=eF(e,{isStreaming:n}),S=function(e,t={}){return!t.isStreaming&&"length"===e.stopReason}(e,{isStreaming:n}),C=b.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),I=d&&!n?t7(e.timestamp):null,E=d&&!n&&(t||e.model)||null,M=d&&!n&&!!(E||C||I);return 0!==b.length||n||j||S?(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:v.map(({block:t,originalIndex:i},d)=>{let p="thinking"===t.type?t:null,f=p?p.startedAt??e.timestamp:void 0,g=p?t3(f,p.endedAt??e.completedAt):void 0,x=!!(n&&p&&d===v.length-1&&void 0===g&&"number"==typeof f);return(0,r.jsx)(no,{block:t,searchTarget:t===h,toolResults:o,isStreaming:n,streamingDuration:g,startTime:x?f:void 0,toolCallDurations:k,cwd:l,onOpenFile:s,onOpenSession:a,sessionId:c,entryId:u,blockIndex:i},`${u??"stream"}-${i}`)})}),j&&(f?(0,r.jsx)("div",{style:{marginTop:4*(b.length>0)},children:(0,r.jsx)(nr,{error:j})}):(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: ",j]})),S&&(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:g("chat.truncatedByOutputLimit")}),p&&p.length>0&&(0,r.jsx)(t8,{files:p,onOpenFile:s}),M&&(0,r.jsxs)("div",{"data-answer-footer":!0,style:{display:"flex",alignItems:"center",gap:6,marginTop:2},children:[E&&(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:E}),(C||I)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:"auto",flexShrink:0},children:[C&&(0,r.jsx)("button",{type:"button",className:"answer-copy-button message-action-button","data-copied":x?"true":void 0,onClick:()=>{tU(C).then(()=>{y(!0),setTimeout(()=>y(!1),1500)})},title:g(x?"i18n.copied":"i18n.copyMessage"),"aria-label":g(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"})]})}),I&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)",userSelect:"none"},children:I})]})]})]}):null}function nr({error:e}){let{t}=(0,m.s)(),[n,o]=(0,i.useState)(!1),l=(0,i.useId)(),s=(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":l,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: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: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:l,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 ni({startTime:e}){let[t,n]=(0,i.useState)(()=>Math.max(0,Math.round((Date.now()-e)/1e3)));return(0,i.useEffect)(()=>{let t=setInterval(()=>{n(Math.max(0,Math.round((Date.now()-e)/1e3)))},500);return()=>clearInterval(t)},[e]),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[t,"s"]})}function no({block:e,searchTarget:t,toolResults:n,isStreaming:i,streamingDuration:o,startTime:l,toolCallDurations:s,cwd:a,onOpenFile:d,onOpenSession:c,sessionId:u,entryId:h,blockIndex:p}){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)(nl,{block:e,isStreaming:i,cwd:a,onOpenFile:d})}):null}if("image"===e.type){let n=nC(e);return n?(0,r.jsx)("div",{"data-search-target":t||void 0,style:{margin:"8px 0"},children:(0,r.jsx)(ea,{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)(ns,{block:e,duration:o,startTime:l,isStreaming:i,sessionId:u,entryId:h,blockIndex:p});if("toolCall"===e.type){let t=n?.get(e.toolCallId),i=s?.get(e.toolCallId);return(0,r.jsx)(na,{block:e,result:t,duration:i,onOpenSession:c})}return null}function nl({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(t6,{className:"markdown-assistant-message",isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function ns({block:e,duration:t,startTime:n,isStreaming:o,sessionId:l,entryId:s,blockIndex:a}){var d;let{t:c}=(0,m.s)(),[u,h]=(0,i.useState)(t4),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(!1),[y,v]=(0,i.useState)(null),b=(0,i.useRef)(c);b.current=c;let w=(d=e.thinking,d.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>h(t4());return window.addEventListener(t2,e),()=>window.removeEventListener(t2,e)},[]),(0,i.useEffect)(()=>{if(!u||!e.deferred||null!==p)return;if(!l||!s)return void v(b.current("i18n.thinkingUnavailable"));let t=!1;return x(!0),v(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=t5.get(r);if(i)return t5.delete(r),t5.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 t5.delete(r),e});if(t5.set(r,o),t5.size>100){let e=t5.keys().next().value;e&&t5.delete(e)}return o})(l,s,a).then(e=>{t||(f(e),x(!1))}).catch(e=>{t||(v(e instanceof Error?e.message:String(e)),x(!1))}),()=>{t=!0}},[u,e.deferred,p,l,s,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")}${w?`: ${w}`:""}`,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)(tY,{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:w?(0,r.jsx)(tr.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:w}):"..."}),u&&(0,r.jsx)("div",{style:{flex:1}}),void 0!==t?(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums",lineHeight:1.35},children:[t,"s"]}):o&&n?(0,r.jsx)(ni,{startTime:n}):null,(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:y?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:g?c("i18n.loadingThinking"):y??(e.deferred?p:e.thinking)})]})}function na({block:e,result:t,duration:n,onOpenSession:o}){var l,s;let{t:a}=(0,m.s)(),[d,c]=(0,i.useState)(!1),u=(s=e).rawInput??JSON.stringify(s.input,null,2),h=void 0!==e.rawInput,p=e4(e.toolName),f=e8(e.toolName),g=f?"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,x=em(e.toolName,e.input,t?.details),y="edit"===x?a("image.edit"):"generate"===x?a("image.generate"):e.toolName,v=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,b=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,w=nS(t?.content??[]),k=null!==b&&("(no output)"===b.trim()||""===b.trim()),j=t?.isError??!1,S=(l=t?.details)&&"object"==typeof l&&"pi-web-subagent"===l.kind&&"string"==typeof l.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:j?"1px solid rgba(248,113,113,0.45)":"1px solid var(--border)",background:j?"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":d,"data-step-trigger":"",onClick:()=>c(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)(tZ,{toolName:e.toolName,isError:j,size:12})}),(0,r.jsx)("span",{style:{color:j?"#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:h?a("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)}),void 0!==n&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums",lineHeight:1.35},children:[n,"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:d?"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"})})]}),S&&o&&(0,r.jsx)("button",{type:"button",onClick:()=>o(S.sessionId),title:a("subagent.open"),"aria-label":a("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"})]})})]}),d&&(h||!p)&&!f&&(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:j?"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:u}),d&&f&&void 0!==g&&(0,r.jsx)("div",{style:{borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)(nh,{patch:g})}),d&&f&&void 0===g&&(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:a("chat.generatingToolInput")}),d&&t&&!(f&&void 0!==g)&&(v?(0,r.jsx)(nc,{diff:v}):(0,r.jsx)(nm,{text:b??"",images:w,isEmpty:k,isError:j})),!d&&w.length>0&&(0,r.jsx)("div",{style:{padding:"6px 10px 8px",borderTop:j?"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)(nd,{images:w,thumbnails:!0})})})]})}function nd({images:e,thumbnails:t=!1}){return(0,r.jsx)(r.Fragment,{children:e.map((e,n)=>{let i=nC(e);return i?(0,r.jsx)(ea,{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 nc({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(nu,{text:e.text})})}function nu({text:e}){let t=(0,i.useMemo)(()=>tQ(e),[e]);return t?(0,r.jsx)(np,{files:t}):(0,r.jsx)(nx,{text:e})}function nh({patch:e}){let t=(0,i.useMemo)(()=>eX(e),[e]);return t?(0,r.jsx)(np,{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)(nx,{text:e})}function np({files:e}){let{t}=(0,m.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)(nf,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(nf,{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)(ng,{cell:e.left,side:"left"}),(0,r.jsx)(ng,{cell:e.right,side:"right"})]},t))})]},i))})}function nf({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 ng({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 nx({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 nm({text:e,images:t,isEmpty:n,isError:i}){let{t:o}=(0,m.s)(),l=!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)(nd,{images:t})}),l&&(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 ny({message:e}){let{t}=(0,m.s)(),n=nj(e.content),o=(0,i.useMemo)(()=>{let e,t,r,i,o;return e=[],t=[],r=n.match(tG),i=r?.[1]??"",o=r?.index===void 0?n:n.slice(0,r.index),i.replace(tX,(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]),l=t7(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"}),l&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:l})]}),(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)(tJ,{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)(nv,{readFiles:o.readFiles,modifiedFiles:o.modifiedFiles})]})]})})}function nv({readFiles:e,modifiedFiles:t}){let{t:n}=(0,m.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)(nb,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(nb,{title:n("i18n.readFiles"),files:e})]})}function nb({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 nw({message:e,cwd:t,onOpenFile:n}){let{t:o}=(0,m.s)(),[l,s]=(0,i.useState)(!1),a=(e.details?.sessionIds??[]).length||1,d=1===a?o("subagent.notificationSingle"):o("subagent.notificationMany",{count:a}),c=nj(e.content);return(0,r.jsxs)("div",{"data-step-card":"",style:{overflow:"hidden",borderRadius:4},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":l,"data-step-trigger":"",title:d,onClick:()=>s(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)(V,{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:l?"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"})})]}),l&&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)(t6,{className:"markdown-subagent-notification",cwd:t,onOpenFile:n,children:c})})]})}function nk({message:e,cwd:t,onOpenFile:n}){let o,{t:l}=(0,m.s)(),s=!1===e.display,[a,d]=(0,i.useState)(!s),[c,u]=(0,i.useState)(!1),[h,p]=(0,i.useState)(!1),f=nj(e.content),g=nS(e.content),x=void 0!==e.details,y=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",v=e.customType||"extension",b=t7(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:s?"var(--bg-subtle)":"var(--bg)",opacity:s&&!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}),s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),b&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:b})]}),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=nC(e);return n?(0,r.jsx)(ea,{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)(tJ,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("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":l("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||y?(0,r.jsx)("button",{onClick:()=>{tU(f||y).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:l(h?"i18n.copied":"i18n.copy")}):null,(x||s)&&(0,r.jsx)("button",{onClick:()=>{s?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:l(s?a?"i18n.collapse":"i18n.expand":c?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(s&&a||!s&&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:y})]})})}function nj(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function nS(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function nC(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 nI({message:e,sessionId:t}){let[n,o]=(0,i.useState)(null),[l,s]=(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){s(!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{s(!1)}}}let x=e.excludeFromContext?"bash (local)":"bash",m={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:x,input:{command:e.command}},y=c?void 0:{role:"toolResult",toolCallId:m.toolCallId,toolName:x,content:f?[{type:"text",text:f}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(na,{block:m,result:y}),e.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[p&&(0,r.jsx)("button",{onClick:g,disabled:l,style:{background:"none",border:"none",color:"var(--accent)",cursor:l?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:l?"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,")"]})]})]})}let nE=["off","minimal","low","medium","high","xhigh","max"],nM=RegExp(`:(${nE.join("|")})$`),nT=new Map;function nL(e){return`pi-chat-draft:${encodeURIComponent(e)}`}function nR(){try{return window.sessionStorage}catch{return null}}function nN(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function n$(e){return!e.value&&0===e.images.length}function nW(e){let t=nT.get(e)??function(e){try{let t=nR()?.getItem(nL(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 nN(n)}catch{return null}}(e);return t&&!nT.has(e)&&nT.set(e,t),t?nN(t):null}function nz(e,t){if(n$(t))return nP(e),!0;let n=nN(t);nT.set(e,n);let r=nR();if(!r)return!1;try{return r.setItem(nL(e),JSON.stringify(n)),!0}catch{return r.removeItem(nL(e)),!1}}function nP(e){nT.delete(e);try{nR()?.removeItem(nL(e))}catch{}}function nA(e,t){return e.trim()?t.trim()?`${e}
|
|
8
8
|
|
|
9
|
-
${t}`:e:t}function nD(e){return{data:e.data,mimeType:e.mimeType}}function nH(e,t,n,r){return{value:nA(e,n),images:[...t??[],...r].map(nD)}}function nB(e,t,n){if(e===t)return n?nN(n):nW(t);let r=nW(e),i=n&&!n$(n)?nN(n):r??(n?nN(n):null),o=nW(t);if(nP(e),!i)return o;let l=o?nH(o.value,o.images,i.value,i.images):i;return nz(t,l),nN(l)}function nF(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 nO(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function nU(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 n_(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}let nq="(max-width: 640px)",nK=e=>(function(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)})(nq,e),nV=()=>!!window.matchMedia&&window.matchMedia(nq).matches;function nJ(){return!1}function nY(){return(0,i.useSyncExternalStore)(nK,nV,nJ)}let nZ="pi-chat-content-width",nX="pi-chat-content-font-size",nG={width:820,fontSize:14},nQ=null,n0=new Set;function n1(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function n2(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function n4(e){try{return window.localStorage.getItem(e)}catch{return null}}function n8({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 n5(){return nQ||n8(nQ={width:n1(n4(nZ)),fontSize:n2(n4(nX))}),nQ}function n6(e){return n0.add(e),()=>{n0.delete(e)}}function n3(e,t){let n="width"===e?n1(t):n2(t);n8(nQ={...n5(),[e]:n});try{window.localStorage.setItem("width"===e?nZ:nX,String(n))}catch{}n0.forEach(e=>e())}let n7=e=>n3("width",e),n9=e=>n3("fontSize",e);function re(){return{...(0,i.useSyncExternalStore)(n6,n5,()=>nG),setWidth:n7,setFontSize:n9}}var rt=n(14755);function rn(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 rr="pi-shift-enter-to-send";function ri(){try{return"true"===window.localStorage.getItem(rr)}catch{return!1}}let ro=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rl(e,t){return ro.compare(e.name||e.modelId,t.name||t.modelId)||ro.compare(e.provider,t.provider)||ro.compare(e.modelId,t.modelId)}function rs({options:e,value:t,onChange:n,onClear:o,emptyLabel:l,selectedLabel:s,disabled:a=!1,busy:d=!1,isAutoSelection:c=!1,ariaLabel:u,variant:h="toolbar",placement:p="up"}){let f,g,x,m,y,v,b,w,k=nY(),j=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),I=(0,i.useId)(),[E,M]=(0,i.useState)(!1),[T,L]=(0,i.useState)(0),[R,N]=(0,i.useState)(null),$=a||d,W=(0,i.useMemo)(()=>[...e].sort(rl),[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=s??(t?W.find(e=>e.modelId===t.modelId&&e.provider===t.provider)?.name??t.modelId:l??(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(T,A.length-1):0,B=A.length?`${I}-option-${H}`:void 0,F=(0,i.useCallback)(()=>{let e=S.current?.getBoundingClientRect();e&&N({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)&&M(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{$&&M(!1)},[$]),(0,i.useEffect)(()=>{if(!E)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)}},[E,F]),(0,i.useEffect)(()=>{E&&L(Math.max(0,Math.min(D>=0?D:0,A.length-1)))},[E,D,A.length]),(0,i.useEffect)(()=>{E&&B&&document.getElementById(B)?.scrollIntoView({block:"nearest"})},[E,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:E?"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;M(!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&&E&&(e.preventDefault(),e.stopPropagation(),M(!1))},children:[(0,r.jsxs)("button",{ref:S,type:"button",role:"combobox","aria-label":u,"aria-haspopup":"listbox","aria-controls":I,"aria-activedescendant":E?B:void 0,"aria-expanded":E,onKeyDown:e=>{if("Escape"===e.key&&E){e.preventDefault(),M(!1);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!E){F(),L(D>=0?D:0),M(!0);return}let t="ArrowDown"===e.key?1:-1;L(e=>A.length?(e+t+A.length)%A.length:0);return}if(E&&A.length){if("Home"===e.key||"End"===e.key)e.preventDefault(),L("Home"===e.key?0:A.length-1);else if("Enter"===e.key||" "===e.key){e.preventDefault();let t=A[H];null===t?(M(!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(),M(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=E?"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"})})]}),E&&R&&(f=window.visualViewport?.height??window.innerHeight,g=window.visualViewport?.width??window.innerWidth,x=R.top-8,m=f-R.bottom-8,v=Math.max(120,Math.min((y="up"===p||x>m)?x:m,.6*f)),b=y?{bottom:f-R.top+6}:{top:R.bottom+6},w=k?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:R.left,width:"max-content",minWidth:R.width,maxWidth:Math.max(R.width,g-R.left-8)},(0,r.jsx)("div",{ref:C,id:I,role:"listbox","aria-label":u,"aria-activedescendant":B,style:{position:"fixed",...b,...w,zIndex:500,display:"flex",flexDirection:"column",maxHeight:v,overflow:"hidden",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:y?"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)(ra,{id:`${I}-option-0`,active:!t,highlighted:0===H,label:l??"Default",onActive:()=>L(0),onClick:()=>{M(!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)(ra,{id:`${I}-option-${A.indexOf(e)}`,active:e.modelId===t?.modelId&&e.provider===t?.provider,highlighted:H===A.indexOf(e),label:e.name,onActive:()=>L(A.indexOf(e)),onClick:()=>U(e)},`${e.provider}:${e.modelId}`))]},e.provider))]})}))]})}function ra({id:e,active:t,highlighted:n,label:i,onActive:o,onClick:l}){return(0,r.jsxs)("button",{id:e,type:"button",role:"option","aria-selected":t,"data-active":n||void 0,onClick:l,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 rd=["configured","chat-only","read-only","default","full"],rc={configured:rt.Q8,"chat-only":"none","read-only":"read-only",default:"default",full:"full"},ru=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rh(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,l=o?.parentElement,s="u">typeof ResizeObserver&&o?new ResizeObserver(i):null;o&&s?.observe(o),l&&s?.observe(l);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{s?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let rp=["auto",...nE],rf={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},rg=[{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 rx(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return rg.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}function rm(e,t){return`${t.map(e=>n_(e,!1)).join("")}${e.trim()}`.trim()}let ry=["builtin","extension","prompt","skill"],rv={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},rb={builtin:0,extension:1,prompt:2,skill:3};function rw(e,t,n){let r=e.name.toLowerCase(),i=rk(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function rk(e,t){return"builtin"===e.source?t(e.description):e.description??""}function rj(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 rS={name:"<session-title>",session:"[session-id]",clone:"[new-title]"};function rC(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function rI(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 l=i.toDataURL("image/jpeg",.85).split(",")[1];return l&&l.length<4*Math.ceil(e.size/3)?{data:l,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function rE(e){return{data:e.data,mimeType:e.mimeType}}function rM(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function rT(e){return(e??[]).map(rM)}function rL(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function rR({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 rN({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 r$({error:e}){let{t}=(0,m.s)();return e?(0,r.jsx)(rN,{tone:"error",title:t("chat.modelError"),body:e}):null}function rW({warnings:e}){let{t}=(0,m.s)();return e&&0!==e.length?(0,r.jsx)(rN,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let rz=(0,i.forwardRef)(function({onSend:e,onOpenImageGeneration:t,onAbort:n,onSteer:o,onFollowUp:l,isStreaming:s,disabled:a=!1,model:d,isAutoModelSelection:c,modelNames:u,modelList:h,modelError:p,modelScopeWarnings:f,onModelChange:g,modelSwitching:x,onCompact:y,onAbortCompaction:v,isCompacting:b,compactError:w,compactResult:k,toolPreset:j,onToolPresetChange:S,contextUsage:C,cacheHitRate:I,onOpenSessionStats:E,thinkingLevel:M,onThinkingLevelChange:T,availableThinkingLevels:R,thinkingLevelMap:N,retryInfo:W,queuedMessages:z,inputHistory:P=[],onRecallQueue:A,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,el,{t:es}=(0,m.s)(),{fontSize:ea}=re(),ed=nY(),ec=(0,i.useId)(),[eu,eh]=(0,i.useState)(()=>K?nW(K)?.value??"":""),[ep,ef]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),[em,ey]=(0,i.useState)(!1),[ev,ew]=(0,i.useState)(!1),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)([]),eI=(0,i.useRef)([]);eI.current=eS;let[eE,eM]=(0,i.useState)(()=>K?rT(nW(K)?.images):[]),eT=eu.trimStart(),eL=0===eE.length&&eT.startsWith("!"),eR=eL&&eT.startsWith("!!"),[eN,e$]=(0,i.useState)(!1),[eW,ez]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(0),[eD,eH]=(0,i.useState)(null),[eB,eF]=(0,i.useState)(null),[eO,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(0),[eJ,eY]=(0,i.useState)(!1),[eZ,eX]=(0,i.useState)(!1),[eG,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(0),e2=(0,i.useRef)(null),[e4,e8]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(null),tr=Y&&tt?.cwd===Y?tt.values:{},ti=(0,i.useRef)(null),to=(0,i.useRef)(null),tl=(0,i.useRef)(null),ts=(0,i.useRef)(null),ta=(0,i.useRef)(null),td=(0,i.useRef)(null),tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),th=(0,i.useRef)(null),tp=(0,i.useRef)(null),tf=(0,i.useRef)(!1),tg=(0,i.useRef)(0),tx=(0,i.useRef)(!1),tm=(0,i.useRef)(null),ty=(0,i.useRef)([]),tv=(0,i.useRef)(null),tb=(0,i.useRef)([]),tw=(0,i.useRef)(!1),tk=(0,i.useRef)([]),tj=(0,i.useRef)(null),tS=(0,i.useRef)(null),tC=(0,i.useRef)(0),tI=(0,i.useRef)(K),tE=(0,i.useRef)(eu),tM=(0,i.useRef)(eE),tT=(0,i.useRef)(0);tE.current=eu,tM.current=eE,(0,i.useImperativeHandle)(X,()=>({insertIfEmpty(e){let t=ti.current;(t?t.value:eu).trim()||(tE.current=e,eh(e),eF(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=ti.current;if(t=i?i.value:eu,n=tM.current.length,r=tT.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"),l=rT("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]}));tE.current=o,tM.current=l,eh(o),eF(null),eQ(!1),eM(e=>(e.forEach(rL),l)),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=ti.current,n=[e,t?t.value:eu].filter(e=>e.trim()).join("\n\n");tE.current=n,eh(n),eF(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(tI.current!==e)return void nB(e,t);let n={value:tE.current,images:tM.current.map(rE)},r=nB(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(tI.current=t,i)return;let o=rT(r.images);tE.current=r.value,tM.current=o,eh(r.value),eM(e=>(e.forEach(rL),o)),eF(null),eQ(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tI.current,i=n??r,o=i===r,l=!o&&i?nW(i):null,s=nH(e,t,o?tE.current:l?.value??"",o?tM.current.map(rE):l?.images??[]);if(i&&nz(i,s),!o)return;let a=rT(s.images);tE.current=s.value,tM.current=a,eh(t=>{let n=nA(e,t);return tE.current=n,n}),eF(null),eQ(!1),eM(e=>(e.forEach(rL),tM.current=a,a)),requestAnimationFrame(()=>{let e=ti.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=ti.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),l=i.length>0&&!i.endsWith(" ")?" ":"",s=i+l+e+o;tE.current=s,eh(s),eF(null),requestAnimationFrame(()=>{if(!t)return;let r=n+l.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){tL(e)},mentionImage(e){eC(t=>t.includes(e)?t:[...t,e]),requestAnimationFrame(()=>ti.current?.focus())}}));let tL=(0,i.useCallback)(async e=>{if(Z)return;let t=Math.max(0,10-tM.current.length-tT.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(!n.length)return;let r=tC.current;tT.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await rI(e),previewUrl:URL.createObjectURL(e)})));eM(t=>{if(r!==tC.current)return e.forEach(rL),t;let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(rL);let i=[...t,...n];return tM.current=i,i})}finally{tT.current-=n.length}},[Z]),tR=(0,i.useCallback)(e=>{eM(t=>{let n=[...t],[r]=n.splice(e,1);return r&&rL(r),tM.current=n,n})},[]),tN=(0,i.useCallback)(()=>{tM.current=[],eM(e=>(e.forEach(rL),[]))},[]),t$=(0,i.useCallback)(()=>{tC.current+=1,e2.current=null,tE.current="",eh(""),eF(null),eQ(!1),K&&nP(K),tI.current&&tI.current!==K&&nP(tI.current),tN(),eI.current=[],eC([]),ti.current&&(ti.current.style.height="auto")},[tN,K]);(0,i.useEffect)(()=>{K&&tI.current===K&&(e8(!nz(K,{value:eu,images:eE.map(rE)})),V?.(K,eu,eE.length))},[eE,K,V,eu]),(0,i.useEffect)(()=>{let e=tI.current;if(e===K)return;e&&nz(e,{value:tE.current,images:tM.current.map(rE)});let t=K?nW(K):null;tI.current=K;let n=t?.value??"",r=rT(t?.images);tC.current+=1,tE.current=n,tM.current=r,eh(n),eF(null),eQ(!1),eM(e=>(e.forEach(rL),r)),K&&V?.(K,n,r.length)},[K,V]);let tW=(0,i.useCallback)(()=>{let e=ti.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tW,[eu,ea,tW]),(0,i.useEffect)(()=>{let e=ti.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,tW())});return n.observe(e),()=>n.disconnect()},[tW]),(0,i.useEffect)(()=>()=>{tC.current+=1,tM.current.forEach(rL)},[]);let tz=(0,i.useCallback)(async e=>{if(eE.length||!e.startsWith("/")||!F)return!1;if(tw.current)return!0;tw.current=!0,eY(!0);try{var t,n;let r=await F(e);if(!r.handled)return!1;return r.error||(t=tE.current,n=tM.current.length,0!==n||t.trim()!==e)||t$(),!0}finally{tw.current=!1,eY(!1)}},[eE.length,t$,F]),tP=(0,i.useCallback)(async()=>{if(a)return;let t=eu.trim();if(eE.length>10)return;let n=rm(t,eS);if(!n&&!eE.length||(_?.(),(!s||rx(t))&&await tz(t)||s))return;let r=eE.length?eE:void 0;t$(),e(n,r)},[a,eu,eE,eS,s,tz,e,t$,_]),tA=!Z&&eu.startsWith("/")&&!/\s/.test(eu.slice(1))?eu.slice(1).toLowerCase():null,tD=null===tA?[]:[...s?rg.filter(e=>e.availableWhileStreaming):rg,...D??[]].filter(e=>{let t=e.name.toLowerCase(),n=rk(e,es).toLowerCase();return t.includes(tA)||n.includes(tA)}).sort((e,t)=>{let n=rw(e,tA,es)-rw(t,tA,es);return 0!==n?n:rb[e.source]-rb[t.source]||ru.compare(e.name,t.name)}),{commands:tH,groups:tB}=(G=0,{commands:(Q=ry.map(e=>{let t=tD.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!rC(e,tr)),...t.filter(e=>rC(e,tr))]: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}),tF=(()=>{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&&rS[n[1]]?{command:n[1],signature:rS[n[1]],hasArgument:n[2].trim().length>0}:null})(),tO=1===tD.length?es(tA?"chat.match":"chat.command"):es(tA?"chat.matches":"chat.commands",{count:tD.length}),tU=!!eu.trim(),t_=eE.length>10,tq=!t_&&(tU||eE.length>0||eS.length>0),tK=!a&&!t_&&(tU||eE.length>0||eS.length>0),tV=eE.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)&&!eZ;(0,i.useEffect)(()=>{0===eE.length&&eX(!1)},[eE.length]);let tJ=(0,i.useCallback)((e,t)=>{if(!Y)return void eF(null);let n=t??e.length;eF(nF(e.slice(0,n)))},[Y]),tZ=eB?.query??null,tX=i.useMemo(()=>null!==tZ&&e5&&e5.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:nU(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:nU(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||nO(e.entry.path)-nO(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(e5.entries,tZ):[],[tZ,e5,Y]),tG=!!(tZ&&e5?.clientTruncated&&e5.cwd===Y);(0,i.useEffect)(()=>{if(!tG||!Y||!tZ)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(Y)}&q=${encodeURIComponent(tZ)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>te({cwd:Y,query:tZ,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tG,tZ,Y]);let tQ=tG&&null!==e9&&e9.cwd===Y&&e9.query===tZ,t0=tQ?e9.matches:tX,t1=null===eB?null:`${eB.start}:${+!!eB.quoted}:${eB.query}`;(0,i.useEffect)(()=>{if(null===t1){eU(!1),eV(0);return}eU(!0),eV(0)},[t1]);let t2=null!==eB;(0,i.useEffect)(()=>{if(!t2||!Y)return;let e=tj.current;e&&e.cwd===Y&&Date.now()-e.fetchedAt<1e4||tS.current===Y||(tS.current=Y,e7(!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=>{e6({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)=>nO(e.path)-nO(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),clientTruncated:!!e.clientTruncated,serverHardTruncated:!!e.serverHardTruncated}),tj.current={cwd:Y,fetchedAt:Date.now()}}).catch(()=>{tj.current=null}).finally(()=>{tS.current=null,e7(!1)}))},[t2,Y]);let t4=(0,i.useCallback)(e=>{if(!eB)return;let t=ti.current,n=t?.selectionStart??eu.length,r=eu.slice(0,eB.start),i=eu.slice(n);eB.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,eB.quoted),l=r+o.text+i,s=r.length+o.cursorOffset;tE.current=l,eh(l),ez(s),eF(nF(l.slice(0,s))),rj(ti,s)},[eB,eu]);(0,i.useEffect)(()=>{eK>=t0.length&&eV(Math.max(0,t0.length-1))},[t0.length,eK]),(0,i.useEffect)(()=>{tb.current.length=t0.length},[t0.length]),(0,i.useEffect)(()=>{eO&&tb.current[eK]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eK,eO]),(0,i.useEffect)(()=>{e0>=P.length&&e1(Math.max(0,P.length-1))},[P.length,e0]),(0,i.useEffect)(()=>{tk.current.length=P.length},[P.length]),(0,i.useEffect)(()=>{eG&&tk.current[e0]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e0,eG]);let t8=(0,i.useCallback)(()=>{let e=e2.current;e2.current=null,e&&(tE.current=e.text,eh(e.text)),eQ(!1)},[]),t5=(0,i.useCallback)(e=>{e2.current=null,tE.current=e,eh(e),ez(e.length),eQ(!1),e1(0),eF(null),rj(ti,e.length)},[]),t6=(0,i.useCallback)(e=>{let t=`/${e.name} `;tE.current=t,eh(t),ez(t.length),e$(!1),eA(0),rj(ti,t.length)},[]),t3=(0,i.useCallback)(e=>{let t=eu.trim();if(eE.length>10)return;let n=rm(t,eS);if(!n&&!eE.length)return;if(_?.(),!eE.length&&F&&rx(t))return void tz(t);let r=eE.length?eE:void 0;if(t.startsWith("/")&&q){t$(),q(t,"steer"===e?"steer":"followUp",r);return}t$(),"steer"===e&&o?o(n,r):"followup"===e&&l&&l(n,r)},[eu,eE,eS,F,q,o,l,t$,_,tz]),t7=(0,i.useCallback)(e=>{let t=e.nativeEvent,r=!ed&&ri(),i="Enter"===e.key&&e.shiftKey===r&&(!ed||e.ctrlKey||e.metaKey),a=Date.now()-tg.current<100,d=tf.current||t.isComposing||229===t.keyCode;if(i&&(d||a)){a&&e.preventDefault();return}if(eG&&!d){if("ArrowDown"===e.key){e.preventDefault(),e1(e=>Math.min(Math.max(0,P.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e1(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),t8();return}if(("Tab"===e.key||i)&&P[e0]){e.preventDefault(),t5(P[e0]);return}}if(eN&&null!==tA&&!d){if("ArrowDown"===e.key){e.preventDefault(),eA(e=>0===tH.length?0:(e+1)%tH.length);return}if("ArrowUp"===e.key){e.preventDefault(),eA(e=>0===tH.length?0:(e-1+tH.length)%tH.length);return}if("Escape"===e.key){e.preventDefault(),e$(!1);return}let t=tH[eP];if("Tab"===e.key&&t){e.preventDefault(),t6(t);return}if(i&&t)return void((e.preventDefault(),s&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||eu.trim()!==`/${t.name}`)?t6(t):(e$(!1),tP()))}if(eO&&null!==eB&&!d){if("ArrowDown"===e.key){e.preventDefault(),eV(e=>0===t0.length?0:(e+1)%t0.length);return}if("ArrowUp"===e.key){e.preventDefault(),eV(e=>0===t0.length?0:(e-1+t0.length)%t0.length);return}if("Escape"===e.key){e.preventDefault(),eU(!1);return}if(("Tab"===e.key||i)&&t0[eK]){e.preventDefault(),t4(t0[eK]);return}}if("ArrowUp"===e.key&&!d&&!s&&P.length>0){e.preventDefault(),e$(!1),eU(!1),e2.current={text:eu},e1(P.length-1),eQ(!0);return}if("Escape"===e.key&&ev){e.preventDefault(),ew(!1);return}if("Escape"===e.key&&!d&&s&&n){e.preventDefault(),n();return}i&&(e.preventDefault(),s&&(o||l)?t3(e.altKey&&l||!o?"followup":"steer"):tP())},[ed,s,o,l,n,ev,eN,tA,tH,eP,t6,t3,tP,eO,eB,t0,eK,t4,eG,P,e0,t5,t8,eu]),t9=(0,i.useCallback)(()=>{let e=ti.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),ne=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!Z&&t.length){e.preventDefault(),tL(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:l,occurrence:s}of t){if(!o||!l)continue;let t=0;for(let n=0;n<=s&&!((t=e.indexOf(o,n?t+o.length:0))<0);n++);if(t<r)continue;let a=o.replace(/([\\[\]])/g,"\\$1"),d=l.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 l=e.currentTarget,s=l.selectionStart,a=l.value.slice(0,s)+o+l.value.slice(l.selectionEnd);e.preventDefault(),tE.current=a,eh(a),eQ(!1),tJ(a,s+o.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(s+o.length,s+o.length)})},[Z,tL,tJ]);(0,i.useEffect)(()=>{if(null===tA){e$(!1),eA(0),tx.current=!1;return}e$(!0),eA(0),!tx.current&&B&&(tx.current=!0,Promise.resolve(B()).catch(()=>{tx.current=!1}))},[tA,B]),(0,i.useEffect)(()=>{if(!eN||!Y)return;let e=!1;return tn({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;tn({cwd:Y,values:n})}).catch(()=>{e||tn({cwd:Y,values:{}})}),()=>{e=!0}},[eN,Y]),(0,i.useEffect)(()=>{eP>=tH.length&&eA(Math.max(0,tH.length-1))},[tH.length,eP]),(0,i.useEffect)(()=>{ty.current.length=tH.length},[tH.length]),(0,i.useEffect)(()=>{eN&&ty.current[eP]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eP,eN]),(0,i.useLayoutEffect)(()=>{if(!eN||null===tA)return void eH(null);let e=tm.current;if(e)return rh(e,e=>{eH(t=>t===e?t:e)})},[eN,tA]),(0,i.useLayoutEffect)(()=>{if(!eO||null===eB)return void eq(null);let e=tv.current;if(e)return rh(e,e=>{eq(t=>t===e?t:e)})},[eO,eB]);let nt=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})),nn=k?Math.max(0,k.tokensBefore-k.estimatedTokensAfter):0,nr=k?`${k.reason&&"manual"!==k.reason?`${k.reason[0].toUpperCase()}${k.reason.slice(1)} `:es("chat.compacted")} ${rn(k.tokensBefore)} -> ${rn(k.estimatedTokensAfter)} tokens (${es("chat.tokensSaved",{saved:rn(nn)})})`:null,ni="auto"!==(ee=M??"auto")&&N?N[ee]??ee:ee,no=Object.entries(rc).find(([,e])=>e===(j??rt.Q8))?.[0]??"configured",nl="chat-only"===no?es("chat.chatOnly"):no,ns=C?.percent??null,na=[ni,null!=ns&&ns>=70?`${Math.round(ns)}%`:null].filter(Boolean).join(" \xb7 ");(0,i.useEffect)(()=>{let e=e=>{let t=e.target;to.current&&!to.current.contains(t)&&ef(!1),tl.current&&!tl.current.contains(t)&&ex(!1),ts.current&&!ts.current.contains(t)&&ew(!1),ta.current&&!ta.current.contains(t)&&ej(!1),tu.current&&!tu.current.contains(t)&&ey(!1),!tm.current||tm.current.contains(t)||ti.current?.contains(t)||e$(!1),!tv.current||tv.current.contains(t)||ti.current?.contains(t)||eU(!1),!th.current||th.current.contains(t)||ti.current?.contains(t)||t8()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[t8]),(0,i.useEffect)(()=>{ed||ej(!1)},[ed]);let nd=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,l=null!==i&&i>=85,s=null!==i&&i>=70&&i<85,a=null!==n?`${rn(n)}/${rn(t)}`:`?/${rn(t)}`,d=null!==n?Math.max(0,t-n):null,c=[`${es("chat.contextUsage")}: ${null!==n?rn(n):"?"} / ${rn(t)} (${null!==i?i.toFixed(1):"?"}%)`,null!==d?`${es("chat.contextRemaining")}: ${rn(d)}`:null,null!=I?`${es("session.cacheHitRate")}: ${I.toFixed(1)}%`:null,l?`⚠️ ${es("chat.contextHighWarning")}`:null].filter(Boolean).join("\n");return(0,r.jsxs)("button",{ref:tu,type:"button",onClick:()=>{ey(e=>!e),E?.()},title:c,"aria-label":c,"data-top-panel-trigger":E?"session":void 0,"aria-controls":E?"workspace-top-panel":void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",height:e?32:28,background:em?l?"rgba(239,68,68,0.12)":"var(--bg-hover)":l?"rgba(239,68,68,0.06)":"none",border:l?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:l?"#ef4444":s?"rgba(234,179,8,0.95)":"var(--text-muted)",cursor:E?"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||!E||em||(t.currentTarget.style.background=l?"rgba(239,68,68,0.12)":"var(--bg-hover)")},onMouseLeave:t=>{e||!E||em||(t.currentTarget.style.background=l?"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:l?600:400,letterSpacing:"-0.01em",lineHeight:1},children:a}),null!=I&&(0,r.jsxs)("span",{style:{lineHeight:1},children:[I.toFixed(0),"%"]})]})};(0,i.useLayoutEffect)(()=>{if(!ed||!ek)return;let e=tc.current;if(e)return e.style.height="32px",()=>{e.style.height=""}},[ed,ek]),(0,i.useEffect)(()=>{s&&(ex(!1),ef(!1),ew(!1))},[s]);let nc=`${ec}-history`,nu=`${ec}-slash`,nh=`${ec}-files`,np=eG&&P.length>0?nc:eN&&null!==tA?nu:eO&&null!==eB?nh:void 0,nf=np===nc&&void 0!==P[e0]?`${nc}-${e0}`:np===nu&&tH[eP]?`${nu}-${eP}`:np===nh&&t0[eK]?`${nh}-${eK}`:void 0;return(0,r.jsxs)("fieldset",{disabled:eJ,"aria-busy":eJ,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:eJ?.5:1,transition:"opacity 0.15s"},children:[!Z&&(0,r.jsx)("input",{ref:tp,type:"file",accept:"image/*",multiple:!0,disabled:a,style:{display:"none"},onChange:e=>{tL(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)(r$,{error:p}),(0,r.jsx)(rW,{warnings:f}),t_&&(0,r.jsx)(rN,{tone:"error",title:es("chat.tooManyImagesTitle"),body:es("chat.tooManyImagesBody",{count:eE.length,max:10})}),tV&&(et=h?.find(e=>e.provider===d?.provider&&e.id===d?.modelId),(0,r.jsx)(rN,{tone:"warning",title:es("chat.imageNotSupportedTitle"),body:es("chat.imageNotSupportedBody",{model:et?.name||d?.modelId||""}),onClose:()=>eX(!0)})),(z?.steering.length??0)+(z?.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:es("chat.queued",{count:(z?.steering.length??0)+(z?.followUp.length??0)})}),A&&(0,r.jsxs)("button",{onClick:A,title:es("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"})]}),es("chat.recall")]})]}),z?.steering.map((e,t)=>(0,r.jsx)(rR,{kind:"steer",text:e},`steer-${t}`)),z?.followUp.map((e,t)=>(0,r.jsx)(rR,{kind:"follow-up",text:e},`followup-${t}`))]}),W&&(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"})]}),es("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),nr&&(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"})}),nr]}),w&&(0,r.jsx)("div",{role:"alert",className:"chat-input-feedback chat-input-feedback-error chat-input-feedback-detail",style:{whiteSpace:"pre-wrap"},children:w}),(e4||J)&&(0,r.jsx)("div",{role:"status",className:"chat-input-feedback chat-input-feedback-warning chat-input-feedback-draft",children:es("chat.draftPageOnly")}),(eE.length>0||eS.length>0)&&(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:8,flexWrap:"wrap",padding:"0 2px"},children:[eS.map(e=>(0,r.jsx)(eb,{path:e,cwd:Y??void 0,onRemove:()=>eC(t=>t.filter(t=>t!==e))},e)),eE.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:()=>tR(t),title:es("i18n.close"),"aria-label":es("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:td,style:{position:"relative",minWidth:0},children:[tF&&!eN&&(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:tF.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:["/",tF.command]}),(0,r.jsx)("span",{children:tF.signature})]}),eG&&P.length>0&&(0,r.jsxs)("div",{ref:th,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:es("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:nc,role:"listbox",style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:P.map((e,t)=>{let n=t===e0;return(0,r.jsxs)("button",{ref:e=>{tk.current[t]=e},type:"button",id:`${nc}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),t5(e)},onMouseEnter:()=>e1(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}`)})})]}),eN&&null!==tA&&(0,r.jsxs)("div",{ref:tm,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===eD?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eD}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?es("chat.loadingCommands"):es("chat.slashCommands",{label:tO})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nu,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:6},children:H||0!==tD.length?tB.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:es(rv[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===eP,i=rC(e,tr);return(0,r.jsxs)("button",{ref:e=>{ty.current[t]=e},type:"button",id:`${nu}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),t6(e)},onMouseEnter:()=>eA(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,tA),"builtin"===e.source&&rS[e.name]&&(0,r.jsx)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11,fontWeight:400},children:rS[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:es("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:rk(e,es)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"4px 8px",fontSize:12,color:"var(--text-dim)"},children:es("chat.noCommands")})})]}),eO&&null!==eB&&(en=e3&&(!e5||e5.cwd!==Y),er=1===t0.length?es("chat.match"):es("chat.matches",{count:t0.length}),ei=e5?.serverHardTruncated?es("chat.serverIndexTruncated"):e5?.clientTruncated&&!tQ?eB.query?es("chat.searchingAll"):es("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tv,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===e_?"min(48vh, 400px)":`min(48vh, 400px, ${e_}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?es("chat.loadingFiles"):es("chat.files",{label:er,hint:ei})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nh,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:en||0!==t0.length?t0.map((e,t)=>{let n=t===eK,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tb.current[t]=e},type:"button",id:`${nh}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),t4(e)},onMouseEnter:()=>eV(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)(L,{size:14}):$(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,eB?.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:tG&&!tQ?es("chat.searching"):es("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-input-composer${eL?" is-bash-mode":""}`,style:{minWidth:0,display:"flex",flexDirection:Z?"column":"row",gap:8,alignItems:Z?"stretch":"center",background:eL?"color-mix(in srgb, var(--bg-panel) 75%, var(--bg))":"var(--bg)",border:Z?"none":`1px solid ${eL?eR?"rgba(100,116,139,0.45)":"color-mix(in srgb, var(--accent) 45%, var(--border))":s&&(o||l)?"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":eL?"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:[eL&&(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2px 6px",borderRadius:4,background:eR?"rgba(100,116,139,0.12)":"rgba(37,99,235,0.12)",color:eR?"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:eR?"Local":"Shell"})]}),(0,r.jsx)("textarea",{ref:ti,className:"chat-input-textarea",role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-expanded":!!np,"aria-controls":np,"aria-activedescendant":nf,"aria-label":Z?es("chat.quoteQuestion"):es("chat.message"),disabled:a,placeholder:a?es("agentSwitcher.status.queued"):void 0,value:eu,onChange:e=>{tE.current=e.target.value,eh(e.target.value),ez(e.target.selectionStart),e2.current=null,eQ(!1),tJ(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;ez(t.selectionStart),tJ(t.value,t.selectionStart)},onKeyDown:t7,onCompositionStart:()=>{tf.current=!0},onCompositionEnd:e=>{tf.current=!1,tg.current=Date.now();let t=e.currentTarget;ez(t.selectionStart),tJ(t.value,t.selectionStart)},onInput:t9,onPaste:ne,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:eL?"var(--font-mono)":"var(--font-chat)",minHeight:Z?96:24,maxHeight:200,overflow:"auto"}}),s?tq?(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":es("chat.stop"),title:es("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"})})}),l&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.followUp"),onClick:()=>t3("followup"),title:`${es("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:es("chat.followUp")})]}),o&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.steer"),onClick:()=>t3("steer"),title:es("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:es("chat.steer")})]})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.stop"),title:es("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:es("chat.stop")})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.send"),title:t_?es("chat.tooManyImagesTitle"):es("chat.send"),onClick:tP,disabled:!tK,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:tK?"var(--accent)":"none",border:"none",borderRadius:5,color:tK?"var(--accent-contrast)":"var(--text-dim)",opacity:tK?1:.45,cursor:tK?"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=>{tK&&(e.currentTarget.style.filter="brightness(1.08)")},onMouseLeave:e=>{tK&&(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:es("chat.send")})]})]})]}),eL&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eR?"var(--text-muted)":"var(--accent)",marginTop:4},children:[es("chat.shell")," \xb7 ",eR?es("chat.outputLocal"):es("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:ts,style:{position:"relative",display:"flex",alignItems:"center"},children:[(0,r.jsx)("button",{type:"button",disabled:a,onClick:()=>{t?ew(e=>!e):tp.current?.click()},title:t?`${es("chat.attachImage")} / ${es("image.title")}`:es("chat.attachImage"),"aria-label":t?`${es("chat.attachImage")} / ${es("image.title")}`:es("chat.attachImage"),"aria-expanded":t?ev: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:ev?"var(--bg-hover)":"none",border:"none",borderRadius:4,color:eE.length?"var(--accent)":ev?"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=eE.length?"var(--accent)":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=ev?"var(--bg-hover)":"none",e.currentTarget.style.color=eE.length?"var(--accent)":ev?"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"})]})}),ev&&t&&(0,r.jsxs)("div",{role:"menu",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),ew(!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:()=>{ew(!1),tp.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:es("chat.attachImage")})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{ew(!1),t()},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:es("image.title")})]})]})]}),(nt.length>0||d||p)&&g&&(0,r.jsx)(rs,{options:nt,value:d,onChange:g,disabled:s,busy:x,isAutoSelection:c})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),ed&&ek&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent"},onClick:()=>{ef(!1),ex(!1),ej(!1)}}),ed&&(ek||ep||eg||ev)&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent",WebkitTapHighlightColor:"transparent"},onClick:()=>{ef(!1),ex(!1),ew(!1),ej(!1),ey(!1)},"aria-hidden":"true"}),(0,r.jsxs)("div",{ref:ta,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto",zIndex:ed&&ek?60:void 0},children:[ed&&nd(!0),ed&&(eo=!!(null!=ns&&ns>=85),(0,r.jsxs)("button",{type:"button",title:ek?es("chat.collapseControls"):es("chat.moreControls"),"aria-label":es("chat.moreControls"),"aria-expanded":ek,onClick:()=>{ek?(ef(!1),ex(!1),ej(!1)):ej(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,maxWidth:"min(48vw, 200px)",height:32,padding:"0 6px",background:ek?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!=ns&&ns>=70&&ns<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)(tY,{size:14,style:{display:"block"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:na})]})),(0,r.jsxs)("div",{ref:tc,className:"chat-input-toolbar-controls",style:{display:ed?ek?"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:[T&&(0,r.jsxs)("div",{ref:tl,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!s&&(ef(!1),ex(e=>!e)),disabled:s,title:es("chat.changeReasoning",{level:ni}),"aria-label":es("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:s?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:s?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{s||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)(tY,{size:14,style:{display:"block"}}),(!ed||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:ni})]}),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:rp.filter(e=>!R||"auto"===e||R.includes(e)).map(e=>{let t=(M??"auto")===e,n=es(rf[e]),i="auto"!==e&&N?N[e]:void 0,o=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{ex(!1),ed&&ej(!1),t||T(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,l&&(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&&nd(!1),!s&&S&&(0,r.jsxs)("div",{ref:to,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!s&&(ex(!1),ef(e=>!e)),disabled:s,title:es("chat.changeToolPreset")+`: ${nl}`,"aria-label":es("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:s?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:s?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{s||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||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:nl})]}),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:rd.map(e=>{let t,n=rc[e],i=(j??rt.Q8)===n;return t="configured"===e?es("chat.configuredTools"):"chat-only"===e?es("chat.chatOnly"):"read-only"===e?es("chat.readOnlyTools",{count:4}):"default"===e?es("chat.builtInTools",{count:4}):es("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ef(!1),ed&&ej(!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)})})]}),!s&&y&&(el=!!(C?.percent&&C.percent>=85),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center"},children:(0,r.jsx)("button",{onClick:()=>{ed&&ej(!1),b?v?.():y?.()},disabled:s&&!b,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",width:ed?"auto":void 0,height:ed?32:28,background:b?"rgba(239,68,68,0.08)":el?"rgba(239,68,68,0.06)":"none",border:el&&!b?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:b||el?"#ef4444":"var(--text-muted)",cursor:s&&!b?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:s&&!b?.5:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{ed||s&&!b||(e.currentTarget.style.background=b?"rgba(239,68,68,0.16)":el?"rgba(239,68,68,0.12)":"var(--bg-hover)",e.currentTarget.style.color=b||el?"#ef4444":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=b?"rgba(239,68,68,0.08)":el?"rgba(239,68,68,0.06)":"none",e.currentTarget.style.color=b||el?"#ef4444":"var(--text-muted)")},title:b?es("chat.stopCompaction"):el?`${es("chat.compactContext")} (${es("chat.contextHighWarning")})`:es("chat.compactContext"),"aria-label":b?es("chat.stopCompaction"):es("chat.compactContext"),children:b?(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||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:es("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||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:es("chat.compact")})]})})})),void 0!==U&&(0,r.jsx)("button",{onClick:()=>{ed&&ej(!1),U?.()},title:O?es("chat.disableSound"):es("chat.enableSound"),"aria-label":O?es("chat.disableSound"):es("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 rP(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),l=e[o-1]??null;for(let e of t)n.has(e)&&(l=e),null!==l&&r.set(e,l);for(let t of e)r.set(t,t);return r}function rA(e,t,n){return n-t>0&&e+t>=n-8?1/0:e+48}function rD(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 rH=n(88576),rB=n.n(rH);function rF({items:e,activeEntryId:t,onJumpToEntry:n,label:o,left:l,top:s,maxHeight:a=360,width:d=310}){var c,u;let h,p,f,{t:g}=(0,m.s)(),x=(0,i.useRef)(null),y=(0,i.useRef)(null),[v,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(0),[C,I]=(0,i.useState)(null),E=(0,i.useRef)(0),M=(0,i.useRef)(null),T=(0,i.useRef)(!1),L=(0,i.useRef)(null),R=(0,i.useRef)(null),N=(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(w,28*u-p)))/28)-1),end:Math.min(u,Math.ceil((f+p)/28)+1)});(0,i.useEffect)(()=>()=>{E.current++,L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),N.current&&clearTimeout(N.current)},[]);let H=(0,i.useCallback)(()=>{L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),N.current&&clearTimeout(N.current),M.current=null,b(!1)},[]),B=(0,i.useCallback)(()=>{R.current&&(clearTimeout(R.current),R.current=null),v||(L.current=setTimeout(()=>{b(!0)},100))},[v]),F=(0,i.useCallback)(e=>{L.current&&(clearTimeout(L.current),L.current=null);let t=document.activeElement;t instanceof HTMLElement&&e.currentTarget.contains(t)&&t.matches(":focus-visible")||(R.current=setTimeout(()=>{H()},150))},[H]);async function O(e){let t=++E.current;I({entryId:e,state:"loading"});try{await n(e),E.current===t&&(I(null),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{H()},160))}catch(n){if(E.current!==t)return;if(n&&"object"==typeof n&&"name"in n&&"AbortError"===n.name)return void I(null);I({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));M.current=n,S(n);let r=y.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&&(M.current=null,t.focus({preventScroll:!0}))}b(!0)}return((0,i.useLayoutEffect)(()=>{if(!v){T.current=!1;return}let e=y.current;if(e){if(!T.current){let t=Math.max(0,W);e.scrollTop=Math.max(0,(t+.5)*28-P/2),S(t),T.current=!0}k(e.scrollTop)}},[v,W,P]),(0,i.useLayoutEffect)(()=>{if(!v||null===M.current)return;let e=y.current?.querySelector(`[data-outline-index="${M.current}"]`);e&&(M.current=null,e.focus({preventScroll:!0}))}),e.length)?(0,r.jsxs)("div",{className:rB().minimap,style:{left:l,top:s},onMouseEnter:B,onMouseLeave:F,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||H()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),H(),x.current?.focus({preventScroll:!0}))},children:[(0,r.jsx)("button",{ref:x,type:"button",className:rB().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)):(L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),b(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:rB().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:rB().panel,style:{width:d},children:(0,r.jsxs)("nav",{id:$,className:rB().menu,"aria-label":o,children:[(0,r.jsx)("div",{ref:y,className:rB().list,style:{height:P},onScroll:e=>k(e.currentTarget.scrollTop),children:(0,r.jsx)("div",{className:rB().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:rB().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:rB().rowText,children:n.preview})},n.entryId)})})}),C?.state==="error"&&(0,r.jsxs)("div",{className:rB().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 rO({items:e,scrollContainer:t,contentContainer:n,loadedEntryIds:o,onJumpToEntry:l,label:s}){let[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),h=(0,i.useMemo)(()=>rP(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,l=!0,s=[],a=[],c=new ResizeObserver(()=>f()),p=()=>{o||(o=requestAnimationFrame(g))},f=()=>{l=!0,p()};function g(){if(o=0,l){l=!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"));s=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 x=new Set(g),m=new Set(a);for(let e of a)x.has(e)||c.unobserve(e);for(let e of g)m.has(e)||c.observe(e);a=g}d(rD(s,rA(r.scrollTop,r.clientHeight,r.scrollHeight)))}c.observe(r),c.observe(i);let x=new MutationObserver(f);x.observe(i,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),r.addEventListener("scroll",p,{passive:!0}),window.addEventListener("resize",f);let m=e=>{e.target!==r&&e.target instanceof Node&&e.target.contains(r)&&f()};return window.addEventListener("scroll",m,!0),p(),()=>{cancelAnimationFrame(o),c.disconnect(),x.disconnect(),r.removeEventListener("scroll",p),window.removeEventListener("resize",f),window.removeEventListener("scroll",m,!0)}},[e.length,h,t,n]),!c||c.maxHeight<52||c.width<80)?null:(0,S.createPortal)((0,r.jsx)(rF,{items:e,activeEntryId:a,onJumpToEntry:l,label:s,...c}),document.body)}function rU(e,t,n){let r=JSON.stringify([e,t]),[o,l]=(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||l({key:r,items:e.items??[]})}).catch(()=>{n.signal.aborted||l({key:r,items:[]})}),()=>n.abort()},[e,t,n,r]),e&&o?.key===r)?o.items:[]}function r_({sessionId:e,leafId:t,outlineRevision:n,...i}){let{t:o}=(0,m.s)(),l=rU(e,t,n);return e&&l.length?(0,r.jsx)(rO,{...i,items:l,label:o("chatMinimap.userOutline")},JSON.stringify([e,t])):null}function rq({sessionId:e,leafId:t,outlineRevision:n,scrollContainer:o,contentContainer:l,loadedEntryIds:s,onJumpToEntry:a}){let{t:d}=(0,m.s)(),c=rU(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||!l?.current)return;let e=o.current,t=l.current,n=rP(c.map(e=>e.entryId),s??[]),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(rD(i,rA(e.scrollTop,e.clientHeight,e.scrollHeight)))},[u,c,s,o,l]),(0,i.useEffect)(()=>{u&&g.current&&g.current.scrollIntoView({block:"center"})},[u,p]),u&&c.length&&!("u"<typeof document))?(0,S.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 rK=n(42790);function rV({text:e}){let t=(0,i.useMemo)(()=>new rK.v().ansi_to_html(e),[e]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:t}})}let rJ="/icons/icon-192.png";function rY(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function rZ(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 rX(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 rG(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,icon:rJ,badge:rJ,...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 rQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r0(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(!rQ(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=rQ(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=rQ(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 r1 extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function r2(e){return e instanceof r1&&"prompt_rejected"===e.code&&!1===e.accepted}async function r4(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 r1(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let r8="pi-tool-preset";function r5(){try{return window.localStorage}catch{return null}}function r6(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 r3(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,r6(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),r6(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function r7(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 r9(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(r7).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class ie 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 it{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 ie("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof ie?"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 ie("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 ie("closed");if(this.current!==t){if(this.current?.sessionId===e)continue;throw new ie("closed")}if(1===t.source.readyState)return;this.discard(t,new ie("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new ie("closed"));try{t=this.options.createSource(e)}catch(e){throw new ie("closed",e instanceof Error?e.message:String(e))}let i=!1,o=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(a,new ie("ready_timeout"))},this.options.readinessTimeoutMs),s={promise:o,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a={sessionId:e,source:t,attempt:s};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)s.ready=!0,s.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(a,new ie("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new ie("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 ir(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 ii={isStreaming:!1,streamingMessage:null};function io(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 il(e,t){switch(t.type){case"text_start":return io(e,t.contentIndex,()=>({type:"text",text:""}));case"text_delta":return io(e,t.contentIndex,e=>e?.type==="text"?{...e,text:e.text+t.delta}:null);case"text_end":return io(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 io(e,t.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+t.delta,startedAt:e.startedAt??Date.now()}:null);case"thinking_end":return io(e,t.contentIndex,e=>({...e?.type==="thinking"?e:{startedAt:Date.now()},type:"thinking",thinking:t.content,endedAt:Date.now()}));case"toolcall_start":return io(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 io(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 io(e,t.contentIndex,()=>({type:"toolCall",toolCallId:t.toolCall.id,toolName:t.toolCall.name,input:t.toolCall.arguments}));default:return e}}function is(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=r0(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,l=e.endedAt??(n?.type==="thinking"?n.endedAt:void 0);return e.startedAt===o&&e.endedAt===l?e:{...e,startedAt:o,..."number"==typeof l?{endedAt:l}:{}}});return{isStreaming:!0,streamingMessage:{...n,timestamp:r,content:o}}}case"delta":return il(e,t.event);case"deltas":return t.events.reduce(il,e);case"end":return ii;default:return e}}class ia{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 id(e,t,n,r){return e===t&&"string"==typeof n&&n.length>0&&n===r}async function ic(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()&&id(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()&&id(n,e.currentRunId(),i,e.currentSessionId()))return{status:"cancelled_after_dispatch",sessionId:i};return{status:"stale"}}finally{t.forget(n)}}async function iu(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 ih(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 ip=new Map,ig=new Map;function ix(e){return"string"==typeof e?e:e?.text??""}function im(e){return{steering:(e?.steering??[]).map(ix),followUp:(e?.followUp??[]).map(ix)}}function iy(e,t){return e===t||null!==e&&null!==t&&e.tokens===t.tokens&&e.percent===t.percent&&e.contextWindow===t.contextWindow?e:t}let iv=[2e3,5e3,1e4];function ib(e){return new Promise(t=>setTimeout(t,e))}function iw(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ik(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:iw(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iw(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=iw(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function ij(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 iS(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 iC(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 iI({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)(K,{size:12})})}function iE({cwd:e,onChange:t,recentPaths:n,pinnedPaths:o,onTogglePinnedCwd:l,homeDir:s,worktreeInfo:a}){let{t:d}=(0,m.s)(),c=(0,i.useRef)(null),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(!1),[y,v]=(0,i.useState)(!1),[b,w]=(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),I=C?.branch??null,E=j?.projectRoot??e,T=s&&E.startsWith(s)?`~${E.slice(s.length)}`:E,L=()=>{h(!1),f(!1)},R=n=>{n===e?L():(v(!0),t(n).then(L).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")}: ${E}`,"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:T})})}),I&&(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")}: ${I}`,"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:I})]}),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:y,onClick:()=>R(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:y?"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:s&&t.startsWith(s)?`~${t.slice(s.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:()=>l?.(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),x(!0),w(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:y,onClick:()=>R(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:y?"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)(M,{initialPath:e,busy:y,error:b,onCancel:()=>{x(!1),w(null)},onSelect:e=>{v(!0),w(null),t(e).then(()=>x(!1),e=>w(e instanceof Error?e.message:String(e))).finally(()=>v(!1))}})]})}function iM({label:e}){let[t,n]=(0,i.useState)(null);if((0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/app-update",{signal:e.signal}).then(async e=>e.ok?e.json():null).then(e=>{e?.updateAvailable&&e.latestVersion&&e.releaseUrl&&n(e)}).catch(()=>{}),()=>e.abort()},[]),!t)return null;let o=e(t.latestVersion);return(0,r.jsxs)("a",{href:t.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,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",t.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"})]})]})}function iT(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&e_(r))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}function iL(e){return e?.content.at(-1)}function iR(e,t,n,r,i=!1){if(!e)return!1;if(r?.kind==="running_tools")return!0;let o=iL(n);return!!t&&(o?.type==="thinking"||o?.type==="toolCall")||!i}function iN(e,t,n){if(!e)return null;let r=em(e,t);return"edit"===r?n("image.edit"):"generate"===r?n("image.generate"):null}function i$(e,t,n){if(t?.kind==="running_tools"){let e=t.tools[t.tools.length-1]?.name??null;return iN(e,void 0,n)??e}let r=iL(e);return r?.type==="thinking"?n("chat.thinking"):r?.type==="toolCall"?iN(r.toolName,r.input,n)??r.toolName??null:null}function iW(e,t,n,r){return t?(e&&(n.current=e),n.current??r):(n.current=null,null)}function iz(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 iP(e,t){return e<60?t("chat.decodeSeconds",{seconds:e}):t("chat.decodeMinutes",{minutes:Math.floor(e/60),seconds:e%60})}function iA({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:iP(n,t)})}function iD({messageCount:e,toolCallCount:t,durationSeconds:n,startTime:o,defaultExpanded:l=!1,reveal:s=!1,isMobile:a=!1,activeStepSummary:d=null,isStreaming:c=!1,children:u,t:h}){let p,[f,g]=(0,i.useState)(l),x=(0,i.useRef)(null),m=(0,i.useRef)(!1),y=(0,i.useRef)(!1);(0,i.useLayoutEffect)(()=>{y.current||g(l)},[l]);let v=f||s,b=t>0?t:e,w=h(1===b?"chat.step":"chat.steps");if(void 0!==n&&n>0){let e=iP(n,h);p=t>0?h("chat.workedForSteps",{duration:e,count:b,steps:w}):h("chat.workedFor",{duration:e})}else p=`${b} ${w}`;return(0,i.useLayoutEffect)(()=>{if(!v){m.current=!1;return}let e=x.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:()=>{y.current=!0,g(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)(K,{size:12}),o&&(0,r.jsx)(iA,{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:p}),(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:x,onScroll:()=>{let e=x.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 iH({session:e,searchTarget:t,onSearchTargetHandled:o,initialScrollPosition:l,onScrollPositionChange:s,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onDraftChange:u,onKeepTabOpen:h,onNewSessionCwdChange:p,recentProjectPaths:f=[],pinnedCwds:g=[],onTogglePinnedCwd:x,homeDir:y="",worktreeInfo:b=null,draftPersistenceWarning:w=!1,onAgentEnd:k,onAttentionNeeded:C,onSessionCreated:I,onSessionForked:E,modelsRefreshKey:M,chatInputRef:T,isFocusedPane:L=!1,isVisiblePane:R=L,onBranchDataChange:N,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,m.s)(),G=nY(),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,T&&(e?T.current=e:T.current===t&&(T.current=null))},[T]),eo=(0,i.useRef)(null),el=(0,i.useCallback)(()=>{Q&&et.current&&ee.current(),k?.(en.current)},[Q,k]),es=(0,i.useCallback)(e=>{C?.(e,en.current)},[C]),ea=(0,i.useCallback)(e=>{E?.(e,en.current?.id??null)},[E]),ec=(0,i.useCallback)((e,t)=>{H?.(e,en.current?.id??null,t)},[H]),eu=(0,i.useCallback)(()=>{let e=en.current?.id;e&&h?.(e)},[h]),eh=(0,i.useCallback)(e=>{er.current?.replaceMessage(e)},[]),ep=(0,i.useRef)(t?null:l??null),[ef,eg]=(0,i.useState)(()=>{let e=ep.current;return e&&!e.atBottom?e:null}),[em,ey]=(0,i.useState)(!1),{data:ev,loading:eb,error:ew,messages:eS,activeToolResults:eC,entryIds:eE,historyCursor:eM,hasEarlierMessages:eT,streamState:eL,agentRunning:eR,directImageRunning:eN,bashRunning:e$,pendingBash:eW,modelNames:ez,modelList:eH,modelError:eO,modelScopeWarnings:eU,modelThinkingLevels:e_,modelThinkingLevelMaps:eK,toolPreset:eJ,thinkingLevel:eY,retryInfo:eZ,contextUsage:eG,forkingEntryId:eQ,isCompacting:e0,compactError:e2,compactResult:tr,displayModel:ti,modelSwitching:to,sessionStats:tl,slashCommands:ts,slashCommandsLoading:ta,queuedMessages:td,notices:tc,extensionDialog:tu,extensionCustomUi:th,respondToExtensionUi:tp,sendExtensionCustomInput:tf,addNotice:tg,setNoticePaused:tx,isAutoModelSelection:tm,agentPhase:ty,isNew:tv,sessionIdRef:tb,scrollContainerRef:tw,handleSend:tk,handleDirectImageGeneration:tj,abortDirectImageGeneration:tS,handleAbort:tC,handleFork:tI,handleNavigate:tE,handleModelChange:tM,handleCompact:tT,handleSteer:tL,handleFollowUp:tR,handlePromptWithStreamingBehavior:tN,handleAbortCompaction:t$,handleRecallQueue:tW,handleBuiltinSlashCommand:tz,handleToolPresetChange:tP,handleThinkingLevelChange:tA,loadSlashCommands:tD,loadContext:tH,activeLeafId:tB,scrollToBottom:tF,scrollToMessage:tO}=function(e){let{session:t,sessionRunning:r,newSessionCwd:o,newSessionDraftKey:l,onAgentEnd:s,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:h,onSystemPromptChange:p,onSystemToolsChange:f,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:x,isVisiblePane:m=!1}=e,y=null===t&&null!==o,v=o??t?.cwd??"",b=v?`/api/models?cwd=${encodeURIComponent(v)}`:"/api/models",w=ip.get(b)?.data,k=y?iS(w):null,j=k?w?.thinkingLevelPins?.[`${k.provider}/${k.modelId}`]:void 0,[S,C]=(0,i.useState)(null),[I,E]=(0,i.useState)(!y),[M,T]=(0,i.useState)(null),[L,R]=(0,i.useState)(null),[N,$]=(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:N,entryIds:P,oldestEntryId:D,hasMore:B});O.current={messages:N,entryIds:P,oldestEntryId:D,hasMore:B};let[U,_]=(0,i.useReducer)(is,ii),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,el]=(0,i.useState)(()=>w?.modelList??[]),[es,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,ex]=(0,i.useState)(null),[em,ey]=(0,i.useState)(k),[ev,eb]=(0,i.useState)(rt.Q8),[ew,ek]=(0,i.useState)(j??"auto"),[ej,eS]=(0,i.useState)(null),[eC,eI]=(0,i.useState)(null),[eE,eM]=(0,i.useState)(null),[eT,eL]=(0,i.useState)(null),[eR,eN]=(0,i.useState)(null),[e$,eW]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(!1),[eA,eD]=(0,i.useState)(!1),[eH,eB]=(0,i.useState)(!0),[eF,eO]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(null),[eq,eK]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)([]),[eY,eZ]=(0,i.useState)(!1),[eX,eG]=(0,i.useReducer)(ik,{visible:[],pending:[]}),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(null),[e5,e6]=(0,i.useState)({steering:[],followUp:[]}),e7=(0,i.useRef)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(0),tt=(0,i.useRef)(!1),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(t?.id??null),ti=(0,i.useRef)(t?.id??null),to=(0,i.useRef)(!!r),tl=(0,i.useRef)(m),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(!1),td=(0,i.useRef)(!1),tc=(0,i.useRef)(-1),tu=(0,i.useRef)(!1),th=(0,i.useRef)(!1),tp=(0,i.useRef)(0),tf=(0,i.useRef)(null),tg=(0,i.useRef)(!!e.deferInitialScroll),tx=(0,i.useRef)(!1),tm=(0,i.useRef)(!0),ty=(0,i.useRef)(0),tv=(0,i.useRef)(null),tb=(0,i.useRef)([]),tw=(0,i.useRef)(void 0),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(null),tI=(0,i.useRef)(null),tE=(0,i.useRef)(0),tM=(0,i.useRef)(new ia),tT=(0,i.useRef)(null),tL=(0,i.useRef)(!1),tR=(0,i.useRef)(null),tN=(0,i.useRef)(!1),t$=(0,i.useRef)(u),tW=(0,i.useRef)(new Map),tz=(0,i.useRef)(!0);ti.current=t?.id??null,to.current=!!r,tl.current=m,e7.current||(e7.current=new it({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tf.current?.(e),shouldMaintain:e=>tz.current&&tr.current===e&&(tl.current||ts.current||tt.current||ti.current===e&&to.current),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tP=e.setToolPreset??eb,tA=t?.id;(0,i.useLayoutEffect)(()=>{(tA||y&&!tr.current)&&tP(function(e=r5()){if(!e)return rt.Q8;try{let t=e.getItem(r8);return(0,rt.sn)(t)?t:rt.Q8}catch{return rt.Q8}}())},[tA,y,tP]);let tD=(0,i.useCallback)((e="instant")=>{let t=tk.current;t&&(tm.current=!0,t.scrollTo({top:Math.max(0,t.scrollHeight-t.clientHeight),behavior:e}),ty.current=t.scrollTop)},[]),tH=eR??S?.context.model??e$??null,tB=y?eg??em:tH,tF=t?.id??l??void 0,tO=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tW.current.get(t);if(!e)break;t=e}return t},[]),tU=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=tO(r);if(!tz.current&&!tS.current&&r===l)return;let s=e.chatInputRef?.current;if(s)s.restoreSubmission(t,i,o);else{let e,n;o&&(n=nH(t,i,(e=nW(o)??{value:"",images:[]}).value,e.images),nz(o,n))}},[l,e.chatInputRef,tO]),t_=(0,i.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:S?.totalActiveMs,...eC?{contextUsage:eC}:{}};let e=S?.stats,n=function(e,t,n){let r=r3(n);if(!e)return r;let i=r3(t),o=(e,t)=>Math.max(0,e-t),l={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 l.total=l.input+l.output+l.cacheRead+l.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:l,cost:e.cost+o(r.cost,i.cost)}}(e,S?.context.messages??[],N);return 0!==n.tokens.total||0!==N.length||e?{sessionFile:S?.filePath||void 0,sessionId:tr.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:S?.totalActiveMs,...eC?{contextUsage:eC}:{}}:null},[N,eQ,eC,S?.context.messages,S?.filePath,S?.totalActiveMs,S?.stats,t?.id,t?.name]),tq=(0,i.useCallback)(async(e,t=!1,n=!1)=>{let r=!1;try{t&&E(!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),R(null),$([]),A([]),H(null),F(!1),eI(null),T(null)),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(tr.current!==e)return null;let s={messages:l.context.messages,entryIds:l.context.entryIds??[],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore},a=t?s: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,s);if(C({...l,context:{...l.context,...a}}),R(l.leafId),$(a.messages),A(a.entryIds),H(a.oldestEntryId),F(a.hasMore),tn.current=void 0!==l.toolNames,tP(void 0!==l.toolNames?(0,rt.YO)(l.toolNames):rt.Q8),eN(e=>tN.current?e:null),T(null),l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ek(l.context.thinkingLevel),void 0!==l.contextUsage&&eI(l.contextUsage??null),r=!0,t&&E(!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(tr.current!==e)return null;let r=n.state;return r?(void 0!==r.contextUsage&&eI(r.contextUsage??null),void 0!==r.systemPrompt&&eM(r.systemPrompt??null),void 0!==r.thinkingLevel&&ek(r.thinkingLevel??"auto"),void 0!==r.queuedMessages&&e6(im(r.queuedMessages))):n.running||e6({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return T(String(e)),null}finally{t&&!r&&E(!1)}},[tP]),tK=(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}`,l=await fetch(o,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let s=await l.json();if(tr.current!==e||r?.signal?.aborted||!tz.current)return;return H(s.context.oldestEntryId),F(s.context.hasMore),C(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...s.context.messages,...t.context.messages],entryIds:[...s.context.entryIds,...t.context.entryIds],oldestEntryId:s.context.oldestEntryId,hasMore:s.context.hasMore}:s.context;return{...t,context:r}}),n?($(e=>[...s.context.messages,...e]),A(e=>[...s.context.entryIds,...e])):($(s.context.messages),A(s.context.entryIds??[])),s.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),tV=(0,i.useCallback)(async e=>{try{let t=await r4(e,{type:"get_tools"});if(!t||!tz.current||tr.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tP(tn.current?r(t):rt.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,tP]),tJ=(0,i.useCallback)((t=0,n="(no messages)")=>{let r=tr.current;if(y&&o&&r&&!tS.current&&(tS.current=!0,l)){if(l!==r){tW.current.set(l,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(l,r):nB(l,r)}d?.({id:r,path:"",cwd:o,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},l)}},[y,o,l,d,e.chatInputRef]),tY=(0,i.useCallback)(e=>{e instanceof ie||console.error("Failed to maintain the agent event stream:",e)},[]),tZ=(0,i.useCallback)(async()=>{if(tr.current||!y||!o)return tr.current;if(tj.current)return tj.current;let e=(async()=>{let e=tC.current,t=tI.current;e&&eW(e);let n=(0,rt.xG)(ev);tn.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(),l=i.sessionId;return tr.current=l,tl.current&&e7.current?.ensureConnected(l).catch(tY),void 0!==i.contextUsage&&eI(i.contextUsage??null),i.model&&tC.current===e&&(eW(i.model),e||ey(i.model)),i.thinkingLevel&&tI.current===t&&ek(i.thinkingLevel),l})();tj.current=e;try{return await e}finally{tj.current=null}},[tY,y,o,ev]),tX=(0,i.useCallback)(async()=>{let e=tr.current??await tZ();if(!e)return;let[t]=await Promise.all([r4(e,{type:"get_state"}),tV(e)]);tz.current&&tr.current===e&&eM(t.systemPrompt??"")},[tZ,tV]),tG=(0,i.useCallback)(async()=>{let e=tr.current??await tZ();if(!e)return eJ([]),[];eZ(!0);try{let t=await r4(e,{type:"get_commands"}),n=t?.commands??[];return eJ(n),n}catch(e){return console.error("Failed to load slash commands:",e),eJ([]),[]}finally{eZ(!1)}},[tZ]),tQ=(0,i.useCallback)(()=>{te.current+=1,tt.current=!1,e9.current&&(clearTimeout(e9.current),e9.current=null)},[]),t0=(0,i.useCallback)(()=>{e7.current?.close()},[]),t1=(0,i.useCallback)(e=>e7.current.ensureConnected(e),[]),t2=(0,i.useCallback)(e=>{e7.current.maintain(e)},[]),t4=(0,i.useCallback)(e=>{e7.current?.reconnect(e).catch(tY)},[tY]);(0,i.useEffect)(()=>{if(t?.id&&r)return t2(t.id),()=>{tr.current!==t.id||ts.current||tt.current||tl.current||ti.current===t.id&&to.current||e7.current?.close()}},[t2,t?.id,r]),(0,i.useEffect)(()=>{if(!m){ts.current||to.current||tt.current||t0();return}let e=t?.id??tr.current??null;e&&(tQ(),e7.current?.ensureConnected(e).catch(tY))},[tQ,t0,tY,m,t?.id]);let t8=(0,i.useCallback)(async(e,t)=>{let n=tr.current;if(e2(t=>t?.id===e.id?null:t),n)try{await r4(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),t5=(0,i.useCallback)(async(e,t)=>{let n=tr.current;if(n)try{await r4(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),t6=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eG({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"}})},[]),t3=(0,i.useCallback)(t=>{switch(rX(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":e2(t);break;case"notify":t6({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":e8(e=>t.closed?e?.id===t.id?null:e:t)}},[t6,a,e.chatInputRef]),t7=(0,i.useCallback)(()=>{null!==tv.current&&(cancelAnimationFrame(tv.current),tv.current=null);let e=tb.current;0!==e.length&&(tb.current=[],_({type:"deltas",events:e}))},[]),t9=(0,i.useCallback)(e=>{tb.current.push(e),null===tv.current&&(tv.current=requestAnimationFrame(()=>{tv.current=null,t7()}))},[t7]),ne=(0,i.useCallback)(()=>{t7();let e=ts.current;return ts.current=!1,V(!1),eK(null),eS(null),z(new Map),_({type:"end"}),e},[t7]),nt=(0,i.useCallback)(e=>tc.current!==e&&(tc.current=e,s?.(),!0),[s]),nn=(0,i.useCallback)(e=>{if(tl.current&&tr.current===e)return void tQ();tQ(),tt.current=!0;let t=te.current,n=async()=>{if(t===te.current&&tr.current===e&&tt.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!==te.current||tr.current!==e||!tt.current)return;let o=i.state;if(i.running&&o&&(o.isStreaming||o.isPromptRunning)){tt.current=!1,e9.current=null,ta.current=!!o?.isStreaming,td.current=!!o?.isPromptRunning,ts.current=!0,V(!0),eK(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eD(!0),e9.current=setTimeout(()=>void n(),600);return}tt.current=!1,e9.current=null,t0()}catch{if(t!==te.current||tr.current!==e||!tt.current)return;e9.current=setTimeout(()=>void n(),600)}};e9.current=setTimeout(()=>void n(),3e4)},[tQ,t0]),nr=(0,i.useCallback)(async(e=tr.current,t=tE.current)=>{if(tE.current===t)try{e&&await tq(e)}finally{if(tE.current!==t)return;let n=td.current,r=ta.current;td.current=!1,ta.current=!1,tR.current=null;let i=ne();n?nt(t):r&&i&&s?.(),e&&nn(e)}},[tq,nt,s,nn,ne]),ni=(0,i.useCallback)(async(e,t)=>{await ib(800);let n=Date.now();for(;ts.current&&Date.now()-n<2e4;){if(void 0!==t&&tE.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 nr(e,t)}}catch{}await ib(600)}},[nr]),no=(0,i.useCallback)(async e=>{let t=tp.current+1;for(tp.current=t;tu.current&&tp.current===t&&tr.current===e;){await ib(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 tq(e),tp.current!==t||tr.current!==e)return;tu.current=!1,Y(!1),X(null);return}catch{}}},[tq]),nl=(0,i.useCallback)(async e=>{if(!ts.current||tr.current!==e)return;let t=tE.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(tr.current!==e||tE.current!==t)return;let i=r.state;if(eD(i?.isCompacting??!1),e6(im(i?.queuedMessages)),"boolean"==typeof i?.autoCompactionEnabled&&eB(i.autoCompactionEnabled),i?.contextUsage!==void 0&&eI(e=>iy(e,i.contextUsage??null)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){ta.current=!!i.isStreaming,td.current=!!i.isPromptRunning;return}if(!ts.current)return;i&&void 0!==i.systemPrompt&&eM(i.systemPrompt??null),await nr(e,t)}catch{}},[nr]);(0,i.useEffect)(()=>{if(!K)return;let e=()=>{let e=tr.current;e&&nl(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,nl]),(0,i.useEffect)(()=>{let e=()=>{let e=tr.current;if(e&&"hidden"!==document.visibilityState){if(tl.current)return void t4(e);(ts.current||tt.current||ti.current===e&&to.current)&&t2(e)}},t=()=>{"visible"===document.visibilityState&&e()};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[t2,t4]),(0,i.useEffect)(()=>{ts.current=K},[K]),tf.current=(0,i.useCallback)(e=>{switch("message_update"!==e.type&&t7(),e.type){case"connected":_({type:!0===e.isStreaming?"resume":"end"}),!0===e.isStreaming&&(tQ(),ta.current=!0,ts.current=!0,V(!0),eK({kind:"waiting_model"}));break;case"agent_start":tQ(),ta.current=!0,ts.current=!0,V(!0),eK({kind:"waiting_model"}),_({type:"start"});break;case"agent_end":if(!ts.current)break;eK(null),eS(null),_({type:"end"}),tr.current&&(tq(tr.current),fetch(`/api/agent/${encodeURIComponent(tr.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eI(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eM(e.state.systemPrompt??null),e6(im(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=ta.current;if(ta.current=!1,!e||td.current)break;let t=tr.current,n=ne();eD(!1),t&&(tq(t),nn(t)),n&&s?.();break}case"prompt_done":{let e=tE.current,t=td.current;td.current=!1,tR.current=null;let n=nt(e);if(!t&&!n)break;let r=tr.current;r&&tq(r),!ta.current&&(ne(),r&&nn(r))}break;case"prompt_error":t6({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t6({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!ts.current||ir(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&&eK(null)):t&&eK(null)}else{let t=e.assistantMessageEvent;t&&(t9(t),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eK(null))}break;case"message_end":{if(!ts.current||ir(e))break;let t=e.message;if(t&&"user"===t.role){let e=r0(t),n=r9(e),r=tR.current;tR.current=null,$(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&r9(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let e=r0(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:iy(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],l=(o?.type==="thinking"?o.startedAt:void 0)??e.startedAt??t.timestamp,s=(o?.type==="thinking"?o.endedAt:void 0)??e.endedAt??n;return e.startedAt===l&&e.endedAt===s?e:(r=!0,{...e,..."number"==typeof l?{startedAt:l}:{},..."number"==typeof s?{endedAt:s}:{}})});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"}),eK({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;eK(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}),eK(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}),eK(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":e6({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eS({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eS(null);break;case"auto_compaction_start":case"compaction_start":eD(!0),eO(null),e_(null);break;case"auto_compaction_end":case"compaction_end":eD(!1),e.errorMessage?(eO(e.errorMessage),e_(null)):!e.aborted&&(e_(ij(e.result,e.reason??"auto")),tr.current&&tq(tr.current));break;case"extension_ui_request":t3(e);break;case"extension_ui_closed":e2(t=>t?.id===e.id?null:t)}},[t6,tQ,t7,t3,tq,nt,s,t9,nn,ne]);let ns=(0,i.useCallback)(async(e,n)=>{let r=e.trim();if(!r&&!n?.length)return;if(ts.current||tu.current)return void tU(e,n,tF);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 tw.current?.(i,t):void tU(e,n,tF)}let l=tE.current+1;tQ(),td.current=!0;let s=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:s?.length?[...e.trim()?[{type:"text",text:e}]:[],...s]:e,timestamp:Date.now()};$(e=>[...e,a]),tR.current=r9(a),tE.current=l,ts.current=!0,V(!0),eK(i?{kind:"running_command"}:{kind:"waiting_model"}),_({type:"start"}),tx.current=!0,tT.current={runId:l,message:e,images:n,userMsg:a};let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=!1;tM.current.begin(l);let u=async e=>{try{await r4(e,{type:"abort"})}catch(e){t6({type:"error",message:e instanceof Error?e.message:String(e)})}},h=await ic({gate:tM.current,runId:l,currentRunId:()=>tE.current,currentSessionId:()=>tr.current,promptPending:()=>td.current,abandonUnsent:()=>{tT.current?.runId===l&&(tT.current=null,td.current=!1,$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tU(e,n,tF),tR.current=null,tE.current===l&&(ts.current=!1,V(!1),eK(null),_({type:"end"})))},onDispatched:()=>{tT.current?.runId===l&&(tT.current=null)},abort:u,prepare:async()=>{if(y&&o){let e=tr.current??await tj.current;if(tM.current.isCancelled(l))return null;let t=e??await tZ();if(tM.current.isCancelled(l))return null;if(!t)throw Error("Unable to create a session for the prompt");return eg&&(eW(eg),e)&&(await r4(t,{type:"set_model",provider:eg.provider,modelId:eg.modelId}),tM.current.isCancelled(l))?null:(await t1(t),tM.current.isCancelled(l))?null:t}if(t)return(await t1(t.id),tM.current.isCancelled(l))?null:t.id;throw Error("No active session for the prompt")},send:async t=>{let n=await r4(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 ni(h.sessionId,l);if("failed"===h.status){let t=h.error,r=h.sessionId,i=h.requestStarted;return(console.error("Failed to send message:",t),!(!i||r2(t))&&r)?void ni(r,l):(td.current=!1,tT.current?.runId===l&&(tT.current=null),$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),t6({type:"error",message:t instanceof Error?t.message:String(t)}),tU(e,n,tF),tR.current=null,r)?void nl(r):(ts.current=!1,t0(),V(!1),eK(null),void _({type:"end"}))}if(y&&o&&tJ(1,e),c&&h.sessionId){td.current=!1,ni(h.sessionId,l);return}i&&h.sessionId&&ni(h.sessionId,l)}},[y,o,eg,t,tZ,t1,tJ,ni,t6,tQ,t0,tF,nl,tU]),na=(0,i.useCallback)(async e=>{if(ts.current||tu.current||ee.current)throw Error("Cannot generate an image while the session is busy");let n=crypto.randomUUID();ee.current=!0,et.current=n,en.current=!1,Q(!0);try{let r=t?.id??(y&&o?await tZ():null);if(!r)throw Error("No active session for image generation");if(en.current)throw new DOMException("Image generation cancelled","AbortError");let i=await r4(r,{type:"generate_image_direct",requestId:n,arguments:e});return await tq(r),y&&o&&tJ(1,e.prompt),i}finally{et.current===n&&(ee.current=!1,et.current=null,en.current=!1,Q(!1))}},[tZ,y,tq,o,tJ,t?.id]),nd=(0,i.useCallback)(async()=>{en.current=!0;let e=tr.current,t=et.current;e&&t&&await r4(e,{type:"abort_image_generation",requestId:t})},[]);tw.current=(0,i.useCallback)(async(e,n)=>{if(ts.current||tu.current)return;let r=`${n?"!!":"!"}${e}`;tL.current=!1,tu.current=!0,X({command:e,excludeFromContext:n}),Y(!0);try{let i=await iu({abortRequested:()=>tL.current,prepare:async()=>tr.current??t?.id??await tZ(),send:async t=>{await r4(t,{type:"bash",command:e,excludeFromContext:n})},loadResults:async e=>{tr.current===e&&await tq(e)},restoreUnsent:()=>tU(r,void 0,tF)});("completed"===i.status||"cancelled_after_dispatch"===i.status)&&tJ(1,r)}catch(e){console.error("Failed to execute shell command:",e),t6({type:"error",message:e instanceof Error?e.message:String(e)}),tU(r,void 0,tF)}finally{tu.current=!1,X(null),Y(!1)}},[t6,tF,tZ,tq,tJ,tU,t]);let nc=(0,i.useCallback)(async()=>{var e;let n=tE.current,r=tr.current,i=async e=>{if(r&&!th.current){th.current=!0;try{await r4(r,{type:e})}catch(e){console.error("Failed to abort:",e),t6({type:"error",message:e instanceof Error?e.message:String(e)})}finally{th.current=!1}}};if(tu.current){tL.current=!0,await i("abort_bash");return}let o=tT.current;(tM.current.isInFlight(n)||o?.runId===n)&&tM.current.cancel(n);let l=!!(o&&o.runId===n&&tM.current.shouldAbandonUnsent(n));if(l&&o){tT.current=null,td.current=!1,$(e=>{let t=e.lastIndexOf(o.userMsg);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tU(o.message,o.images,tF),tR.current=null,ts.current=!1,V(!1),eK(null),_({type:"end"});return}let s=(e={bashRunning:!1,hasSessionId:!!r,localUnsent:l,agentRunning:ts.current||td.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"!==s&&r&&await i("abort_bash"===s?"abort_bash":"abort")},[t6,tF,tU,t]),nu=(0,i.useCallback)(async e=>{if(tu.current)return;let t=tr.current;if(t){eL(e);try{let{cancelled:n,newSessionId:r}=await r4(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e)}finally{eL(null)}}},[c]),nh=(0,i.useCallback)(async e=>{if(tu.current)return;let t=tr.current;t&&(r4(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),R(e),await tK(t,e))},[tK]),np=(0,i.useCallback)(async e=>{if(tu.current)return;R(e);let t=tr.current;t&&(await tK(t,e),e&&r4(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tK]),nf=(0,i.useCallback)(async(e,t)=>{if(y){let n={provider:e,modelId:t};tC.current=n,ex(n),eW(n);let r=tr.current??await tj.current;if(!r)return;try{await r4(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tr.current;if(n&&!tN.current){tN.current=!0,eN({provider:e,modelId:t}),eP(!0);try{await r4(n,{type:"set_model",provider:e,modelId:t}),tN.current=!1,await tq(n)}catch(e){console.error("Failed to set model:",e),tN.current=!1,eN(eR),t6({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await tq(n)}finally{tN.current=!1,eP(!1)}}},[t6,eR,y,tq,ex]),ng=(0,i.useCallback)(async()=>{let e=tr.current;if(e&&!eA){eD(!0),eO(null),e_(null);try{let t=await r4(e,{type:"compact"});e_(ij(t,"manual")),await tq(e,!0)}catch(e){eO(e instanceof Error?e.message:String(e)),e_(null)}finally{eD(!1)}}},[eA,tq]),nx=(0,i.useCallback)(async(e,t=!1,n)=>{let r;try{r=await function(e,t,n={}){let r=ip.get(e);if(!n.force&&r&&r.loadedAt+6e4>Date.now())return Promise.resolve(r.data);let i=ig.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(ip.delete(e),ip.set(e,{data:t,loadedAt:Date.now()});ip.size>32;){let e=ip.keys().next().value;if(void 0===e)break;ip.delete(e)}return t}).finally(()=>{ig.get(e)?.promise===o&&ig.delete(e)});return ig.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??{}),el(r.modelList??[]),y&&!tr.current){let e=iS(r);ey(e);let t=e&&r.thinkingLevelPins?.[`${e.provider}/${e.modelId}`];null===tI.current&&ek(t??"auto")}},[y,b]),nm=(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=tr.current??await tZ(),l=e=>(e.handled&&(e.error?t6({type:"error",message:e.error}):"openSessionStats"!==e.action&&t6({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eA)return l({handled:!0,error:"No active session to compact"});eD(!0),eO(null),e_(null);let e=await r4(o,{type:"compact",...i?{customInstructions:i}:{}});return e_(ij(e,"manual")),await tq(o,!0)&&tJ(),l({handled:!0,message:"Compacted context"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await r4(o,{type:"reload"}),await Promise.all([tq(o,!1,!0),tV(o),tG(),nx(void 0,!0)]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return l({handled:!0,error:"No active session to name"});if(!i)return l({handled:!0,error:"Usage: /name <name>"});return await r4(o,{type:"set_session_name",name:i}),await tq(o)&&tJ(),l({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});let e=await r4(o,{type:"get_session_stats"});return e&&e0(e),x?.(),l({handled:!0,action:"openSessionStats"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await r4(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),l({handled:!0,message:"Copied last assistant message"})}case"auto-compact":{if(!o)return l({handled:!0,error:"No active session"});let e=await r4(o,{type:"get_state"}),t=!("boolean"!=typeof e?.autoCompactionEnabled||e.autoCompactionEnabled);return await r4(o,{type:"set_auto_compaction",enabled:t}),eB(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"clone":{if(!o)return l({handled:!0,error:"No active session to clone"});if(ts.current||tu.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=await r4(o,{type:"clone",leafId:L});if(e?.cancelled||!e?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=l({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}case"bug":{if(!o)return l({handled:!0,error:"No active session to report"});if(ts.current||tu.current)return l({handled:!0,error:"Cannot report a bug while the session is running"});let e=await r4(o,{type:"bug_report",...i?{hint:i}:{}});if(!e)return l({handled:!0,error:"Bug report failed"});return l({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 l({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eD(!1)}},[L,t6,tZ,eA,nx,tq,tG,tV,tJ,c,x]),ny=(0,i.useCallback)(async(e,t,n)=>{let r=tr.current;if(!r){tU(e,n,tF),t6({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 r4(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),r2(t)&&tU(e,n,tF),t6({type:"error",message:t instanceof Error?t.message:String(t)})}},[t6,tF,tU]),nv=(0,i.useCallback)(async(e,t)=>{await ny(e,"steer",t)},[ny]),nb=(0,i.useCallback)(async(e,t,n)=>{await ny(e,t,n)},[ny]),nw=(0,i.useCallback)(async(e,t)=>{await ny(e,"followUp",t)},[ny]),nk=(0,i.useCallback)(async()=>{let e=tr.current;if(e)try{await r4(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nj=(0,i.useCallback)(async()=>{let e=tr.current;if(e)try{let t=await r4(e,{type:"clear_queue"});e6({steering:[],followUp:[]});let n=[...ih(t?.steering),...ih(t?.followUp)];if(0===n.length)return;tU(n.map(e=>e.text).filter(Boolean).join("\n\n"),n.flatMap(e=>e.images).map(e=>({...e,previewUrl:""})),tF)}catch(e){console.error("Failed to recall queued messages:",e),t6({type:"error",message:e instanceof Error?e.message:"Failed to recall queued messages"})}},[t6,tF,tU]),nS=(0,i.useCallback)(async e=>{if(ek(e),y&&!tr.current&&(tI.current="auto"===e?null:e),"auto"===e)return;let t=tr.current??await tj.current;if(t)try{await r4(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[y]),nC=(0,i.useCallback)(async e=>{let t=(0,rt.xG)(e);!function(e,t=r5()){if(t)try{t.setItem(r8,e)}catch{}}(e),tP(e);let n=tr.current??await tj.current;if(!n){tn.current=void 0!==t;return}try{let e=await r4(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tn.current=void 0!==t;let r=e?.sessionId??n,i=e?.recreated===!0;r!==n&&(tQ(),t0(),tr.current=r),eJ([]),tl.current&&(i||r!==n)&&t4(r);let[o]=await Promise.all([r4(r,{type:"get_state"}),tV(r)]);tz.current&&tr.current===r&&eM(o.systemPrompt??"")}catch(e){console.error("Failed to set tools:",e)}},[tQ,t0,tV,t4,tP]),nI=(0,i.useCallback)((e,t=16)=>{let n=tk.current;n&&(tg.current=!0,tx.current=!1,tm.current=!1,n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),ty.current=n.scrollTop)},[]),nE=(0,i.useCallback)(()=>{let e=tk.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=ts.current,o=tm.current,l=function(e,t,n,r,i,o=96){return!!e3(n,r,i)||!(n<t)&&(!!(!e&&n>t&&e3(n,r,i,o))||e)}(o,ty.current,t,n,r,i?96:8);tm.current=l,ty.current=t,!o&&l&&i&&tD("instant")}},[tD]);(0,i.useEffect)(()=>(tz.current=!0,t&&(tr.current=t.id,tq(t.id,!0,!0).then(e=>{e?.running&&(tV(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(ta.current=!!e.state.isStreaming,td.current=!!e.state.isPromptRunning,ts.current=!0,V(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),_({type:"resume"}),t2(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&ni(t.id)),e.state?.isBashRunning&&(tu.current=!0,Y(!0),no(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eD(e.state.isCompacting),"boolean"==typeof e.state.autoCompactionEnabled&&eB(e.state.autoCompactionEnabled),void 0!==e.state.contextUsage&&eI(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eM(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&ek(e.state.thinkingLevel??"auto"),void 0!==e.state.queuedMessages&&e6(im(e.state.queuedMessages)))})),()=>{tz.current=!1,null!==tv.current&&cancelAnimationFrame(tv.current),tv.current=null,tb.current=[],tp.current+=1,tQ(),t0()}),[]),(0,i.useEffect)(()=>{p?.(eE)},[eE,p]),(0,i.useEffect)(()=>(g?.(tX),()=>g?.(null)),[tX,g]),(0,i.useEffect)(()=>{h&&h(S?.tree??[],L,np)},[S?.tree,L,np,h]),(0,i.useEffect)(()=>{let e=tk.current;if(e)return ty.current=e.scrollTop,e.addEventListener("scroll",nE,{passive:!0}),()=>{e.removeEventListener("scroll",nE)}},[N.length,I,nE]),(0,i.useLayoutEffect)(()=>{N.length>0&&(tx.current?(tx.current=!1,tg.current=!0,tD("instant")):tg.current?tm.current&&tD("instant"):(tg.current=!0,tD("instant")))},[N.length,K,tD,U.streamingMessage]),(0,i.useEffect)(()=>{let e=new AbortController,t=t$.current!==u;return t$.current=u,(async()=>{for(let n=0;;n++)try{await nx(e.signal,t,u);return}catch(t){if(e.signal.aborted||t instanceof DOMException&&"AbortError"===t.name||n>=iv.length||(await ib(iv[n]),e.signal.aborted))return}})(),()=>e.abort()},[nx,u]),(0,i.useEffect)(()=>{if(!eU)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eU]);let[nM,nT]=(0,i.useState)(null),nL=(0,i.useRef)(5e3),nR=(0,i.useRef)(null),nN=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===eX.visible.length){nN.current=null;return}let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eG({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=eX.visible[0];if(!t||(nN.current!==t.id&&(nN.current=t.id,nL.current=5e3),eX.visible.some(e=>e.id===nM)))return;nR.current=Date.now();let n=setTimeout(()=>{eG({type:"mark_oldest_exiting"})},nL.current);return()=>{clearTimeout(n),null!==nR.current&&(nL.current=Math.max(0,nL.current-(Date.now()-nR.current)),nR.current=null)}},[eX.visible,nM]),(0,i.useEffect)(()=>{e0(null)},[N.length,eC?.tokens,eC?.percent,eC?.contextWindow]),{data:S,loading:I,error:M,activeLeafId:L,messages:N,activeToolResults:W,entryIds:P,historyCursor:D,hasEarlierMessages:B,streamState:U,agentRunning:K,directImageRunning:G,modelNames:er,modelList:eo,modelError:es,modelScopeWarnings:ed,modelThinkingLevels:eu,modelThinkingLevelMaps:ep,newSessionModel:eg,toolPreset:ev,thinkingLevel:ew,retryInfo:ej,contextUsage:eC,systemPrompt:eE,forkingEntryId:eT,isCompacting:eA,autoCompactionEnabled:eH,compactError:eF,compactResult:eU,currentModel:tH,displayModel:tB,modelSwitching:ez,sessionStats:t_,slashCommands:eV,slashCommandsLoading:eY,queuedMessages:e5,notices:eX.visible,extensionDialog:e1,extensionCustomUi:e4,respondToExtensionUi:t8,sendExtensionCustomInput:t5,isAutoModelSelection:y&&null===eg,agentPhase:eq,isNew:y,sessionIdRef:tr,scrollContainerRef:tk,initialScrollDoneRef:tg,handleSend:ns,handleDirectImageGeneration:na,abortDirectImageGeneration:nd,handleAbort:nc,handleFork:nu,handleNavigate:nh,handleModelChange:nf,handleCompact:ng,handleSteer:nv,handleFollowUp:nw,handlePromptWithStreamingBehavior:nb,handleAbortCompaction:nk,handleRecallQueue:nj,handleBuiltinSlashCommand:nm,addNotice:t6,setNoticePaused:nT,handleToolPresetChange:nC,handleThinkingLevelChange:nS,loadTools:tV,loadSlashCommands:tG,setActiveLeafId:R,setData:C,setMessages:$,loadContext:tK,scrollToBottom:tD,scrollToMessage:nI,dispatch:_,setAgentRunning:V,setForkingEntryId:eL,bashRunning:J,pendingBash:Z,handleAgentEventRef:tf}}({session:e,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onAgentEnd:el,onAttentionNeeded:es,onSessionCreated:I,onSessionForked:ea,modelsRefreshKey:M,chatInputRef:er,onBranchDataChange:N,onSystemPromptChange:$,onSystemToolsChange:W,onSystemInfoLoaderChange:z,onSessionStatsPanelOpen:A,deferInitialScroll:!!ef,isVisiblePane:R}),tU=eR||eN||e$,t_=(0,i.useCallback)(()=>eN?tS():tC(),[tS,eN,tC]),tq=(0,i.useRef)(null),tK=tl?tl.tokens.input+tl.tokens.cacheRead+tl.tokens.cacheWrite:0,tV=tl&&tK>0?tl.tokens.cacheRead/tK*100:null,[tJ,tY]=(0,i.useState)(null),tZ=tv&&0===eS.length&&!eL.isStreaming&&!tU&&null===tJ,[tX,tG]=(0,i.useState)(!1),[tQ,t0]=(0,i.useState)(null),[t1,t2]=(0,i.useState)(!1),[t4,t8]=(0,i.useState)(null),[t5,t6]=(0,i.useState)(0),[t3,t7]=(0,i.useState)(null),[ne,nt]=(0,i.useState)(!1),[nn,nr]=(0,i.useState)(!1),[ni,no]=(0,i.useState)(null),nl=(0,i.useRef)(null),ns=(0,i.useRef)(null),na=(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?t0(t.config):(t0(null),t2(!1),t8(null))}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load image generation config:",e)}),()=>e.abort()},[t5,M]);let nd=(0,i.useCallback)(async t=>{eu();let n=null;for(let e=eS.length-1;e>=0;e--){let t=ex(eS[e].details);if(t){n=t;break}}let r=e?.cwd??d,i=t.target,o=i&&(i.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(i)?i:r?j(r,i):i);tY({prompt:t.prompt,size:t.size,width:n?.width,height:n?.height,previewUrl:o?`/api/files/${v(o)}?type=read`:void 0});try{await tj(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;tg({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tY(null)}},[tg,tj,eu,eS,d,e?.cwd]),nc=(0,i.useCallback)(async e=>{let t=await tz(e);return!("error"in t)&&/^\/reload(?:\s|$)/.test(e.trim())&&t6(e=>e+1),t},[tz]),nu=(0,i.useCallback)(()=>{t7(null),nt(!1),no(null)},[]);(0,i.useEffect)(()=>{O||nu()},[O,nu]);let nh=(0,i.useCallback)(e=>{let t=na.current;if(t&&!(null!=e&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)||!O||ne)return;let n=window.getSelection(),r=n?.rangeCount?n.getRangeAt(0):null,i=nS.current;if(!n||n.isCollapsed||!r||!i||!i.contains(r.commonAncestorContainer))return void t7(null);let o=n.toString().trim();if(!o)return void t7(null);let l=r.getBoundingClientRect(),s=[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);t7({text:o,top:Math.min(window.innerHeight-44,l.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,l.left+l.width/2)),sourceEntryId:s})},[O,ne]);(0,i.useEffect)(()=>{ne&&t3&&ns.current?.insertIfEmpty(e5(t3.text,X("chat.quoteIntro"),X("chat.quoteQuestion")))},[ne,t3,X]),(0,i.useLayoutEffect)(()=>{let e=nl.current;if(!e||!t3)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(t3.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(t3.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)}},[t3,ne,ni]),(0,i.useEffect)(()=>{if(!t3)return;let e=e=>{if(ne||nl.current?.contains(e.target))return;na.current={x:e.clientX,y:e.clientY};let t=()=>{document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),queueMicrotask(()=>{na.current=null})};document.addEventListener("pointerup",t),document.addEventListener("pointercancel",t),nu()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),nn||nu())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[t3,ne,nn,nu]);let np=(0,i.useCallback)(()=>{t3&&(er.current?.insertText(e5(t3.text,X("chat.quoteIntro"),X("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),nu())},[t3,nu,X]),nf=(0,i.useCallback)(async t=>{let n=tb.current??e?.id;if(!nn&&t.trim()&&t3?.sourceEntryId&&n&&F){nr(!0),no(null),J?.();try{await F(t,n,t3.sourceEntryId),nu()}catch(e){ns.current?.restoreSubmission(t),no(e instanceof Error?e.message:String(e))}finally{nr(!1)}}},[F,t3,nn,e?.id,tb,nu,J]),ng=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(eb||ew||!U||ng.current)return;let t=tb.current??e?.id;t&&(ng.current=!0,_?.(t),eu(),tk(U))},[U,eb,ew,tk,_,eu,e?.id,tb]),(0,i.useEffect)(()=>{Q&&tu&&eo.current!==tu.id&&(eo.current=tu.id,ee.current())},[Q,tu]);let[nx,nm]=(0,i.useState)(0),[ny,nv]=(0,i.useState)(50),nb=(0,i.useRef)(null),nw=(0,i.useRef)(null),nk=(0,i.useRef)({startIndex:0,endIndex:0,totalCount:0}),nj=(0,i.useRef)(null),nS=(0,i.useRef)(null),nC=(0,i.useRef)(null),nI=(0,i.useRef)(!1),nE=(0,i.useRef)(null),[nM,nT]=(0,i.useState)(null),nL=(0,i.useRef)(!1),nR=(0,i.useRef)(tB),nN=(0,i.useRef)(ef);nN.current=ef;let[n$,nP]=(0,i.useState)(null),nA=eS[eE.indexOf(n$?.entryId??"")],nD=nA?.role==="assistant"?n$?.blockIndex===void 0?nA.content.find(e=>"text"===e.type):nA.content[n$.blockIndex]:void 0,nF=(0,i.useRef)({entryIds:eE,historyCursor:eM,hasEarlierMessages:eT});nF.current={entryIds:eE,historyCursor:eM,hasEarlierMessages:eT},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=tw.current,r=nS.current;if(t&&s&&n&&r)return()=>{if(nN.current)return;if(e3(n.scrollTop,n.clientHeight,n.scrollHeight))return void s(t,{atBottom:!0});let e=n.getBoundingClientRect().top,i=iC(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&&s(t,{atBottom:!1,...i,oldestEntryId:nF.current.historyCursor})}},[eb,s,tw,e?.id]),(0,i.useEffect)(()=>{t&&eg(null)},[t]);let nO=(0,i.useCallback)(async(e,t,n)=>{do await new Promise(e=>requestAnimationFrame(()=>e())),n.throwIfAborted();while(nI.current);nI.current=!0;try{let r=nF.current;await tt(e,{entryIds:r.entryIds,oldestEntryId:r.historyCursor,hasMore:r.hasEarlierMessages},e=>tH(t,tB,e,{signal:n}),n)}finally{nI.current=!1}},[tB,tH]),nU=(0,i.useRef)(nO);nU.current=nO;let n_=(0,i.useCallback)(()=>{let e=nk.current;nm(e.totalCount-e.endIndex),nv(50)},[]);(0,i.useEffect)(()=>{let n=e?.id;if(!ef||!n||eb||t||nL.current)return;nL.current=!0,nE.current?.abort();let r=new AbortController;nE.current=r,nT(null),nP(null);let i=()=>{ey(!1),eg(null)};return(async()=>{try{if(await nU.current(ef.anchorEntryId,n,r.signal),r.signal.aborted)return void i();ey(!0)}catch(e){if(tn(e,r.signal))return void i();tF("instant"),eg(null)}})(),()=>{r.abort(),nE.current===r&&(nE.current=null),eg(null),ey(!1)}},[eb,ef,tF,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=nS.current;if(!ef||!e||t)return;let n=e.querySelector(`[data-entry-id="${CSS.escape(ef.anchorEntryId)}"]`);if(n){n_(),tO(n,ef.anchorOffset),eg(null);return}em&&(tF("instant"),eg(null))},[eE,n_,ef,em,tF,tO,t,ny,nx]),(0,i.useEffect)(()=>{if(!t||eb)return;nE.current?.abort();let e=new AbortController;nE.current=e,nT(null),nP(null);let n=t.sessionId;return(async()=>{try{if(await nU.current(t.entryId,n,e.signal),e.signal.aborted)return;nC.current=null,nP(t)}catch(n){if(tn(n,e.signal))return;tg({type:"warning",message:"other_branch"===(n instanceof e7&&"exhausted"===n.reason?function(e,t,n){if(!t||!n)return"not_found";let r=te(t,n);return!r||r.some(t=>e9(t,e))?"not_found":te(t,e)?"other_branch":"not_found"}(t.entryId,ev?.tree,tB):"not_found")?X("chat.locateOtherBranch"):n instanceof e7&&"stalled"===n.reason?X("chat.locateHistoryStalled"):n instanceof e7&&"load_failed"===n.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")}),o?.(t)}})(),()=>{e.abort(),nE.current===e&&(nE.current=null)}},[tB,tg,ev?.tree,eb,o,t,X]),(0,i.useLayoutEffect)(()=>{var e;let n=n$?`[data-entry-id="${CSS.escape(n$.entryId)}"]`:null,r=n?tw.current?.querySelector(nA?.role==="user"?n:`${n} [data-search-target]`)??tw.current?.querySelector(n):null,i=(e={pending:n$??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?nP(null):r&&n$&&(n_(),tO(r),r.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500}),nP(null),o?.(n$)))},[eE,n_,eS.length,ny,n$,t,nA,tw,tO,o,nx]),(0,i.useEffect)(()=>{nm(0),nv(50)},[e?.id]),(0,i.useEffect)(()=>{let e=tw.current;e&&(tU||eL.isStreaming)&&e3(e.scrollTop,e.clientHeight,e.scrollHeight)&&nm(0)},[tU,eL.isStreaming,tw]),(0,i.useEffect)(()=>{let e=tw.current;if(!e)return void tG(!1);let t=()=>{let t=e.scrollHeight-e.scrollTop-e.clientHeight;tG(nx>0||t>160)},n=()=>{t(),nE.current||nx>0||e3(e.scrollTop,e.clientHeight,e.scrollHeight)&&(nm(0),nv(50))};t();let r=new ResizeObserver(t);return r.observe(e),nS.current&&r.observe(nS.current),e.addEventListener("scroll",n,{passive:!0}),()=>{r.disconnect(),e.removeEventListener("scroll",n)}},[tZ,eb,tw,e?.id,nx]);let nq=(0,i.useCallback)(()=>{if(nI.current||nE.current)return;let t=tw.current;if(nk.current.startIndex>0){let e=nS.current;if(e&&t){let n=t.getBoundingClientRect().top;nj.current=iC(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)}nm(e=>e+25),nv(50);return}if(!eT||!eM)return;let n=e?.id??tb.current;n&&(nI.current=!0,t&&(nC.current=t.scrollHeight-t.scrollTop),tH(n,tB,eM).finally(()=>{nI.current=!1}))},[eM,eT,e,tB,tH,tb,tw]);(0,i.useEffect)(()=>{let e=nb.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nq()},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nq,tw]),(0,i.useEffect)(()=>{let e=nw.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&!nE.current&&nm(e=>Math.max(0,e-25))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nx,tw]),(0,i.useLayoutEffect)(()=>{let e=nj.current,t=nS.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&&tO(n,e.anchorOffset),nj.current=null},[nx,tO]),(0,i.useEffect)(()=>{if(null==nC.current)return;let e=tw.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nC.current),nC.current=null}},[eS.length,tw]);let nK=tl?[tl.sessionId,tl.sessionFile??"",tl.sessionName??"",tl.userMessages,tl.assistantMessages,tl.toolCalls,tl.toolResults,tl.totalMessages,tl.tokens.input,tl.tokens.output,tl.tokens.cacheRead,tl.tokens.cacheWrite,tl.tokens.total,tl.cost??0,tl.totalActiveMs??0,tl.contextUsage?.percent??"null",tl.contextUsage?.contextWindow??"",tl.contextUsage?.tokens??"null"].join("|"):null,nV=(0,i.useRef)(tl);nV.current=tl,(0,i.useEffect)(()=>{eb||P?.(nV.current)},[eb,nK,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let nJ=eG?`${eG.percent??"null"}|${eG.contextWindow}|${eG.tokens??"null"}`:null,nZ=(0,i.useRef)(eG);nZ.current=eG,(0,i.useEffect)(()=>{eb||D?.(nZ.current)},[nJ,eb,D]),(0,i.useEffect)(()=>()=>{D?.(null)},[D]);let{isDragOver:nX,handleDragEnter:nG,handleDragOver:nQ,handleDragLeave:n0,handleDrop:n1}=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))},[]),l=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:o,handleDragOver:l,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)},[])),n2=e?.cwd??d??void 0,n4=(0,i.useMemo)(()=>eS.filter(e=>eD(e)||"assistant"===e.role||"toolResult"===e.role&&!e.isError&&ex(e.details)),[eS]),n8=(0,i.useMemo)(()=>{let e=new Map(eC);for(let t of eS)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eC,eS]),n5=(0,i.useMemo)(()=>eS.map(e=>"assistant"===e.role?eV(e):null),[eS]),n6=(0,i.useMemo)(()=>{let e=new Map;for(let t=0;t<eS.length;){let n=eD(eS[t])?t:-1,r=n>=0?t+1:t;for(;r<eS.length&&!eD(eS[r]);)r+=1;let i=iT(eS,n,r);if(i>=0&&n5[i]?.answerMessage){let t=[];for(let e=n+1;e<=i;e+=1){let n=eS[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")||e4(e)||e8(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=eX(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),l=t?i(t).replace(/\/+$/,""):void 0,s=/^[a-zA-Z]:\//.test(o),a=o.startsWith("//");if(s||a)n=o;else if(o.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${o}`:o}else{if(!l)return null;n=`${l}/${o}`}return e1(n)}(e,n);t&&(r.has(t)||(r.add(t),i.push({filePath:t})))}}return i}(t,n8,n2))}t=r}return e},[n5,n2,eS,n8]),n3=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eS.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}(eS[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eS]),n7=(Y=n4.length,(Z=(0,i.useRef)([])).current=Array(Y).fill(null).map((e,t)=>Z.current[t]??null),Z),n9=(0,i.useMemo)(()=>{for(let e=eS.length-1;e>=0;e--)if(eS[e]?.role==="user")return eE[e]??"";return""},[eE,eS]);(0,i.useEffect)(()=>{let e=nR.current;nR.current=tB,null!==e&&e!==tB&&(nE.current?.abort(),nN.current&&(eg(null),ey(!1)))},[tB]),(0,i.useEffect)(()=>()=>{nE.current?.abort()},[e?.id]);let re=(0,i.useCallback)(async t=>{let n=e?.id??tb.current;if(!n)return;nE.current?.abort();let r=new AbortController;nE.current=r,nT(null),nP(null);try{nC.current=null,nj.current=null,await nO(t,n,r.signal),r.signal.throwIfAborted(),await new Promise((e,n)=>{r.signal.addEventListener("abort",()=>n(r.signal.reason),{once:!0}),nT({entryId:t,signal:r.signal,resolve:e})})}catch(e){if(tn(e,r.signal))return;tg({type:"warning",message:e instanceof e7&&"stalled"===e.reason?X("chat.locateHistoryStalled"):e instanceof e7&&"load_failed"===e.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")})}finally{nT(e=>e?.signal===r.signal?null:e),nE.current===r&&(nE.current=null)}},[tg,nO,e?.id,tb,X]);(0,i.useLayoutEffect)(()=>{if(!nM||nM.signal.aborted)return;let e=nS.current?.querySelector(`[data-entry-id="${CSS.escape(nM.entryId)}"]`);e&&(n_(),tO(e),nM.resolve())},[nM,eE,n_,eS.length,ny,nx,tO]);let rn=!!eL.streamingMessage?.content.length,rr=(0,i.useMemo)(()=>{let e=-1;for(let t=eS.length-1;t>=0;t--)if(eD(eS[t])){e=t;break}let t=e>=0&&eA(eS[e])?e:e+1;for(let e=t;e<eS.length;e++){let t=eS[e];if("custom"===t.role||"assistant"===t.role&&(eB(t).length>0||eF(t)))return!0}return!1},[eS]),ri=eL.streamingMessage?.role==="assistant"?eL.streamingMessage:null,ro=ri?eV(ri,{isStreaming:!0}):{processMessage:null,answerMessage:null},rl=(0,i.useRef)(L);(0,i.useLayoutEffect)(()=>{let e=rl.current;rl.current=L,!e&&L&&tU&&!tX&&tF("instant")},[L,tU,tX,tF]);let rs=ti?e_[`${ti.provider}:${ti.modelId}`]??null:null,ra=ti?eK[`${ti.provider}:${ti.modelId}`]??null:null,rd=(0,i.useCallback)(async(e,t)=>{eu(),nE.current?.abort(),nT(null),nP(null),nm(0),nv(50),await tk(e,t)},[tk,eu]),rc=(0,i.useCallback)(e=>(eu(),tI(e)),[tI,eu]),ru=(0,i.useCallback)((e,t)=>(eu(),tL(e,t)),[tL,eu]),rh=(0,i.useCallback)((e,t)=>(eu(),tR(e,t)),[tR,eu]),rp=(0,i.useCallback)((e,t,n)=>(eu(),tN(e,t,n)),[tN,eu]),rf=!tv&&eb,rg=e?.relation?.kind==="subagent"&&"queued"===e.relation.status,rx=(0,r.jsx)(rz,{ref:ei,onSend:rd,onOpenImageGeneration:!tQ||rf||tU||rg?void 0:()=>{t8(null),t6(e=>e+1),t2(!0)},onAbort:t_,onSteer:eR?ru:void 0,onFollowUp:eR?rh:void 0,onPromptWithStreamingBehavior:eR?rp:void 0,isStreaming:tU||rg,disabled:rg,model:rf?null:ti,isAutoModelSelection:!rf&&tm,modelNames:ez,modelList:eH,modelError:rf?null:eO,modelScopeWarnings:rf?[]:eU,onModelChange:rf||rg?void 0:tM,modelSwitching:to,onCompact:!rg&&(e||tv)?tT:void 0,onAbortCompaction:t$,isCompacting:e0,compactError:e2,compactResult:tr,contextUsage:rf?null:eG,cacheHitRate:tV,onOpenSessionStats:A,toolPreset:eJ,onToolPresetChange:!rg&&(e||tv)?tP:void 0,thinkingLevel:rf?void 0:eY,onThinkingLevelChange:rf||rg?void 0:e||tv?tA:void 0,availableThinkingLevels:rs,thinkingLevelMap:ra,retryInfo:eZ,queuedMessages:td,inputHistory:n3,onRecallQueue:tW,slashCommands:ts,slashCommandsLoading:ta,onLoadSlashCommands:tD,onBuiltinCommand:nc,soundEnabled:q,onSoundToggle:K,onAudioUnlock:J,draftKey:e?.id??c??void 0,onDraftChange:u,draftPersistenceWarning:w,cwd:e?.cwd??d});return eb?(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:rx})]}):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:nG,onDragOver:nQ,onDragLeave:n0,onDrop:n1,children:[nX&&(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)(iF,{notices:tc,floating:!0,onPauseChange:tx})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[t1&&tQ&&(0,r.jsx)(eI,{config:tQ,edit:t4,editPreviewUrl:t4?`/api/files/${v(t4.path.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(t4.path)?t4.path:n2?j(n2,t4.path):t4.path)}?type=read`:void 0,onClose:()=>{t2(!1),t8(null)},onSubmit:nd}),tu&&(0,r.jsx)(iO,{request:tu,onRespond:tp},tu.id),th&&(0,r.jsx)(iU,{request:th,onInput:tf},th.id),!tZ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:tw,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:nS,onPointerUp:nh,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=eS.length-1;e>=0;e--)if(eD(eS[e])){o=e;break}let l=new Map,s=0;eS.forEach((e,t)=>{let n=("toolResult"!==e.role||e.isError)&&("custom"!==e.role||e.customType!==ed)?null:ex(e.details);(eD(e)||"assistant"===e.role||n)&&l.set(t,s++)});let a=(t,n={})=>{var i,o;let s,a,d,c=n.messageOverride??eS[t],u="user"===c.role&&t>0&&"assistant"===eS[t-1].role?eE[t-1]:void 0,h=("toolResult"!==c.role||c.isError)&&("custom"!==c.role||c.customType!==ed)?null:ex(c.details),p=eD(c)||"assistant"===c.role||!!h,f=l.get(t),g=n.keyPrefix??"message",x=eE[t]??t,m=h?(0,r.jsx)(ek,{value:h,cwd:n2,onEdit:tQ&&!tU&&tQ.connections.some(e=>e.id===h.connection&&!0===e.capabilities.editing)?e=>{t8(e),t6(e=>e+1),t2(!0)}:void 0,onMention:tQ?e=>{er.current?.mentionImage(e)}:void 0,showPrompt:"custom"===c.role,createdAt:c.timestamp},`${g}-image-${x}`):(0,r.jsx)(t9,{message:c,modelName:n.isTurnEnd&&"assistant"===c.role?(i=c.provider??"",o=c.model??"",s=i.toLowerCase(),a=o.toLowerCase(),d=Object.entries(ez??{}).flatMap(([e,t])=>{let n=e.indexOf(":");return n>0&&e.slice(0,n).toLowerCase()===s?[{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(ez??{}).find(([e])=>e.toLowerCase()===a)?.[1]??(i&&o?`${i}/${o}`:o)):void 0,toolResults:n8,cwd:n2,onOpenFile:ec,onOpenSession:B,entryId:eE[t],searchBlock:eE[t]===n$?.entryId?nD:void 0,onFork:tU||tv?void 0:rc,forking:eQ===eE[t],onNavigate:tU?void 0:tE,prevAssistantEntryId:tU?void 0:u,onEditContent:eh,isTurnEnd:n.isTurnEnd,sessionId:e?.id??tb.current??void 0,writtenFiles:n.writtenFiles,isProcess:n.isProcess},`${g}-view-${x}`);return p?(0,r.jsx)("div",{"data-entry-id":eE[t],"data-slot-index":`msg-${t}`,ref:!1===n.attachRef||void 0===f?void 0:e=>{n7.current[f]=e},children:m},`${g}-${x}`):m},d=(n={outline:nM?{entryId:nM.entryId,aborted:nM.signal.aborted}:null,search:n$?{entryId:n$.entryId,matchesTarget:n$===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<eS.length;){let t,n,i,s=eD(eS[e]),u=eP(eS[e]),f=s?e:-1,g=f>=0&&eA(eS[f]),x=s?e+1:e;for(;x<eS.length&&!eD(eS[x]);)x+=1;let m=s?f:e,y=g?f:f+1,v=iT(eS,f,x),b=(tU||eL.isStreaming)&&x===eS.length&&f===o;if(b&&(p=x-m),-1===v&&!g){for(let e=m;e<x;e++)h([eE[e]]),c.push(a(e));if(b&&ro.processMessage){h([]);let e=iR(!0,eL.isStreaming,ri,ty,!!ro.answerMessage),t=f>=0&&"number"==typeof eS[f]?.timestamp&&Number.isFinite(eS[f].timestamp)?eS[f].timestamp:ro.processMessage.timestamp,n=iz(t,ro.processMessage.completedAt);c.push((0,r.jsx)("div",{children:(0,r.jsx)(iD,{messageCount:1,toolCallCount:eq(ro.processMessage.content??[]),durationSeconds:n,startTime:t,defaultExpanded:!0,isMobile:G,activeStepSummary:iW(i$(ro.processMessage,ty,X),e,tq,X("chat.thinking")),isStreaming:e,t:X,children:(0,r.jsx)(t9,{message:ro.processMessage,isStreaming:!0,isProcess:!0,toolResults:n8,cwd:n2,onOpenFile:ec,onOpenSession:B},"streaming-process-view")})},`process-group-${eE[m]??m}`))}e=x;continue}u&&(h([eE[f]]),c.push(a(f)));let w=n5[v],k=w?.answerMessage??null,j=v>=0?v:x-1,S=[],C=[],I=[],E=0,M=!1;for(let e=y;e<=j;e++){let r=eS[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??=l.get(e),M||=!!(d&&d===eE[e]),eE[e]&&C.push(eE[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",isProcess:!0}));continue}if("assistant"!==r.role)continue;let o=n5[e];e!==v&&o?.answerMessage&&I.push({idx:e,message:o.answerMessage});let s=o?.processMessage;if(!s)continue;let c=eB(s),u=!!eF(s);(0!==c.length||u)&&(t??=l.get(e),E+=eq(c),M||=!!(d&&eE[e]===d&&(!nD||n$?.entryId!==d||c.includes(nD))),eE[e]&&C.push(eE[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",messageOverride:s,isTurnEnd:!1,isProcess:!0})))}b&&ro.processMessage&&S.push((0,r.jsx)(t9,{message:ro.processMessage,isStreaming:!0,isProcess:!0,toolResults:n8,cwd:n2,onOpenFile:ec,onOpenSession:B},"streaming-process-view"));let T=!!(k||ro.answerMessage),L=iR(b,eL.isStreaming,ri,ty,T),R=iW(i$(ri,ty,X),L,tq,X("chat.thinking")),N=f>=0&&"number"==typeof eS[f]?.timestamp&&Number.isFinite(eS[f].timestamp)?eS[f].timestamp:n,$=iz(N??n,i);S.length>0&&(h(C),c.push((0,r.jsx)("div",{"data-entry-id":eE[y],ref:void 0===t?void 0:e=>{n7.current[t]=e},children:(0,r.jsx)(iD,{messageCount:S.length,toolCallCount:E,durationSeconds:$,startTime:N??n,defaultExpanded:!k&&x===eS.length,reveal:M,isMobile:G,activeStepSummary:R,isStreaming:L,t:X,children:S})},`process-group-${eE[m]??m}`)));for(let e=m;e<=j;e++){let t=eS[e];"toolResult"===t.role&&!t.isError&&ex(t.details)&&(h([eE[e]]),c.push(a(e)))}for(let e of I)h([eE[e.idx]]),c.push(a(e.idx,{keyPrefix:"promoted",messageOverride:e.message}));if(k&&(h([eE[v]]),c.push(a(v,{isTurnEnd:!0,messageOverride:k,writtenFiles:n6.get(v)}))),v>=0)for(let e=v+1;e<x;e++)h([eE[e]]),c.push(a(e));e=x}let f=Math.max(ny,50+p),{startIndex:g,endIndex:x}=u>=0?e6(i=c.length,i-Math.max(0,u-5)-50):e6(c.length,nx,f);nk.current={startIndex:g,endIndex:x,totalCount:c.length};let m=g>0||eT;return(0,r.jsxs)(r.Fragment,{children:[m&&(0,r.jsx)("button",{type:"button",ref:nb,onClick:nq,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,x),x<c.length&&(0,r.jsx)("div",{ref:nw,className:"py-3 text-center text-xs text-text-muted"})]})})(),eL.isStreaming&&ro.answerMessage&&(0,r.jsx)(t9,{message:ro.answerMessage,isStreaming:!0,cwd:n2,onOpenFile:ec,onOpenSession:B}),eR&&!rn&&!rr&&(0,r.jsx)(iI,{label:X("chat.agentWorking")}),e$&&!eW&&(0,r.jsx)(iI,{label:X("chat.agentWorking")}),eW&&(0,r.jsx)(t9,{message:{role:"bashExecution",command:eW.command,output:"",excludeFromContext:eW.excludeFromContext},sessionId:e?.id??tb.current??void 0,onOpenSession:B}),tJ&&(0,r.jsx)(ej,{prompt:tJ.prompt,size:tJ.size,width:tJ.width,height:tJ.height,previewUrl:tJ.previewUrl})]})})}),tX&&!ef&&(0,r.jsx)("button",{type:"button",onClick:()=>{nE.current?.abort(),nT(null),nP(null),nm(0),nv(50),requestAnimationFrame(()=>tF("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&&R&&(0,r.jsx)(rq,{sessionId:e?.id??tb.current,leafId:tB,outlineRevision:n9,scrollContainer:tw,contentContainer:nS,loadedEntryIds:eE,onJumpToEntry:re}),!R||G||ef?null:(0,r.jsx)(r_,{sessionId:e?.id??tb.current,leafId:tB,outlineRevision:n9,scrollContainer:tw,contentContainer:nS,loadedEntryIds:eE,onJumpToEntry:re})]})]}),O&&t3&&(0,S.createPortal)((0,r.jsx)("div",{ref:nl,role:ne?"dialog":"toolbar","aria-label":X(ne?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:t3.top,left:t3.left,zIndex:130,display:"flex",flexWrap:"wrap",gap:2,width:ne?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:ne?12:2,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)"},children:ne?(0,r.jsxs)("fieldset",{disabled:nn,"aria-busy":nn,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:nn,onClick:nu,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)(rz,{ref:ns,compact:!0,onSend:nf,onAbort:nu,isStreaming:!1}),ni&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:ni})]}):(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:np,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"@"}),(0,r.jsx)("span",{children:X("chat.askInCurrent")})]}),F&&t3.sourceEntryId&&!tU&&(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:()=>{nt(!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:[tZ&&(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)(iM,{label:e=>X("appUpdate.releaseNotes",{version:e})})]}),d&&p&&(0,r.jsx)(iE,{cwd:d,onChange:p,recentPaths:f,pinnedPaths:g,onTogglePinnedCwd:x,homeDir:y,worktreeInfo:b})]}),rx]}),tZ&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function iB({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 iF({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)(iB,{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 iO({request:e,onRespond:t}){let{t:n}=(0,m.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[s,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:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(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)(tJ,{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)(tJ,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(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=>l(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 iU({request:e,onInput:t}){let{t:n}=(0,m.s)(),o=(0,i.useRef)(null),l=(0,i.useRef)(!1),[s,a]=(0,i.useState)(!1),d=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eT,""),i=eL(e).trimEnd();if(t.test(i))continue;let o=e,l=e$(o);("│"===l||"┃"===l)&&" "===e$(o=eN(o,0))&&(o=eN(o,0));let s=function(e){let t=eR(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=s>=0?eR(o)[s]?.char:void 0;("│"===a||"┃"===a)&&(o=eN(o,s)),n.push(function(e){let t=e;for(;;){let e=eR(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&&""===eL(n[0]).trim();)n.shift();for(;n.length>0&&""===eL(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)(()=>{s||o.current?.focus()},[s]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(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(l.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=ez[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":" ":eW[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(l.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:n=>{l.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)(rV,{text:d.join("\n")})})]})})}function i_({tabs:e,activeTabId:t,splitTabId:n=null,activePane:o="primary",runningSessionIds:l,onSelectTab:s,onCloseTab:a,onPinTab:d,onNewTab:c,onToggleSplit:u,onClosePane:h,canSplit:p=!0,isSecondaryPane:f=!1,unifiedHeader:g=!1,isMobile:x=!1}){let{t:y}=(0,m.s)(),[v,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(!1),[j,C]=(0,i.useState)(!1),[I,E]=(0,i.useState)({top:0,left:0,width:320}),M=(0,i.useRef)(null),T=(0,i.useRef)(null),L=(0,i.useRef)(null),R=(0,i.useRef)(null);(0,i.useEffect)(()=>{M.current&&M.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),(0,i.useEffect)(()=>{let e=T.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();R.current&&t.includes(R.current)||L.current&&t.includes(L.current)||C(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),C(!1),L.current?.focus())},n=()=>C(!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)(()=>{w||C(!1)},[w]);let N=!!(n&&!x),$=e=>{let t=e?Array.from(document.querySelectorAll("[data-chat-tab-id]")).find(t=>t.dataset.chatTabId===e):null,n=M.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":y("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:T,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&&l?.has(i.session.id));return(0,r.jsxs)("div",{"data-chat-tab":"true","data-chat-tab-id":i.id,ref:u?M:void 0,role:"tab","aria-label":i.dirty?`${i.title}, ${y("chatTabs.unsentDraft")}`:i.title,"aria-selected":p,tabIndex:f||!t&&0===c?0:-1,onClick:()=>s(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(),s(i.id);else if(["ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault();let n=(c+("ArrowRight"===t.key?1:-1)+e.length)%e.length;s(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:x?4:6,height:"100%",paddingLeft:x?8:10,paddingRight:x?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:x?130:200,minWidth:x?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 ${y("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)(K,{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:y("chatTabs.unsentDraft"),"aria-hidden":"true",style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",flexShrink:0}}),(!x||p)&&(0,r.jsx)("button",{type:"button",tabIndex:-1,onClick:e=>{e.stopPropagation(),a(i.id)},onDoubleClick:e=>e.stopPropagation(),onMouseEnter:()=>b(i.id),onMouseLeave:()=>b(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:x?22:20,height:x?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:y("chatTabs.closeTab",{defaultValue:"关闭标签"}),"aria-label":`${y("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:x?"-4px 0 10px -2px rgba(0,0,0,0.18)":void 0,zIndex:2,position:"relative"},children:[w&&!x&&(0,r.jsx)("button",{ref:L,type:"button",onClick:()=>{if(j)return void C(!1);let e=L.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}),C(!0)},"aria-expanded":j,title:y("chatTabs.allTabs"),"aria-label":y("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:y("chatTabs.newTab",{defaultValue:"新建对话标签"}),"aria-label":y("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&&!x&&u&&(0,r.jsx)("button",{type:"button",onClick:u,"aria-pressed":N,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:N?"var(--bg-selected)":"transparent",border:"none",color:N?"var(--accent)":"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:N?y("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):y("chatTabs.splitView",{defaultValue:"向右分屏"}),"aria-label":N?y("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):y("chatTabs.splitView",{defaultValue:"向右分屏"}),onMouseEnter:e=>{N||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{N||(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:y("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),"aria-label":y("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,S.createPortal)((0,r.jsx)("div",{ref:R,role:"dialog","aria-label":y("chatTabs.allTabs"),style:{position:"fixed",top:I.top,left:I.left,width:I.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&&l?.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:()=>{C(!1),s(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)(K,{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=T.current;if(e&&e.scrollWidth>e.clientWidth+1){let e=R.current?.querySelectorAll("[data-tab-menu-close]"),t=e?.[Math.min(i,e.length-1)];if(t)return void t.focus()}C(!1),$()})},title:`${y("chatTabs.closeTab")}: ${e.title}`,"aria-label":`${y("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 iq(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 iK(e){return e.pane??"primary"}function iV(e,t){return e.filter(e=>iK(e)===t)}function iJ(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&&iK(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 iY(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 iZ(e,t){let n=[...iV(e,"primary"),...iV(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 iX(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 iG(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 iQ(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),l=iK(e[i]),s=iV(e,l),a=iV(o,l),d=a[Math.min(s.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"===l?u:c;return{tabs:iZ(o,e),nextActiveTabId:e,nextSplitTabId:null}}return{tabs:o,nextActiveTabId:c,nextSplitTabId:u}}var i0=n(50640);let i1={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"},i2={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"},i4={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function i8(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i5(e){return null!==(i1[i8(e)]??null)}function i6(e){return null!==(i2[i8(e)]??null)}function i3(e){return null!==(i4[i8(e)]??null)}function i7(e){let t;return null!==("pdf"===(t=i8(e))||"docx"===t?t:null)}let i9=new Set(["md","mdx","html","htm"]);var oe=n(73620);let ot=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function on(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 or(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 oi=/^ {0,3}(`{3,}|~{3,})/,oo=/^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*#*[ \t]*$/,ol=["tags","categories","keywords","tag","category"];function os({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=ol.find(t=>Array.isArray(e[t])),l=o?e[o].map(on).filter(Boolean):[],s=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}),l.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:l.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),s.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:s.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=on(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 oa({items:e,scrollRoot:t}){let{t:n}=(0,m.s)(),o=(0,i.useId)(),l=(0,i.useRef)(null),[s,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(!s)return;let e=e=>{l.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)}},[s]),0===e.length)return null;let h=e.map(()=>!1);if(u)for(let t=0;t<e.length;t++){let n=or(e,t);n>=0&&(h[n]=!0)}return(0,r.jsxs)("div",{ref:l,className:"file-outline",children:[(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button","aria-expanded":s,"aria-haspopup":"menu","aria-controls":o,"aria-label":n("i18n.outline"),title:n("i18n.outline"),onClick:()=>a(e=>!e),style:{background:s?"var(--bg-selected)":"transparent",color:s?"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"})]})}),s&&(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=or(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 od(e,t,n){var r;return r=n??(i9.has(i8(e))?"preview":void 0),t?.displayMode??r??"source"}let oc={fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.6},ou={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 oh(){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 op(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function of(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=op(n.startContainer),i=op(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let o=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(o)||!Number.isInteger(l))return null;if(o<l){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]")&&(l=Number((i=e).dataset.lineNumber))}}}return o>l?null:{startLine:o,endLine:l}}function og({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,o)=>{let l=e.children??[],s=l[0]?.properties?.className,a=Array.isArray(s)&&s.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":o+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,i0.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,i0.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${o}-${r}`}))})]},`source-line-${o}`)})}function ox(e,t,n,r={}){let i=v(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 om({filePath:e,sourceSessionId:t}){let{t:n}=(0,m.s)();return(0,r.jsx)("a",{href:ox(e,"download",t),download:b(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 oy(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ov({patch:e}){let{t}=(0,m.s)(),n=(0,i.useMemo)(()=>{let t;return(t=tQ(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%",...oc},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:{...ou,width:40,minWidth:40,paddingInline:6},children:e.oldLineNo}),(0,r.jsx)("span",{style:{...ou,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 ob({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),y=(0,i.useRef)(null),v=(0,i.useRef)(0),w=b(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));y.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&h(e.size),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(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),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),y.current===r&&(y.current=null)}},[e,n,o]);let j=ox(e,"read",n,d?{v:d}:void 0),S=null!=u?oy(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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),S&&(0,r.jsx)("span",{children:S}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(om,{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:j,alt:e,onLoad:e=>{let t=e.currentTarget;f({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function ow(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 ok({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),y=(0,i.useRef)(null),v=(0,i.useRef)(0),w=b(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));y.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&h(e.size),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(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),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),y.current===r&&(y.current=null)}},[e,n,o]);let j=ox(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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"audio"}),null!=p&&(0,r.jsx)("span",{children:ow(p)}),null!=u&&(0,r.jsx)("span",{children:oy(u)}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(om,{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:j,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x("Failed to load audio"),style:{width:"100%"}},j)]})})]})}function oj({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),y=(0,i.useRef)(null),v=(0,i.useRef)(0),w=b(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));y.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&h(e.size),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(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),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),y.current===r&&(y.current=null)}},[e,n,o]);let j=ox(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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"video"}),null!=p&&(0,r.jsx)("span",{children:ow(p)}),null!=u&&(0,r.jsx)("span",{children:oy(u)}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(om,{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:j,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},j)]})})]})}function oS({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0,pdfPage:l}){let{t:s}=(0,m.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),x=(0,i.useRef)(null),y=(0,i.useRef)(0),v=i8(e),w="pdf"===v,j=w?ox(e,"read",n,c?{v:c}:void 0)+(l?`#page=${l}`:""):ox(e,"preview",n,c?{v:c}:void 0);return(0,i.useEffect)(()=>{u(0),p(null),g(null),d(!1);let t=!0,r=++y.current;return fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{t&&r===y.current&&(e.error&&g(e.error),"number"==typeof e.size&&(p(e.size),!w&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===y.current&&g(String(e))}),()=>{t=!1}},[e,w,n]),(0,i.useEffect)(()=>{if(d(!1),x.current&&(x.current.close(),x.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));x.current=r,r.addEventListener("connected",()=>{let r;d(!0),r=++y.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===y.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(p(e.size),!w&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),u(e=>e+1)}}).catch(e=>{t&&r===y.current&&g(String(e))})}),r.addEventListener("change",e=>{y.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(p(t.size),!w&&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(),x.current===r&&(x.current=null)}},[e,w,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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===v?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:oy(h)}),(0,r.jsx)(om,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(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:j,sandbox:w?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:b(e)}),style:{width:"100%",height:"100%",border:"none",background:w?"var(--bg)":"#eef1f5"}},j)})]})}function oC({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u=!0,pdfPage:h}){let p="diff"===od(e,d,a);return!p&&i5(e)?(0,r.jsx)(ob,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&i6(e)?(0,r.jsx)(ok,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&i3(e)?(0,r.jsx)(oj,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&i7(e)?(0,r.jsx)(oS,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u,pdfPage:h}):(0,r.jsx)(oI,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u})}function oI({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:o,onMentionLines:l,onAtMention:s,gitRefreshKey:a,initialDisplayMode:d,initialState:c,onStateChange:u,watchEnabled:h=!0}){let{isDark:p}=tO(),{t:f}=(0,m.s)(),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(null),[b,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[I,E]=(0,i.useState)(null),[M,T]=(0,i.useState)(!0),[L,R]=(0,i.useState)(!1),[N,$]=(0,i.useState)(null),W=od(e,c,d),z="diff"===W&&(i5(e)||i6(e)||i3(e)||i7(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,el]=(0,i.useState)(null);ei.current=u;let es=(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(ox(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,x(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(j(!0),E(null),!t){v(null),j(!1),C(!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||E(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),E(e instanceof Error?e.message:String(e)))}finally{n===Q.current&&(j(!1),C(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;if(T(!0),$(null),x(null),v(null),C(!1),E(null),K(!1),Y.current=null,Z.current=0,G.current=!1,z)return T(!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&&T(!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(ox(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=y?.supported===!0&&"string"==typeof y.patch,eh=eu&&"deleted"===y.status;(0,i.useEffect)(()=>{S&&!eu&&"diff"===F&&es("source")},[F,S,eu,es]),(0,i.useEffect)(()=>{"diff"===W&&eu&&!et.current&&(et.current=!0,es("diff"))},[W,eu,es]);let ep=(0,i.useMemo)(()=>g?.language==="markdown"?tg(g.content):"",[g]),ef=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=ot.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,oe.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=oi.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=oo.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]),ex=g?.content??"",em=(0,i.useMemo)(()=>ex.split("\n"),[ex]),ey=g?.language??"text",ev="html"===ey,eb="markdown"===ey,ew=!g?.truncated&&(ev||eb),ek=eh?"diff":"preview"!==F||ew?F:"source",ej=(em.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)(t_.A,{className:U?"file-source-view is-wrapped":"file-source-view",language:"text"===ey?"plaintext":ey,style:p?tC.xJ:tC.vs,showLineNumbers:!0,lineNumberStyle:{...ou},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...oc,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)(og,{...e,wrapLines:U}),wrapLongLines:U,children:ex}):null,[p,ey,eS,ex,U]),eI=(0,i.useMemo)(()=>ej?em.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:ou,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,[em,ej,U]);(0,i.useEffect)(()=>{let e=()=>{let e=ee.current;el(t=>{let n=l&&"source"===F&&e?of(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),l&&"source"===F)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,F,l]);let eE=(0,i.useCallback)(n=>{l&&n&&l(k(e,t),n.startLine,n.endLine,t)},[t,e,l]);if((0,i.useEffect)(()=>{if(!l||"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?of(n,window.getSelection()):null;r&&(e.preventDefault(),eE(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[F,eE,l]),(0,i.useEffect)(()=>{if(!en.current||M||N&&!eh||"diff"===W&&!S||"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,N,S,eu,eh,M,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]),M||"diff"===W&&b&&!S)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&&S&&I)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:I});if(N&&!("diff"===ek&&eu))return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:N});if(!g&&!("diff"===ek&&eu))return null;let eM=w(e),eT=!g||eh?["diff"]:["source",...ew?["preview"]:[],...eu?["diff"]:[]],eL=eh?f("files.deleted"):g?`${ey} \xb7 ${em.length} lines \xb7 ${oy(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:k(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eL,children:eL}),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:[eT.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":f("i18n.fileViewMode"),children:eT.map(e=>{let t=ek===e;return(0,r.jsx)("button",{type:"button",onClick:()=>es(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)(oa,{items:eg,scrollRoot:ee}),(s||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{eo&&l?eE(eo):s?.(k(e,t),!1,t)},title:eo&&l?`${f("i18n.mentionSelectedLines")} (L${eo.startLine}${eo.startLine!==eo.endLine?`-L${eo.endLine}`:""})`:f("files.insertPath"),"aria-label":f("files.mention"),disabled:!s&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(oh,{})}),"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)(om,{filePath:e,sourceSessionId:n})]})]}),g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",children:[(0,r.jsxs)("span",{children:[oy(g.nextOffset)," / ",oy(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:L,onClick:()=>{R(!0),ed(e,g.nextOffset).finally(()=>R(!1))},children:L?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)(ov,{patch:y.patch}):ev&&"preview"===ek?(0,r.jsx)("iframe",{srcDoc:ex,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)(os,{data:ef.data}),(0,r.jsx)(tr.oz,{remarkPlugins:tk,rehypePlugins:tS,urlTransform:o?tp: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)(tq,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tV,{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 l=o?e2(e,eM,t??eM):null;return l&&o?(0,r.jsx)("a",{href:e,...i,onClick:e=>{eG(e)&&(e.preventDefault(),o(l))},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 l="string"==typeof e?e2(e,eM,t??eM):null,s=l?ox(l,"read",n):e;return(0,r.jsx)("img",{src:s,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)",...oc},children:eI}):eC})]})}function oE(e,t){if(t<=0)return"";let n=Math.max(0,e.length-1-t);return e.slice(n,-1).join("/")||e[0]||""}function oM(e,t){return t?`${e} \xb7 ${t}`:e}function oT(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function oL({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:o}){let{t:l}=(0,m.s)(),[s,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||b(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=y(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),l=!0;for(;l;){l=!1;let t=r.map((t,r)=>oM(e,oE(n[r],o[r]))),s=oT(t);for(let e=0;e<r.length;e+=1)!((s.get(t[e])??0)<=1)&&(o[e]>=i[e]||(o[e]+=1,l=!0))}let s=r.map((t,r)=>oM(e,oE(n[r],o[r]))),a=oT(s);r.forEach((n,r)=>{t.set(n.id,(a.get(s[r])??0)>1?e:s[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?l("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"})]}):$(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:s===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:s===i.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:l("terminal"===i.kind?"terminal.close":"i18n.close"),"aria-label":`${l("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 oR(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 oN=["general","models","agents","images","skills","plugins"],o$="pi-web:settings-navigation",oW=new Set(["skills","agents","plugins"]);function oz(){try{return window.localStorage}catch{return null}}function oP(e){let t=e.getItem(o$);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 oA(e,t){return"models"===e?e:t?JSON.stringify([e,t]):null}function oD(e,t=oz()){if(t)try{let n=oP(t);n.section=e,t.setItem(o$,JSON.stringify(n))}catch{}}function oH(e,t,n=oz()){if(!n)return null;let r=oA(e,t);if(!r)return null;try{let e=oP(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function oB(e,t,n,r=oz()){if(!r||!t)return;let i=oA(e,n);if(i)try{let e=oP(r);e.selections={...e.selections,[i]:t},r.setItem(o$,JSON.stringify(e))}catch{}}let oF="pi-auto-session-title";function oO(){try{return"false"!==window.localStorage.getItem(oF)}catch{return!0}}let oU=["input","output","cacheRead","cacheWrite"];function o_(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 oq(e){if(!oK(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 oK(e){return oU.some(t=>""!==e[t].trim())}let oV=["name","reasoning","thinkingLevelMap","input","contextWindow","maxTokens","cost","headers","compat"];function oJ(e,t){return`${e}/${t}`}function oY(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function oZ(e){let t=e.trim(),n=t.match(nM),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 oX(e,t){let n=t.trim();return oY(e).filter(e=>e!==n)}function oG(e){let t=oY(e);return t.length>0&&t.every(e=>null!==oZ(e))}function oQ({embedded:e,title:t,subtitle:n,closeLabel:i="Close",onClose:o,children:l,width:s=900,height:a="78vh"}){let d=e?void 0:{"--config-panel-width":`${s}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"})]}),l]})})}function o0({children:e}){return(0,r.jsx)("div",{className:"config-split-view",children:e})}function o1({children:e}){return(0,r.jsx)("aside",{className:"config-sidebar",children:e})}function o2({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-list",children:e})}function o4({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-group-label",children:e})}function o8({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 o5({className:e,...t}){return(0,r.jsx)("span",{...t,className:["config-sidebar-text",e].filter(Boolean).join(" ")})}function o6({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-stack",e].filter(Boolean).join(" ")})}function o3({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header",e].filter(Boolean).join(" ")})}function o7({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header-info",e].filter(Boolean).join(" ")})}function o9({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-actions",e].filter(Boolean).join(" ")})}function le({children:e}){return(0,r.jsx)("div",{className:"config-detail-title",children:e})}function lt({children:e}){return(0,r.jsx)("div",{className:"config-section-title",children:e})}function ln({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 lr({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function li({children:e,style:t}){return(0,r.jsx)("div",{className:"config-detail",style:t,children:e})}function lo({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 ll({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 ls({checked:e,disabled:t=!1,loading:n=!1,label:i,onChange:o}){let l=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:l,className:`config-switch${n?" is-loading":""}`,onClick:()=>o(!e),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function la({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 ld({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 lc={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 lu({id:e,size:t}){let n=lc[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 lh(){let e=oH("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if("runtime-model"===t.type&&"string"==typeof t.providerName&&"string"==typeof t.id)return{type:"runtime-model",providerName:t.providerName,id:t.id};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}function lp(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}}let lf=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function lg({label:e,children:t}){return(0,r.jsx)(ln,{label:e,children:t})}let lx={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function lm({value:e,onChange:t,placeholder:n,mono:i,disabled:o}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,disabled:o,style:{...lx,fontFamily:i?"var(--font-mono)":"inherit",opacity:o?.7:1}})}function ly({value:e,onChange:t,placeholder:n,mono:o,onKeyDown:l,autoComplete:s="off",spellCheck:a=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:h}=(0,m.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:n,style:{...lx,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:s,spellCheck:a}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":h(c?"i18n.hideDetails":"i18n.showDetails"),title:h(c?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:c?(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 lv({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:lx})}function lb({value:e,onChange:t,options:n,required:i}){let{t:o}=(0,m.s)();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...lx,color:e?"var(--text)":"var(--text-dim)"},children:[!i&&(0,r.jsxs)("option",{value:"",children:["— ",o("i18n.default")," / none —"]}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function lw({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function lk({children:e}){return(0,r.jsx)(lt,{children:e})}function lj({providerId:e,provider:t,usableRefs:n,selectedModelIndex:o,onChange:l,onDelete:s,onAddModel:a,onAddModels:d,onSelectModel:c}){let{t:u}=(0,m.s)(),[h,p]=(0,i.useState)({phase:"idle"}),[f,g]=(0,i.useState)(""),[x,y]=(0,i.useState)([]),v=(0,i.useRef)(0),b=(0,i.useRef)(null),w=(e,n)=>l({...t,[e]:n});(0,i.useEffect)(()=>{t.api||l({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{v.current+=1,p({phase:"idle"}),g(""),y([])},[e,t.baseUrl,t.api,t.apiKey]);let k=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===h.phase)return;let n=++v.current;p({phase:"loading"}),y([]);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!==v.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==v.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[h.phase,e,t]),j=new Set((t.models??[]).map(e=>e.id)),S="success"===h.phase?h.models:[],C=f.trim().toLocaleLowerCase(),I=S.filter(e=>!C||e.id.toLocaleLowerCase().includes(C)||e.name?.toLocaleLowerCase().includes(C)),E=I.slice(0,300),M=E.filter(e=>!j.has(e.id)).map(e=>e.id),T=x.filter(e=>!j.has(e)).length,L=M.length>0&&M.every(e=>x.includes(e)),R=!L&&M.some(e=>x.includes(e));return(0,i.useEffect)(()=>{b.current&&(b.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lk,{children:t.name??e}),(0,r.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:u("i18n.delete")})]}),(0,r.jsxs)(lg,{label:u("models.displayName"),children:[(0,r.jsx)(lm,{value:t.name??"",onChange:e=>w("name",e.trim()||void 0),placeholder:e}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("models.providerIdHint",{id:e})})]}),(0,r.jsx)(lg,{label:"Base URL",children:(0,r.jsx)(lm,{value:t.baseUrl??"",onChange:e=>w("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(lg,{label:"API Key",children:[(0,r.jsx)(ly,{value:t.apiKey??"",onChange:e=>w("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(lg,{label:"API",children:(0,r.jsx)(lb,{value:t.api??"openai-completions",onChange:e=>w("api",e),options:lf,required:!0})}),(0,r.jsxs)(lg,{label:"Headers",children:[(0,r.jsx)(lM,{headers:t.headers,onChange:e=>w("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(t.models?.length??0)>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)(lk,{children:u("models.definitions")}),(0,r.jsx)("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:2},children:(t.models??[]).map((t,i)=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsx)(o8,{active:o===i,onClick:()=>c(i),style:{flex:1,width:"auto"},children:(0,r.jsx)(o5,{className:"is-grow",children:t.name&&t.name!==t.id?`${t.name} \xb7 ${t.id}`:t.id})}),!n.has(`${e}/${t.id}`)&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0},children:u("models.notUsable")})]},`${t.id}:${i}`))})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:a,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:u("models.newModel")}),"success"!==h.phase&&(0,r.jsx)("button",{onClick:k,disabled:!t.baseUrl?.trim()||"loading"===h.phase,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==h.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==h.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===h.phase?u("models.discoveryFetching"):u("models.discoveryFetch")})]}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:f,onChange:e=>g(e.target.value),placeholder:u("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":u("models.discoveryFilter"),style:{...lx,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:M.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:b,type:"checkbox",checked:L,disabled:0===M.length,onChange:()=>{let e=new Set(M);y(t=>L?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...M])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),u("models.discoverySelectShown")]}),0===E.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:u("models.discoveryNoMatches")}):E.map((e,t)=>{let n=j.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void y(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:u("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:I.length>E.length?u("models.discoveryShowing",{shown:E.length,total:I.length}):u("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!j.has(t.id));0!==t.length&&(d(t),y([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"#fff":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?u("models.discoveryAddSelectedCount",{count:T}):u("models.discoveryAddSelected")})]})]})]})]})}let lS={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function lC({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:nE.map(e=>{let t=n[e],o=e in n?null===t?"null":"string":"omit",l="string"==typeof t?t:"",s=lS[e],a={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--accent)",color:"#fff",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:s,flexShrink:0,opacity:"null"===o?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===o?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===o?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...a,..."omit"===o?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...a,borderLeft:"1px solid var(--border)",..."null"===o?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===o?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,l||e),style:{...a,..."string"===o?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:l,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==o&&i(e,l||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===o?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===o?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let lI={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lE(e){return e.compat?.thinkingFormat==="deepseek"}function lM({headers:e,onChange:t}){let[n,o]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),l=(0,i.useRef)(n.length),s=e=>{o(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))},a=(e,t)=>{s(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>a(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...lx,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>a(e.id,{value:t.target.value}),placeholder:"value",style:{...lx,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void s(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>o(e=>[...e,{id:l.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function lT({providerName:e,provider:t,model:n,onChange:o,onDelete:l,lockId:s=!1,cwd:a=null}){let[d,c]=(0,i.useState)({phase:"idle"}),{t:u}=(0,m.s)(),[h,p]=(0,i.useState)({phase:"idle"}),[f,g]=(0,i.useState)(!1),[x,y]=(0,i.useState)(()=>o_(n.cost)),v=(0,i.useRef)(x),[b,w]=(0,i.useState)(!1),k=(0,i.useRef)(0),j=(0,i.useRef)(null),S=(0,i.useRef)(n.cost),C=(e,t)=>o({...n,[e]:t}),I=(()=>{if("idle"===d.phase)return null;if("testing"===d.phase)return u("i18n.testingModel");let e=[void 0!==d.latencyMs?`${d.latencyMs}ms`:null,void 0!==d.status?`HTTP ${d.status}`:null].filter(Boolean);return"success"===d.phase?[u("i18n.connected"),...e,d.responseText||null].filter(Boolean).join(" \xb7 "):[u("i18n.failed"),...e,d.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{c({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{k.current+=1,p({phase:"idle"}),j.current=null},[e,t.baseUrl,n.id]);let E=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==d.phase){c({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 c({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});c({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){c({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,d.phase,a]),M=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===h.phase)return;let i=++k.current;p({phase:"loading"});try{let l=new URLSearchParams({q:r,provider:e,limit:"50"});a&&l.set("cwd",a),t.baseUrl?.trim()&&l.set("baseUrl",t.baseUrl.trim());let s=await fetch(`/api/models-config/catalog?${l}`),d=await s.json();if(i!==k.current)return;if(!s.ok||d.error||!d.recommendation)return void p({phase:"error",message:d.error??`HTTP ${s.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 l=oq(o_(i));o>0&&l&&(n.cost={...i,...l},r+=o)}return{model:n,appliedCount:r}}(n,d.recommendation.preset);c.appliedCount>0&&(j.current=n,o(c.model)),g(!1),p({phase:"success",recommendation:d.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==k.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[h.phase,n,o,t.baseUrl,e,a]),T=(()=>{if("success"!==h.phase)return null;let{recommendation:t,appliedCount:n}=h,r=n>0?u("models.catalogFilled",{count:n}):u("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?u("models.catalogNoExactMatch"):u("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?u("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?u("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):u("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),L="error"===h.phase?h.message:T,R="error"===h.phase?"#ef4444":"success"===h.phase&&"unreliable"===h.recommendation.price.status?"#d97706":"var(--text-dim)",N=[{key:"input",label:u("models.costInput")},{key:"output",label:u("models.costOutput")},{key:"cacheRead",label:u("models.costCacheRead")},{key:"cacheWrite",label:u("models.costCacheWrite")}],$=new Set(Object.keys(n.compat??{})),W=0;lE(n)&&(W+=1,$.delete("thinkingFormat"),$.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&(W+=1,$.delete("supportsDeveloperRole")),W+=$.size;let z=[n.api?`API: ${n.api}`:null,Object.keys(n.headers??{}).length?u("models.headersSummary",{count:Object.keys(n.headers??{}).length}):null,W?u("models.compatSummary",{count:W}):null,Object.keys(n.thinkingLevelMap??{}).length?u("models.thinkingSummary",{count:Object.keys(n.thinkingLevelMap??{}).length}):null].filter(e=>!!e),P=z.length?z.join(" \xb7 "):u("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lk,{children:u("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[I&&(0,r.jsx)("span",{title:I,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===d.phase?"#fecaca":"success"===d.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===d.phase?"#fee2e2":"success"===d.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:I}),(0,r.jsxs)("button",{onClick:E,disabled:!n.id.trim()||"testing"===d.phase,title:u("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===d.phase?"#16a34a":"none",border:`1px solid ${"success"===d.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===d.phase?"#fff":n.id.trim()&&"testing"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==d.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===d.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===d.phase?u("i18n.checking"):"success"===d.phase?u("common.ok"):u("i18n.test")]}),l&&(0,r.jsx)("button",{onClick:l,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:u("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(lg,{label:"ID *",children:(0,r.jsx)(lm,{value:n.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0,disabled:s})}),(0,r.jsx)(lg,{label:"Name",children:(0,r.jsx)(lm,{value:n.name??"",onChange:e=>C("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void M(),disabled:!n.id.trim()||"loading"===h.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==h.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==h.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===h.phase?u("models.catalogFilling"):u("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:u("models.catalogSource")})]}),L&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:R,fontSize:10},children:[(0,r.jsx)("span",{title:L,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:L}),j.current&&(0,r.jsx)("button",{onClick:()=>{let e=j.current;e&&(j.current=null,o(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:u("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(lk,{children:u("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(lw,{label:u("models.reasoning"),checked:n.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(lw,{label:u("models.imageInput"),checked:n.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(lk,{children:u("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(f)return void g(!1);S.current=n.cost;let e=o_(n.cost);v.current=e,y(e),g(!0)},"aria-expanded":f,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:f?u("models.finishEditingCosts"):u("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(lg,{label:u("models.contextWindow"),children:(0,r.jsx)(lv,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(lg,{label:u("models.maxOutputTokens"),children:(0,r.jsx)(lv,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:u("models.costPerMillion")}),f?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[N.map(({key:e,label:t})=>(0,r.jsx)(lg,{label:t,children:(0,r.jsx)(lv,{value:x[e],onChange:t=>{let r,i,l;return i=oq(r={...v.current,[e]:t}),l={...n},void(v.current=r,y(r),i?(l.cost={...S.current??{},...i},S.current=l.cost):delete l.cost,o(l))},placeholder:"0"})},e)),oK(x)&&!oq(x)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:u("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:N.map(({key:e,label:t})=>{let i,o=n.cost?.[e]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t}),(0,r.jsx)("div",{style:{marginTop:3,color:o?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(i=n.cost?.[e])?u("models.notProvided"):`$${String(i)}`})]},e)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>w(e=>!e),"aria-expanded":b,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:u("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P})]}),(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",style:{color:"var(--text-dim)",transform:b?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[!s&&(0,r.jsx)(lg,{label:u("models.apiOverride"),children:(0,r.jsx)(lb,{value:n.api??"",onChange:e=>C("api",e||void 0),options:lf})}),(0,r.jsxs)(lg,{label:u("models.headers"),children:[(0,r.jsx)(lM,{headers:n.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("models.headersHelp")})]}),n.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(lk,{children:u("models.compatibility")}),(0,r.jsx)(lw,{label:u("models.deepSeekThinkingCompat"),checked:lE(n),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lI}};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)(lw,{label:u("models.developerRole"),checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>o({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(lk,{children:u("models.thinkingLevelMap")}),n.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:u("models.clearAll")})]}),(0,r.jsx)(lC,{value:n.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function lL(e,t){return window.confirm(e("models.disconnectConfirm",{name:t}))}function lR({provider:e,onRefresh:t,cwd:n}){let[o,l]=(0,i.useState)({phase:"idle"}),{t:s}=(0,m.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)(()=>{l({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(),l({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?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(l({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?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?(r.close(),l({phase:"success"}),t()):"error"===n.type?(r.close(),l({phase:"error",message:n.message})):"cancelled"===n.type&&(r.close(),l({phase:"idle"}))},r.onerror=()=>{r.close(),l(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t,n]),p=(0,i.useCallback)(async()=>{lL(s,e.name)&&(await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),l({phase:"idle"}),t())},[e.id,e.name,t,s,n]),f=(0,i.useCallback)(async(t,n)=>{if(n.trim()){l({phase:"progress",message:"Verifying…"});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.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`});return}d("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),g=(0,i.useCallback)(async(t,n)=>{l({phase:"progress",message:"Continuing…"});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(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),x="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return e.loggedIn&&"idle"===o.phase?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,color:"#4ade80"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:"#4ade80",display:"inline-block"}}),s("i18n.connected")]}),(0,r.jsxs)("span",{style:{display:"inline-flex",gap:8},children:[(0,r.jsx)("button",{onClick:h,style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:s("i18n.relogin")}),(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:s("i18n.disconnect")})]})]}):(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lk,{children:s("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?s("i18n.connected"):s("i18n.notConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s("i18n.openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:o.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:o.options.map(e=>(0,r.jsx)("button",{onClick:()=>g(o.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===o.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":o.message}),"auth"===o.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:u,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f(o.token,a)},placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>f(o.token,a),disabled:!a.trim(),style:{padding:"6px 12px",background:a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()?"#fff":"var(--text-dim)",cursor:a.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:s("i18n.submit")})]})]}),"device_code"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:o.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:o.verificationUri}),o.expiresInSeconds?` Expires in ${Math.ceil(o.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o.message}),"success"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:s("i18n.connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:o.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:x?(0,r.jsx)("button",{onClick:()=>{c.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:s("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:h,style:{padding:"5px 14px",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:e.loggedIn?s("i18n.relogin"):s("i18n.login")}),e.loggedIn&&(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:s("i18n.disconnect")})]})})]})}function lN({provider:e,onRefresh:t,cwd:n}){let[o,l]=(0,i.useState)(""),[s,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,m.s)();(0,i.useEffect)(()=>{l(""),h(null),f(!1)},[e.id]);let x=(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}`):(l(""),f(!0),setTimeout(()=>f(!1),2e3),t())}catch(e){h(String(e))}finally{a(!1)}}},[o,e.id,t,n]),y=(0,i.useCallback)(async()=>{if(lL(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",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,color:e.configured?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),e.configured?g("i18n.configured"):g("i18n.notConfigured")]}),e.configured&&(0,r.jsx)("button",{onClick:y,disabled:d,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:d?"not-allowed":"pointer",fontSize:12},children:d?g("i18n.removing"):g("i18n.disconnect")})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(ly,{value:o,onChange:l,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&x()},placeholder:e.configured?g("models.replaceKeyPlaceholder"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:x,disabled:s||!o.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":o.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:o.trim()||p?"#fff":"var(--text-dim)",cursor:s||!o.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),p?g("i18n.saved"):s?g("i18n.saving"):g("models.updateKey")]})]}),u&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:u})]})}function l$({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:o,onAddCustom:l,onClose:s}){let[a,d]=(0,i.useState)(""),{t:c}=(0,m.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let h=a.trim().toLowerCase(),p=e.filter(e=>!e.loggedIn&&(!h||e.name.toLowerCase().includes(h))),f=t.filter(e=>!e.configured&&(!h||e.displayName.toLowerCase().includes(h)||e.id.toLowerCase().includes(h))),g=!h||"custom".includes(h)||"openai-compatible".includes(h)||"anthropic-compatible".includes(h),x=p.length+f.length+ +!!g,y={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&s()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),s())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},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:{color:"var(--text-dim)",flexShrink:0},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:u,value:a,onChange:e=>d(e.target.value),placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{l(),s()},style:y,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",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",style:{color:"var(--text-dim)"},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"})]})})]}),p.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!g,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),p.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),s()},style:y,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(lu,{id:e.id,size:28})]},e.id)),f.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(p.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),f.map(e=>(0,r.jsxs)("button",{onClick:()=>{o(e.id),s()},style:y,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(lu,{id:e.id,size:28})]},e.id))]})})]})})}function lW({catalog:e,listedRefs:t,mode:n,providerFilter:o,saving:l,error:s,onClose:a,onApply:d,onEditModel:c}){let{t:u}=(0,m.s)(),[h,p]=(0,i.useState)(""),[f,g]=(0,i.useState)(new Set),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>x.current?.focus(),30)},[]);let y=h.trim().toLocaleLowerCase(),v=e.filter(e=>(!o||e.provider===o)&&!t.has(oJ(e.provider,e.id))&&(!y||e.id.toLocaleLowerCase().includes(y)||e.name?.toLocaleLowerCase().includes(y))),b=new Map;for(let e of v){let t=b.get(e.provider)??[];t.push(e),b.set(e.provider,t)}return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},children:(0,r.jsxs)("div",{style:{width:560,maxWidth:"calc(100vw - 32px)",maxHeight:"min(76vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)",display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600},children:u("models.pickModels")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)"},children:"replace"===n?u("models.pickReplaceHint"):u("models.pickAddHint")})]}),(0,r.jsx)("div",{style:{padding:"8px 14px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{ref:x,value:h,onChange:e=>p(e.target.value),placeholder:u("models.pickFilterPlaceholder"),"aria-label":u("models.pickFilter"),style:{width:"100%",boxSizing:"border-box",padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:14,display:"flex",flexDirection:"column",gap:12},children:[0===v.length?(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:u("models.noExtraModels")}):[...b.entries()].map(([e,t])=>{let n=t.map(e=>oJ(e.provider,e.id)),i=n.every(e=>f.has(e));return(0,r.jsxs)("div",{children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"var(--text-dim)",marginBottom:4,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:i,onChange:()=>g(e=>{let t=new Set(e);for(let e of n)i?t.delete(e):t.add(e);return t}),style:{width:12,height:12,accentColor:"var(--accent)",flexShrink:0}}),e]}),t.map(e=>{let t=oJ(e.provider,e.id);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"3px 8px 3px 22px"},children:[(0,r.jsx)("input",{id:t,type:"checkbox",checked:f.has(t),onChange:()=>g(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsx)("label",{htmlFor:t,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",cursor:"pointer",fontSize:12},children:e.name&&e.name!==e.id?`${e.name} \xb7 ${e.id}`:e.id}),(0,r.jsx)("button",{type:"button",onClick:()=>c(e.provider,e.id),style:{flexShrink:0,border:0,background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:u("i18n.edit")})]},t)})]},e)}),s&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px",borderTop:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:u("models.pickSelected",{count:f.size})}),(0,r.jsxs)("span",{style:{display:"inline-flex",gap:8},children:[(0,r.jsx)(ll,{type:"button",onClick:a,children:u("i18n.cancel")}),(0,r.jsx)(ll,{type:"button",variant:"primary",disabled:0===f.size||l,onClick:()=>d([...f]),children:u("models.pickApply",{count:f.size})})]})]})]})})}function lz({title:e,hint:t,entries:n,readOnly:i,onRemove:o}){let{t:l}=(0,m.s)();return(0,r.jsxs)("div",{style:{flexShrink:0,padding:"8px 8px 0",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontWeight:600},children:e}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2,lineHeight:1.4},children:t}),n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(o5,{className:"is-grow",style:{color:"var(--text-dim)"},children:oZ(e)?.id??e}),!i&&(0,r.jsx)("button",{type:"button",onClick:()=>o(e),style:{border:0,background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11,padding:"0 6px"},children:l("models.removeFromChat")})]},e))]})}function lP({onClose:e,embedded:t=!1,cwd:n=null,onModelsChanged:o}){var l;let s,a,{t:d}=(0,m.s)(),[c,u]=(0,i.useState)({providers:{}}),[h,p]=(0,i.useState)({providers:{}}),[f,g]=(0,i.useState)(!0),[x,y]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(lh),[E,M]=(0,i.useState)([]),[T,L]=(0,i.useState)([]),[R,N]=(0,i.useState)(!1),[$,W]=(0,i.useState)(null),[z,P]=(0,i.useState)([]),[A,D]=(0,i.useState)(null),[H,B]=(0,i.useState)(!1),[F,O]=(0,i.useState)(null),[U,_]=(0,i.useState)(null),[q,K]=(0,i.useState)(null),V=(0,i.useCallback)(()=>{fetch(`/api/auth/providers${n?`?cwd=${encodeURIComponent(n)}`:""}`).then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&M(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&L(e.apiKeyProviders)}).catch(()=>{})},[n]),J=(0,i.useCallback)(()=>{if(!n)return void P([]);let e=new URLSearchParams({cwd:n});fetch(`/api/models-config/runtime?${e}`).then(e=>e.json()).then(e=>{Array.isArray(e.catalog)&&P(e.catalog),K(e.modelError??null)}).catch(()=>{})},[n]),Y=(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?(O(null),D(t)):O(t.error??d("models.scopeError"))}).catch(()=>O(d("models.scopeError"))):D(null)},[n,d]);(0,i.useEffect)(()=>{if(!U)return;let e=setTimeout(()=>_(null),4e3);return()=>clearTimeout(e)},[U]);let Z=(0,i.useCallback)(()=>{V(),J()},[V,J]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};b(e.error??null),u(t),p(t);let n=Object.keys(t.providers??{});I(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(()=>u({providers:{}})).finally(()=>g(!1)),V()},[V]),(0,i.useEffect)(()=>{J(),Y()},[J,Y]),(0,i.useEffect)(()=>{C&&oB("models",JSON.stringify(C))},[C]);let X=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;u(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),I({type:"provider",name:e})},[c.providers]),G=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),Q=(0,i.useCallback)(e=>{u(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),u(e=>{let t=Object.keys(e.providers??{});return I(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),ee=(0,i.useCallback)(e=>{u(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),u(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return I({type:"model",providerName:e,index:n}),t})},[]),et=(0,i.useCallback)((e,t)=>{u(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}}}})},[]),en=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),er=(0,i.useCallback)((e,t,n)=>{let r=function(e,t){let n={};for(let i of oV){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}(lp(t),{...n,id:t.id});u(n=>{var i,o;let l,s=n.providers?.[e]??{},a={...s},d=(i=s.modelOverrides,o=t.id,l={...i??{}},delete l[o],r&&(l[o]=r),Object.keys(l).length>0?l:void 0);return d?a.modelOverrides=d:delete a.modelOverrides,{...n,providers:{...n.providers??{},[e]:a}}})},[]),ei=(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]),eo=(0,i.useRef)(0),el=(0,i.useCallback)(async()=>{let e=++eo.current,t=await ei();return t&&e===eo.current&&D(t),t},[ei]),es=(0,i.useRef)(Promise.resolve()),ea=(0,i.useCallback)(e=>{if(!n)return Promise.resolve(!1);let t=es.current.then(async()=>{let t=await ei();if(!t)return O(d("models.scopeError")),!1;if(t.readOnly)return!1;let r=e(t);if(0===r.length)return O(d("models.keepOneModel")),!1;B(!0),O(null),_(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 O("untrusted"===t.code?d("models.scopeReadOnly"):t.error??d("models.scopeError")),!1;return D(t),o?.(),!0}catch{return O(d("models.scopeError")),!1}finally{B(!1)}});return es.current=t.catch(()=>!1),t},[n,ei,o,d]),ed=(0,i.useCallback)(e=>{n&&A&&W("none"===A.source?{mode:"replace",...e?{providerFilter:e}:{}}:{mode:"add",...e?{providerFilter:e}:{}})},[n,A]),ec=(0,i.useCallback)(async e=>{let t=!!A&&!oG(A?.patterns??[]);await ea(t=>(function(e){let t=oY(e.patterns);if(oG(t)){let n,r;return r=(n=e.ref.trim()).slice(n.indexOf("/")+1),oY(t).filter(e=>{let t=oZ(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=>oJ(e.provider,e.id)),pins:t.pins,ref:e}))&&t&&_(d("models.listWritten"))},[ea,A,d]),eu=(0,i.useCallback)((e,t)=>{u(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}}}}),I({type:"provider",name:e})},[]),eh=(0,i.useCallback)(async()=>{y(!0),k(null),S(!1);try{var e;let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),n=await t.json();if(!t.ok||n.error)return void k(n.error??`HTTP ${t.status}`);p(c),S(!0),setTimeout(()=>S(!1),2e3),J();let r=A?.defined,i=await el(),l=r&&i?(e={patterns:r.length?A?.patterns??[]:[],before:new Set(r),after:new Set(i.defined)},oY(e.patterns).filter(t=>{let n=oZ(t);return null!==n&&void 0!==n.provider&&e.before.has(n.ref)&&!e.after.has(n.ref)})):[];l.length>0&&await ea(e=>e.patterns.filter(e=>!l.includes(e)))&&_(d("models.removedWithDefinition",{count:l.length})),o?.()}catch(e){k(String(e))}finally{y(!1)}},[c,el,o,J,ea,A,d]),ep=[v,q].filter(Boolean).map(e=>String(e).split("\n")[0]).join(" \xb7 ")||null,ef=Object.entries(c.providers??{}),eg=E.filter(e=>e.loggedIn),ex=T.filter(e=>e.configured),em=JSON.stringify(c)!==JSON.stringify(h),ey=new Set([...eg.map(e=>e.id),...ex.map(e=>e.id)]),ev=(e,t)=>{let n=(c.providers?.[e]?.models??[]).findIndex(e=>e.id===t);n>=0?I({type:"model",providerName:e,index:n}):I({type:"runtime-model",providerName:e,id:t})},eb=A?.visible??[],ew=new Set(eb.map(e=>oJ(e.provider,e.id))),ek=!!A&&"none"!==A.source&&!A.readOnly,ej=A?(s=new Set((l={patterns:A.patterns,visible:[...ew]}).visible),a=new Set(l.visible.map(e=>e.slice(e.indexOf("/")+1))),oY(l.patterns).filter(e=>{let t=oZ(e);return null!==t&&(t.provider?!s.has(t.ref):!a.has(t.id))})).filter(e=>!(A.ambiguous??[]).includes(e)):[],eS=e=>{let t=c.providers?.[e]?.models??[],n=eb.filter(t=>t.provider===e),i=z.filter(t=>t.provider===e&&!ew.has(oJ(t.provider,t.id))).length;return 0===n.length&&0===i?null:(0,r.jsxs)(r.Fragment,{children:[n.map(n=>{let i=oJ(n.provider,n.id),o=z.some(t=>t.provider===e&&t.id===n.id),l=A?.pins[i];return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,r.jsxs)(o8,{className:"models-sidebar-indented-item",style:{flex:1,width:"auto"},onClick:()=>o||t.some(e=>e.id===n.id)?ev(e,n.id):void 0,children:[(0,r.jsx)(o5,{className:"is-grow",style:{color:o?"var(--text-muted)":"var(--text-dim)"},children:n.id}),l&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:d("models.thinkingPin",{level:l})})]}),ek&&(0,r.jsx)("button",{type:"button",onClick:()=>void ec(i),style:{border:0,background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11,padding:"0 6px"},children:d("models.removeFromChat")})]},i)}),i>0&&(0,r.jsx)("button",{type:"button",className:"models-sidebar-indented-item",onClick:()=>ed(e),style:{display:"block",width:"100%",padding:"6px 8px 6px 26px",border:0,background:"none",color:"var(--accent)",cursor:"pointer",fontSize:11,textAlign:"left"},children:d("models.availableMore",{count:i})})]})},eC=(()=>{var e,t;if(!C)return null;if("oauth"===C.type){let e=E.find(e=>e.id===C.providerId);if(!e)return null;let t=T.find(t=>t.id===e.id&&t.configured);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lR,{provider:e,onRefresh:Z,cwd:n},e.id),t&&(0,r.jsx)(lN,{provider:t,onRefresh:Z,cwd:n},`${e.id}-key`)]})}if("apikey"===C.type){let e=T.find(e=>e.id===C.providerId);return e?(0,r.jsx)(lN,{provider:e,onRefresh:Z,cwd:n},e.id):null}if("provider"===C.type){let t,n=c.providers?.[C.name];return n?(e=C.name,t=(0,r.jsx)(lj,{providerId:e,provider:n,usableRefs:new Set(z.map(e=>oJ(e.provider,e.id))),selectedModelIndex:C?.type==="model"&&C.providerName===e?C.index:null,onChange:t=>G(e,t),onDelete:()=>Q(e),onAddModel:()=>ee(e),onAddModels:t=>et(e,t),onSelectModel:t=>I({type:"model",providerName:e,index:t})},`${e}-json`),z.some(t=>t.provider===e)?(0,r.jsxs)("details",{children:[(0,r.jsx)("summary",{style:{cursor:"pointer",fontSize:11,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em",textTransform:"uppercase"},children:d("models.endpoint")}),(0,r.jsx)("div",{style:{marginTop:12},children:t})]}):t):null}if("runtime-model"===C.type){let e=z.find(e=>e.provider===C.providerName&&e.id===C.id);if(!e)return null;let i=c.providers?.[C.providerName]??{},o=i.modelOverrides?.[e.id],l=(t=lp(e),o?{...t,...o,id:t.id,cost:o.cost?{...t.cost,...o.cost}:t.cost}:{...t,id:t.id});return(0,r.jsx)(lT,{providerName:C.providerName,provider:i,model:l,lockId:!0,cwd:n,onChange:t=>er(C.providerName,e,t)},`${C.providerName}-${C.id}`)}let i=c.providers?.[C.providerName],o=i?.models?.[C.index];return o?(0,r.jsx)(lT,{providerName:C.providerName,provider:i,model:o,cwd:n,onChange:e=>en(C.providerName,C.index,e),onDelete:()=>eu(C.providerName,C.index)},`${C.providerName}-${C.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(oQ,{embedded:t,title:d("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:d("i18n.close"),onClose:e,children:[(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsxs)("div",{style:{padding:"8px 8px 4px",fontSize:11,color:"var(--text-dim)"},children:[n?A?.source==="none"?d("models.chatAll"):d("models.chatList"):d("models.scopeNoCwd"),A?.readOnly&&(0,r.jsx)("div",{style:{color:"#d97706",marginTop:4},children:d("models.scopeReadOnly")}),A?.source==="none"&&n&&!A.readOnly&&(0,r.jsx)("button",{type:"button",onClick:()=>ed(),style:{marginTop:6,padding:"4px 8px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:d("models.pickOnlyThese")}),U&&(0,r.jsx)("div",{style:{marginTop:4},children:U}),F&&(0,r.jsx)("div",{style:{color:"#f87171",marginTop:4},children:F})]}),eg.map(e=>{let t=C?.type==="oauth"&&C.providerId===e.id;return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o8,{active:t,onClick:()=>I({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(lu,{id:e.id,size:16}),(0,r.jsx)(o5,{className:"is-grow",children:e.name})]}),eS(e.id)]},e.id)}),ex.filter(e=>!eg.some(t=>t.id===e.id)).map(e=>{let t=C?.type==="apikey"&&C.providerId===e.id;return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o8,{active:t,onClick:()=>I({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(lu,{id:e.id,size:16}),(0,r.jsx)(o5,{className:"is-grow",children:e.displayName})]}),eS(e.id)]},e.id)}),(eg.length>0||ex.length>0)&&ef.some(([e])=>!ey.has(e))&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),f?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:d("i18n.loading")}):ef.filter(([e])=>!ey.has(e)).map(([e])=>{let t=C?.type==="provider"&&C.name===e;return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o8,{onClick:()=>I({type:"provider",name:e}),active:t,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:{color:"var(--text-dim)",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"})]}),(0,r.jsxs)(o5,{className:"is-grow",children:[c.providers?.[e]?.name??e,(0,r.jsx)("span",{style:{display:"block",color:"var(--text-dim)",fontSize:10},children:d("models.customEndpoint")})]})]}),eS(e)]},e)}),eb.flatMap(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t&&!ey.has(e)&&!c.providers?.[e]).map(e=>(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsx)(o8,{children:(0,r.jsx)(o5,{className:"is-grow",children:e})}),eS(e)]},e))]}),ej.length>0&&(0,r.jsx)(lz,{title:d("models.unavailable",{count:ej.length}),hint:d("models.unavailableHint"),entries:ej,readOnly:!!A?.readOnly,onRemove:e=>void ea(t=>oX(t.patterns,e))}),(A?.ambiguous?.length??0)>0&&(0,r.jsx)(lz,{title:d("models.ambiguous",{count:A?.ambiguous?.length??0}),hint:d("models.ambiguousHint"),entries:A?.ambiguous??[],readOnly:!!A?.readOnly,onRemove:e=>void ea(t=>oX(t.patterns,e))}),(0,r.jsx)(la,{onClick:()=>ed(),children:d("models.add")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:f?null:eC??(0,r.jsx)(lr,{children:d("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(lo,{status:(w||ep)&&(0,r.jsx)("span",{style:{color:"#f87171"},title:ep??void 0,children:w||ep}),children:[!t&&(0,r.jsx)(ll,{onClick:e,children:d("i18n.cancel")}),(em||x||j)&&(0,r.jsxs)(ll,{variant:"primary",onClick:eh,disabled:x||j,className:j?"is-success":void 0,children:[j&&(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:j?d("i18n.saved"):x?d("i18n.saving"):d("models.saveModelsJson")})]})]})]}),R&&(0,r.jsx)(l$,{oauthProviders:E,apiKeyProviders:T,onSelectOAuth:e=>I({type:"oauth",providerId:e}),onSelectApiKey:e=>I({type:"apikey",providerId:e}),onAddCustom:X,onClose:()=>N(!1)}),$&&(0,r.jsx)(lW,{catalog:z,listedRefs:"replace"===$.mode?new Set:ew,mode:$.mode,...$.providerFilter?{providerFilter:$.providerFilter}:{},saving:H,error:F,onClose:()=>W(null),onEditModel:(e,t)=>{W(null),ev(e,t)},onApply:e=>{let{mode:t}=$;W(null),ea(n=>"replace"===t?e:e.reduce((e,t)=>{let n,r;return n=oY(e),!(r=t.trim())||n.includes(r)?n:[...n,r]},n.patterns))}})]})}function lA(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lD(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lH(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lB(e){return e?e.slice(0,8):"unknown"}function lF({skill:e,cwd:t,onToggle:n,toggling:i,saveError:o,updateStatus:l,checkingUpdate:s,updating:a,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:h}=(0,m.s)(),p=lD(e),f=!e.disableModelInvocation;return(0,r.jsxs)(o6,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(o3,{children:[(0,r.jsxs)(o7,{children:[(0,r.jsx)("span",{className:`config-scope-tag${"project"===p?" is-project":""}`,children:p}),(0,r.jsx)("span",{className:"config-detail-path",children:function(e){if("project"===p&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return lA(e)}(e.filePath)})]}),(0,r.jsx)(o9,{children:(0,r.jsx)(ls,{checked:f,loading:i,label:h(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>n(e)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:h("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),e.install?.skillsShUrl&&(0,r.jsx)(ln,{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)(ln,{label:"Version",children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:lB(l?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)(ll,{size:"small",onClick:c,disabled:s||a,children:h("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:lB(l.latestVersion)}),(s||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${s?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:s?h("i18n.checking"):l?.state==="up-to-date"?h("i18n.upToDate"):l?.state==="unsupported"?h("i18n.automaticChecksUnavailable"):l?.message||h("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(ll,{variant:"primary",size:"small",onClick:u,disabled:a||s,children:h(a?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)(ln,{label:"Name",children:(0,r.jsx)("span",{className:"skill-name-value",children:e.name})}),(0,r.jsx)(ln,{label:"Description",children:(0,r.jsx)("span",{className:"skill-description",children:e.description})})]})}function lO({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:o}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(null),[b,w]=(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)}}},[]),I=(0,i.useCallback)(async t=>{x(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}`);w(e=>new Set(e).add(`${k}:${t}`)),o()}catch(e){v(String(e))}finally{x(null)}},[o,k,e]),E="global"===k?"~/.pi/agent/skills/":`${lA(e)}/.pi/skills/`;return(0,r.jsxs)(o6,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(le,{children:l("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:s,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(s)},placeholder:l("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)(ll,{variant:"primary",onClick:()=>C(s),disabled:u||!s.trim(),children:u?l("i18n.searching"):l("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:l("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:["→ ",E]})]}),p&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:p}),y&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:y})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[k].has(e.package)||b.has(`${k}:${e.package}`),i=g===e.package,o=e.package.indexOf("@"),s=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??s}),(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:s}),(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)(ll,{size:"small",onClick:()=>!n&&!i&&I(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?`✓ ${l("i18n.installed")}`:i?l("i18n.installing"):l("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 lU({cwd:e,onClose:t,embedded:n=!1}){let{t:o}=(0,m.s)(),[l,s]=(0,i.useState)([]),[a,d]=(0,i.useState)(!0),[c,u]=(0,i.useState)(null),[h,p]=(0,i.useState)(()=>oH("skills",e)),[f,g]=(0,i.useState)(new Set),[x,y]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,I]=(0,i.useState)(!1),[E,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(null),[R,N]=(0,i.useState)(!0),$=(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 s(r),N(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({}),L(null),$()},[e]),(0,i.useEffect)(()=>{h&&oB("skills",h,e)},[e,h]);let W=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(lH).filter(e=>!!e);if(0!==n.length){L(null),S(e=>new Set([...e,...n])),t||I(!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){L(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||I(!1)}}},[e,l]),z=(0,i.useCallback)(async t=>{if(!t.install)return;let n=lH(t);M(n),L(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 $();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){L(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,$]),P=(0,i.useCallback)(async t=>{let n=!t.disableModelInvocation;g(e=>new Set(e).add(t.filePath)),y(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 y(i.error??`HTTP ${r.status}`);s(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:n}:e))}catch(e){y(String(e))}finally{g(e=>{let n=new Set(e);return n.delete(t.filePath),n})}},[e]),A=l.find(e=>e.filePath===h)??null;return(0,r.jsxs)(oQ,{embedded:n,title:o("common.skills"),subtitle:lA(e),closeLabel:o("i18n.close"),onClose:t,children:[!R&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:o("trust.skillsNotLoaded")}),(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{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===l.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"===lD(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===lD(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===lD(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===lD(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===lD(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!v&&h===e.filePath,l=e.disableModelInvocation;return(0,r.jsxs)(o8,{active:i,onClick:()=>{p(e.filePath),b(!1)},children:[(0,r.jsx)(ld,{active:!l}),(0,r.jsx)(o5,{className:`is-grow${l?" is-muted":""}`,children:e.name}),(n=(t=lH(e))?w[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)(o4,{children:e}),[...t.filter(e=>!e.disableModelInvocation),...t.filter(e=>e.disableModelInvocation)].map(n)]},e))})()}),(0,r.jsx)(la,{onClick:()=>b(!0),active:v,children:o("i18n.addSkill")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:v?(0,r.jsx)(lO,{cwd:e,projectResourcesLoaded:R,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{$()}}):a?null:A?(0,r.jsx)(lF,{skill:A,cwd:e,onToggle:P,toggling:f.has(A.filePath),saveError:x,updateStatus:lH(A)?w[lH(A)]:void 0,checkingUpdate:!!lH(A)&&j.has(lH(A)),updating:E===lH(A),updateError:T,onCheckUpdate:()=>void W(A),onUpdate:()=>void z(A)},A.filePath):(0,r.jsx)(lr,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(lo,{status:Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!n&&(0,r.jsx)(ll,{onClick:t,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(ll,{variant:"secondary",onClick:()=>void W(),disabled:C||null!==E,children:C?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let l_={builtin:0,global:1,workspace:2,project:3},lq=["read","bash","edit","write","grep","find","ls"],lK=["",...nE],lV={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},lJ={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"},lY={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lZ(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 lX(e){return`${e.scope}:${e.name}`}function lG(e){return"global"===e||"project"===e}function lQ(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l0({label:e,children:t}){return(0,r.jsx)(ln,{label:e,children:t})}function l1({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 l2({cwd:e,sessionId:t=null,onClose:n,onReloaded:o,embedded:l=!1}){let s=nY(),{t:a}=(0,m.s)(),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)([]),[p,f]=(0,i.useState)(!0),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(()=>oH("agents",e)),[b,w]=(0,i.useState)(lV),[k,j]=(0,i.useState)("view"),[S,C]=(0,i.useState)("global"),[I,E]=(0,i.useState)(!0),[M,T]=(0,i.useState)(!1),[L,R]=(0,i.useState)(!1),[N,$]=(0,i.useState)(!1),[W,z]=(0,i.useState)(null),[P,A]=(0,i.useState)(!0),[D,H]=(0,i.useState)(10),[B,F]=(0,i.useState)(!0),[O,U]=(0,i.useState)(!1),[_,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),Z=(0,i.useMemo)(()=>d.find(e=>lX(e)===y)??null,[d,y]),X=(0,i.useMemo)(()=>u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[u]),G=(0,i.useCallback)(async t=>{E(!0),z(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(e)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];c(i);let o=t??oH("agents",e),l=i.find(e=>lX(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;v(l?lX(l):null),l&&(w(lZ(l)),j(lG(l.scope)?"edit":"view"),lG(l.scope)&&C(l.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{E(!1)}},[e]);(0,i.useEffect)(()=>{G()},[G]),(0,i.useEffect)(()=>{let e=new AbortController;return F(!0),q(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}`);A(n.enabled),"number"==typeof n.maxConcurrent&&H(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||F(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{y&&oB("agents",y,e)},[e,y]),(0,i.useEffect)(()=>{let t=new AbortController;return f(!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}`);h(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||f(!1)}})(),()=>t.abort()},[e]);let Q=async()=>{T(!0),z(null),R(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:S,profile:b})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await G(lX(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}},ee=async()=>{if(Z&&lG(Z.scope)&&window.confirm(a("agents.deleteConfirm",{name:Z.displayName}))){T(!0),z(null);try{let t=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Z.scope,name:Z.name})}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);await G()}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}}},et="view"!==k,en="create"===k,er=!et||M||N,ei=en?S:Z?.scope,eo=en?"global"===S?`~/.pi/agent/agents/${b.name||"..."}.md`:`./.pi/agents/${b.name||"..."}.md`:Z?function(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 lQ(e.filePath)}(Z,e)??a("agents.builtinPath"):"",el=en?eo:Z?.filePath??eo,es=!b.model||u.some(e=>`${e.provider}/${e.id}`===b.model),ea=(()=>{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)}})(),ed=er?{...lJ,...lY}:lJ,ec=(e,t)=>{w(n=>({...n,[e]:t}))},eu=async t=>{if(en)return void ec("enabled",t);if(Z&&lG(Z.scope)){$(!0),z(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Z.scope,name:Z.name,enabled:t})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;c(e=>e.map(e=>lX(e)===lX(i)?i:e)),w(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}}},eh=async e=>{U(!0),q(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}`);A(r.enabled),V(!!t)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},ep=async e=>{H(e),q(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}`);H(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ef=async()=>{if(t){Y(!0),q(null);try{await r4(t,{type:"reload"}),V(!1),o?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(oQ,{embedded:l,title:a("common.agents"),subtitle:lQ(e),closeLabel:a("agents.close"),onClose:n,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:a("agents.builtInTitle")}),(0,r.jsx)("span",{children:a("agents.builtInDescription")}),K&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:a("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[K&&t&&(0,r.jsx)(ll,{size:"small",onClick:()=>void ef(),disabled:J||O,children:J?a("agents.reloading"):a("agents.reloadSession")}),(0,r.jsx)(ls,{checked:P,disabled:B||J,loading:O,label:a("agents.builtInTitle"),onChange:e=>void eh(e)})]})]}),(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:a("agents.maxConcurrent")}),(0,r.jsx)("span",{children:a("agents.maxConcurrentDescription")})]}),(0,r.jsx)("input",{"aria-label":a("agents.maxConcurrent"),type:"number",min:1,max:32,value:D,disabled:B||O,onChange:e=>H(Number(e.target.value)),onBlur:()=>void ep(D),style:{...lJ,width:76}})]}),(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{children:I?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:a("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=d.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o4,{children:a(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=l_[e.scope],d.some(e=>e.name.toLowerCase()===t&&l_[e.scope]>n));return(0,r.jsxs)(o8,{active:y===lX(e)&&!en,onClick:()=>{v(lX(e)),w(lZ(e)),j(lG(e.scope)?"edit":"view"),lG(e.scope)&&C(e.scope),z(null)},children:[(0,r.jsx)(ld,{active:e.enabled}),(0,r.jsx)(o5,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:a("agents.overridden")})]},lX(e))})]},e)})}),(0,r.jsx)(la,{active:en,onClick:()=>{let e="custom-agent",t=2;for(;d.some(t=>t.name===e);)e=`custom-agent-${t++}`;v(null),w({...lV,name:e,displayName:e}),j("create"),C("global"),z(null)},children:a("agents.new")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:Z||en?(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{children:[(0,r.jsxs)(o7,{children:[ei&&(0,r.jsx)("span",{className:`config-scope-tag${"project"===ei?" is-project":""}`,children:a(`agents.scope.${ei}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:eo})]}),(0,r.jsxs)(o9,{children:[Z&&("view"===k||"edit"===k)&&(0,r.jsx)(ll,{size:"small",onClick:()=>{if(!Z)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}(Z.name,d);v(null),w({...lZ(Z),name:e,displayName:a("agents.copyName",{name:Z.displayName})}),j("create"),C(lG(Z.scope)?Z.scope:"global"),z(null)},disabled:M||N,children:a("agents.duplicate")}),Z&&lG(Z.scope)&&"edit"===k&&(0,r.jsx)(ll,{variant:"danger",size:"small",onClick:()=>void ee(),disabled:M||N,children:a("agents.delete")}),(0,r.jsx)(ls,{checked:b.enabled,disabled:er,label:b.enabled?a("agents.disable"):a("agents.enable"),onChange:e=>void eu(e)})]})]}),en&&(0,r.jsx)(l0,{label:a("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:()=>C(e),disabled:M,style:{height:28,border:"none",borderRadius:4,background:S===e?"var(--bg-selected)":"transparent",color:S===e?"var(--text)":"var(--text-muted)",cursor:M?"default":"pointer",fontSize:11,fontWeight:S===e?600:400},children:a(`agents.scope.${e}`)},e))})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(l0,{label:a("agents.name"),children:en?(0,r.jsx)("input",{"aria-label":a("agents.name"),value:b.name,disabled:er,onChange:e=>ec("name",e.target.value),style:lJ}):(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)(l0,{label:a("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":a("agents.displayName"),value:b.displayName,disabled:er,onChange:e=>ec("displayName",e.target.value),style:ed})})]}),(0,r.jsx)(l0,{label:a("agents.description"),children:(0,r.jsx)("input",{"aria-label":a("agents.description"),value:b.description,disabled:er,onChange:e=>ec("description",e.target.value),style:ed})}),(0,r.jsx)(l0,{label:a("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":a("agents.prompt"),value:b.systemPrompt,disabled:er,onChange:e=>ec("systemPrompt",e.target.value),style:{...ed,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:er?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(l0,{label:a("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:lq.map(e=>(0,r.jsx)(l1,{label:e,disabled:er,checked:b.tools.includes(e),onChange:t=>ec("tools",t?[...b.tools,e]:b.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(l0,{label:a("agents.resources"),children:(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(l1,{label:a("agents.loadSkills"),disabled:er,checked:b.loadSkills,onChange:e=>ec("loadSkills",e)}),(0,r.jsx)(l1,{label:a("agents.loadExtensions"),disabled:er,checked:b.loadExtensions,onChange:e=>ec("loadExtensions",e)})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(l0,{label:a("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(rs,{options:X,value:ea,onChange:(e,t)=>ec("model",`${e}/${t}`),onClear:()=>ec("model",void 0),emptyLabel:p?a("agents.modelsLoading"):a("agents.inherit"),selectedLabel:b.model&&!es?a("agents.modelUnavailable",{model:b.model}):void 0,disabled:er||p||0===u.length&&!b.model,ariaLabel:a("agents.model"),variant:"field",placement:"auto"}),g&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:g})]})}),(0,r.jsx)(l0,{label:a("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":a("agents.thinking"),value:b.thinking??"",disabled:er,onChange:e=>ec("thinking",e.target.value||void 0),style:ed,children:lK.map(e=>(0,r.jsx)("option",{value:e,children:e||a("agents.inherit")},e||"default"))})}),(0,r.jsx)(l0,{label:a("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":a("agents.maxTurns"),type:"number",min:1,value:b.maxTurns??"",disabled:er,onChange:e=>ec("maxTurns",e.target.value?Number(e.target.value):void 0),style:ed})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(l1,{label:a("agents.inheritContext"),disabled:er,checked:b.inheritContext,onChange:e=>ec("inheritContext",e)}),(0,r.jsx)(l1,{label:a("agents.background"),disabled:er,checked:b.runInBackground,onChange:e=>ec("runInBackground",e)})]})]}):(0,r.jsx)(lr,{children:a("agents.empty")})})})]}),(0,r.jsx)(lo,{status:(_||W)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:_||W}),children:et&&(0,r.jsxs)(ll,{variant:"primary",onClick:()=>void Q(),disabled:M||L||N||!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?a("i18n.saved"):M?a("agents.saving"):a("agents.save")})]})})]})}function l4(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l8(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function l5(e){return`${e.scope}\0${e.source}`}function l6(e){return`extension\0${e.path}`}function l3(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function l7({pkg:e}){let{t}=(0,m.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 l9({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 se({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,m.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 l=e===o,s="project"===o&&!t;return(0,r.jsx)("button",{onClick:()=>{s||n(o)},disabled:s,title:s?i("trust.projectScopeUnavailable"):void 0,style:{width:76,border:"none",borderRight:"global"===o?"1px solid var(--border)":"none",background:l?"var(--bg-selected)":"none",color:l?"var(--text)":"var(--text-muted)",cursor:s?"not-allowed":"pointer",opacity:s?.45:1,fontSize:12},children:o},o)})})}function st({cwd:e,source:t,scope:n,projectResourcesLoaded:o,busy:l,actionError:s,onSourceChange:a,onScopeChange:d,onInstall:c}){let{t:u}=(0,m.s)(),h=(0,i.useRef)(null);return(0,i.useEffect)(()=>{h.current?.focus()},[]),(0,r.jsxs)(o6,{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)(le,{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?`${l4(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsx)(ln,{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=l8(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(l8(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()&&!l&&c()}})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(se,{value:n,projectResourcesLoaded:o,onChange:d}),(0,r.jsx)(ll,{variant:"primary",onClick:c,disabled:l||!t.trim(),className:"is-pushed-right",children:u(l?"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))})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:s})]})}function sn({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:o,sessionId:l,updateStatus:s,checkingUpdate:a,updateError:d,onAction:c,onCheckUpdate:u,onReloadSession:h}){let p,{t:f}=(0,m.s)(),g=l5(e),x=n?.endsWith(g)??!1,y="reload"===n,v=!e.disabled,b=e.canCheckForUpdates,w=s?.state==="update-available";return(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{className:"is-top-aligned",children:[(0,r.jsxs)(o7,{children:[(0,r.jsx)(l9,{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)(o9,{children:[(0,r.jsx)(ll,{size:"small",variant:w?"primary":void 0,onClick:w||!b?()=>c("update",e):u,disabled:x||y||a,title:w?f("i18n.updateAvailable"):void 0,children:f(n===`update:${g}`?"i18n.updating":a?"i18n.checking":w||!b?"i18n.update":"i18n.check")}),(0,r.jsx)(ll,{size:"small",onClick:h,disabled:!l||y||x,title:f(l?"i18n.reloadSession":"i18n.openSessionToReload"),children:f(y?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(ll,{variant:"danger",size:"small",onClick:()=>c("remove",e),disabled:x||y,children:f(n===`remove:${g}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(ls,{checked:v,loading:x||y,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:l3(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"))}),w&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:s.displayName,children:f("i18n.updateAvailable")}),b&&(a||s&&!w)&&(0,r.jsx)("span",{className:`skill-update-status ${a?"is-checking":s?.state==="up-to-date"?"is-success":s?.state==="error"?"is-error":"is-muted"}`,children:a?f("i18n.checking"):s?.state==="up-to-date"?f("i18n.upToDate"):s?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):s?.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?l4(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:l4(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(lt,{children:f("i18n.resolvedResources")}),(0,r.jsx)(l7,{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 sr({extension:e}){let{t}=(0,m.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsxs)(o6,{children:[(0,r.jsx)(o3,{children:(0,r.jsxs)(o7,{children:[(0,r.jsx)(l9,{scope:e.scope}),(0,r.jsx)(le,{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:l4(e.path)})]})]})}function si({cwd:e,sessionId:t,onClose:n,onReloaded:o,embedded:l=!1}){let{t:s}=(0,m.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(()=>oH("plugins",e)),[x,y]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[w,k]=(0,i.useState)("global"),[j,S]=(0,i.useState)(null),[C,I]=(0,i.useState)(null),[E,M]=(0,i.useState)(null),[T,L]=(0,i.useState)({}),[R,N]=(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=>l5(e)===f)??null,O=B.find(e=>l6(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),y(e=>0===n.packages.length&&0===n.standaloneExtensions.length||e),g(e=>e&&(n.packages.some(t=>l5(t)===e)||n.standaloneExtensions.some(t=>l6(t)===e))?e:n.packages[0]?l5(n.packages[0]):n.standaloneExtensions[0]?l6(n.standaloneExtensions[0]):null)}catch(e){p(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{L({}),P(null),q()},[e]),(0,i.useEffect)(()=>{f&&oB("plugins",f,e)},[e,f]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:H.filter(e=>e.canCheckForUpdates)).map(l5);if(0!==n.length){P(null),N(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}`);L(e=>{let t={...e};for(let e of r.updates??[])t[l5(e)]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{N(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),I(null),M(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),L({}),M(s("i18n.packagesUpdated")),t&&M(`${s("i18n.packagesUpdated")} ${s("agents.reloadRequired")}`)}catch(e){I(e instanceof Error?e.message:String(e))}finally{D(!1)}},[e,t,s]),J=(0,i.useCallback)(async(t,n)=>{let r=l5(n);S(`${t}:${r}`),I(null),M(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]?l5(o.packages[0]):o.standaloneExtensions[0]?l6(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&y(!0),M("Package removed."),L(e=>{let t={...e};return delete t[r],t})):(M({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&L(e=>{let t={...e};return delete t[r],t}))}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=l8(v).trim();if(!t)return;b(t);let n=`${w}\0${t}`;S(`install:${n}`),I(null),M(null);try{var r;let i,o,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:w,cwd:e})}),s=await l.json();if(!l.ok||s.error)throw Error(s.error??`HTTP ${l.status}`);d(s);let a=(r=s.packages,o=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${o}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));g(a?l5(a):n),y(!1),b(""),M("Package installed.")}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,w,v]),Z=(0,i.useCallback)(async()=>{if(t){S("reload"),I(null),M(null);try{await r4(t,{type:"reload"}),o?.(),await q(),M("Session reloaded.")}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}}},[q,o,t]),X=j?.startsWith("install:")??!1,G=Object.values(T).filter(e=>"update-available"===e.state).length,Q=H.some(e=>e.canCheckForUpdates),ee=c||null!==j||R.size>0||A;return(0,r.jsxs)(oQ,{embedded:l,title:s("common.plugins"),subtitle:l4(e),closeLabel:s("i18n.close"),onClose:n,children:[!U&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:s("trust.pluginsNotLoaded")}),(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{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)(o4,{children:s("i18n.extensions")}),B.map(e=>{let t=l6(e);return(0,r.jsxs)(o8,{active:!x&&f===t,title:e.path,onClick:()=>{g(t),y(!1),I(null),M(null)},children:[(0,r.jsx)(ld,{active:e.enabled}),(0,r.jsx)(o5,{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)(o4,{children:e.scope}),e.packages.map(e=>{let t=l5(e),n=!x&&f===t;return(0,r.jsxs)(o8,{active:n,onClick:()=>{g(t),y(!1),I(null),M(null)},children:[(0,r.jsx)(ld,{active:!e.disabled,color:l3(e.status)}),(0,r.jsx)(o5,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),T[l5(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:s("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope))]})}),(0,r.jsx)(la,{active:x,onClick:()=>{y(!0),I(null),M(null)},children:s("i18n.addPlugin")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:x?(0,r.jsx)(st,{cwd:e,source:v,scope:w,projectResourcesLoaded:U,busy:X,actionError:C,onSourceChange:b,onScopeChange:k,onInstall:Y}):c?null:O?(0,r.jsx)(sr,{extension:O}):F?(0,r.jsx)(sn,{pkg:F,cwd:e,busyKey:j,actionError:C,actionMessage:E,sessionId:t,updateStatus:T[l5(F)],checkingUpdate:R.has(l5(F)),updateError:z,onAction:J,onCheckUpdate:()=>void K(F),onReloadSession:Z},l5(F)):(0,r.jsx)(lr,{children:s("i18n.selectPackage")})})})]}),(0,r.jsxs)(lo,{status:G>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[G," ",1===G?s("i18n.update"):s("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:[!l&&(0,r.jsx)(ll,{onClick:n,children:s("i18n.close")}),Q&&(0,r.jsx)(ll,{variant:G>0?"primary":"secondary",onClick:()=>void(G>0?V():K()),disabled:ee,title:G>0?s("i18n.updateAllPluginsHint"):void 0,children:A?s("i18n.updating"):$?s("i18n.checking"):G>0?`${s("i18n.updateAllPlugins")} (${G})`:s("i18n.checkUpdates")}),(0,r.jsx)(ll,{variant:"secondary",onClick:()=>void q(),disabled:ee,children:s("i18n.refresh")})]})]})}let so=new Set(["openai-codex","antigravity","xai"]);function sl({sessionId:e=null,onReloaded:t}){let{t:n}=(0,m.s)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(null),[b,w]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=new AbortController;return a(!0),x(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=ss(n);l(r)}catch(e){e instanceof DOMException&&"AbortError"===e.name||x(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}`);l(ss(n)),f(!!e)},j=async e=>{c(!0),x(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){x(e instanceof Error?e.message:String(e))}finally{c(!1)}},S=async()=>{if(!b||!b.label.trim())return void w(null);c(!0),x(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:b.id,label:b.label.trim()})});await k(e),w(null)}catch(e){x(e instanceof Error?e.message:String(e))}finally{c(!1)}},C=async()=>{if(y){c(!0),x(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"edit"===y.mode?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify("edit"===y.mode?{id:y.id,label:y.label,provider:y.provider,model:y.model}:{label:y.label,provider:y.provider,model:y.model})});await k(e),v(null)}catch(e){x(e instanceof Error?e.message:String(e))}finally{c(!1)}}},I=async e=>{if(window.confirm(n("agents.deleteConfirm",{name:e.label}))){c(!0),x(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),y?.mode==="edit"&&y.id===e.id&&v(null)}catch(e){x(e instanceof Error?e.message:String(e))}finally{c(!1)}}},E=async()=>{if(e){h(!0),x(null);try{await r4(e,{type:"reload"}),f(!1),t?.()}catch(e){x(e instanceof Error?e.message:String(e))}finally{h(!1)}}},M=o?.connections.filter(e=>"custom"!==e.kind)??[],T=o?.connections.filter(e=>"custom"===e.kind)??[],L=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)("section",{className:"settings-general-section",children:[(0,r.jsx)("p",{className:"settings-general-description",children:n("settings.imagesDescription")}),(0,r.jsxs)("div",{className:"settings-image-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:n("settings.imagesEnabled")}),(0,r.jsxs)("div",{className:"settings-image-actions",children:[p&&e&&(0,r.jsx)(ll,{size:"small",onClick:()=>void E(),disabled:u||d,children:u?n("agents.reloading"):n("agents.reloadSession")}),(0,r.jsx)(ls,{checked:o?.enabled===!0,disabled:s||u||!o,loading:d&&!y&&!b,label:n("settings.imagesEnabled"),onChange:e=>void j({enabled:e})})]})]}),o?.enabled&&(0,r.jsxs)(r.Fragment,{children:[o.connections.some(e=>e.enabled)&&(0,r.jsxs)("label",{className:"settings-image-field",children:[(0,r.jsx)("span",{children:n("settings.imagesDefault")}),(0,r.jsx)("select",{value:o.defaultConnection,disabled:s||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))})]}),(0,r.jsxs)("div",{className:"settings-general-columns",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"settings-image-group",children:n("settings.imagesBuiltin")}),M.map(e=>(0,r.jsx)(sa,{connection:e,disabled:s||u||d,unsignedLabel:n("settings.imagesSignedOut"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),renaming:b?.id===e.id,renameValue:b?.id===e.id?b.label:e.label,onRenameChange:t=>w({id:e.id,label:t}),onRenameSubmit:()=>void S(),onRenameCancel:()=>w(null),onEdit:()=>{v(null),w({id:e.id,label:e.label})},editLabel:n("i18n.rename")},e.id))]}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"settings-image-group-row",children:[(0,r.jsx)("h3",{className:"settings-image-group",children:n("settings.imagesCustom")}),L.length>0&&!y&&(0,r.jsx)(ll,{size:"small",disabled:s||u||d,onClick:()=>{w(null),v({mode:"create",label:"",provider:L.find(e=>!so.has(e.id))?.id??L[0]?.id??"",model:""})},children:n("settings.imagesAddConnection")})]}),0===L.length&&(0,r.jsx)("p",{className:"settings-general-description",children:n("settings.imagesNoProviders")}),T.map(e=>(0,r.jsx)(sa,{connection:e,disabled:s||u||d,unsignedLabel:n("settings.imagesNotConfigured"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),onEdit:()=>{w(null),v({mode:"edit",id:e.id,label:e.label,provider:e.provider,model:e.model})},onDelete:()=>void I(e),editLabel:n("image.edit"),deleteLabel:n("agents.delete")},e.id)),y&&(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:y.label,onChange:e=>v({...y,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:y.provider,onChange:e=>v({...y,provider:e.target.value}),required:!0,children:L.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)(sc,{value:y.model,t:n,onChange:e=>{let t=ec.find(t=>t.model===e);v({...y,model:e,..."create"===y.mode&&!y.label.trim()&&t?{label:t.label}:{}})}},"edit"===y.mode?y.id:"create")]}),(0,r.jsxs)("div",{className:"settings-image-form-actions",children:[(0,r.jsx)(ll,{type:"submit",variant:"primary",size:"small",disabled:d||!y.label.trim()||!y.provider||!y.model.trim(),children:d?n("agents.saving"):n("agents.save")}),(0,r.jsx)(ll,{type:"button",size:"small",disabled:d,onClick:()=>v(null),children:n("trust.cancel")})]})]})]})]})]}),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})]})]})]})}function ss(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 sa({connection:e,disabled:t,unsignedLabel:n,onChange:o,onEdit:l,onDelete:s,editLabel:a,deleteLabel:d,renaming:c=!1,renameValue:u,onRenameChange:h,onRenameSubmit:p,onRenameCancel:f}){let g=(0,i.useRef)(!1),x=!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:[l&&!c?(0,r.jsx)(ll,{size:"small",disabled:t,onClick:l,children:a}):null,s?(0,r.jsx)(ll,{size:"small",disabled:t,onClick:s,children:d}):null,(0,r.jsx)(ls,{checked:e.enabled,disabled:t||x,label:e.label,onChange:o})]})]})}let sd="__other__";function sc({value:e,onChange:t,t:n}){let o=ec.some(t=>t.model===e),[l,s]=(0,i.useState)(!o),a=l||!o?sd:e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("select",{value:a,onChange:e=>{let n=e.target.value;n===sd?s(!0):(s(!1),t(n))},children:[ec.map(e=>(0,r.jsxs)("option",{value:e.model,children:[e.label," \xb7 ",e.model]},e.model)),(0,r.jsx)("option",{value:sd,children:n("settings.imagesOtherModel")})]}),a===sd?(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),required:!0}):null]})}let su=null;async function sh(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(su)return su;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 su=null,!1}})();return su=t,t.then(e=>{e||su!==t||(su=null)}),t}let sp="pi-web-sarasa-enabled";async function sf(){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(sp,"1"),await document.fonts.load('14px "Sarasa Term SC Web"')}function sg({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)(V,{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 sx({preference:e}){return"light"===e?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",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:"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)("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:"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:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}function sm({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:o}){let{locale:l,setLocale:s,supportedLocales:a,t:d}=(0,m.s)(),{preference:c,setThemePreference:u}=tO(),{width:h,setWidth:p,fontSize:f,setFontSize:g}=re(),[x,y]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(!0),[E,M]=(0,i.useState)(!1),[T,L]=(0,i.useState)(null),[R,N]=(0,i.useState)(!1),[$,W]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[A,D]=(0,i.useState)(!1),[H,B]=(0,i.useState)(""),[F,O]=(0,i.useState)("available"),[U,_]=(0,i.useState)(null);(0,i.useEffect)(()=>{S(t4()),I(oO()),M(ri())},[]),(0,i.useEffect)(()=>{fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>P(e?.enabled===!0)).catch(()=>{})},[]),(0,i.useEffect)(()=>rZ(L),[]);let q=[{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||y(n)}).catch(t=>{e||k(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let K=async n=>{b(!0),k(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}`);y(i),e&&(await r4(e,{type:"reload"}),t())}catch(e){k(e instanceof Error?e.message:String(e))}finally{b(!1)}},V=async()=>{if(!R){N(!0),W(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 sh(l))throw Error("unsupported or not permitted");W({kind:"ok",message:d("settings.pushRegistered")})}catch(e){W({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{N(!1)}}};(0,i.useEffect)(()=>{O("1"===localStorage.getItem(sp)?"cached":"available")},[]);let J=async()=>{O("loading"),_(null);try{await sf(),O("cached")}catch(e){O("error"),_(e instanceof Error?e.message:String(e))}},Y=async()=>{D(!0),B("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{B(d("auth.logoutFailed"))}finally{D(!1)}};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-general-columns",children:[(0,r.jsxs)("div",{children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:q.map(e=>{let t=c===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>u(e.id),className:"settings-theme-option",children:[(0,r.jsx)(sx,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",children:e.label})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.thinkingExpandedDefault")}),(0,r.jsx)(ls,{checked:j,label:d("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(t1,String(e)),window.dispatchEvent(new Event(t2)),S(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.autoSessionTitle")}),(0,r.jsx)(ls,{checked:C,label:d("settings.autoSessionTitle"),onChange:e=>{window.localStorage.setItem(oF,String(e)),I(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:d("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(ll,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>p(820),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",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"})})})]}),(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)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:d("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[f,"px"]}),(0,r.jsx)(ll,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("settings.resetChatContentFontSize"),disabled:14===f,onClick:()=>g(14),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",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"})})})]}),(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)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.shiftEnterToSend")}),(0,r.jsx)(ls,{checked:E,label:d("settings.shiftEnterToSend"),onChange:e=>{window.localStorage.setItem(rr,String(e)),M(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(ls,{checked:n,label:d("settings.quoteSelection"),onChange:o})]}),T&&(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.browserNotifications")}),"granted"===T?(0,r.jsx)("span",{className:"settings-chat-status",children:d("settings.browserNotificationsOn")}):"denied"===T?(0,r.jsx)("span",{className:"settings-chat-status",children:d("settings.browserNotificationsBlocked")}):(0,r.jsx)(ll,{size:"small",onClick:()=>{Notification.requestPermission().then(L)},children:d("settings.browserNotificationsEnable")})]})]})]}),x?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(ls,{checked:x.powerShellEnabled,loading:v,label:d("settings.usePowerShell"),onChange:e=>void K(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-language-options",children:a.map(e=>{let t=l===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>s(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),z&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(ll,{variant:"secondary",disabled:A,onClick:()=>void Y(),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",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),A?d("auth.loggingOut"):d("auth.logOut")]}),H&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:H})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.typography")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.typographyDescription")}),"cached"===F?(0,r.jsxs)("div",{role:"status",className:"settings-font-status",children:[(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsxs)("span",{children:[d("settings.fontCached")," \xb7 ",d("settings.fontCachedDescription")]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"settings-font-link-row",children:(0,r.jsx)(ll,{size:"small",variant:"secondary",disabled:"loading"===F,onClick:()=>void J(),children:"loading"===F?d("settings.fontDownloadLoading"):d("settings.fontDownload")})}),(0,r.jsx)("p",{role:"status",className:"error"===F?"settings-general-error":"settings-general-description",children:"error"===F?`${d("settings.fontDownloadFailed")} ${U}`:d("settings.fontNotInstalled")})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.pushPermissionDescription")}),(0,r.jsx)("div",{className:"settings-font-link-row",children:(0,r.jsx)(ll,{size:"small",variant:"secondary",disabled:R,onClick:()=>void V(),children:R?d("settings.pushRegisterLoading"):d("settings.pushRegister")})}),$&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===$.kind?{color:"var(--accent)"}:void 0,children:$.message})]})]})]})]})}function sy({cwd:e,sessionId:t,initialSection:n,onClose:o,onSessionReloaded:l,onModelsChanged:s,quoteSelectionEnabled:a,onQuoteSelectionChange:d}){let{t:c}=(0,m.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}];(0,i.useEffect)(()=>oD(n),[n]),(0,i.useEffect)(()=>{let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),o())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),(0,i.useEffect)(()=>{e||"skills"!==u&&"agents"!==u&&"plugins"!==u||(h("general"),f(e=>new Set(e).add("general")),oD("general"))},[e,u]);let x=e=>{f(t=>new Set(t).add(e)),h(e),oD(e)},y=(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&&o()},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=>x(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:()=>x(t.id),children:[(0,r.jsx)(sg,{section:t.id}),(0,r.jsx)("span",{children:t.label})]},t.id)})}),(0,r.jsx)("button",{type:"button",onClick:o,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:[y("general",(0,r.jsx)(sm,{sessionId:t,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),y("models",(0,r.jsx)(lP,{embedded:!0,onClose:o,cwd:e,onModelsChanged:s})),e&&y("agents",(0,r.jsx)(l2,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e)),y("images",(0,r.jsx)(sl,{sessionId:t,onReloaded:l})),e&&y("skills",(0,r.jsx)(lU,{embedded:!0,cwd:e,onClose:o},e)),e&&y("plugins",(0,r.jsx)(si,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e))]})]})})}function sv({cwd:e,busy:t,error:n,onCancel:o,onConfirm:l}){let{t:s}=(0,m.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:s("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:s("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:s("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:l,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:s(t?"trust.trusting":"trust.trustProject")})]})]})})}function sb(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function sw(e){let t=e,n=t.branchPreview,r=sb(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&sb(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function sk(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 sj({node:e,activePathIds:t,depth:n,isLast:i,parentLines:o,onSelect:l}){let{node:s,skipped:a,branchPreview:d,labelEntry:c}=sw(e),u=t.has(s.entry.id),h=t.has(e.entry.id)||t.has(s.entry.id),p=d?.text??function(e){if("message"===e.type&&sb(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:sb(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:()=>l(s.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})]}),s.children.map((e,a)=>(0,r.jsx)(sj,{node:e,activePathIds:t,depth:n+1,isLast:a===s.children.length-1,parentLines:[...o,!i],onSelect:l},e.entry.id))]})}function sS({tree:e,activeLeafId:t,onLeafChange:n,inline:o,containerRef:l,open:s,onToggle:a,hasSession:d,compact:c,hideInlineButton:u,disabled:h=!1}){let{t:p}=(0,m.s)(),[f,g]=(0,i.useState)(!1),x=void 0!==s?s:f,y=(0,i.useRef)(null),[v,b]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!o)return;let e=l?.current??y.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();b({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,o,l]);let w=(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?sk(e)?null:p("i18n.noBranches"):p("i18n.noActiveSession"),S=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=sw(e[0]).node;return t.children.length>1?t.children:[]}(e),C=!j&&S.length>0,I=h||!C,E=(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:I?"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"})]}),M=(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:x?"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:y,disabled:I,onClick:()=>{I||(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:x?"var(--bg-selected)":"none",border:"none",cursor:I?"not-allowed":"pointer",color:I?"var(--text-dim)":x?"var(--text)":"var(--text-muted)",opacity:I?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{I||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{I||(e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=x?"var(--bg-selected)":"none")},title:I?p("i18n.noBranches",{defaultValue:"没有分支"}):p("i18n.branches"),"aria-label":p("i18n.branches"),"aria-pressed":x,children:[E,!c&&(0,r.jsx)("span",{style:{lineHeight:1},children:p("i18n.branches")})]}),x&&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)(sj,{node:e,activePathIds:w,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:[E,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:p("i18n.branches")}),M]}),x&&(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)(sj,{node:e,activePathIds:w,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 sC({mobile:e,disabled:t,menuOpen:n,exporting:o=!1,error:l,labels:s,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?s.unsaved:s.menu,"aria-label":s.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":s.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:sI,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:s.full})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",title:s.exportMarkdownTitle,disabled:o,onClick:()=>{d()},style:{...sI,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:s.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"})]})]}),l&&(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"#dc2626",lineHeight:1.35},children:l})]})]})}let sI={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 sE({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:`
|
|
9
|
+
${t}`:e:t}function nD(e){return{data:e.data,mimeType:e.mimeType}}function nH(e,t,n,r){return{value:nA(e,n),images:[...t??[],...r].map(nD)}}function nB(e,t,n){if(e===t)return n?nN(n):nW(t);let r=nW(e),i=n&&!n$(n)?nN(n):r??(n?nN(n):null),o=nW(t);if(nP(e),!i)return o;let l=o?nH(o.value,o.images,i.value,i.images):i;return nz(t,l),nN(l)}function nF(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 nO(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function nU(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 n_(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}let nq="(max-width: 640px)",nK=e=>(function(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)})(nq,e),nV=()=>!!window.matchMedia&&window.matchMedia(nq).matches;function nJ(){return!1}function nY(){return(0,i.useSyncExternalStore)(nK,nV,nJ)}let nZ="pi-chat-content-width",nX="pi-chat-content-font-size",nG={width:820,fontSize:14},nQ=null,n0=new Set;function n1(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function n2(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function n4(e){try{return window.localStorage.getItem(e)}catch{return null}}function n8({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 n5(){return nQ||n8(nQ={width:n1(n4(nZ)),fontSize:n2(n4(nX))}),nQ}function n6(e){return n0.add(e),()=>{n0.delete(e)}}function n3(e,t){let n="width"===e?n1(t):n2(t);n8(nQ={...n5(),[e]:n});try{window.localStorage.setItem("width"===e?nZ:nX,String(n))}catch{}n0.forEach(e=>e())}let n7=e=>n3("width",e),n9=e=>n3("fontSize",e);function re(){return{...(0,i.useSyncExternalStore)(n6,n5,()=>nG),setWidth:n7,setFontSize:n9}}var rt=n(14755);function rn(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 rr="pi-shift-enter-to-send";function ri(){try{return"true"===window.localStorage.getItem(rr)}catch{return!1}}let ro=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rl(e,t){return ro.compare(e.name||e.modelId,t.name||t.modelId)||ro.compare(e.provider,t.provider)||ro.compare(e.modelId,t.modelId)}function rs({options:e,value:t,onChange:n,onClear:o,emptyLabel:l,selectedLabel:s,disabled:a=!1,busy:d=!1,isAutoSelection:c=!1,ariaLabel:u,variant:h="toolbar",placement:p="up"}){let f,g,x,m,y,v,b,w,k=nY(),j=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),I=(0,i.useId)(),[E,M]=(0,i.useState)(!1),[T,L]=(0,i.useState)(0),[R,N]=(0,i.useState)(null),$=a||d,W=(0,i.useMemo)(()=>[...e].sort(rl),[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=s??(t?W.find(e=>e.modelId===t.modelId&&e.provider===t.provider)?.name??t.modelId:l??(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(T,A.length-1):0,B=A.length?`${I}-option-${H}`:void 0,F=(0,i.useCallback)(()=>{let e=S.current?.getBoundingClientRect();e&&N({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)&&M(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{$&&M(!1)},[$]),(0,i.useEffect)(()=>{if(!E)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)}},[E,F]),(0,i.useEffect)(()=>{E&&L(Math.max(0,Math.min(D>=0?D:0,A.length-1)))},[E,D,A.length]),(0,i.useEffect)(()=>{E&&B&&document.getElementById(B)?.scrollIntoView({block:"nearest"})},[E,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:E?"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;M(!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&&E&&(e.preventDefault(),e.stopPropagation(),M(!1))},children:[(0,r.jsxs)("button",{ref:S,type:"button",role:"combobox","aria-label":u,"aria-haspopup":"listbox","aria-controls":I,"aria-activedescendant":E?B:void 0,"aria-expanded":E,onKeyDown:e=>{if("Escape"===e.key&&E){e.preventDefault(),M(!1);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!E){F(),L(D>=0?D:0),M(!0);return}let t="ArrowDown"===e.key?1:-1;L(e=>A.length?(e+t+A.length)%A.length:0);return}if(E&&A.length){if("Home"===e.key||"End"===e.key)e.preventDefault(),L("Home"===e.key?0:A.length-1);else if("Enter"===e.key||" "===e.key){e.preventDefault();let t=A[H];null===t?(M(!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(),M(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=E?"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"})})]}),E&&R&&(f=window.visualViewport?.height??window.innerHeight,g=window.visualViewport?.width??window.innerWidth,x=R.top-8,m=f-R.bottom-8,v=Math.max(120,Math.min((y="up"===p||x>m)?x:m,.6*f)),b=y?{bottom:f-R.top+6}:{top:R.bottom+6},w=k?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:R.left,width:"max-content",minWidth:R.width,maxWidth:Math.max(R.width,g-R.left-8)},(0,r.jsx)("div",{ref:C,id:I,role:"listbox","aria-label":u,"aria-activedescendant":B,style:{position:"fixed",...b,...w,zIndex:500,display:"flex",flexDirection:"column",maxHeight:v,overflow:"hidden",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:y?"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)(ra,{id:`${I}-option-0`,active:!t,highlighted:0===H,label:l??"Default",onActive:()=>L(0),onClick:()=>{M(!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)(ra,{id:`${I}-option-${A.indexOf(e)}`,active:e.modelId===t?.modelId&&e.provider===t?.provider,highlighted:H===A.indexOf(e),label:e.name,onActive:()=>L(A.indexOf(e)),onClick:()=>U(e)},`${e.provider}:${e.modelId}`))]},e.provider))]})}))]})}function ra({id:e,active:t,highlighted:n,label:i,onActive:o,onClick:l}){return(0,r.jsxs)("button",{id:e,type:"button",role:"option","aria-selected":t,"data-active":n||void 0,onClick:l,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 rd=["configured","chat-only","read-only","default","full"],rc={configured:rt.Q8,"chat-only":"none","read-only":"read-only",default:"default",full:"full"},ru=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function rh(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,l=o?.parentElement,s="u">typeof ResizeObserver&&o?new ResizeObserver(i):null;o&&s?.observe(o),l&&s?.observe(l);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{s?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let rp=["auto",...nE],rf={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},rg=[{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 rx(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return rg.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}function rm(e,t){return`${t.map(e=>n_(e,!1)).join("")}${e.trim()}`.trim()}let ry=["builtin","extension","prompt","skill"],rv={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},rb={builtin:0,extension:1,prompt:2,skill:3};function rw(e,t,n){let r=e.name.toLowerCase(),i=rk(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function rk(e,t){return"builtin"===e.source?t(e.description):e.description??""}function rj(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 rS={name:"<session-title>",session:"[session-id]",clone:"[new-title]"};function rC(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function rI(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 l=i.toDataURL("image/jpeg",.85).split(",")[1];return l&&l.length<4*Math.ceil(e.size/3)?{data:l,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function rE(e){return{data:e.data,mimeType:e.mimeType}}function rM(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function rT(e){return(e??[]).map(rM)}function rL(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function rR({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 rN({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 r$({error:e}){let{t}=(0,m.s)();return e?(0,r.jsx)(rN,{tone:"error",title:t("chat.modelError"),body:e}):null}function rW({warnings:e}){let{t}=(0,m.s)();return e&&0!==e.length?(0,r.jsx)(rN,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let rz=(0,i.forwardRef)(function({onSend:e,onOpenImageGeneration:t,onAbort:n,onSteer:o,onFollowUp:l,isStreaming:s,disabled:a=!1,model:d,isAutoModelSelection:c,modelNames:u,modelList:h,modelError:p,modelScopeWarnings:f,onModelChange:g,modelSwitching:x,onCompact:y,onAbortCompaction:v,isCompacting:b,compactError:w,compactResult:k,toolPreset:j,onToolPresetChange:S,contextUsage:C,cacheHitRate:I,onOpenSessionStats:E,thinkingLevel:M,onThinkingLevelChange:T,availableThinkingLevels:R,thinkingLevelMap:N,retryInfo:W,queuedMessages:z,inputHistory:P=[],onRecallQueue:A,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,el,{t:es}=(0,m.s)(),{fontSize:ea}=re(),ed=nY(),ec=(0,i.useId)(),[eu,eh]=(0,i.useState)(()=>K?nW(K)?.value??"":""),[ep,ef]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),[em,ey]=(0,i.useState)(!1),[ev,ew]=(0,i.useState)(!1),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)([]),eI=(0,i.useRef)([]);eI.current=eS;let[eE,eM]=(0,i.useState)(()=>K?rT(nW(K)?.images):[]),eT=eu.trimStart(),eL=0===eE.length&&eT.startsWith("!"),eR=eL&&eT.startsWith("!!"),[eN,e$]=(0,i.useState)(!1),[eW,ez]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(0),[eD,eH]=(0,i.useState)(null),[eB,eF]=(0,i.useState)(null),[eO,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(0),[eJ,eY]=(0,i.useState)(!1),[eZ,eX]=(0,i.useState)(!1),[eG,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(0),e2=(0,i.useRef)(null),[e4,e8]=(0,i.useState)(!1),[e5,e6]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(null),tr=Y&&tt?.cwd===Y?tt.values:{},ti=(0,i.useRef)(null),to=(0,i.useRef)(null),tl=(0,i.useRef)(null),ts=(0,i.useRef)(null),ta=(0,i.useRef)(null),td=(0,i.useRef)(null),tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),th=(0,i.useRef)(null),tp=(0,i.useRef)(null),tf=(0,i.useRef)(!1),tg=(0,i.useRef)(0),tx=(0,i.useRef)(!1),tm=(0,i.useRef)(null),ty=(0,i.useRef)([]),tv=(0,i.useRef)(null),tb=(0,i.useRef)([]),tw=(0,i.useRef)(!1),tk=(0,i.useRef)([]),tj=(0,i.useRef)(null),tS=(0,i.useRef)(null),tC=(0,i.useRef)(0),tI=(0,i.useRef)(K),tE=(0,i.useRef)(eu),tM=(0,i.useRef)(eE),tT=(0,i.useRef)(0);tE.current=eu,tM.current=eE,(0,i.useImperativeHandle)(X,()=>({insertIfEmpty(e){let t=ti.current;(t?t.value:eu).trim()||(tE.current=e,eh(e),eF(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=ti.current;if(t=i?i.value:eu,n=tM.current.length,r=tT.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"),l=rT("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]}));tE.current=o,tM.current=l,eh(o),eF(null),eQ(!1),eM(e=>(e.forEach(rL),l)),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=ti.current,n=[e,t?t.value:eu].filter(e=>e.trim()).join("\n\n");tE.current=n,eh(n),eF(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(tI.current!==e)return void nB(e,t);let n={value:tE.current,images:tM.current.map(rE)},r=nB(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(tI.current=t,i)return;let o=rT(r.images);tE.current=r.value,tM.current=o,eh(r.value),eM(e=>(e.forEach(rL),o)),eF(null),eQ(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tI.current,i=n??r,o=i===r,l=!o&&i?nW(i):null,s=nH(e,t,o?tE.current:l?.value??"",o?tM.current.map(rE):l?.images??[]);if(i&&nz(i,s),!o)return;let a=rT(s.images);tE.current=s.value,tM.current=a,eh(t=>{let n=nA(e,t);return tE.current=n,n}),eF(null),eQ(!1),eM(e=>(e.forEach(rL),tM.current=a,a)),requestAnimationFrame(()=>{let e=ti.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=ti.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),l=i.length>0&&!i.endsWith(" ")?" ":"",s=i+l+e+o;tE.current=s,eh(s),eF(null),requestAnimationFrame(()=>{if(!t)return;let r=n+l.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){tL(e)},mentionImage(e){eC(t=>t.includes(e)?t:[...t,e]),requestAnimationFrame(()=>ti.current?.focus())}}));let tL=(0,i.useCallback)(async e=>{if(Z)return;let t=Math.max(0,10-tM.current.length-tT.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(!n.length)return;let r=tC.current;tT.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await rI(e),previewUrl:URL.createObjectURL(e)})));eM(t=>{if(r!==tC.current)return e.forEach(rL),t;let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(rL);let i=[...t,...n];return tM.current=i,i})}finally{tT.current-=n.length}},[Z]),tR=(0,i.useCallback)(e=>{eM(t=>{let n=[...t],[r]=n.splice(e,1);return r&&rL(r),tM.current=n,n})},[]),tN=(0,i.useCallback)(()=>{tM.current=[],eM(e=>(e.forEach(rL),[]))},[]),t$=(0,i.useCallback)(()=>{tC.current+=1,e2.current=null,tE.current="",eh(""),eF(null),eQ(!1),K&&nP(K),tI.current&&tI.current!==K&&nP(tI.current),tN(),eI.current=[],eC([]),ti.current&&(ti.current.style.height="auto")},[tN,K]);(0,i.useEffect)(()=>{K&&tI.current===K&&(e8(!nz(K,{value:eu,images:eE.map(rE)})),V?.(K,eu,eE.length))},[eE,K,V,eu]),(0,i.useEffect)(()=>{let e=tI.current;if(e===K)return;e&&nz(e,{value:tE.current,images:tM.current.map(rE)});let t=K?nW(K):null;tI.current=K;let n=t?.value??"",r=rT(t?.images);tC.current+=1,tE.current=n,tM.current=r,eh(n),eF(null),eQ(!1),eM(e=>(e.forEach(rL),r)),K&&V?.(K,n,r.length)},[K,V]);let tW=(0,i.useCallback)(()=>{let e=ti.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tW,[eu,ea,tW]),(0,i.useEffect)(()=>{let e=ti.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,tW())});return n.observe(e),()=>n.disconnect()},[tW]),(0,i.useEffect)(()=>()=>{tC.current+=1,tM.current.forEach(rL)},[]);let tz=(0,i.useCallback)(async e=>{if(eE.length||!e.startsWith("/")||!F)return!1;if(tw.current)return!0;tw.current=!0,eY(!0);try{var t,n;let r=await F(e);if(!r.handled)return!1;return r.error||(t=tE.current,n=tM.current.length,0!==n||t.trim()!==e)||t$(),!0}finally{tw.current=!1,eY(!1)}},[eE.length,t$,F]),tP=(0,i.useCallback)(async()=>{if(a)return;let t=eu.trim();if(eE.length>10)return;let n=rm(t,eS);if(!n&&!eE.length||(_?.(),(!s||rx(t))&&await tz(t)||s))return;let r=eE.length?eE:void 0;t$(),e(n,r)},[a,eu,eE,eS,s,tz,e,t$,_]),tA=!Z&&eu.startsWith("/")&&!/\s/.test(eu.slice(1))?eu.slice(1).toLowerCase():null,tD=null===tA?[]:[...s?rg.filter(e=>e.availableWhileStreaming):rg,...D??[]].filter(e=>{let t=e.name.toLowerCase(),n=rk(e,es).toLowerCase();return t.includes(tA)||n.includes(tA)}).sort((e,t)=>{let n=rw(e,tA,es)-rw(t,tA,es);return 0!==n?n:rb[e.source]-rb[t.source]||ru.compare(e.name,t.name)}),{commands:tH,groups:tB}=(G=0,{commands:(Q=ry.map(e=>{let t=tD.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!rC(e,tr)),...t.filter(e=>rC(e,tr))]: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}),tF=(()=>{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&&rS[n[1]]?{command:n[1],signature:rS[n[1]],hasArgument:n[2].trim().length>0}:null})(),tO=1===tD.length?es(tA?"chat.match":"chat.command"):es(tA?"chat.matches":"chat.commands",{count:tD.length}),tU=!!eu.trim(),t_=eE.length>10,tq=!t_&&(tU||eE.length>0||eS.length>0),tK=!a&&!t_&&(tU||eE.length>0||eS.length>0),tV=eE.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)&&!eZ;(0,i.useEffect)(()=>{0===eE.length&&eX(!1)},[eE.length]);let tJ=(0,i.useCallback)((e,t)=>{if(!Y)return void eF(null);let n=t??e.length;eF(nF(e.slice(0,n)))},[Y]),tZ=eB?.query??null,tX=i.useMemo(()=>null!==tZ&&e5&&e5.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:nU(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:nU(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||nO(e.entry.path)-nO(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(e5.entries,tZ):[],[tZ,e5,Y]),tG=!!(tZ&&e5?.clientTruncated&&e5.cwd===Y);(0,i.useEffect)(()=>{if(!tG||!Y||!tZ)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(Y)}&q=${encodeURIComponent(tZ)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>te({cwd:Y,query:tZ,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tG,tZ,Y]);let tQ=tG&&null!==e9&&e9.cwd===Y&&e9.query===tZ,t0=tQ?e9.matches:tX,t1=null===eB?null:`${eB.start}:${+!!eB.quoted}:${eB.query}`;(0,i.useEffect)(()=>{if(null===t1){eU(!1),eV(0);return}eU(!0),eV(0)},[t1]);let t2=null!==eB;(0,i.useEffect)(()=>{if(!t2||!Y)return;let e=tj.current;e&&e.cwd===Y&&Date.now()-e.fetchedAt<1e4||tS.current===Y||(tS.current=Y,e7(!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=>{e6({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)=>nO(e.path)-nO(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),clientTruncated:!!e.clientTruncated,serverHardTruncated:!!e.serverHardTruncated}),tj.current={cwd:Y,fetchedAt:Date.now()}}).catch(()=>{tj.current=null}).finally(()=>{tS.current=null,e7(!1)}))},[t2,Y]);let t4=(0,i.useCallback)(e=>{if(!eB)return;let t=ti.current,n=t?.selectionStart??eu.length,r=eu.slice(0,eB.start),i=eu.slice(n);eB.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,eB.quoted),l=r+o.text+i,s=r.length+o.cursorOffset;tE.current=l,eh(l),ez(s),eF(nF(l.slice(0,s))),rj(ti,s)},[eB,eu]);(0,i.useEffect)(()=>{eK>=t0.length&&eV(Math.max(0,t0.length-1))},[t0.length,eK]),(0,i.useEffect)(()=>{tb.current.length=t0.length},[t0.length]),(0,i.useEffect)(()=>{eO&&tb.current[eK]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eK,eO]),(0,i.useEffect)(()=>{e0>=P.length&&e1(Math.max(0,P.length-1))},[P.length,e0]),(0,i.useEffect)(()=>{tk.current.length=P.length},[P.length]),(0,i.useEffect)(()=>{eG&&tk.current[e0]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e0,eG]);let t8=(0,i.useCallback)(()=>{let e=e2.current;e2.current=null,e&&(tE.current=e.text,eh(e.text)),eQ(!1)},[]),t5=(0,i.useCallback)(e=>{e2.current=null,tE.current=e,eh(e),ez(e.length),eQ(!1),e1(0),eF(null),rj(ti,e.length)},[]),t6=(0,i.useCallback)(e=>{let t=`/${e.name} `;tE.current=t,eh(t),ez(t.length),e$(!1),eA(0),rj(ti,t.length)},[]),t3=(0,i.useCallback)(e=>{let t=eu.trim();if(eE.length>10)return;let n=rm(t,eS);if(!n&&!eE.length)return;if(_?.(),!eE.length&&F&&rx(t))return void tz(t);let r=eE.length?eE:void 0;if(t.startsWith("/")&&q){t$(),q(t,"steer"===e?"steer":"followUp",r);return}t$(),"steer"===e&&o?o(n,r):"followup"===e&&l&&l(n,r)},[eu,eE,eS,F,q,o,l,t$,_,tz]),t7=(0,i.useCallback)(e=>{let t=e.nativeEvent,r=!ed&&ri(),i="Enter"===e.key&&e.shiftKey===r&&(!ed||e.ctrlKey||e.metaKey),a=Date.now()-tg.current<100,d=tf.current||t.isComposing||229===t.keyCode;if(i&&(d||a)){a&&e.preventDefault();return}if(eG&&!d){if("ArrowDown"===e.key){e.preventDefault(),e1(e=>Math.min(Math.max(0,P.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e1(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),t8();return}if(("Tab"===e.key||i)&&P[e0]){e.preventDefault(),t5(P[e0]);return}}if(eN&&null!==tA&&!d){if("ArrowDown"===e.key){e.preventDefault(),eA(e=>0===tH.length?0:(e+1)%tH.length);return}if("ArrowUp"===e.key){e.preventDefault(),eA(e=>0===tH.length?0:(e-1+tH.length)%tH.length);return}if("Escape"===e.key){e.preventDefault(),e$(!1);return}let t=tH[eP];if("Tab"===e.key&&t){e.preventDefault(),t6(t);return}if(i&&t)return void((e.preventDefault(),s&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||eu.trim()!==`/${t.name}`)?t6(t):(e$(!1),tP()))}if(eO&&null!==eB&&!d){if("ArrowDown"===e.key){e.preventDefault(),eV(e=>0===t0.length?0:(e+1)%t0.length);return}if("ArrowUp"===e.key){e.preventDefault(),eV(e=>0===t0.length?0:(e-1+t0.length)%t0.length);return}if("Escape"===e.key){e.preventDefault(),eU(!1);return}if(("Tab"===e.key||i)&&t0[eK]){e.preventDefault(),t4(t0[eK]);return}}if("ArrowUp"===e.key&&!d&&!s&&P.length>0){e.preventDefault(),e$(!1),eU(!1),e2.current={text:eu},e1(P.length-1),eQ(!0);return}if("Escape"===e.key&&ev){e.preventDefault(),ew(!1);return}if("Escape"===e.key&&!d&&s&&n){e.preventDefault(),n();return}i&&(e.preventDefault(),s&&(o||l)?t3(e.altKey&&l||!o?"followup":"steer"):tP())},[ed,s,o,l,n,ev,eN,tA,tH,eP,t6,t3,tP,eO,eB,t0,eK,t4,eG,P,e0,t5,t8,eu]),t9=(0,i.useCallback)(()=>{let e=ti.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),ne=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!Z&&t.length){e.preventDefault(),tL(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:l,occurrence:s}of t){if(!o||!l)continue;let t=0;for(let n=0;n<=s&&!((t=e.indexOf(o,n?t+o.length:0))<0);n++);if(t<r)continue;let a=o.replace(/([\\[\]])/g,"\\$1"),d=l.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 l=e.currentTarget,s=l.selectionStart,a=l.value.slice(0,s)+o+l.value.slice(l.selectionEnd);e.preventDefault(),tE.current=a,eh(a),eQ(!1),tJ(a,s+o.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(s+o.length,s+o.length)})},[Z,tL,tJ]);(0,i.useEffect)(()=>{if(null===tA){e$(!1),eA(0),tx.current=!1;return}e$(!0),eA(0),!tx.current&&B&&(tx.current=!0,Promise.resolve(B()).catch(()=>{tx.current=!1}))},[tA,B]),(0,i.useEffect)(()=>{if(!eN||!Y)return;let e=!1;return tn({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;tn({cwd:Y,values:n})}).catch(()=>{e||tn({cwd:Y,values:{}})}),()=>{e=!0}},[eN,Y]),(0,i.useEffect)(()=>{eP>=tH.length&&eA(Math.max(0,tH.length-1))},[tH.length,eP]),(0,i.useEffect)(()=>{ty.current.length=tH.length},[tH.length]),(0,i.useEffect)(()=>{eN&&ty.current[eP]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eP,eN]),(0,i.useLayoutEffect)(()=>{if(!eN||null===tA)return void eH(null);let e=tm.current;if(e)return rh(e,e=>{eH(t=>t===e?t:e)})},[eN,tA]),(0,i.useLayoutEffect)(()=>{if(!eO||null===eB)return void eq(null);let e=tv.current;if(e)return rh(e,e=>{eq(t=>t===e?t:e)})},[eO,eB]);let nt=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})),nn=k?Math.max(0,k.tokensBefore-k.estimatedTokensAfter):0,nr=k?`${k.reason&&"manual"!==k.reason?`${k.reason[0].toUpperCase()}${k.reason.slice(1)} `:es("chat.compacted")} ${rn(k.tokensBefore)} -> ${rn(k.estimatedTokensAfter)} tokens (${es("chat.tokensSaved",{saved:rn(nn)})})`:null,ni="auto"!==(ee=M??"auto")&&N?N[ee]??ee:ee,no=Object.entries(rc).find(([,e])=>e===(j??rt.Q8))?.[0]??"configured",nl="chat-only"===no?es("chat.chatOnly"):no,ns=C?.percent??null,na=[ni,null!=ns&&ns>=70?`${Math.round(ns)}%`:null].filter(Boolean).join(" \xb7 ");(0,i.useEffect)(()=>{let e=e=>{let t=e.target;to.current&&!to.current.contains(t)&&ef(!1),tl.current&&!tl.current.contains(t)&&ex(!1),ts.current&&!ts.current.contains(t)&&ew(!1),ta.current&&!ta.current.contains(t)&&ej(!1),tu.current&&!tu.current.contains(t)&&ey(!1),!tm.current||tm.current.contains(t)||ti.current?.contains(t)||e$(!1),!tv.current||tv.current.contains(t)||ti.current?.contains(t)||eU(!1),!th.current||th.current.contains(t)||ti.current?.contains(t)||t8()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[t8]),(0,i.useEffect)(()=>{ed||ej(!1)},[ed]);let nd=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,l=null!==i&&i>=85,s=null!==i&&i>=70&&i<85,a=null!==n?`${rn(n)}/${rn(t)}`:`?/${rn(t)}`,d=null!==n?Math.max(0,t-n):null,c=[`${es("chat.contextUsage")}: ${null!==n?rn(n):"?"} / ${rn(t)} (${null!==i?i.toFixed(1):"?"}%)`,null!==d?`${es("chat.contextRemaining")}: ${rn(d)}`:null,null!=I?`${es("session.cacheHitRate")}: ${I.toFixed(1)}%`:null,l?`⚠️ ${es("chat.contextHighWarning")}`:null].filter(Boolean).join("\n");return(0,r.jsxs)("button",{ref:tu,type:"button",onClick:()=>{ey(e=>!e),E?.()},title:c,"aria-label":c,"data-top-panel-trigger":E?"session":void 0,"aria-controls":E?"workspace-top-panel":void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",height:e?32:28,background:em?l?"rgba(239,68,68,0.12)":"var(--bg-hover)":l?"rgba(239,68,68,0.06)":"none",border:l?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:l?"#ef4444":s?"rgba(234,179,8,0.95)":"var(--text-muted)",cursor:E?"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||!E||em||(t.currentTarget.style.background=l?"rgba(239,68,68,0.12)":"var(--bg-hover)")},onMouseLeave:t=>{e||!E||em||(t.currentTarget.style.background=l?"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:l?600:400,letterSpacing:"-0.01em",lineHeight:1},children:a}),null!=I&&(0,r.jsxs)("span",{style:{lineHeight:1},children:[I.toFixed(0),"%"]})]})};(0,i.useLayoutEffect)(()=>{if(!ed||!ek)return;let e=tc.current;if(e)return e.style.height="32px",()=>{e.style.height=""}},[ed,ek]),(0,i.useEffect)(()=>{s&&(ex(!1),ef(!1),ew(!1))},[s]);let nc=`${ec}-history`,nu=`${ec}-slash`,nh=`${ec}-files`,np=eG&&P.length>0?nc:eN&&null!==tA?nu:eO&&null!==eB?nh:void 0,nf=np===nc&&void 0!==P[e0]?`${nc}-${e0}`:np===nu&&tH[eP]?`${nu}-${eP}`:np===nh&&t0[eK]?`${nh}-${eK}`:void 0;return(0,r.jsxs)("fieldset",{disabled:eJ,"aria-busy":eJ,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:eJ?.5:1,transition:"opacity 0.15s"},children:[!Z&&(0,r.jsx)("input",{ref:tp,type:"file",accept:"image/*",multiple:!0,disabled:a,style:{display:"none"},onChange:e=>{tL(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)(r$,{error:p}),(0,r.jsx)(rW,{warnings:f}),t_&&(0,r.jsx)(rN,{tone:"error",title:es("chat.tooManyImagesTitle"),body:es("chat.tooManyImagesBody",{count:eE.length,max:10})}),tV&&(et=h?.find(e=>e.provider===d?.provider&&e.id===d?.modelId),(0,r.jsx)(rN,{tone:"warning",title:es("chat.imageNotSupportedTitle"),body:es("chat.imageNotSupportedBody",{model:et?.name||d?.modelId||""}),onClose:()=>eX(!0)})),(z?.steering.length??0)+(z?.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:es("chat.queued",{count:(z?.steering.length??0)+(z?.followUp.length??0)})}),A&&(0,r.jsxs)("button",{onClick:A,title:es("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"})]}),es("chat.recall")]})]}),z?.steering.map((e,t)=>(0,r.jsx)(rR,{kind:"steer",text:e},`steer-${t}`)),z?.followUp.map((e,t)=>(0,r.jsx)(rR,{kind:"follow-up",text:e},`followup-${t}`))]}),W&&(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"})]}),es("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),nr&&(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"})}),nr]}),w&&(0,r.jsx)("div",{role:"alert",className:"chat-input-feedback chat-input-feedback-error chat-input-feedback-detail",style:{whiteSpace:"pre-wrap"},children:w}),(e4||J)&&(0,r.jsx)("div",{role:"status",className:"chat-input-feedback chat-input-feedback-warning chat-input-feedback-draft",children:es("chat.draftPageOnly")}),(eE.length>0||eS.length>0)&&(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:8,flexWrap:"wrap",padding:"0 2px"},children:[eS.map(e=>(0,r.jsx)(eb,{path:e,cwd:Y??void 0,onRemove:()=>eC(t=>t.filter(t=>t!==e))},e)),eE.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:()=>tR(t),title:es("i18n.close"),"aria-label":es("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:td,style:{position:"relative",minWidth:0},children:[tF&&!eN&&(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:tF.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:["/",tF.command]}),(0,r.jsx)("span",{children:tF.signature})]}),eG&&P.length>0&&(0,r.jsxs)("div",{ref:th,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:es("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:nc,role:"listbox",style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:P.map((e,t)=>{let n=t===e0;return(0,r.jsxs)("button",{ref:e=>{tk.current[t]=e},type:"button",id:`${nc}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),t5(e)},onMouseEnter:()=>e1(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}`)})})]}),eN&&null!==tA&&(0,r.jsxs)("div",{ref:tm,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===eD?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eD}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?es("chat.loadingCommands"):es("chat.slashCommands",{label:tO})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nu,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:6},children:H||0!==tD.length?tB.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:es(rv[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===eP,i=rC(e,tr);return(0,r.jsxs)("button",{ref:e=>{ty.current[t]=e},type:"button",id:`${nu}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),t6(e)},onMouseEnter:()=>eA(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,tA),"builtin"===e.source&&rS[e.name]&&(0,r.jsx)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11,fontWeight:400},children:rS[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:es("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:rk(e,es)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"4px 8px",fontSize:12,color:"var(--text-dim)"},children:es("chat.noCommands")})})]}),eO&&null!==eB&&(en=e3&&(!e5||e5.cwd!==Y),er=1===t0.length?es("chat.match"):es("chat.matches",{count:t0.length}),ei=e5?.serverHardTruncated?es("chat.serverIndexTruncated"):e5?.clientTruncated&&!tQ?eB.query?es("chat.searchingAll"):es("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tv,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===e_?"min(48vh, 400px)":`min(48vh, 400px, ${e_}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?es("chat.loadingFiles"):es("chat.files",{label:er,hint:ei})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nh,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:en||0!==t0.length?t0.map((e,t)=>{let n=t===eK,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tb.current[t]=e},type:"button",id:`${nh}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),t4(e)},onMouseEnter:()=>eV(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)(L,{size:14}):$(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,eB?.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:tG&&!tQ?es("chat.searching"):es("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-input-composer${eL?" is-bash-mode":""}`,style:{minWidth:0,display:"flex",flexDirection:Z?"column":"row",gap:8,alignItems:Z?"stretch":"center",background:eL?"color-mix(in srgb, var(--bg-panel) 75%, var(--bg))":"var(--bg)",border:Z?"none":`1px solid ${eL?eR?"rgba(100,116,139,0.45)":"color-mix(in srgb, var(--accent) 45%, var(--border))":s&&(o||l)?"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":eL?"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:[eL&&(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2px 6px",borderRadius:4,background:eR?"rgba(100,116,139,0.12)":"rgba(37,99,235,0.12)",color:eR?"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:eR?"Local":"Shell"})]}),(0,r.jsx)("textarea",{ref:ti,className:"chat-input-textarea",role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-expanded":!!np,"aria-controls":np,"aria-activedescendant":nf,"aria-label":Z?es("chat.quoteQuestion"):es("chat.message"),disabled:a,placeholder:a?es("agentSwitcher.status.queued"):void 0,value:eu,onChange:e=>{tE.current=e.target.value,eh(e.target.value),ez(e.target.selectionStart),e2.current=null,eQ(!1),tJ(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;ez(t.selectionStart),tJ(t.value,t.selectionStart)},onKeyDown:t7,onCompositionStart:()=>{tf.current=!0},onCompositionEnd:e=>{tf.current=!1,tg.current=Date.now();let t=e.currentTarget;ez(t.selectionStart),tJ(t.value,t.selectionStart)},onInput:t9,onPaste:ne,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:eL?"var(--font-mono)":"var(--font-chat)",minHeight:Z?96:24,maxHeight:200,overflow:"auto"}}),s?tq?(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":es("chat.stop"),title:es("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"})})}),l&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.followUp"),onClick:()=>t3("followup"),title:`${es("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:es("chat.followUp")})]}),o&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.steer"),onClick:()=>t3("steer"),title:es("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:es("chat.steer")})]})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.stop"),title:es("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:es("chat.stop")})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":es("chat.send"),title:t_?es("chat.tooManyImagesTitle"):es("chat.send"),onClick:tP,disabled:!tK,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:tK?"var(--accent)":"none",border:"none",borderRadius:5,color:tK?"var(--accent-contrast)":"var(--text-dim)",opacity:tK?1:.45,cursor:tK?"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=>{tK&&(e.currentTarget.style.filter="brightness(1.08)")},onMouseLeave:e=>{tK&&(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:es("chat.send")})]})]})]}),eL&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eR?"var(--text-muted)":"var(--accent)",marginTop:4},children:[es("chat.shell")," \xb7 ",eR?es("chat.outputLocal"):es("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:ts,style:{position:"relative",display:"flex",alignItems:"center"},children:[(0,r.jsx)("button",{type:"button",disabled:a,onClick:()=>{t?ew(e=>!e):tp.current?.click()},title:t?`${es("chat.attachImage")} / ${es("image.title")}`:es("chat.attachImage"),"aria-label":t?`${es("chat.attachImage")} / ${es("image.title")}`:es("chat.attachImage"),"aria-expanded":t?ev: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:ev?"var(--bg-hover)":"none",border:"none",borderRadius:4,color:eE.length?"var(--accent)":ev?"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=eE.length?"var(--accent)":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=ev?"var(--bg-hover)":"none",e.currentTarget.style.color=eE.length?"var(--accent)":ev?"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"})]})}),ev&&t&&(0,r.jsxs)("div",{role:"menu",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),ew(!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:()=>{ew(!1),tp.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:es("chat.attachImage")})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{ew(!1),t()},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:es("image.title")})]})]})]}),(nt.length>0||d||p)&&g&&(0,r.jsx)(rs,{options:nt,value:d,onChange:g,disabled:s,busy:x,isAutoSelection:c})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),ed&&ek&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent"},onClick:()=>{ef(!1),ex(!1),ej(!1)}}),ed&&(ek||ep||eg||ev)&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent",WebkitTapHighlightColor:"transparent"},onClick:()=>{ef(!1),ex(!1),ew(!1),ej(!1),ey(!1)},"aria-hidden":"true"}),(0,r.jsxs)("div",{ref:ta,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto",zIndex:ed&&ek?60:void 0},children:[ed&&nd(!0),ed&&(eo=!!(null!=ns&&ns>=85),(0,r.jsxs)("button",{type:"button",title:ek?es("chat.collapseControls"):es("chat.moreControls"),"aria-label":es("chat.moreControls"),"aria-expanded":ek,onClick:()=>{ek?(ef(!1),ex(!1),ej(!1)):ej(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,maxWidth:"min(48vw, 200px)",height:32,padding:"0 6px",background:ek?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!=ns&&ns>=70&&ns<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)(tY,{size:14,style:{display:"block"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:na})]})),(0,r.jsxs)("div",{ref:tc,className:"chat-input-toolbar-controls",style:{display:ed?ek?"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:[T&&(0,r.jsxs)("div",{ref:tl,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!s&&(ef(!1),ex(e=>!e)),disabled:s,title:es("chat.changeReasoning",{level:ni}),"aria-label":es("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:s?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:s?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{s||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)(tY,{size:14,style:{display:"block"}}),(!ed||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:ni})]}),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:rp.filter(e=>!R||"auto"===e||R.includes(e)).map(e=>{let t=(M??"auto")===e,n=es(rf[e]),i="auto"!==e&&N?N[e]:void 0,o=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{ex(!1),ed&&ej(!1),t||T(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,l&&(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&&nd(!1),!s&&S&&(0,r.jsxs)("div",{ref:to,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!s&&(ex(!1),ef(e=>!e)),disabled:s,title:es("chat.changeToolPreset")+`: ${nl}`,"aria-label":es("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:s?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:s?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{s||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||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:nl})]}),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:rd.map(e=>{let t,n=rc[e],i=(j??rt.Q8)===n;return t="configured"===e?es("chat.configuredTools"):"chat-only"===e?es("chat.chatOnly"):"read-only"===e?es("chat.readOnlyTools",{count:4}):"default"===e?es("chat.builtInTools",{count:4}):es("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ef(!1),ed&&ej(!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)})})]}),!s&&y&&(el=!!(C?.percent&&C.percent>=85),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center"},children:(0,r.jsx)("button",{onClick:()=>{ed&&ej(!1),b?v?.():y?.()},disabled:s&&!b,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",width:ed?"auto":void 0,height:ed?32:28,background:b?"rgba(239,68,68,0.08)":el?"rgba(239,68,68,0.06)":"none",border:el&&!b?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:b||el?"#ef4444":"var(--text-muted)",cursor:s&&!b?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:s&&!b?.5:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{ed||s&&!b||(e.currentTarget.style.background=b?"rgba(239,68,68,0.16)":el?"rgba(239,68,68,0.12)":"var(--bg-hover)",e.currentTarget.style.color=b||el?"#ef4444":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=b?"rgba(239,68,68,0.08)":el?"rgba(239,68,68,0.06)":"none",e.currentTarget.style.color=b||el?"#ef4444":"var(--text-muted)")},title:b?es("chat.stopCompaction"):el?`${es("chat.compactContext")} (${es("chat.contextHighWarning")})`:es("chat.compactContext"),"aria-label":b?es("chat.stopCompaction"):es("chat.compactContext"),children:b?(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||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:es("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||ek)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:es("chat.compact")})]})})})),void 0!==U&&(0,r.jsx)("button",{onClick:()=>{ed&&ej(!1),U?.()},title:O?es("chat.disableSound"):es("chat.enableSound"),"aria-label":O?es("chat.disableSound"):es("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 rP(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),l=e[o-1]??null;for(let e of t)n.has(e)&&(l=e),null!==l&&r.set(e,l);for(let t of e)r.set(t,t);return r}function rA(e,t,n){return n-t>0&&e+t>=n-8?1/0:e+48}function rD(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 rH=n(88576),rB=n.n(rH);function rF({items:e,activeEntryId:t,onJumpToEntry:n,label:o,left:l,top:s,maxHeight:a=360,width:d=310}){var c,u;let h,p,f,{t:g}=(0,m.s)(),x=(0,i.useRef)(null),y=(0,i.useRef)(null),[v,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(0),[C,I]=(0,i.useState)(null),E=(0,i.useRef)(0),M=(0,i.useRef)(null),T=(0,i.useRef)(!1),L=(0,i.useRef)(null),R=(0,i.useRef)(null),N=(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(w,28*u-p)))/28)-1),end:Math.min(u,Math.ceil((f+p)/28)+1)});(0,i.useEffect)(()=>()=>{E.current++,L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),N.current&&clearTimeout(N.current)},[]);let H=(0,i.useCallback)(()=>{L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),N.current&&clearTimeout(N.current),M.current=null,b(!1)},[]),B=(0,i.useCallback)(()=>{R.current&&(clearTimeout(R.current),R.current=null),v||(L.current=setTimeout(()=>{b(!0)},100))},[v]),F=(0,i.useCallback)(e=>{L.current&&(clearTimeout(L.current),L.current=null);let t=document.activeElement;t instanceof HTMLElement&&e.currentTarget.contains(t)&&t.matches(":focus-visible")||(R.current=setTimeout(()=>{H()},150))},[H]);async function O(e){let t=++E.current;I({entryId:e,state:"loading"});try{await n(e),E.current===t&&(I(null),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{H()},160))}catch(n){if(E.current!==t)return;if(n&&"object"==typeof n&&"name"in n&&"AbortError"===n.name)return void I(null);I({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));M.current=n,S(n);let r=y.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&&(M.current=null,t.focus({preventScroll:!0}))}b(!0)}return((0,i.useLayoutEffect)(()=>{if(!v){T.current=!1;return}let e=y.current;if(e){if(!T.current){let t=Math.max(0,W);e.scrollTop=Math.max(0,(t+.5)*28-P/2),S(t),T.current=!0}k(e.scrollTop)}},[v,W,P]),(0,i.useLayoutEffect)(()=>{if(!v||null===M.current)return;let e=y.current?.querySelector(`[data-outline-index="${M.current}"]`);e&&(M.current=null,e.focus({preventScroll:!0}))}),e.length)?(0,r.jsxs)("div",{className:rB().minimap,style:{left:l,top:s},onMouseEnter:B,onMouseLeave:F,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||H()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),H(),x.current?.focus({preventScroll:!0}))},children:[(0,r.jsx)("button",{ref:x,type:"button",className:rB().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)):(L.current&&clearTimeout(L.current),R.current&&clearTimeout(R.current),b(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:rB().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:rB().panel,style:{width:d},children:(0,r.jsxs)("nav",{id:$,className:rB().menu,"aria-label":o,children:[(0,r.jsx)("div",{ref:y,className:rB().list,style:{height:P},onScroll:e=>k(e.currentTarget.scrollTop),children:(0,r.jsx)("div",{className:rB().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:rB().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:rB().rowText,children:n.preview})},n.entryId)})})}),C?.state==="error"&&(0,r.jsxs)("div",{className:rB().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 rO({items:e,scrollContainer:t,contentContainer:n,loadedEntryIds:o,onJumpToEntry:l,label:s}){let[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),h=(0,i.useMemo)(()=>rP(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,l=!0,s=[],a=[],c=new ResizeObserver(()=>f()),p=()=>{o||(o=requestAnimationFrame(g))},f=()=>{l=!0,p()};function g(){if(o=0,l){l=!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"));s=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 x=new Set(g),m=new Set(a);for(let e of a)x.has(e)||c.unobserve(e);for(let e of g)m.has(e)||c.observe(e);a=g}d(rD(s,rA(r.scrollTop,r.clientHeight,r.scrollHeight)))}c.observe(r),c.observe(i);let x=new MutationObserver(f);x.observe(i,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),r.addEventListener("scroll",p,{passive:!0}),window.addEventListener("resize",f);let m=e=>{e.target!==r&&e.target instanceof Node&&e.target.contains(r)&&f()};return window.addEventListener("scroll",m,!0),p(),()=>{cancelAnimationFrame(o),c.disconnect(),x.disconnect(),r.removeEventListener("scroll",p),window.removeEventListener("resize",f),window.removeEventListener("scroll",m,!0)}},[e.length,h,t,n]),!c||c.maxHeight<52||c.width<80)?null:(0,S.createPortal)((0,r.jsx)(rF,{items:e,activeEntryId:a,onJumpToEntry:l,label:s,...c}),document.body)}function rU(e,t,n){let r=JSON.stringify([e,t]),[o,l]=(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||l({key:r,items:e.items??[]})}).catch(()=>{n.signal.aborted||l({key:r,items:[]})}),()=>n.abort()},[e,t,n,r]),e&&o?.key===r)?o.items:[]}function r_({sessionId:e,leafId:t,outlineRevision:n,...i}){let{t:o}=(0,m.s)(),l=rU(e,t,n);return e&&l.length?(0,r.jsx)(rO,{...i,items:l,label:o("chatMinimap.userOutline")},JSON.stringify([e,t])):null}function rq({sessionId:e,leafId:t,outlineRevision:n,scrollContainer:o,contentContainer:l,loadedEntryIds:s,onJumpToEntry:a}){let{t:d}=(0,m.s)(),c=rU(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||!l?.current)return;let e=o.current,t=l.current,n=rP(c.map(e=>e.entryId),s??[]),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(rD(i,rA(e.scrollTop,e.clientHeight,e.scrollHeight)))},[u,c,s,o,l]),(0,i.useEffect)(()=>{u&&g.current&&g.current.scrollIntoView({block:"center"})},[u,p]),u&&c.length&&!("u"<typeof document))?(0,S.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 rK=n(42790);function rV({text:e}){let t=(0,i.useMemo)(()=>new rK.v().ansi_to_html(e),[e]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:t}})}let rJ="/icons/icon-192.png";function rY(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function rZ(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 rX(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 rG(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,icon:rJ,badge:rJ,...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 rQ(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r0(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(!rQ(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=rQ(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=rQ(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 r1 extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function r2(e){return e instanceof r1&&"prompt_rejected"===e.code&&!1===e.accepted}async function r4(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 r1(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let r8="pi-tool-preset";function r5(){try{return window.localStorage}catch{return null}}function r6(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 r3(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,r6(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),r6(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function r7(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 r9(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(r7).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class ie 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 it{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 ie("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof ie?"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 ie("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 ie("closed");if(this.current!==t){if(this.current?.sessionId===e)continue;throw new ie("closed")}if(1===t.source.readyState)return;this.discard(t,new ie("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new ie("closed"));try{t=this.options.createSource(e)}catch(e){throw new ie("closed",e instanceof Error?e.message:String(e))}let i=!1,o=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(a,new ie("ready_timeout"))},this.options.readinessTimeoutMs),s={promise:o,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a={sessionId:e,source:t,attempt:s};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)s.ready=!0,s.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(a,new ie("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new ie("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 ir(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 ii={isStreaming:!1,streamingMessage:null};function io(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 il(e,t){switch(t.type){case"text_start":return io(e,t.contentIndex,()=>({type:"text",text:""}));case"text_delta":return io(e,t.contentIndex,e=>e?.type==="text"?{...e,text:e.text+t.delta}:null);case"text_end":return io(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 io(e,t.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+t.delta,startedAt:e.startedAt??Date.now()}:null);case"thinking_end":return io(e,t.contentIndex,e=>({...e?.type==="thinking"?e:{startedAt:Date.now()},type:"thinking",thinking:t.content,endedAt:Date.now()}));case"toolcall_start":return io(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 io(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 io(e,t.contentIndex,()=>({type:"toolCall",toolCallId:t.toolCall.id,toolName:t.toolCall.name,input:t.toolCall.arguments}));default:return e}}function is(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=r0(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,l=e.endedAt??(n?.type==="thinking"?n.endedAt:void 0);return e.startedAt===o&&e.endedAt===l?e:{...e,startedAt:o,..."number"==typeof l?{endedAt:l}:{}}});return{isStreaming:!0,streamingMessage:{...n,timestamp:r,content:o}}}case"delta":return il(e,t.event);case"deltas":return t.events.reduce(il,e);case"end":return ii;default:return e}}class ia{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 id(e,t,n,r){return e===t&&"string"==typeof n&&n.length>0&&n===r}async function ic(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()&&id(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()&&id(n,e.currentRunId(),i,e.currentSessionId()))return{status:"cancelled_after_dispatch",sessionId:i};return{status:"stale"}}finally{t.forget(n)}}async function iu(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 ih(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 ip=new Map,ig=new Map;function ix(e){return"string"==typeof e?e:e?.text??""}function im(e){return{steering:(e?.steering??[]).map(ix),followUp:(e?.followUp??[]).map(ix)}}function iy(e,t){return e===t||null!==e&&null!==t&&e.tokens===t.tokens&&e.percent===t.percent&&e.contextWindow===t.contextWindow?e:t}let iv=[2e3,5e3,1e4];function ib(e){return new Promise(t=>setTimeout(t,e))}function iw(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ik(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:iw(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iw(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=iw(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function ij(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 iS(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 iC(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 iI({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)(K,{size:12})})}function iE({cwd:e,onChange:t,recentPaths:n,pinnedPaths:o,onTogglePinnedCwd:l,homeDir:s,worktreeInfo:a}){let{t:d}=(0,m.s)(),c=(0,i.useRef)(null),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(!1),[y,v]=(0,i.useState)(!1),[b,w]=(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),I=C?.branch??null,E=j?.projectRoot??e,T=s&&E.startsWith(s)?`~${E.slice(s.length)}`:E,L=()=>{h(!1),f(!1)},R=n=>{n===e?L():(v(!0),t(n).then(L).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")}: ${E}`,"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:T})})}),I&&(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")}: ${I}`,"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:I})]}),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:y,onClick:()=>R(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:y?"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:s&&t.startsWith(s)?`~${t.slice(s.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:()=>l?.(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),x(!0),w(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:y,onClick:()=>R(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:y?"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)(M,{initialPath:e,busy:y,error:b,onCancel:()=>{x(!1),w(null)},onSelect:e=>{v(!0),w(null),t(e).then(()=>x(!1),e=>w(e instanceof Error?e.message:String(e))).finally(()=>v(!1))}})]})}function iM({label:e}){let[t,n]=(0,i.useState)(null);if((0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/app-update",{signal:e.signal}).then(async e=>e.ok?e.json():null).then(e=>{e?.updateAvailable&&e.latestVersion&&e.releaseUrl&&n(e)}).catch(()=>{}),()=>e.abort()},[]),!t)return null;let o=e(t.latestVersion);return(0,r.jsxs)("a",{href:t.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,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",t.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"})]})]})}function iT(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&e_(r))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}function iL(e){return e?.content.at(-1)}function iR(e,t,n,r,i=!1){if(!e)return!1;if(r?.kind==="running_tools")return!0;let o=iL(n);return!!t&&(o?.type==="thinking"||o?.type==="toolCall")||!i}function iN(e,t,n){if(!e)return null;let r=em(e,t);return"edit"===r?n("image.edit"):"generate"===r?n("image.generate"):null}function i$(e,t,n){if(t?.kind==="running_tools"){let e=t.tools[t.tools.length-1]?.name??null;return iN(e,void 0,n)??e}let r=iL(e);return r?.type==="thinking"?n("chat.thinking"):r?.type==="toolCall"?iN(r.toolName,r.input,n)??r.toolName??null:null}function iW(e,t,n,r){return t?(e&&(n.current=e),n.current??r):(n.current=null,null)}function iz(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 iP(e,t){return e<60?t("chat.decodeSeconds",{seconds:e}):t("chat.decodeMinutes",{minutes:Math.floor(e/60),seconds:e%60})}function iA({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:iP(n,t)})}function iD({messageCount:e,toolCallCount:t,durationSeconds:n,startTime:o,defaultExpanded:l=!1,reveal:s=!1,isMobile:a=!1,activeStepSummary:d=null,isStreaming:c=!1,children:u,t:h}){let p,[f,g]=(0,i.useState)(l),x=(0,i.useRef)(null),m=(0,i.useRef)(!1),y=(0,i.useRef)(!1);(0,i.useLayoutEffect)(()=>{y.current||g(l)},[l]);let v=f||s,b=t>0?t:e,w=h(1===b?"chat.step":"chat.steps");if(void 0!==n&&n>0){let e=iP(n,h);p=t>0?h("chat.workedForSteps",{duration:e,count:b,steps:w}):h("chat.workedFor",{duration:e})}else p=`${b} ${w}`;return(0,i.useLayoutEffect)(()=>{if(!v){m.current=!1;return}let e=x.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:()=>{y.current=!0,g(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)(K,{size:12}),o&&(0,r.jsx)(iA,{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:p}),(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:x,onScroll:()=>{let e=x.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 iH({session:e,searchTarget:t,onSearchTargetHandled:o,initialScrollPosition:l,onScrollPositionChange:s,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onDraftChange:u,onKeepTabOpen:h,onNewSessionCwdChange:p,recentProjectPaths:f=[],pinnedCwds:g=[],onTogglePinnedCwd:x,homeDir:y="",worktreeInfo:b=null,draftPersistenceWarning:w=!1,onAgentEnd:k,onAttentionNeeded:C,onSessionCreated:I,onSessionForked:E,modelsRefreshKey:M,chatInputRef:T,isFocusedPane:L=!1,isVisiblePane:R=L,onBranchDataChange:N,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,m.s)(),G=nY(),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,T&&(e?T.current=e:T.current===t&&(T.current=null))},[T]),eo=(0,i.useRef)(null),el=(0,i.useCallback)(()=>{Q&&et.current&&ee.current(),k?.(en.current)},[Q,k]),es=(0,i.useCallback)(e=>{C?.(e,en.current)},[C]),ea=(0,i.useCallback)(e=>{E?.(e,en.current?.id??null)},[E]),ec=(0,i.useCallback)((e,t)=>{H?.(e,en.current?.id??null,t)},[H]),eu=(0,i.useCallback)(()=>{let e=en.current?.id;e&&h?.(e)},[h]),eh=(0,i.useCallback)(e=>{er.current?.replaceMessage(e)},[]),ep=(0,i.useRef)(t?null:l??null),[ef,eg]=(0,i.useState)(()=>{let e=ep.current;return e&&!e.atBottom?e:null}),[em,ey]=(0,i.useState)(!1),{data:ev,loading:eb,error:ew,messages:eS,activeToolResults:eC,entryIds:eE,historyCursor:eM,hasEarlierMessages:eT,streamState:eL,agentRunning:eR,directImageRunning:eN,bashRunning:e$,pendingBash:eW,modelNames:ez,modelList:eH,modelError:eO,modelScopeWarnings:eU,modelThinkingLevels:e_,modelThinkingLevelMaps:eK,toolPreset:eJ,thinkingLevel:eY,retryInfo:eZ,contextUsage:eG,forkingEntryId:eQ,isCompacting:e0,compactError:e2,compactResult:tr,displayModel:ti,modelSwitching:to,sessionStats:tl,slashCommands:ts,slashCommandsLoading:ta,queuedMessages:td,notices:tc,extensionDialog:tu,extensionCustomUi:th,respondToExtensionUi:tp,sendExtensionCustomInput:tf,addNotice:tg,setNoticePaused:tx,isAutoModelSelection:tm,agentPhase:ty,isNew:tv,sessionIdRef:tb,scrollContainerRef:tw,handleSend:tk,handleDirectImageGeneration:tj,abortDirectImageGeneration:tS,handleAbort:tC,handleFork:tI,handleNavigate:tE,handleModelChange:tM,handleCompact:tT,handleSteer:tL,handleFollowUp:tR,handlePromptWithStreamingBehavior:tN,handleAbortCompaction:t$,handleRecallQueue:tW,handleBuiltinSlashCommand:tz,handleToolPresetChange:tP,handleThinkingLevelChange:tA,loadSlashCommands:tD,loadContext:tH,activeLeafId:tB,scrollToBottom:tF,scrollToMessage:tO}=function(e){let{session:t,sessionRunning:r,newSessionCwd:o,newSessionDraftKey:l,onAgentEnd:s,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:h,onSystemPromptChange:p,onSystemToolsChange:f,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:x,isVisiblePane:m=!1}=e,y=null===t&&null!==o,v=o??t?.cwd??"",b=v?`/api/models?cwd=${encodeURIComponent(v)}`:"/api/models",w=ip.get(b)?.data,k=y?iS(w):null,j=k?w?.thinkingLevelPins?.[`${k.provider}/${k.modelId}`]:void 0,[S,C]=(0,i.useState)(null),[I,E]=(0,i.useState)(!y),[M,T]=(0,i.useState)(null),[L,R]=(0,i.useState)(null),[N,$]=(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:N,entryIds:P,oldestEntryId:D,hasMore:B});O.current={messages:N,entryIds:P,oldestEntryId:D,hasMore:B};let[U,_]=(0,i.useReducer)(is,ii),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,el]=(0,i.useState)(()=>w?.modelList??[]),[es,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,ex]=(0,i.useState)(null),[em,ey]=(0,i.useState)(k),[ev,eb]=(0,i.useState)(rt.Q8),[ew,ek]=(0,i.useState)(j??"auto"),[ej,eS]=(0,i.useState)(null),[eC,eI]=(0,i.useState)(null),[eE,eM]=(0,i.useState)(null),[eT,eL]=(0,i.useState)(null),[eR,eN]=(0,i.useState)(null),[e$,eW]=(0,i.useState)(null),[ez,eP]=(0,i.useState)(!1),[eA,eD]=(0,i.useState)(!1),[eH,eB]=(0,i.useState)(!0),[eF,eO]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(null),[eq,eK]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)([]),[eY,eZ]=(0,i.useState)(!1),[eX,eG]=(0,i.useReducer)(ik,{visible:[],pending:[]}),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(null),[e5,e6]=(0,i.useState)({steering:[],followUp:[]}),e7=(0,i.useRef)(null),e9=(0,i.useRef)(null),te=(0,i.useRef)(0),tt=(0,i.useRef)(!1),tn=(0,i.useRef)(!1),tr=(0,i.useRef)(t?.id??null),ti=(0,i.useRef)(t?.id??null),to=(0,i.useRef)(!!r),tl=(0,i.useRef)(m),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(!1),td=(0,i.useRef)(!1),tc=(0,i.useRef)(-1),tu=(0,i.useRef)(!1),th=(0,i.useRef)(!1),tp=(0,i.useRef)(0),tf=(0,i.useRef)(null),tg=(0,i.useRef)(!!e.deferInitialScroll),tx=(0,i.useRef)(!1),tm=(0,i.useRef)(!0),ty=(0,i.useRef)(0),tv=(0,i.useRef)(null),tb=(0,i.useRef)([]),tw=(0,i.useRef)(void 0),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null),tS=(0,i.useRef)(!1),tC=(0,i.useRef)(null),tI=(0,i.useRef)(null),tE=(0,i.useRef)(0),tM=(0,i.useRef)(new ia),tT=(0,i.useRef)(null),tL=(0,i.useRef)(!1),tR=(0,i.useRef)(null),tN=(0,i.useRef)(!1),t$=(0,i.useRef)(u),tW=(0,i.useRef)(new Map),tz=(0,i.useRef)(!0);ti.current=t?.id??null,to.current=!!r,tl.current=m,e7.current||(e7.current=new it({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tf.current?.(e),shouldMaintain:e=>tz.current&&tr.current===e&&(tl.current||ts.current||tt.current||ti.current===e&&to.current),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tP=e.setToolPreset??eb,tA=t?.id;(0,i.useLayoutEffect)(()=>{(tA||y&&!tr.current)&&tP(function(e=r5()){if(!e)return rt.Q8;try{let t=e.getItem(r8);return(0,rt.sn)(t)?t:rt.Q8}catch{return rt.Q8}}())},[tA,y,tP]);let tD=(0,i.useCallback)((e="instant")=>{let t=tk.current;t&&(tm.current=!0,t.scrollTo({top:Math.max(0,t.scrollHeight-t.clientHeight),behavior:e}),ty.current=t.scrollTop)},[]),tH=eR??S?.context.model??e$??null,tB=y?eg??em:tH,tF=t?.id??l??void 0,tO=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tW.current.get(t);if(!e)break;t=e}return t},[]),tU=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),o=tO(r);if(!tz.current&&!tS.current&&r===l)return;let s=e.chatInputRef?.current;if(s)s.restoreSubmission(t,i,o);else{let e,n;o&&(n=nH(t,i,(e=nW(o)??{value:"",images:[]}).value,e.images),nz(o,n))}},[l,e.chatInputRef,tO]),t_=(0,i.useMemo)(()=>{if(eQ)return{...eQ,totalActiveMs:S?.totalActiveMs,...eC?{contextUsage:eC}:{}};let e=S?.stats,n=function(e,t,n){let r=r3(n);if(!e)return r;let i=r3(t),o=(e,t)=>Math.max(0,e-t),l={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 l.total=l.input+l.output+l.cacheRead+l.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:l,cost:e.cost+o(r.cost,i.cost)}}(e,S?.context.messages??[],N);return 0!==n.tokens.total||0!==N.length||e?{sessionFile:S?.filePath||void 0,sessionId:tr.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:S?.totalActiveMs,...eC?{contextUsage:eC}:{}}:null},[N,eQ,eC,S?.context.messages,S?.filePath,S?.totalActiveMs,S?.stats,t?.id,t?.name]),tq=(0,i.useCallback)(async(e,t=!1,n=!1)=>{let r=!1;try{t&&E(!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),R(null),$([]),A([]),H(null),F(!1),eI(null),T(null)),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(tr.current!==e)return null;let s={messages:l.context.messages,entryIds:l.context.entryIds??[],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore},a=t?s: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,s);if(C({...l,context:{...l.context,...a}}),R(l.leafId),$(a.messages),A(a.entryIds),H(a.oldestEntryId),F(a.hasMore),tn.current=void 0!==l.toolNames,tP(void 0!==l.toolNames?(0,rt.YO)(l.toolNames):rt.Q8),eN(e=>tN.current?e:null),T(null),l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ek(l.context.thinkingLevel),void 0!==l.contextUsage&&eI(l.contextUsage??null),r=!0,t&&E(!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(tr.current!==e)return null;let r=n.state;return r?(void 0!==r.contextUsage&&eI(r.contextUsage??null),void 0!==r.systemPrompt&&eM(r.systemPrompt??null),void 0!==r.thinkingLevel&&ek(r.thinkingLevel??"auto"),void 0!==r.queuedMessages&&e6(im(r.queuedMessages))):n.running||e6({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return T(String(e)),null}finally{t&&!r&&E(!1)}},[tP]),tK=(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}`,l=await fetch(o,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let s=await l.json();if(tr.current!==e||r?.signal?.aborted||!tz.current)return;return H(s.context.oldestEntryId),F(s.context.hasMore),C(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...s.context.messages,...t.context.messages],entryIds:[...s.context.entryIds,...t.context.entryIds],oldestEntryId:s.context.oldestEntryId,hasMore:s.context.hasMore}:s.context;return{...t,context:r}}),n?($(e=>[...s.context.messages,...e]),A(e=>[...s.context.entryIds,...e])):($(s.context.messages),A(s.context.entryIds??[])),s.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),tV=(0,i.useCallback)(async e=>{try{let t=await r4(e,{type:"get_tools"});if(!t||!tz.current||tr.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tP(tn.current?r(t):rt.Q8),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,tP]),tJ=(0,i.useCallback)((t=0,n="(no messages)")=>{let r=tr.current;if(y&&o&&r&&!tS.current&&(tS.current=!0,l)){if(l!==r){tW.current.set(l,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(l,r):nB(l,r)}d?.({id:r,path:"",cwd:o,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},l)}},[y,o,l,d,e.chatInputRef]),tY=(0,i.useCallback)(e=>{e instanceof ie||console.error("Failed to maintain the agent event stream:",e)},[]),tZ=(0,i.useCallback)(async()=>{if(tr.current||!y||!o)return tr.current;if(tj.current)return tj.current;let e=(async()=>{let e=tC.current,t=tI.current;e&&eW(e);let n=(0,rt.xG)(ev);tn.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(),l=i.sessionId;return tr.current=l,tl.current&&e7.current?.ensureConnected(l).catch(tY),void 0!==i.contextUsage&&eI(i.contextUsage??null),i.model&&tC.current===e&&(eW(i.model),e||ey(i.model)),i.thinkingLevel&&tI.current===t&&ek(i.thinkingLevel),l})();tj.current=e;try{return await e}finally{tj.current=null}},[tY,y,o,ev]),tX=(0,i.useCallback)(async()=>{let e=tr.current??await tZ();if(!e)return;let[t]=await Promise.all([r4(e,{type:"get_state"}),tV(e)]);tz.current&&tr.current===e&&eM(t.systemPrompt??"")},[tZ,tV]),tG=(0,i.useCallback)(async()=>{let e=tr.current??await tZ();if(!e)return eJ([]),[];eZ(!0);try{let t=await r4(e,{type:"get_commands"}),n=t?.commands??[];return eJ(n),n}catch(e){return console.error("Failed to load slash commands:",e),eJ([]),[]}finally{eZ(!1)}},[tZ]),tQ=(0,i.useCallback)(()=>{te.current+=1,tt.current=!1,e9.current&&(clearTimeout(e9.current),e9.current=null)},[]),t0=(0,i.useCallback)(()=>{e7.current?.close()},[]),t1=(0,i.useCallback)(e=>e7.current.ensureConnected(e),[]),t2=(0,i.useCallback)(e=>{e7.current.maintain(e)},[]),t4=(0,i.useCallback)(e=>{e7.current?.reconnect(e).catch(tY)},[tY]);(0,i.useEffect)(()=>{if(t?.id&&r)return t2(t.id),()=>{tr.current!==t.id||ts.current||tt.current||tl.current||ti.current===t.id&&to.current||e7.current?.close()}},[t2,t?.id,r]),(0,i.useEffect)(()=>{if(!m){ts.current||to.current||tt.current||t0();return}let e=t?.id??tr.current??null;e&&(tQ(),e7.current?.ensureConnected(e).catch(tY))},[tQ,t0,tY,m,t?.id]);let t8=(0,i.useCallback)(async(e,t)=>{let n=tr.current;if(e2(t=>t?.id===e.id?null:t),n)try{await r4(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),t5=(0,i.useCallback)(async(e,t)=>{let n=tr.current;if(n)try{await r4(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),t6=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eG({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"}})},[]),t3=(0,i.useCallback)(t=>{switch(rX(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":e2(t);break;case"notify":t6({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":e8(e=>t.closed?e?.id===t.id?null:e:t)}},[t6,a,e.chatInputRef]),t7=(0,i.useCallback)(()=>{null!==tv.current&&(cancelAnimationFrame(tv.current),tv.current=null);let e=tb.current;0!==e.length&&(tb.current=[],_({type:"deltas",events:e}))},[]),t9=(0,i.useCallback)(e=>{tb.current.push(e),null===tv.current&&(tv.current=requestAnimationFrame(()=>{tv.current=null,t7()}))},[t7]),ne=(0,i.useCallback)(()=>{t7();let e=ts.current;return ts.current=!1,V(!1),eK(null),eS(null),z(new Map),_({type:"end"}),e},[t7]),nt=(0,i.useCallback)(e=>tc.current!==e&&(tc.current=e,s?.(),!0),[s]),nn=(0,i.useCallback)(e=>{if(tl.current&&tr.current===e)return void tQ();tQ(),tt.current=!0;let t=te.current,n=async()=>{if(t===te.current&&tr.current===e&&tt.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!==te.current||tr.current!==e||!tt.current)return;let o=i.state;if(i.running&&o&&(o.isStreaming||o.isPromptRunning)){tt.current=!1,e9.current=null,ta.current=!!o?.isStreaming,td.current=!!o?.isPromptRunning,ts.current=!0,V(!0),eK(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eD(!0),e9.current=setTimeout(()=>void n(),600);return}tt.current=!1,e9.current=null,t0()}catch{if(t!==te.current||tr.current!==e||!tt.current)return;e9.current=setTimeout(()=>void n(),600)}};e9.current=setTimeout(()=>void n(),3e4)},[tQ,t0]),nr=(0,i.useCallback)(async(e=tr.current,t=tE.current)=>{if(tE.current===t)try{e&&await tq(e)}finally{if(tE.current!==t)return;let n=td.current,r=ta.current;td.current=!1,ta.current=!1,tR.current=null;let i=ne();n?nt(t):r&&i&&s?.(),e&&nn(e)}},[tq,nt,s,nn,ne]),ni=(0,i.useCallback)(async(e,t)=>{await ib(800);let n=Date.now();for(;ts.current&&Date.now()-n<2e4;){if(void 0!==t&&tE.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 nr(e,t)}}catch{}await ib(600)}},[nr]),no=(0,i.useCallback)(async e=>{let t=tp.current+1;for(tp.current=t;tu.current&&tp.current===t&&tr.current===e;){await ib(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 tq(e),tp.current!==t||tr.current!==e)return;tu.current=!1,Y(!1),X(null);return}catch{}}},[tq]),nl=(0,i.useCallback)(async e=>{if(!ts.current||tr.current!==e)return;let t=tE.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(tr.current!==e||tE.current!==t)return;let i=r.state;if(eD(i?.isCompacting??!1),e6(im(i?.queuedMessages)),"boolean"==typeof i?.autoCompactionEnabled&&eB(i.autoCompactionEnabled),i?.contextUsage!==void 0&&eI(e=>iy(e,i.contextUsage??null)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){ta.current=!!i.isStreaming,td.current=!!i.isPromptRunning;return}if(!ts.current)return;i&&void 0!==i.systemPrompt&&eM(i.systemPrompt??null),await nr(e,t)}catch{}},[nr]);(0,i.useEffect)(()=>{if(!K)return;let e=()=>{let e=tr.current;e&&nl(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,nl]),(0,i.useEffect)(()=>{let e=()=>{let e=tr.current;if(e&&"hidden"!==document.visibilityState){if(tl.current)return void t4(e);(ts.current||tt.current||ti.current===e&&to.current)&&t2(e)}},t=()=>{"visible"===document.visibilityState&&e()};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[t2,t4]),(0,i.useEffect)(()=>{ts.current=K},[K]),tf.current=(0,i.useCallback)(e=>{switch("message_update"!==e.type&&t7(),e.type){case"connected":_({type:!0===e.isStreaming?"resume":"end"}),!0===e.isStreaming&&(tQ(),ta.current=!0,ts.current=!0,V(!0),eK({kind:"waiting_model"}));break;case"agent_start":tQ(),ta.current=!0,ts.current=!0,V(!0),eK({kind:"waiting_model"}),_({type:"start"});break;case"agent_end":if(!ts.current)break;eK(null),eS(null),_({type:"end"}),tr.current&&(tq(tr.current),fetch(`/api/agent/${encodeURIComponent(tr.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eI(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eM(e.state.systemPrompt??null),e6(im(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=ta.current;if(ta.current=!1,!e||td.current)break;let t=tr.current,n=ne();eD(!1),t&&(tq(t),nn(t)),n&&s?.();break}case"prompt_done":{let e=tE.current,t=td.current;td.current=!1,tR.current=null;let n=nt(e);if(!t&&!n)break;let r=tr.current;r&&tq(r),!ta.current&&(ne(),r&&nn(r))}break;case"prompt_error":t6({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t6({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!ts.current||ir(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&&eK(null)):t&&eK(null)}else{let t=e.assistantMessageEvent;t&&(t9(t),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eK(null))}break;case"message_end":{if(!ts.current||ir(e))break;let t=e.message;if(t&&"user"===t.role){let e=r0(t),n=r9(e),r=tR.current;tR.current=null,$(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&r9(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let e=r0(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:iy(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],l=(o?.type==="thinking"?o.startedAt:void 0)??e.startedAt??t.timestamp,s=(o?.type==="thinking"?o.endedAt:void 0)??e.endedAt??n;return e.startedAt===l&&e.endedAt===s?e:(r=!0,{...e,..."number"==typeof l?{startedAt:l}:{},..."number"==typeof s?{endedAt:s}:{}})});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"}),eK({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;eK(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}),eK(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}),eK(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":e6({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eS({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eS(null);break;case"auto_compaction_start":case"compaction_start":eD(!0),eO(null),e_(null);break;case"auto_compaction_end":case"compaction_end":eD(!1),e.errorMessage?(eO(e.errorMessage),e_(null)):!e.aborted&&(e_(ij(e.result,e.reason??"auto")),tr.current&&tq(tr.current));break;case"extension_ui_request":t3(e);break;case"extension_ui_closed":e2(t=>t?.id===e.id?null:t)}},[t6,tQ,t7,t3,tq,nt,s,t9,nn,ne]);let ns=(0,i.useCallback)(async(e,n)=>{let r=e.trim();if(!r&&!n?.length)return;if(ts.current||tu.current)return void tU(e,n,tF);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 tw.current?.(i,t):void tU(e,n,tF)}let l=tE.current+1;tQ(),td.current=!0;let s=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:s?.length?[...e.trim()?[{type:"text",text:e}]:[],...s]:e,timestamp:Date.now()};$(e=>[...e,a]),tR.current=r9(a),tE.current=l,ts.current=!0,V(!0),eK(i?{kind:"running_command"}:{kind:"waiting_model"}),_({type:"start"}),tx.current=!0,tT.current={runId:l,message:e,images:n,userMsg:a};let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=!1;tM.current.begin(l);let u=async e=>{try{await r4(e,{type:"abort"})}catch(e){t6({type:"error",message:e instanceof Error?e.message:String(e)})}},h=await ic({gate:tM.current,runId:l,currentRunId:()=>tE.current,currentSessionId:()=>tr.current,promptPending:()=>td.current,abandonUnsent:()=>{tT.current?.runId===l&&(tT.current=null,td.current=!1,$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tU(e,n,tF),tR.current=null,tE.current===l&&(ts.current=!1,V(!1),eK(null),_({type:"end"})))},onDispatched:()=>{tT.current?.runId===l&&(tT.current=null)},abort:u,prepare:async()=>{if(y&&o){let e=tr.current??await tj.current;if(tM.current.isCancelled(l))return null;let t=e??await tZ();if(tM.current.isCancelled(l))return null;if(!t)throw Error("Unable to create a session for the prompt");return eg&&(eW(eg),e)&&(await r4(t,{type:"set_model",provider:eg.provider,modelId:eg.modelId}),tM.current.isCancelled(l))?null:(await t1(t),tM.current.isCancelled(l))?null:t}if(t)return(await t1(t.id),tM.current.isCancelled(l))?null:t.id;throw Error("No active session for the prompt")},send:async t=>{let n=await r4(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 ni(h.sessionId,l);if("failed"===h.status){let t=h.error,r=h.sessionId,i=h.requestStarted;return(console.error("Failed to send message:",t),!(!i||r2(t))&&r)?void ni(r,l):(td.current=!1,tT.current?.runId===l&&(tT.current=null),$(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),t6({type:"error",message:t instanceof Error?t.message:String(t)}),tU(e,n,tF),tR.current=null,r)?void nl(r):(ts.current=!1,t0(),V(!1),eK(null),void _({type:"end"}))}if(y&&o&&tJ(1,e),c&&h.sessionId){td.current=!1,ni(h.sessionId,l);return}i&&h.sessionId&&ni(h.sessionId,l)}},[y,o,eg,t,tZ,t1,tJ,ni,t6,tQ,t0,tF,nl,tU]),na=(0,i.useCallback)(async e=>{if(ts.current||tu.current||ee.current)throw Error("Cannot generate an image while the session is busy");let n=crypto.randomUUID();ee.current=!0,et.current=n,en.current=!1,Q(!0);try{let r=t?.id??(y&&o?await tZ():null);if(!r)throw Error("No active session for image generation");if(en.current)throw new DOMException("Image generation cancelled","AbortError");let i=await r4(r,{type:"generate_image_direct",requestId:n,arguments:e});return await tq(r),y&&o&&tJ(1,e.prompt),i}finally{et.current===n&&(ee.current=!1,et.current=null,en.current=!1,Q(!1))}},[tZ,y,tq,o,tJ,t?.id]),nd=(0,i.useCallback)(async()=>{en.current=!0;let e=tr.current,t=et.current;e&&t&&await r4(e,{type:"abort_image_generation",requestId:t})},[]);tw.current=(0,i.useCallback)(async(e,n)=>{if(ts.current||tu.current)return;let r=`${n?"!!":"!"}${e}`;tL.current=!1,tu.current=!0,X({command:e,excludeFromContext:n}),Y(!0);try{let i=await iu({abortRequested:()=>tL.current,prepare:async()=>tr.current??t?.id??await tZ(),send:async t=>{await r4(t,{type:"bash",command:e,excludeFromContext:n})},loadResults:async e=>{tr.current===e&&await tq(e)},restoreUnsent:()=>tU(r,void 0,tF)});("completed"===i.status||"cancelled_after_dispatch"===i.status)&&tJ(1,r)}catch(e){console.error("Failed to execute shell command:",e),t6({type:"error",message:e instanceof Error?e.message:String(e)}),tU(r,void 0,tF)}finally{tu.current=!1,X(null),Y(!1)}},[t6,tF,tZ,tq,tJ,tU,t]);let nc=(0,i.useCallback)(async()=>{var e;let n=tE.current,r=tr.current,i=async e=>{if(r&&!th.current){th.current=!0;try{await r4(r,{type:e})}catch(e){console.error("Failed to abort:",e),t6({type:"error",message:e instanceof Error?e.message:String(e)})}finally{th.current=!1}}};if(tu.current){tL.current=!0,await i("abort_bash");return}let o=tT.current;(tM.current.isInFlight(n)||o?.runId===n)&&tM.current.cancel(n);let l=!!(o&&o.runId===n&&tM.current.shouldAbandonUnsent(n));if(l&&o){tT.current=null,td.current=!1,$(e=>{let t=e.lastIndexOf(o.userMsg);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tU(o.message,o.images,tF),tR.current=null,ts.current=!1,V(!1),eK(null),_({type:"end"});return}let s=(e={bashRunning:!1,hasSessionId:!!r,localUnsent:l,agentRunning:ts.current||td.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"!==s&&r&&await i("abort_bash"===s?"abort_bash":"abort")},[t6,tF,tU,t]),nu=(0,i.useCallback)(async e=>{if(tu.current)return;let t=tr.current;if(t){eL(e);try{let{cancelled:n,newSessionId:r}=await r4(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e)}finally{eL(null)}}},[c]),nh=(0,i.useCallback)(async e=>{if(tu.current)return;let t=tr.current;t&&(r4(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),R(e),await tK(t,e))},[tK]),np=(0,i.useCallback)(async e=>{if(tu.current)return;R(e);let t=tr.current;t&&(await tK(t,e),e&&r4(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tK]),nf=(0,i.useCallback)(async(e,t)=>{if(y){let n={provider:e,modelId:t};tC.current=n,ex(n),eW(n);let r=tr.current??await tj.current;if(!r)return;try{await r4(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tr.current;if(n&&!tN.current){tN.current=!0,eN({provider:e,modelId:t}),eP(!0);try{await r4(n,{type:"set_model",provider:e,modelId:t}),tN.current=!1,await tq(n)}catch(e){console.error("Failed to set model:",e),tN.current=!1,eN(eR),t6({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await tq(n)}finally{tN.current=!1,eP(!1)}}},[t6,eR,y,tq,ex]),ng=(0,i.useCallback)(async()=>{let e=tr.current;if(e&&!eA){eD(!0),eO(null),e_(null);try{let t=await r4(e,{type:"compact"});e_(ij(t,"manual")),await tq(e,!0)}catch(e){eO(e instanceof Error?e.message:String(e)),e_(null)}finally{eD(!1)}}},[eA,tq]),nx=(0,i.useCallback)(async(e,t=!1,n)=>{let r;try{r=await function(e,t,n={}){let r=ip.get(e);if(!n.force&&r&&r.loadedAt+6e4>Date.now())return Promise.resolve(r.data);let i=ig.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(ip.delete(e),ip.set(e,{data:t,loadedAt:Date.now()});ip.size>32;){let e=ip.keys().next().value;if(void 0===e)break;ip.delete(e)}return t}).finally(()=>{ig.get(e)?.promise===o&&ig.delete(e)});return ig.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??{}),el(r.modelList??[]),y&&!tr.current){let e=iS(r);ey(e);let t=e&&r.thinkingLevelPins?.[`${e.provider}/${e.modelId}`];null===tI.current&&ek(t??"auto")}},[y,b]),nm=(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=tr.current??await tZ(),l=e=>(e.handled&&(e.error?t6({type:"error",message:e.error}):"openSessionStats"!==e.action&&t6({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eA)return l({handled:!0,error:"No active session to compact"});eD(!0),eO(null),e_(null);let e=await r4(o,{type:"compact",...i?{customInstructions:i}:{}});return e_(ij(e,"manual")),await tq(o,!0)&&tJ(),l({handled:!0,message:"Compacted context"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await r4(o,{type:"reload"}),await Promise.all([tq(o,!1,!0),tV(o),tG(),nx(void 0,!0)]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return l({handled:!0,error:"No active session to name"});if(!i)return l({handled:!0,error:"Usage: /name <name>"});return await r4(o,{type:"set_session_name",name:i}),await tq(o)&&tJ(),l({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});let e=await r4(o,{type:"get_session_stats"});return e&&e0(e),x?.(),l({handled:!0,action:"openSessionStats"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await r4(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),l({handled:!0,message:"Copied last assistant message"})}case"auto-compact":{if(!o)return l({handled:!0,error:"No active session"});let e=await r4(o,{type:"get_state"}),t=!("boolean"!=typeof e?.autoCompactionEnabled||e.autoCompactionEnabled);return await r4(o,{type:"set_auto_compaction",enabled:t}),eB(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"clone":{if(!o)return l({handled:!0,error:"No active session to clone"});if(ts.current||tu.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=await r4(o,{type:"clone",leafId:L});if(e?.cancelled||!e?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=l({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}case"bug":{if(!o)return l({handled:!0,error:"No active session to report"});if(ts.current||tu.current)return l({handled:!0,error:"Cannot report a bug while the session is running"});let e=await r4(o,{type:"bug_report",...i?{hint:i}:{}});if(!e)return l({handled:!0,error:"Bug report failed"});return l({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 l({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eD(!1)}},[L,t6,tZ,eA,nx,tq,tG,tV,tJ,c,x]),ny=(0,i.useCallback)(async(e,t,n)=>{let r=tr.current;if(!r){tU(e,n,tF),t6({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 r4(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),r2(t)&&tU(e,n,tF),t6({type:"error",message:t instanceof Error?t.message:String(t)})}},[t6,tF,tU]),nv=(0,i.useCallback)(async(e,t)=>{await ny(e,"steer",t)},[ny]),nb=(0,i.useCallback)(async(e,t,n)=>{await ny(e,t,n)},[ny]),nw=(0,i.useCallback)(async(e,t)=>{await ny(e,"followUp",t)},[ny]),nk=(0,i.useCallback)(async()=>{let e=tr.current;if(e)try{await r4(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nj=(0,i.useCallback)(async()=>{let e=tr.current;if(e)try{let t=await r4(e,{type:"clear_queue"});e6({steering:[],followUp:[]});let n=[...ih(t?.steering),...ih(t?.followUp)];if(0===n.length)return;tU(n.map(e=>e.text).filter(Boolean).join("\n\n"),n.flatMap(e=>e.images).map(e=>({...e,previewUrl:""})),tF)}catch(e){console.error("Failed to recall queued messages:",e),t6({type:"error",message:e instanceof Error?e.message:"Failed to recall queued messages"})}},[t6,tF,tU]),nS=(0,i.useCallback)(async e=>{if(ek(e),y&&!tr.current&&(tI.current="auto"===e?null:e),"auto"===e)return;let t=tr.current??await tj.current;if(t)try{await r4(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[y]),nC=(0,i.useCallback)(async e=>{let t=(0,rt.xG)(e);!function(e,t=r5()){if(t)try{t.setItem(r8,e)}catch{}}(e),tP(e);let n=tr.current??await tj.current;if(!n){tn.current=void 0!==t;return}try{let e=await r4(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});tn.current=void 0!==t;let r=e?.sessionId??n,i=e?.recreated===!0;r!==n&&(tQ(),t0(),tr.current=r),eJ([]),tl.current&&(i||r!==n)&&t4(r);let[o]=await Promise.all([r4(r,{type:"get_state"}),tV(r)]);tz.current&&tr.current===r&&eM(o.systemPrompt??"")}catch(e){console.error("Failed to set tools:",e)}},[tQ,t0,tV,t4,tP]),nI=(0,i.useCallback)((e,t=16)=>{let n=tk.current;n&&(tg.current=!0,tx.current=!1,tm.current=!1,n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),ty.current=n.scrollTop)},[]),nE=(0,i.useCallback)(()=>{let e=tk.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=ts.current,o=tm.current,l=function(e,t,n,r,i,o=96){return!!e3(n,r,i)||!(n<t)&&(!!(!e&&n>t&&e3(n,r,i,o))||e)}(o,ty.current,t,n,r,i?96:8);tm.current=l,ty.current=t,!o&&l&&i&&tD("instant")}},[tD]);(0,i.useEffect)(()=>(tz.current=!0,t&&(tr.current=t.id,tq(t.id,!0,!0).then(e=>{e?.running&&(tV(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(ta.current=!!e.state.isStreaming,td.current=!!e.state.isPromptRunning,ts.current=!0,V(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),_({type:"resume"}),t2(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&ni(t.id)),e.state?.isBashRunning&&(tu.current=!0,Y(!0),no(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eD(e.state.isCompacting),"boolean"==typeof e.state.autoCompactionEnabled&&eB(e.state.autoCompactionEnabled),void 0!==e.state.contextUsage&&eI(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eM(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&ek(e.state.thinkingLevel??"auto"),void 0!==e.state.queuedMessages&&e6(im(e.state.queuedMessages)))})),()=>{tz.current=!1,null!==tv.current&&cancelAnimationFrame(tv.current),tv.current=null,tb.current=[],tp.current+=1,tQ(),t0()}),[]),(0,i.useEffect)(()=>{p?.(eE)},[eE,p]),(0,i.useEffect)(()=>(g?.(tX),()=>g?.(null)),[tX,g]),(0,i.useEffect)(()=>{h&&h(S?.tree??[],L,np)},[S?.tree,L,np,h]),(0,i.useEffect)(()=>{let e=tk.current;if(e)return ty.current=e.scrollTop,e.addEventListener("scroll",nE,{passive:!0}),()=>{e.removeEventListener("scroll",nE)}},[N.length,I,nE]),(0,i.useLayoutEffect)(()=>{N.length>0&&(tx.current?(tx.current=!1,tg.current=!0,tD("instant")):tg.current?tm.current&&tD("instant"):(tg.current=!0,tD("instant")))},[N.length,K,tD,U.streamingMessage]),(0,i.useEffect)(()=>{let e=new AbortController,t=t$.current!==u;return t$.current=u,(async()=>{for(let n=0;;n++)try{await nx(e.signal,t,u);return}catch(t){if(e.signal.aborted||t instanceof DOMException&&"AbortError"===t.name||n>=iv.length||(await ib(iv[n]),e.signal.aborted))return}})(),()=>e.abort()},[nx,u]),(0,i.useEffect)(()=>{if(!eU)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eU]);let[nM,nT]=(0,i.useState)(null),nL=(0,i.useRef)(5e3),nR=(0,i.useRef)(null),nN=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===eX.visible.length){nN.current=null;return}let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eG({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=eX.visible[0];if(!t||(nN.current!==t.id&&(nN.current=t.id,nL.current=5e3),eX.visible.some(e=>e.id===nM)))return;nR.current=Date.now();let n=setTimeout(()=>{eG({type:"mark_oldest_exiting"})},nL.current);return()=>{clearTimeout(n),null!==nR.current&&(nL.current=Math.max(0,nL.current-(Date.now()-nR.current)),nR.current=null)}},[eX.visible,nM]),(0,i.useEffect)(()=>{e0(null)},[N.length,eC?.tokens,eC?.percent,eC?.contextWindow]),{data:S,loading:I,error:M,activeLeafId:L,messages:N,activeToolResults:W,entryIds:P,historyCursor:D,hasEarlierMessages:B,streamState:U,agentRunning:K,directImageRunning:G,modelNames:er,modelList:eo,modelError:es,modelScopeWarnings:ed,modelThinkingLevels:eu,modelThinkingLevelMaps:ep,newSessionModel:eg,toolPreset:ev,thinkingLevel:ew,retryInfo:ej,contextUsage:eC,systemPrompt:eE,forkingEntryId:eT,isCompacting:eA,autoCompactionEnabled:eH,compactError:eF,compactResult:eU,currentModel:tH,displayModel:tB,modelSwitching:ez,sessionStats:t_,slashCommands:eV,slashCommandsLoading:eY,queuedMessages:e5,notices:eX.visible,extensionDialog:e1,extensionCustomUi:e4,respondToExtensionUi:t8,sendExtensionCustomInput:t5,isAutoModelSelection:y&&null===eg,agentPhase:eq,isNew:y,sessionIdRef:tr,scrollContainerRef:tk,initialScrollDoneRef:tg,handleSend:ns,handleDirectImageGeneration:na,abortDirectImageGeneration:nd,handleAbort:nc,handleFork:nu,handleNavigate:nh,handleModelChange:nf,handleCompact:ng,handleSteer:nv,handleFollowUp:nw,handlePromptWithStreamingBehavior:nb,handleAbortCompaction:nk,handleRecallQueue:nj,handleBuiltinSlashCommand:nm,addNotice:t6,setNoticePaused:nT,handleToolPresetChange:nC,handleThinkingLevelChange:nS,loadTools:tV,loadSlashCommands:tG,setActiveLeafId:R,setData:C,setMessages:$,loadContext:tK,scrollToBottom:tD,scrollToMessage:nI,dispatch:_,setAgentRunning:V,setForkingEntryId:eL,bashRunning:J,pendingBash:Z,handleAgentEventRef:tf}}({session:e,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onAgentEnd:el,onAttentionNeeded:es,onSessionCreated:I,onSessionForked:ea,modelsRefreshKey:M,chatInputRef:er,onBranchDataChange:N,onSystemPromptChange:$,onSystemToolsChange:W,onSystemInfoLoaderChange:z,onSessionStatsPanelOpen:A,deferInitialScroll:!!ef,isVisiblePane:R}),tU=eR||eN||e$,t_=(0,i.useCallback)(()=>eN?tS():tC(),[tS,eN,tC]),tq=(0,i.useRef)(null),tK=tl?tl.tokens.input+tl.tokens.cacheRead+tl.tokens.cacheWrite:0,tV=tl&&tK>0?tl.tokens.cacheRead/tK*100:null,[tJ,tY]=(0,i.useState)(null),tZ=tv&&0===eS.length&&!eL.isStreaming&&!tU&&null===tJ,[tX,tG]=(0,i.useState)(!1),[tQ,t0]=(0,i.useState)(null),[t1,t2]=(0,i.useState)(!1),[t4,t8]=(0,i.useState)(null),[t5,t6]=(0,i.useState)(0),[t3,t7]=(0,i.useState)(null),[ne,nt]=(0,i.useState)(!1),[nn,nr]=(0,i.useState)(!1),[ni,no]=(0,i.useState)(null),nl=(0,i.useRef)(null),ns=(0,i.useRef)(null),na=(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?t0(t.config):(t0(null),t2(!1),t8(null))}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load image generation config:",e)}),()=>e.abort()},[t5,M]);let nd=(0,i.useCallback)(async t=>{eu();let n=null;for(let e=eS.length-1;e>=0;e--){let t=ex(eS[e].details);if(t){n=t;break}}let r=e?.cwd??d,i=t.target,o=i&&(i.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(i)?i:r?j(r,i):i);tY({prompt:t.prompt,size:t.size,width:n?.width,height:n?.height,previewUrl:o?`/api/files/${v(o)}?type=read`:void 0});try{await tj(t)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;tg({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tY(null)}},[tg,tj,eu,eS,d,e?.cwd]),nc=(0,i.useCallback)(async e=>{let t=await tz(e);return!("error"in t)&&/^\/reload(?:\s|$)/.test(e.trim())&&t6(e=>e+1),t},[tz]),nu=(0,i.useCallback)(()=>{t7(null),nt(!1),no(null)},[]);(0,i.useEffect)(()=>{O||nu()},[O,nu]);let nh=(0,i.useCallback)(e=>{let t=na.current;if(t&&!(null!=e&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)||!O||ne)return;let n=window.getSelection(),r=n?.rangeCount?n.getRangeAt(0):null,i=nS.current;if(!n||n.isCollapsed||!r||!i||!i.contains(r.commonAncestorContainer))return void t7(null);let o=n.toString().trim();if(!o)return void t7(null);let l=r.getBoundingClientRect(),s=[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);t7({text:o,top:Math.min(window.innerHeight-44,l.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,l.left+l.width/2)),sourceEntryId:s})},[O,ne]);(0,i.useEffect)(()=>{ne&&t3&&ns.current?.insertIfEmpty(e5(t3.text,X("chat.quoteIntro"),X("chat.quoteQuestion")))},[ne,t3,X]),(0,i.useLayoutEffect)(()=>{let e=nl.current;if(!e||!t3)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(t3.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(t3.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)}},[t3,ne,ni]),(0,i.useEffect)(()=>{if(!t3)return;let e=e=>{if(ne||nl.current?.contains(e.target))return;na.current={x:e.clientX,y:e.clientY};let t=()=>{document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),queueMicrotask(()=>{na.current=null})};document.addEventListener("pointerup",t),document.addEventListener("pointercancel",t),nu()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),nn||nu())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[t3,ne,nn,nu]);let np=(0,i.useCallback)(()=>{t3&&(er.current?.insertText(e5(t3.text,X("chat.quoteIntro"),X("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),nu())},[t3,nu,X]),nf=(0,i.useCallback)(async t=>{let n=tb.current??e?.id;if(!nn&&t.trim()&&t3?.sourceEntryId&&n&&F){nr(!0),no(null),J?.();try{await F(t,n,t3.sourceEntryId),nu()}catch(e){ns.current?.restoreSubmission(t),no(e instanceof Error?e.message:String(e))}finally{nr(!1)}}},[F,t3,nn,e?.id,tb,nu,J]),ng=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(eb||ew||!U||ng.current)return;let t=tb.current??e?.id;t&&(ng.current=!0,_?.(t),eu(),tk(U))},[U,eb,ew,tk,_,eu,e?.id,tb]),(0,i.useEffect)(()=>{Q&&tu&&eo.current!==tu.id&&(eo.current=tu.id,ee.current())},[Q,tu]);let[nx,nm]=(0,i.useState)(0),[ny,nv]=(0,i.useState)(50),nb=(0,i.useRef)(null),nw=(0,i.useRef)(null),nk=(0,i.useRef)({startIndex:0,endIndex:0,totalCount:0}),nj=(0,i.useRef)(null),nS=(0,i.useRef)(null),nC=(0,i.useRef)(null),nI=(0,i.useRef)(!1),nE=(0,i.useRef)(null),[nM,nT]=(0,i.useState)(null),nL=(0,i.useRef)(!1),nR=(0,i.useRef)(tB),nN=(0,i.useRef)(ef);nN.current=ef;let[n$,nP]=(0,i.useState)(null),nA=eS[eE.indexOf(n$?.entryId??"")],nD=nA?.role==="assistant"?n$?.blockIndex===void 0?nA.content.find(e=>"text"===e.type):nA.content[n$.blockIndex]:void 0,nF=(0,i.useRef)({entryIds:eE,historyCursor:eM,hasEarlierMessages:eT});nF.current={entryIds:eE,historyCursor:eM,hasEarlierMessages:eT},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=tw.current,r=nS.current;if(t&&s&&n&&r)return()=>{if(nN.current)return;if(e3(n.scrollTop,n.clientHeight,n.scrollHeight))return void s(t,{atBottom:!0});let e=n.getBoundingClientRect().top,i=iC(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&&s(t,{atBottom:!1,...i,oldestEntryId:nF.current.historyCursor})}},[eb,s,tw,e?.id]),(0,i.useEffect)(()=>{t&&eg(null)},[t]);let nO=(0,i.useCallback)(async(e,t,n)=>{do await new Promise(e=>requestAnimationFrame(()=>e())),n.throwIfAborted();while(nI.current);nI.current=!0;try{let r=nF.current;await tt(e,{entryIds:r.entryIds,oldestEntryId:r.historyCursor,hasMore:r.hasEarlierMessages},e=>tH(t,tB,e,{signal:n}),n)}finally{nI.current=!1}},[tB,tH]),nU=(0,i.useRef)(nO);nU.current=nO;let n_=(0,i.useCallback)(()=>{let e=nk.current;nm(e.totalCount-e.endIndex),nv(50)},[]);(0,i.useEffect)(()=>{let n=e?.id;if(!ef||!n||eb||t||nL.current)return;nL.current=!0,nE.current?.abort();let r=new AbortController;nE.current=r,nT(null),nP(null);let i=()=>{ey(!1),eg(null)};return(async()=>{try{if(await nU.current(ef.anchorEntryId,n,r.signal),r.signal.aborted)return void i();ey(!0)}catch(e){if(tn(e,r.signal))return void i();tF("instant"),eg(null)}})(),()=>{r.abort(),nE.current===r&&(nE.current=null),eg(null),ey(!1)}},[eb,ef,tF,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=nS.current;if(!ef||!e||t)return;let n=e.querySelector(`[data-entry-id="${CSS.escape(ef.anchorEntryId)}"]`);if(n){n_(),tO(n,ef.anchorOffset),eg(null);return}em&&(tF("instant"),eg(null))},[eE,n_,ef,em,tF,tO,t,ny,nx]),(0,i.useEffect)(()=>{if(!t||eb)return;nE.current?.abort();let e=new AbortController;nE.current=e,nT(null),nP(null);let n=t.sessionId;return(async()=>{try{if(await nU.current(t.entryId,n,e.signal),e.signal.aborted)return;nC.current=null,nP(t)}catch(n){if(tn(n,e.signal))return;tg({type:"warning",message:"other_branch"===(n instanceof e7&&"exhausted"===n.reason?function(e,t,n){if(!t||!n)return"not_found";let r=te(t,n);return!r||r.some(t=>e9(t,e))?"not_found":te(t,e)?"other_branch":"not_found"}(t.entryId,ev?.tree,tB):"not_found")?X("chat.locateOtherBranch"):n instanceof e7&&"stalled"===n.reason?X("chat.locateHistoryStalled"):n instanceof e7&&"load_failed"===n.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")}),o?.(t)}})(),()=>{e.abort(),nE.current===e&&(nE.current=null)}},[tB,tg,ev?.tree,eb,o,t,X]),(0,i.useLayoutEffect)(()=>{var e;let n=n$?`[data-entry-id="${CSS.escape(n$.entryId)}"]`:null,r=n?tw.current?.querySelector(nA?.role==="user"?n:`${n} [data-search-target]`)??tw.current?.querySelector(n):null,i=(e={pending:n$??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?nP(null):r&&n$&&(n_(),tO(r),r.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500}),nP(null),o?.(n$)))},[eE,n_,eS.length,ny,n$,t,nA,tw,tO,o,nx]),(0,i.useEffect)(()=>{nm(0),nv(50)},[e?.id]),(0,i.useEffect)(()=>{let e=tw.current;e&&(tU||eL.isStreaming)&&e3(e.scrollTop,e.clientHeight,e.scrollHeight)&&nm(0)},[tU,eL.isStreaming,tw]),(0,i.useEffect)(()=>{let e=tw.current;if(!e)return void tG(!1);let t=()=>{let t=e.scrollHeight-e.scrollTop-e.clientHeight;tG(nx>0||t>160)},n=()=>{t(),nE.current||nx>0||e3(e.scrollTop,e.clientHeight,e.scrollHeight)&&(nm(0),nv(50))};t();let r=new ResizeObserver(t);return r.observe(e),nS.current&&r.observe(nS.current),e.addEventListener("scroll",n,{passive:!0}),()=>{r.disconnect(),e.removeEventListener("scroll",n)}},[tZ,eb,tw,e?.id,nx]);let nq=(0,i.useCallback)(()=>{if(nI.current||nE.current)return;let t=tw.current;if(nk.current.startIndex>0){let e=nS.current;if(e&&t){let n=t.getBoundingClientRect().top;nj.current=iC(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)}nm(e=>e+25),nv(50);return}if(!eT||!eM)return;let n=e?.id??tb.current;n&&(nI.current=!0,t&&(nC.current=t.scrollHeight-t.scrollTop),tH(n,tB,eM).finally(()=>{nI.current=!1}))},[eM,eT,e,tB,tH,tb,tw]);(0,i.useEffect)(()=>{let e=nb.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nq()},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nq,tw]),(0,i.useEffect)(()=>{let e=nw.current,t=tw.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&!nE.current&&nm(e=>Math.max(0,e-25))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nx,tw]),(0,i.useLayoutEffect)(()=>{let e=nj.current,t=nS.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&&tO(n,e.anchorOffset),nj.current=null},[nx,tO]),(0,i.useEffect)(()=>{if(null==nC.current)return;let e=tw.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nC.current),nC.current=null}},[eS.length,tw]);let nK=tl?[tl.sessionId,tl.sessionFile??"",tl.sessionName??"",tl.userMessages,tl.assistantMessages,tl.toolCalls,tl.toolResults,tl.totalMessages,tl.tokens.input,tl.tokens.output,tl.tokens.cacheRead,tl.tokens.cacheWrite,tl.tokens.total,tl.cost??0,tl.totalActiveMs??0,tl.contextUsage?.percent??"null",tl.contextUsage?.contextWindow??"",tl.contextUsage?.tokens??"null"].join("|"):null,nV=(0,i.useRef)(tl);nV.current=tl,(0,i.useEffect)(()=>{eb||P?.(nV.current)},[eb,nK,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let nJ=eG?`${eG.percent??"null"}|${eG.contextWindow}|${eG.tokens??"null"}`:null,nZ=(0,i.useRef)(eG);nZ.current=eG,(0,i.useEffect)(()=>{eb||D?.(nZ.current)},[nJ,eb,D]),(0,i.useEffect)(()=>()=>{D?.(null)},[D]);let{isDragOver:nX,handleDragEnter:nG,handleDragOver:nQ,handleDragLeave:n0,handleDrop:n1}=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))},[]),l=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:o,handleDragOver:l,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)},[])),n2=e?.cwd??d??void 0,n4=(0,i.useMemo)(()=>eS.filter(e=>eD(e)||"assistant"===e.role||"toolResult"===e.role&&!e.isError&&ex(e.details)),[eS]),n8=(0,i.useMemo)(()=>{let e=new Map(eC);for(let t of eS)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[eC,eS]),n5=(0,i.useMemo)(()=>eS.map(e=>"assistant"===e.role?eV(e):null),[eS]),n6=(0,i.useMemo)(()=>{let e=new Map;for(let t=0;t<eS.length;){let n=eD(eS[t])?t:-1,r=n>=0?t+1:t;for(;r<eS.length&&!eD(eS[r]);)r+=1;let i=iT(eS,n,r);if(i>=0&&n5[i]?.answerMessage){let t=[];for(let e=n+1;e<=i;e+=1){let n=eS[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")||e4(e)||e8(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=eX(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),l=t?i(t).replace(/\/+$/,""):void 0,s=/^[a-zA-Z]:\//.test(o),a=o.startsWith("//");if(s||a)n=o;else if(o.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${o}`:o}else{if(!l)return null;n=`${l}/${o}`}return e1(n)}(e,n);t&&(r.has(t)||(r.add(t),i.push({filePath:t})))}}return i}(t,n8,n2))}t=r}return e},[n5,n2,eS,n8]),n3=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eS.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}(eS[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eS]),n7=(Y=n4.length,(Z=(0,i.useRef)([])).current=Array(Y).fill(null).map((e,t)=>Z.current[t]??null),Z),n9=(0,i.useMemo)(()=>{for(let e=eS.length-1;e>=0;e--)if(eS[e]?.role==="user")return eE[e]??"";return""},[eE,eS]);(0,i.useEffect)(()=>{let e=nR.current;nR.current=tB,null!==e&&e!==tB&&(nE.current?.abort(),nN.current&&(eg(null),ey(!1)))},[tB]),(0,i.useEffect)(()=>()=>{nE.current?.abort()},[e?.id]);let re=(0,i.useCallback)(async t=>{let n=e?.id??tb.current;if(!n)return;nE.current?.abort();let r=new AbortController;nE.current=r,nT(null),nP(null);try{nC.current=null,nj.current=null,await nO(t,n,r.signal),r.signal.throwIfAborted(),await new Promise((e,n)=>{r.signal.addEventListener("abort",()=>n(r.signal.reason),{once:!0}),nT({entryId:t,signal:r.signal,resolve:e})})}catch(e){if(tn(e,r.signal))return;tg({type:"warning",message:e instanceof e7&&"stalled"===e.reason?X("chat.locateHistoryStalled"):e instanceof e7&&"load_failed"===e.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")})}finally{nT(e=>e?.signal===r.signal?null:e),nE.current===r&&(nE.current=null)}},[tg,nO,e?.id,tb,X]);(0,i.useLayoutEffect)(()=>{if(!nM||nM.signal.aborted)return;let e=nS.current?.querySelector(`[data-entry-id="${CSS.escape(nM.entryId)}"]`);e&&(n_(),tO(e),nM.resolve())},[nM,eE,n_,eS.length,ny,nx,tO]);let rn=!!eL.streamingMessage?.content.length,rr=(0,i.useMemo)(()=>{let e=-1;for(let t=eS.length-1;t>=0;t--)if(eD(eS[t])){e=t;break}let t=e>=0&&eA(eS[e])?e:e+1;for(let e=t;e<eS.length;e++){let t=eS[e];if("custom"===t.role||"assistant"===t.role&&(eB(t).length>0||eF(t)))return!0}return!1},[eS]),ri=eL.streamingMessage?.role==="assistant"?eL.streamingMessage:null,ro=ri?eV(ri,{isStreaming:!0}):{processMessage:null,answerMessage:null},rl=(0,i.useRef)(L);(0,i.useLayoutEffect)(()=>{let e=rl.current;rl.current=L,!e&&L&&tU&&!tX&&tF("instant")},[L,tU,tX,tF]);let rs=ti?e_[`${ti.provider}:${ti.modelId}`]??null:null,ra=ti?eK[`${ti.provider}:${ti.modelId}`]??null:null,rd=(0,i.useCallback)(async(e,t)=>{eu(),nE.current?.abort(),nT(null),nP(null),nm(0),nv(50),await tk(e,t)},[tk,eu]),rc=(0,i.useCallback)(e=>(eu(),tI(e)),[tI,eu]),ru=(0,i.useCallback)((e,t)=>(eu(),tL(e,t)),[tL,eu]),rh=(0,i.useCallback)((e,t)=>(eu(),tR(e,t)),[tR,eu]),rp=(0,i.useCallback)((e,t,n)=>(eu(),tN(e,t,n)),[tN,eu]),rf=!tv&&eb,rg=e?.relation?.kind==="subagent"&&"queued"===e.relation.status,rx=(0,r.jsx)(rz,{ref:ei,onSend:rd,onOpenImageGeneration:!tQ||rf||tU||rg?void 0:()=>{t8(null),t6(e=>e+1),t2(!0)},onAbort:t_,onSteer:eR?ru:void 0,onFollowUp:eR?rh:void 0,onPromptWithStreamingBehavior:eR?rp:void 0,isStreaming:tU||rg,disabled:rg,model:rf?null:ti,isAutoModelSelection:!rf&&tm,modelNames:ez,modelList:eH,modelError:rf?null:eO,modelScopeWarnings:rf?[]:eU,onModelChange:rf||rg?void 0:tM,modelSwitching:to,onCompact:!rg&&(e||tv)?tT:void 0,onAbortCompaction:t$,isCompacting:e0,compactError:e2,compactResult:tr,contextUsage:rf?null:eG,cacheHitRate:tV,onOpenSessionStats:A,toolPreset:eJ,onToolPresetChange:!rg&&(e||tv)?tP:void 0,thinkingLevel:rf?void 0:eY,onThinkingLevelChange:rf||rg?void 0:e||tv?tA:void 0,availableThinkingLevels:rs,thinkingLevelMap:ra,retryInfo:eZ,queuedMessages:td,inputHistory:n3,onRecallQueue:tW,slashCommands:ts,slashCommandsLoading:ta,onLoadSlashCommands:tD,onBuiltinCommand:nc,soundEnabled:q,onSoundToggle:K,onAudioUnlock:J,draftKey:e?.id??c??void 0,onDraftChange:u,draftPersistenceWarning:w,cwd:e?.cwd??d});return eb?(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:rx})]}):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:nG,onDragOver:nQ,onDragLeave:n0,onDrop:n1,children:[nX&&(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)(iF,{notices:tc,floating:!0,onPauseChange:tx})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[t1&&tQ&&(0,r.jsx)(eI,{config:tQ,edit:t4,editPreviewUrl:t4?`/api/files/${v(t4.path.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(t4.path)?t4.path:n2?j(n2,t4.path):t4.path)}?type=read`:void 0,onClose:()=>{t2(!1),t8(null)},onSubmit:nd}),tu&&(0,r.jsx)(iO,{request:tu,onRespond:tp},tu.id),th&&(0,r.jsx)(iU,{request:th,onInput:tf},th.id),!tZ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:tw,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:nS,onPointerUp:nh,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=eS.length-1;e>=0;e--)if(eD(eS[e])){o=e;break}let l=new Map,s=0;eS.forEach((e,t)=>{let n=("toolResult"!==e.role||e.isError)&&("custom"!==e.role||e.customType!==ed)?null:ex(e.details);(eD(e)||"assistant"===e.role||n)&&l.set(t,s++)});let a=(t,n={})=>{var i,o;let s,a,d,c=n.messageOverride??eS[t],u="user"===c.role&&t>0&&"assistant"===eS[t-1].role?eE[t-1]:void 0,h=("toolResult"!==c.role||c.isError)&&("custom"!==c.role||c.customType!==ed)?null:ex(c.details),p=eD(c)||"assistant"===c.role||!!h,f=l.get(t),g=n.keyPrefix??"message",x=eE[t]??t,m=h?(0,r.jsx)(ek,{value:h,cwd:n2,onEdit:tQ&&!tU&&tQ.connections.some(e=>e.id===h.connection&&!0===e.capabilities.editing)?e=>{t8(e),t6(e=>e+1),t2(!0)}:void 0,onMention:tQ?e=>{er.current?.mentionImage(e)}:void 0,showPrompt:"custom"===c.role,createdAt:c.timestamp},`${g}-image-${x}`):(0,r.jsx)(t9,{message:c,modelName:n.isTurnEnd&&"assistant"===c.role?(i=c.provider??"",o=c.model??"",s=i.toLowerCase(),a=o.toLowerCase(),d=Object.entries(ez??{}).flatMap(([e,t])=>{let n=e.indexOf(":");return n>0&&e.slice(0,n).toLowerCase()===s?[{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(ez??{}).find(([e])=>e.toLowerCase()===a)?.[1]??(i&&o?`${i}/${o}`:o)):void 0,toolResults:n8,cwd:n2,onOpenFile:ec,onOpenSession:B,entryId:eE[t],searchBlock:eE[t]===n$?.entryId?nD:void 0,onFork:tU||tv?void 0:rc,forking:eQ===eE[t],onNavigate:tU?void 0:tE,prevAssistantEntryId:tU?void 0:u,onEditContent:eh,isTurnEnd:n.isTurnEnd,sessionId:e?.id??tb.current??void 0,writtenFiles:n.writtenFiles,isProcess:n.isProcess},`${g}-view-${x}`);return p?(0,r.jsx)("div",{"data-entry-id":eE[t],"data-slot-index":`msg-${t}`,ref:!1===n.attachRef||void 0===f?void 0:e=>{n7.current[f]=e},children:m},`${g}-${x}`):m},d=(n={outline:nM?{entryId:nM.entryId,aborted:nM.signal.aborted}:null,search:n$?{entryId:n$.entryId,matchesTarget:n$===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<eS.length;){let t,n,i,s=eD(eS[e]),u=eP(eS[e]),f=s?e:-1,g=f>=0&&eA(eS[f]),x=s?e+1:e;for(;x<eS.length&&!eD(eS[x]);)x+=1;let m=s?f:e,y=g?f:f+1,v=iT(eS,f,x),b=(tU||eL.isStreaming)&&x===eS.length&&f===o;if(b&&(p=x-m),-1===v&&!g){for(let e=m;e<x;e++)h([eE[e]]),c.push(a(e));if(b&&ro.processMessage){h([]);let e=iR(!0,eL.isStreaming,ri,ty,!!ro.answerMessage),t=f>=0&&"number"==typeof eS[f]?.timestamp&&Number.isFinite(eS[f].timestamp)?eS[f].timestamp:ro.processMessage.timestamp,n=iz(t,ro.processMessage.completedAt);c.push((0,r.jsx)("div",{children:(0,r.jsx)(iD,{messageCount:1,toolCallCount:eq(ro.processMessage.content??[]),durationSeconds:n,startTime:t,defaultExpanded:!0,isMobile:G,activeStepSummary:iW(i$(ro.processMessage,ty,X),e,tq,X("chat.thinking")),isStreaming:e,t:X,children:(0,r.jsx)(t9,{message:ro.processMessage,isStreaming:!0,isProcess:!0,toolResults:n8,cwd:n2,onOpenFile:ec,onOpenSession:B},"streaming-process-view")})},`process-group-${eE[m]??m}`))}e=x;continue}u&&(h([eE[f]]),c.push(a(f)));let w=n5[v],k=w?.answerMessage??null,j=v>=0?v:x-1,S=[],C=[],I=[],E=0,M=!1;for(let e=y;e<=j;e++){let r=eS[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??=l.get(e),M||=!!(d&&d===eE[e]),eE[e]&&C.push(eE[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",isProcess:!0}));continue}if("assistant"!==r.role)continue;let o=n5[e];e!==v&&o?.answerMessage&&I.push({idx:e,message:o.answerMessage});let s=o?.processMessage;if(!s)continue;let c=eB(s),u=!!eF(s);(0!==c.length||u)&&(t??=l.get(e),E+=eq(c),M||=!!(d&&eE[e]===d&&(!nD||n$?.entryId!==d||c.includes(nD))),eE[e]&&C.push(eE[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",messageOverride:s,isTurnEnd:!1,isProcess:!0})))}b&&ro.processMessage&&S.push((0,r.jsx)(t9,{message:ro.processMessage,isStreaming:!0,isProcess:!0,toolResults:n8,cwd:n2,onOpenFile:ec,onOpenSession:B},"streaming-process-view"));let T=!!(k||ro.answerMessage),L=iR(b,eL.isStreaming,ri,ty,T),R=iW(i$(ri,ty,X),L,tq,X("chat.thinking")),N=f>=0&&"number"==typeof eS[f]?.timestamp&&Number.isFinite(eS[f].timestamp)?eS[f].timestamp:n,$=iz(N??n,i);S.length>0&&(h(C),c.push((0,r.jsx)("div",{"data-entry-id":eE[y],ref:void 0===t?void 0:e=>{n7.current[t]=e},children:(0,r.jsx)(iD,{messageCount:S.length,toolCallCount:E,durationSeconds:$,startTime:N??n,defaultExpanded:!k&&x===eS.length,reveal:M,isMobile:G,activeStepSummary:R,isStreaming:L,t:X,children:S})},`process-group-${eE[m]??m}`)));for(let e=m;e<=j;e++){let t=eS[e];"toolResult"===t.role&&!t.isError&&ex(t.details)&&(h([eE[e]]),c.push(a(e)))}for(let e of I)h([eE[e.idx]]),c.push(a(e.idx,{keyPrefix:"promoted",messageOverride:e.message}));if(k&&(h([eE[v]]),c.push(a(v,{isTurnEnd:!0,messageOverride:k,writtenFiles:n6.get(v)}))),v>=0)for(let e=v+1;e<x;e++)h([eE[e]]),c.push(a(e));e=x}let f=Math.max(ny,50+p),{startIndex:g,endIndex:x}=u>=0?e6(i=c.length,i-Math.max(0,u-5)-50):e6(c.length,nx,f);nk.current={startIndex:g,endIndex:x,totalCount:c.length};let m=g>0||eT;return(0,r.jsxs)(r.Fragment,{children:[m&&(0,r.jsx)("button",{type:"button",ref:nb,onClick:nq,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,x),x<c.length&&(0,r.jsx)("div",{ref:nw,className:"py-3 text-center text-xs text-text-muted"})]})})(),eL.isStreaming&&ro.answerMessage&&(0,r.jsx)(t9,{message:ro.answerMessage,isStreaming:!0,cwd:n2,onOpenFile:ec,onOpenSession:B}),eR&&!rn&&!rr&&(0,r.jsx)(iI,{label:X("chat.agentWorking")}),e$&&!eW&&(0,r.jsx)(iI,{label:X("chat.agentWorking")}),eW&&(0,r.jsx)(t9,{message:{role:"bashExecution",command:eW.command,output:"",excludeFromContext:eW.excludeFromContext},sessionId:e?.id??tb.current??void 0,onOpenSession:B}),tJ&&(0,r.jsx)(ej,{prompt:tJ.prompt,size:tJ.size,width:tJ.width,height:tJ.height,previewUrl:tJ.previewUrl})]})})}),tX&&!ef&&(0,r.jsx)("button",{type:"button",onClick:()=>{nE.current?.abort(),nT(null),nP(null),nm(0),nv(50),requestAnimationFrame(()=>tF("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&&R&&(0,r.jsx)(rq,{sessionId:e?.id??tb.current,leafId:tB,outlineRevision:n9,scrollContainer:tw,contentContainer:nS,loadedEntryIds:eE,onJumpToEntry:re}),!R||G||ef?null:(0,r.jsx)(r_,{sessionId:e?.id??tb.current,leafId:tB,outlineRevision:n9,scrollContainer:tw,contentContainer:nS,loadedEntryIds:eE,onJumpToEntry:re})]})]}),O&&t3&&(0,S.createPortal)((0,r.jsx)("div",{ref:nl,role:ne?"dialog":"toolbar","aria-label":X(ne?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:t3.top,left:t3.left,zIndex:130,display:"flex",flexWrap:"wrap",gap:2,width:ne?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:ne?12:2,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)"},children:ne?(0,r.jsxs)("fieldset",{disabled:nn,"aria-busy":nn,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:nn,onClick:nu,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)(rz,{ref:ns,compact:!0,onSend:nf,onAbort:nu,isStreaming:!1}),ni&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:ni})]}):(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:np,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"@"}),(0,r.jsx)("span",{children:X("chat.askInCurrent")})]}),F&&t3.sourceEntryId&&!tU&&(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:()=>{nt(!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:[tZ&&(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)(iM,{label:e=>X("appUpdate.releaseNotes",{version:e})})]}),d&&p&&(0,r.jsx)(iE,{cwd:d,onChange:p,recentPaths:f,pinnedPaths:g,onTogglePinnedCwd:x,homeDir:y,worktreeInfo:b})]}),rx]}),tZ&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function iB({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 iF({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)(iB,{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 iO({request:e,onRespond:t}){let{t:n}=(0,m.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[s,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:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(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)(tJ,{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)(tJ,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(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=>l(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 iU({request:e,onInput:t}){let{t:n}=(0,m.s)(),o=(0,i.useRef)(null),l=(0,i.useRef)(!1),[s,a]=(0,i.useState)(!1),d=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eT,""),i=eL(e).trimEnd();if(t.test(i))continue;let o=e,l=e$(o);("│"===l||"┃"===l)&&" "===e$(o=eN(o,0))&&(o=eN(o,0));let s=function(e){let t=eR(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=s>=0?eR(o)[s]?.char:void 0;("│"===a||"┃"===a)&&(o=eN(o,s)),n.push(function(e){let t=e;for(;;){let e=eR(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&&""===eL(n[0]).trim();)n.shift();for(;n.length>0&&""===eL(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)(()=>{s||o.current?.focus()},[s]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(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(l.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=ez[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":" ":eW[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(l.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:n=>{l.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)(rV,{text:d.join("\n")})})]})})}function i_({tabs:e,activeTabId:t,splitTabId:n=null,activePane:o="primary",runningSessionIds:l,onSelectTab:s,onCloseTab:a,onPinTab:d,onNewTab:c,onToggleSplit:u,onClosePane:h,canSplit:p=!0,isSecondaryPane:f=!1,unifiedHeader:g=!1,isMobile:x=!1}){let{t:y}=(0,m.s)(),[v,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(!1),[j,C]=(0,i.useState)(!1),[I,E]=(0,i.useState)({top:0,left:0,width:320}),M=(0,i.useRef)(null),T=(0,i.useRef)(null),L=(0,i.useRef)(null),R=(0,i.useRef)(null);(0,i.useEffect)(()=>{M.current&&M.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),(0,i.useEffect)(()=>{let e=T.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();R.current&&t.includes(R.current)||L.current&&t.includes(L.current)||C(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),C(!1),L.current?.focus())},n=()=>C(!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)(()=>{w||C(!1)},[w]);let N=!!(n&&!x),$=e=>{let t=e?Array.from(document.querySelectorAll("[data-chat-tab-id]")).find(t=>t.dataset.chatTabId===e):null,n=M.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":y("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:T,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&&l?.has(i.session.id));return(0,r.jsxs)("div",{"data-chat-tab":"true","data-chat-tab-id":i.id,ref:u?M:void 0,role:"tab","aria-label":i.dirty?`${i.title}, ${y("chatTabs.unsentDraft")}`:i.title,"aria-selected":p,tabIndex:f||!t&&0===c?0:-1,onClick:()=>s(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(),s(i.id);else if(["ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault();let n=(c+("ArrowRight"===t.key?1:-1)+e.length)%e.length;s(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:x?4:6,height:"100%",paddingLeft:x?8:10,paddingRight:x?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:x?130:200,minWidth:x?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 ${y("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)(K,{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:y("chatTabs.unsentDraft"),"aria-hidden":"true",style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",flexShrink:0}}),(!x||p)&&(0,r.jsx)("button",{type:"button",tabIndex:-1,onClick:e=>{e.stopPropagation(),a(i.id)},onDoubleClick:e=>e.stopPropagation(),onMouseEnter:()=>b(i.id),onMouseLeave:()=>b(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:x?22:20,height:x?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:y("chatTabs.closeTab",{defaultValue:"关闭标签"}),"aria-label":`${y("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:x?"-4px 0 10px -2px rgba(0,0,0,0.18)":void 0,zIndex:2,position:"relative"},children:[w&&!x&&(0,r.jsx)("button",{ref:L,type:"button",onClick:()=>{if(j)return void C(!1);let e=L.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}),C(!0)},"aria-expanded":j,title:y("chatTabs.allTabs"),"aria-label":y("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:y("chatTabs.newTab",{defaultValue:"新建对话标签"}),"aria-label":y("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&&!x&&u&&(0,r.jsx)("button",{type:"button",onClick:u,"aria-pressed":N,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:N?"var(--bg-selected)":"transparent",border:"none",color:N?"var(--accent)":"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:N?y("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):y("chatTabs.splitView",{defaultValue:"向右分屏"}),"aria-label":N?y("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):y("chatTabs.splitView",{defaultValue:"向右分屏"}),onMouseEnter:e=>{N||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{N||(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:y("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),"aria-label":y("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,S.createPortal)((0,r.jsx)("div",{ref:R,role:"dialog","aria-label":y("chatTabs.allTabs"),style:{position:"fixed",top:I.top,left:I.left,width:I.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&&l?.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:()=>{C(!1),s(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)(K,{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=T.current;if(e&&e.scrollWidth>e.clientWidth+1){let e=R.current?.querySelectorAll("[data-tab-menu-close]"),t=e?.[Math.min(i,e.length-1)];if(t)return void t.focus()}C(!1),$()})},title:`${y("chatTabs.closeTab")}: ${e.title}`,"aria-label":`${y("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 iq(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 iK(e){return e.pane??"primary"}function iV(e,t){return e.filter(e=>iK(e)===t)}function iJ(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&&iK(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 iY(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 iZ(e,t){let n=[...iV(e,"primary"),...iV(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 iX(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 iG(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 iQ(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),l=iK(e[i]),s=iV(e,l),a=iV(o,l),d=a[Math.min(s.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"===l?u:c;return{tabs:iZ(o,e),nextActiveTabId:e,nextSplitTabId:null}}return{tabs:o,nextActiveTabId:c,nextSplitTabId:u}}var i0=n(50640);let i1={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"},i2={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"},i4={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function i8(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i5(e){return null!==(i1[i8(e)]??null)}function i6(e){return null!==(i2[i8(e)]??null)}function i3(e){return null!==(i4[i8(e)]??null)}function i7(e){let t;return null!==("pdf"===(t=i8(e))||"docx"===t?t:null)}let i9=new Set(["md","mdx","html","htm"]);var oe=n(73620);let ot=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function on(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 or(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 oi=/^ {0,3}(`{3,}|~{3,})/,oo=/^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*#*[ \t]*$/,ol=["tags","categories","keywords","tag","category"];function os({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=ol.find(t=>Array.isArray(e[t])),l=o?e[o].map(on).filter(Boolean):[],s=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}),l.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:l.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),s.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:s.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=on(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 oa({items:e,scrollRoot:t}){let{t:n}=(0,m.s)(),o=(0,i.useId)(),l=(0,i.useRef)(null),[s,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(!s)return;let e=e=>{l.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)}},[s]),0===e.length)return null;let h=e.map(()=>!1);if(u)for(let t=0;t<e.length;t++){let n=or(e,t);n>=0&&(h[n]=!0)}return(0,r.jsxs)("div",{ref:l,className:"file-outline",children:[(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button","aria-expanded":s,"aria-haspopup":"menu","aria-controls":o,"aria-label":n("i18n.outline"),title:n("i18n.outline"),onClick:()=>a(e=>!e),style:{background:s?"var(--bg-selected)":"transparent",color:s?"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"})]})}),s&&(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=or(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 od(e,t,n){var r;return r=n??(i9.has(i8(e))?"preview":void 0),t?.displayMode??r??"source"}let oc={fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.6},ou={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 oh(){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 op(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function of(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=op(n.startContainer),i=op(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let o=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(o)||!Number.isInteger(l))return null;if(o<l){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]")&&(l=Number((i=e).dataset.lineNumber))}}}return o>l?null:{startLine:o,endLine:l}}function og({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,o)=>{let l=e.children??[],s=l[0]?.properties?.className,a=Array.isArray(s)&&s.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":o+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,i0.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,i0.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${o}-${r}`}))})]},`source-line-${o}`)})}function ox(e,t,n,r={}){let i=v(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 om({filePath:e,sourceSessionId:t}){let{t:n}=(0,m.s)();return(0,r.jsx)("a",{href:ox(e,"download",t),download:b(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 oy(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ov({patch:e}){let{t}=(0,m.s)(),n=(0,i.useMemo)(()=>{let t;return(t=tQ(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%",...oc},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:{...ou,width:40,minWidth:40,paddingInline:6},children:e.oldLineNo}),(0,r.jsx)("span",{style:{...ou,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 ob({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),y=(0,i.useRef)(null),v=(0,i.useRef)(0),w=b(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));y.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&h(e.size),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(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),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),y.current===r&&(y.current=null)}},[e,n,o]);let j=ox(e,"read",n,d?{v:d}:void 0),S=null!=u?oy(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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),S&&(0,r.jsx)("span",{children:S}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(om,{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:j,alt:e,onLoad:e=>{let t=e.currentTarget;f({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function ow(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 ok({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),y=(0,i.useRef)(null),v=(0,i.useRef)(0),w=b(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));y.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&h(e.size),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(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),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),y.current===r&&(y.current=null)}},[e,n,o]);let j=ox(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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"audio"}),null!=p&&(0,r.jsx)("span",{children:ow(p)}),null!=u&&(0,r.jsx)("span",{children:oy(u)}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(om,{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:j,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x("Failed to load audio"),style:{width:"100%"}},j)]})})]})}function oj({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),y=(0,i.useRef)(null),v=(0,i.useRef)(0),w=b(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),f(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),y.current&&(y.current.close(),y.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));y.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&h(e.size),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(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),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),y.current===r&&(y.current=null)}},[e,n,o]);let j=ox(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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:w||"video"}),null!=p&&(0,r.jsx)("span",{children:ow(p)}),null!=u&&(0,r.jsx)("span",{children:oy(u)}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(om,{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:j,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},j)]})})]})}function oS({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0,pdfPage:l}){let{t:s}=(0,m.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),x=(0,i.useRef)(null),y=(0,i.useRef)(0),v=i8(e),w="pdf"===v,j=w?ox(e,"read",n,c?{v:c}:void 0)+(l?`#page=${l}`:""):ox(e,"preview",n,c?{v:c}:void 0);return(0,i.useEffect)(()=>{u(0),p(null),g(null),d(!1);let t=!0,r=++y.current;return fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{t&&r===y.current&&(e.error&&g(e.error),"number"==typeof e.size&&(p(e.size),!w&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===y.current&&g(String(e))}),()=>{t=!1}},[e,w,n]),(0,i.useEffect)(()=>{if(d(!1),x.current&&(x.current.close(),x.current=null),!o)return;let t=!0,r=new EventSource(ox(e,"watch",n));x.current=r,r.addEventListener("connected",()=>{let r;d(!0),r=++y.current,fetch(ox(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===y.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(p(e.size),!w&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),u(e=>e+1)}}).catch(e=>{t&&r===y.current&&g(String(e))})}),r.addEventListener("change",e=>{y.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(p(t.size),!w&&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(),x.current===r&&(x.current=null)}},[e,w,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:k(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===v?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:oy(h)}),(0,r.jsx)(om,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(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:j,sandbox:w?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:b(e)}),style:{width:"100%",height:"100%",border:"none",background:w?"var(--bg)":"#eef1f5"}},j)})]})}function oC({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u=!0,pdfPage:h}){let p="diff"===od(e,d,a);return!p&&i5(e)?(0,r.jsx)(ob,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&i6(e)?(0,r.jsx)(ok,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&i3(e)?(0,r.jsx)(oj,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&i7(e)?(0,r.jsx)(oS,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u,pdfPage:h}):(0,r.jsx)(oI,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u})}function oI({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:o,onMentionLines:l,onAtMention:s,gitRefreshKey:a,initialDisplayMode:d,initialState:c,onStateChange:u,watchEnabled:h=!0}){let{isDark:p}=tO(),{t:f}=(0,m.s)(),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(null),[b,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[I,E]=(0,i.useState)(null),[M,T]=(0,i.useState)(!0),[L,R]=(0,i.useState)(!1),[N,$]=(0,i.useState)(null),W=od(e,c,d),z="diff"===W&&(i5(e)||i6(e)||i3(e)||i7(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,el]=(0,i.useState)(null);ei.current=u;let es=(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(ox(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,x(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(j(!0),E(null),!t){v(null),j(!1),C(!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||E(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),E(e instanceof Error?e.message:String(e)))}finally{n===Q.current&&(j(!1),C(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;if(T(!0),$(null),x(null),v(null),C(!1),E(null),K(!1),Y.current=null,Z.current=0,G.current=!1,z)return T(!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&&T(!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(ox(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=y?.supported===!0&&"string"==typeof y.patch,eh=eu&&"deleted"===y.status;(0,i.useEffect)(()=>{S&&!eu&&"diff"===F&&es("source")},[F,S,eu,es]),(0,i.useEffect)(()=>{"diff"===W&&eu&&!et.current&&(et.current=!0,es("diff"))},[W,eu,es]);let ep=(0,i.useMemo)(()=>g?.language==="markdown"?tg(g.content):"",[g]),ef=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=ot.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,oe.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=oi.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=oo.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]),ex=g?.content??"",em=(0,i.useMemo)(()=>ex.split("\n"),[ex]),ey=g?.language??"text",ev="html"===ey,eb="markdown"===ey,ew=!g?.truncated&&(ev||eb),ek=eh?"diff":"preview"!==F||ew?F:"source",ej=(em.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)(t_.A,{className:U?"file-source-view is-wrapped":"file-source-view",language:"text"===ey?"plaintext":ey,style:p?tC.xJ:tC.vs,showLineNumbers:!0,lineNumberStyle:{...ou},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...oc,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)(og,{...e,wrapLines:U}),wrapLongLines:U,children:ex}):null,[p,ey,eS,ex,U]),eI=(0,i.useMemo)(()=>ej?em.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:ou,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,[em,ej,U]);(0,i.useEffect)(()=>{let e=()=>{let e=ee.current;el(t=>{let n=l&&"source"===F&&e?of(e,window.getSelection()):null;return null===t&&null===n||t&&n&&t.startLine===n.startLine&&t.endLine===n.endLine?t:n})};if(e(),l&&"source"===F)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,F,l]);let eE=(0,i.useCallback)(n=>{l&&n&&l(k(e,t),n.startLine,n.endLine,t)},[t,e,l]);if((0,i.useEffect)(()=>{if(!l||"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?of(n,window.getSelection()):null;r&&(e.preventDefault(),eE(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[F,eE,l]),(0,i.useEffect)(()=>{if(!en.current||M||N&&!eh||"diff"===W&&!S||"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,N,S,eu,eh,M,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]),M||"diff"===W&&b&&!S)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&&S&&I)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:I});if(N&&!("diff"===ek&&eu))return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:N});if(!g&&!("diff"===ek&&eu))return null;let eM=w(e),eT=!g||eh?["diff"]:["source",...ew?["preview"]:[],...eu?["diff"]:[]],eL=eh?f("files.deleted"):g?`${ey} \xb7 ${em.length} lines \xb7 ${oy(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:k(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eL,children:eL}),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:[eT.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":f("i18n.fileViewMode"),children:eT.map(e=>{let t=ek===e;return(0,r.jsx)("button",{type:"button",onClick:()=>es(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)(oa,{items:eg,scrollRoot:ee}),(s||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{eo&&l?eE(eo):s?.(k(e,t),!1,t)},title:eo&&l?`${f("i18n.mentionSelectedLines")} (L${eo.startLine}${eo.startLine!==eo.endLine?`-L${eo.endLine}`:""})`:f("files.insertPath"),"aria-label":f("files.mention"),disabled:!s&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(oh,{})}),"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)(om,{filePath:e,sourceSessionId:n})]})]}),g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",children:[(0,r.jsxs)("span",{children:[oy(g.nextOffset)," / ",oy(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:L,onClick:()=>{R(!0),ed(e,g.nextOffset).finally(()=>R(!1))},children:L?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)(ov,{patch:y.patch}):ev&&"preview"===ek?(0,r.jsx)("iframe",{srcDoc:ex,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)(os,{data:ef.data}),(0,r.jsx)(tr.oz,{remarkPlugins:tk,rehypePlugins:tS,urlTransform:o?tp: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)(tq,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tV,{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 l=o?e2(e,eM,t??eM):null;return l&&o?(0,r.jsx)("a",{href:e,...i,onClick:e=>{eG(e)&&(e.preventDefault(),o(l))},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 l="string"==typeof e?e2(e,eM,t??eM):null,s=l?ox(l,"read",n):e;return(0,r.jsx)("img",{src:s,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)",...oc},children:eI}):eC})]})}function oE(e,t){if(t<=0)return"";let n=Math.max(0,e.length-1-t);return e.slice(n,-1).join("/")||e[0]||""}function oM(e,t){return t?`${e} \xb7 ${t}`:e}function oT(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function oL({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:o}){let{t:l}=(0,m.s)(),[s,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||b(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=y(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),l=!0;for(;l;){l=!1;let t=r.map((t,r)=>oM(e,oE(n[r],o[r]))),s=oT(t);for(let e=0;e<r.length;e+=1)!((s.get(t[e])??0)<=1)&&(o[e]>=i[e]||(o[e]+=1,l=!0))}let s=r.map((t,r)=>oM(e,oE(n[r],o[r]))),a=oT(s);r.forEach((n,r)=>{t.set(n.id,(a.get(s[r])??0)>1?e:s[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?l("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"})]}):$(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:s===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:s===i.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:l("terminal"===i.kind?"terminal.close":"i18n.close"),"aria-label":`${l("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 oR(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 oN=["general","models","agents","images","skills","plugins"],o$="pi-web:settings-navigation",oW=new Set(["skills","agents","plugins"]);function oz(){try{return window.localStorage}catch{return null}}function oP(e){let t=e.getItem(o$);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 oA(e,t){return"models"===e?e:t?JSON.stringify([e,t]):null}function oD(e,t=oz()){if(t)try{let n=oP(t);n.section=e,t.setItem(o$,JSON.stringify(n))}catch{}}function oH(e,t,n=oz()){if(!n)return null;let r=oA(e,t);if(!r)return null;try{let e=oP(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function oB(e,t,n,r=oz()){if(!r||!t)return;let i=oA(e,n);if(i)try{let e=oP(r);e.selections={...e.selections,[i]:t},r.setItem(o$,JSON.stringify(e))}catch{}}let oF="pi-auto-session-title";function oO(){try{return"false"!==window.localStorage.getItem(oF)}catch{return!0}}let oU=["input","output","cacheRead","cacheWrite"];function o_(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 oq(e){if(!oK(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 oK(e){return oU.some(t=>""!==e[t].trim())}let oV=["name","reasoning","thinkingLevelMap","input","contextWindow","maxTokens","cost","headers","compat"];function oJ(e,t){return`${e}/${t}`}function oY(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function oZ(e){let t=e.trim(),n=t.match(nM),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 oX(e,t){let n=t.trim();return oY(e).filter(e=>e!==n)}function oG(e){let t=oY(e);return t.length>0&&t.every(e=>null!==oZ(e))}function oQ({embedded:e,title:t,subtitle:n,closeLabel:i="Close",onClose:o,children:l,width:s=900,height:a="78vh"}){let d=e?void 0:{"--config-panel-width":`${s}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"})]}),l]})})}function o0({children:e}){return(0,r.jsx)("div",{className:"config-split-view",children:e})}function o1({children:e}){return(0,r.jsx)("aside",{className:"config-sidebar",children:e})}function o2({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-list",children:e})}function o4({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-group-label",children:e})}function o8({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 o5({className:e,...t}){return(0,r.jsx)("span",{...t,className:["config-sidebar-text",e].filter(Boolean).join(" ")})}function o6({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-stack",e].filter(Boolean).join(" ")})}function o3({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header",e].filter(Boolean).join(" ")})}function o7({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header-info",e].filter(Boolean).join(" ")})}function o9({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-actions",e].filter(Boolean).join(" ")})}function le({children:e}){return(0,r.jsx)("div",{className:"config-detail-title",children:e})}function lt({children:e}){return(0,r.jsx)("div",{className:"config-section-title",children:e})}function ln({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 lr({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function li({children:e,style:t}){return(0,r.jsx)("div",{className:"config-detail",style:t,children:e})}function lo({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 ll({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 ls({checked:e,disabled:t=!1,loading:n=!1,label:i,onChange:o}){let l=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:l,className:`config-switch${n?" is-loading":""}`,onClick:()=>o(!e),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function la({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 ld({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 lc={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 lu({id:e,size:t}){let n=lc[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 lh(){let e=oH("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if("runtime-model"===t.type&&"string"==typeof t.providerName&&"string"==typeof t.id)return{type:"runtime-model",providerName:t.providerName,id:t.id};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}function lp(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}}let lf=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function lg({label:e,children:t}){return(0,r.jsx)(ln,{label:e,children:t})}let lx={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function lm({value:e,onChange:t,placeholder:n,mono:i,disabled:o}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,disabled:o,style:{...lx,fontFamily:i?"var(--font-mono)":"inherit",opacity:o?.7:1}})}function ly({value:e,onChange:t,placeholder:n,mono:o,onKeyDown:l,autoComplete:s="off",spellCheck:a=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:h}=(0,m.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:n,style:{...lx,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:s,spellCheck:a}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":h(c?"i18n.hideDetails":"i18n.showDetails"),title:h(c?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:c?(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 lv({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:lx})}function lb({value:e,onChange:t,options:n,required:i}){let{t:o}=(0,m.s)();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...lx,color:e?"var(--text)":"var(--text-dim)"},children:[!i&&(0,r.jsxs)("option",{value:"",children:["— ",o("i18n.default")," / none —"]}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function lw({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function lk({children:e}){return(0,r.jsx)(lt,{children:e})}function lj({providerId:e,provider:t,usableRefs:n,selectedModelIndex:o,onChange:l,onDelete:s,onAddModel:a,onAddModels:d,onSelectModel:c}){let{t:u}=(0,m.s)(),[h,p]=(0,i.useState)({phase:"idle"}),[f,g]=(0,i.useState)(""),[x,y]=(0,i.useState)([]),v=(0,i.useRef)(0),b=(0,i.useRef)(null),w=(e,n)=>l({...t,[e]:n});(0,i.useEffect)(()=>{t.api||l({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{v.current+=1,p({phase:"idle"}),g(""),y([])},[e,t.baseUrl,t.api,t.apiKey]);let k=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===h.phase)return;let n=++v.current;p({phase:"loading"}),y([]);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!==v.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==v.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[h.phase,e,t]),j=new Set((t.models??[]).map(e=>e.id)),S="success"===h.phase?h.models:[],C=f.trim().toLocaleLowerCase(),I=S.filter(e=>!C||e.id.toLocaleLowerCase().includes(C)||e.name?.toLocaleLowerCase().includes(C)),E=I.slice(0,300),M=E.filter(e=>!j.has(e.id)).map(e=>e.id),T=x.filter(e=>!j.has(e)).length,L=M.length>0&&M.every(e=>x.includes(e)),R=!L&&M.some(e=>x.includes(e));return(0,i.useEffect)(()=>{b.current&&(b.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lk,{children:t.name??e}),(0,r.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:u("i18n.delete")})]}),(0,r.jsxs)(lg,{label:u("models.displayName"),children:[(0,r.jsx)(lm,{value:t.name??"",onChange:e=>w("name",e.trim()||void 0),placeholder:e}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("models.providerIdHint",{id:e})})]}),(0,r.jsx)(lg,{label:"Base URL",children:(0,r.jsx)(lm,{value:t.baseUrl??"",onChange:e=>w("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(lg,{label:"API Key",children:[(0,r.jsx)(ly,{value:t.apiKey??"",onChange:e=>w("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(lg,{label:"API",children:(0,r.jsx)(lb,{value:t.api??"openai-completions",onChange:e=>w("api",e),options:lf,required:!0})}),(0,r.jsxs)(lg,{label:"Headers",children:[(0,r.jsx)(lM,{headers:t.headers,onChange:e=>w("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(t.models?.length??0)>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)(lk,{children:u("models.definitions")}),(0,r.jsx)("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:2},children:(t.models??[]).map((t,i)=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsx)(o8,{active:o===i,onClick:()=>c(i),style:{flex:1,width:"auto"},children:(0,r.jsx)(o5,{className:"is-grow",children:t.name&&t.name!==t.id?`${t.name} \xb7 ${t.id}`:t.id})}),!n.has(`${e}/${t.id}`)&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0},children:u("models.notUsable")})]},`${t.id}:${i}`))})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:a,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:u("models.newModel")}),"success"!==h.phase&&(0,r.jsx)("button",{onClick:k,disabled:!t.baseUrl?.trim()||"loading"===h.phase,style:{height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==h.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==h.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===h.phase?u("models.discoveryFetching"):u("models.discoveryFetch")})]}),"error"===h.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:h.message}),"success"===h.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:f,onChange:e=>g(e.target.value),placeholder:u("models.discoveryFilterPlaceholder",{count:h.models.length}),"aria-label":u("models.discoveryFilter"),style:{...lx,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:M.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:b,type:"checkbox",checked:L,disabled:0===M.length,onChange:()=>{let e=new Set(M);y(t=>L?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...M])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),u("models.discoverySelectShown")]}),0===E.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:u("models.discoveryNoMatches")}):E.map((e,t)=>{let n=j.has(e.id),i=x.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void y(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:u("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:h.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:I.length>E.length?u("models.discoveryShowing",{shown:E.length,total:I.length}):u("models.discoveryFetched",{count:h.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==h.phase)return;let e=new Set(x),t=h.models.filter(t=>e.has(t.id)&&!j.has(t.id));0!==t.length&&(d(t),y([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"#fff":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?u("models.discoveryAddSelectedCount",{count:T}):u("models.discoveryAddSelected")})]})]})]})]})}let lS={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function lC({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:nE.map(e=>{let t=n[e],o=e in n?null===t?"null":"string":"omit",l="string"==typeof t?t:"",s=lS[e],a={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--accent)",color:"#fff",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:s,flexShrink:0,opacity:"null"===o?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===o?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===o?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...a,..."omit"===o?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...a,borderLeft:"1px solid var(--border)",..."null"===o?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===o?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,l||e),style:{...a,..."string"===o?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:l,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==o&&i(e,l||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===o?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===o?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let lI={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lE(e){return e.compat?.thinkingFormat==="deepseek"}function lM({headers:e,onChange:t}){let[n,o]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),l=(0,i.useRef)(n.length),s=e=>{o(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))},a=(e,t)=>{s(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>a(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...lx,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>a(e.id,{value:t.target.value}),placeholder:"value",style:{...lx,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void s(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>o(e=>[...e,{id:l.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function lT({providerName:e,provider:t,model:n,onChange:o,onDelete:l,lockId:s=!1,cwd:a=null}){let[d,c]=(0,i.useState)({phase:"idle"}),{t:u}=(0,m.s)(),[h,p]=(0,i.useState)({phase:"idle"}),[f,g]=(0,i.useState)(!1),[x,y]=(0,i.useState)(()=>o_(n.cost)),v=(0,i.useRef)(x),[b,w]=(0,i.useState)(!1),k=(0,i.useRef)(0),j=(0,i.useRef)(null),S=(0,i.useRef)(n.cost),C=(e,t)=>o({...n,[e]:t}),I=(()=>{if("idle"===d.phase)return null;if("testing"===d.phase)return u("i18n.testingModel");let e=[void 0!==d.latencyMs?`${d.latencyMs}ms`:null,void 0!==d.status?`HTTP ${d.status}`:null].filter(Boolean);return"success"===d.phase?[u("i18n.connected"),...e,d.responseText||null].filter(Boolean).join(" \xb7 "):[u("i18n.failed"),...e,d.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{c({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{k.current+=1,p({phase:"idle"}),j.current=null},[e,t.baseUrl,n.id]);let E=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==d.phase){c({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 c({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});c({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){c({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,d.phase,a]),M=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===h.phase)return;let i=++k.current;p({phase:"loading"});try{let l=new URLSearchParams({q:r,provider:e,limit:"50"});a&&l.set("cwd",a),t.baseUrl?.trim()&&l.set("baseUrl",t.baseUrl.trim());let s=await fetch(`/api/models-config/catalog?${l}`),d=await s.json();if(i!==k.current)return;if(!s.ok||d.error||!d.recommendation)return void p({phase:"error",message:d.error??`HTTP ${s.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 l=oq(o_(i));o>0&&l&&(n.cost={...i,...l},r+=o)}return{model:n,appliedCount:r}}(n,d.recommendation.preset);c.appliedCount>0&&(j.current=n,o(c.model)),g(!1),p({phase:"success",recommendation:d.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==k.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[h.phase,n,o,t.baseUrl,e,a]),T=(()=>{if("success"!==h.phase)return null;let{recommendation:t,appliedCount:n}=h,r=n>0?u("models.catalogFilled",{count:n}):u("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?u("models.catalogNoExactMatch"):u("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?u("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?u("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):u("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),L="error"===h.phase?h.message:T,R="error"===h.phase?"#ef4444":"success"===h.phase&&"unreliable"===h.recommendation.price.status?"#d97706":"var(--text-dim)",N=[{key:"input",label:u("models.costInput")},{key:"output",label:u("models.costOutput")},{key:"cacheRead",label:u("models.costCacheRead")},{key:"cacheWrite",label:u("models.costCacheWrite")}],$=new Set(Object.keys(n.compat??{})),W=0;lE(n)&&(W+=1,$.delete("thinkingFormat"),$.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&(W+=1,$.delete("supportsDeveloperRole")),W+=$.size;let z=[n.api?`API: ${n.api}`:null,Object.keys(n.headers??{}).length?u("models.headersSummary",{count:Object.keys(n.headers??{}).length}):null,W?u("models.compatSummary",{count:W}):null,Object.keys(n.thinkingLevelMap??{}).length?u("models.thinkingSummary",{count:Object.keys(n.thinkingLevelMap??{}).length}):null].filter(e=>!!e),P=z.length?z.join(" \xb7 "):u("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lk,{children:u("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[I&&(0,r.jsx)("span",{title:I,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===d.phase?"#fecaca":"success"===d.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===d.phase?"#fee2e2":"success"===d.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:I}),(0,r.jsxs)("button",{onClick:E,disabled:!n.id.trim()||"testing"===d.phase,title:u("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===d.phase?"#16a34a":"none",border:`1px solid ${"success"===d.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===d.phase?"#fff":n.id.trim()&&"testing"!==d.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==d.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===d.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===d.phase?u("i18n.checking"):"success"===d.phase?u("common.ok"):u("i18n.test")]}),l&&(0,r.jsx)("button",{onClick:l,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:u("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(lg,{label:"ID *",children:(0,r.jsx)(lm,{value:n.id,onChange:e=>C("id",e),placeholder:"model-id",mono:!0,disabled:s})}),(0,r.jsx)(lg,{label:"Name",children:(0,r.jsx)(lm,{value:n.name??"",onChange:e=>C("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void M(),disabled:!n.id.trim()||"loading"===h.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==h.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==h.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===h.phase?u("models.catalogFilling"):u("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:u("models.catalogSource")})]}),L&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:R,fontSize:10},children:[(0,r.jsx)("span",{title:L,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:L}),j.current&&(0,r.jsx)("button",{onClick:()=>{let e=j.current;e&&(j.current=null,o(e),p({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:u("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(lk,{children:u("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(lw,{label:u("models.reasoning"),checked:n.reasoning??!1,onChange:e=>C("reasoning",e||void 0)}),(0,r.jsx)(lw,{label:u("models.imageInput"),checked:n.input?.includes("image")??!1,onChange:e=>C("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(lk,{children:u("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(f)return void g(!1);S.current=n.cost;let e=o_(n.cost);v.current=e,y(e),g(!0)},"aria-expanded":f,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:f?u("models.finishEditingCosts"):u("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(lg,{label:u("models.contextWindow"),children:(0,r.jsx)(lv,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>C("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(lg,{label:u("models.maxOutputTokens"),children:(0,r.jsx)(lv,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>C("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:u("models.costPerMillion")}),f?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[N.map(({key:e,label:t})=>(0,r.jsx)(lg,{label:t,children:(0,r.jsx)(lv,{value:x[e],onChange:t=>{let r,i,l;return i=oq(r={...v.current,[e]:t}),l={...n},void(v.current=r,y(r),i?(l.cost={...S.current??{},...i},S.current=l.cost):delete l.cost,o(l))},placeholder:"0"})},e)),oK(x)&&!oq(x)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:u("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:N.map(({key:e,label:t})=>{let i,o=n.cost?.[e]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t}),(0,r.jsx)("div",{style:{marginTop:3,color:o?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(i=n.cost?.[e])?u("models.notProvided"):`$${String(i)}`})]},e)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>w(e=>!e),"aria-expanded":b,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:u("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P})]}),(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",style:{color:"var(--text-dim)",transform:b?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[!s&&(0,r.jsx)(lg,{label:u("models.apiOverride"),children:(0,r.jsx)(lb,{value:n.api??"",onChange:e=>C("api",e||void 0),options:lf})}),(0,r.jsxs)(lg,{label:u("models.headers"),children:[(0,r.jsx)(lM,{headers:n.headers,onChange:e=>C("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("models.headersHelp")})]}),n.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(lk,{children:u("models.compatibility")}),(0,r.jsx)(lw,{label:u("models.deepSeekThinkingCompat"),checked:lE(n),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lI}};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)(lw,{label:u("models.developerRole"),checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>o({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(lk,{children:u("models.thinkingLevelMap")}),n.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>C("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:u("models.clearAll")})]}),(0,r.jsx)(lC,{value:n.thinkingLevelMap,onChange:e=>C("thinkingLevelMap",e)})]})]})]})]})]})}function lL(e,t){return window.confirm(e("models.disconnectConfirm",{name:t}))}function lR({provider:e,onRefresh:t,cwd:n}){let[o,l]=(0,i.useState)({phase:"idle"}),{t:s}=(0,m.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)(()=>{l({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(),l({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?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(l({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?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?(r.close(),l({phase:"success"}),t()):"error"===n.type?(r.close(),l({phase:"error",message:n.message})):"cancelled"===n.type&&(r.close(),l({phase:"idle"}))},r.onerror=()=>{r.close(),l(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t,n]),p=(0,i.useCallback)(async()=>{lL(s,e.name)&&(await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),l({phase:"idle"}),t())},[e.id,e.name,t,s,n]),f=(0,i.useCallback)(async(t,n)=>{if(n.trim()){l({phase:"progress",message:"Verifying…"});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.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`});return}d("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),g=(0,i.useCallback)(async(t,n)=>{l({phase:"progress",message:"Continuing…"});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(()=>({}));l({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),x="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return e.loggedIn&&"idle"===o.phase?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,color:"#4ade80"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:"#4ade80",display:"inline-block"}}),s("i18n.connected")]}),(0,r.jsxs)("span",{style:{display:"inline-flex",gap:8},children:[(0,r.jsx)("button",{onClick:h,style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:s("i18n.relogin")}),(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:s("i18n.disconnect")})]})]}):(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(lk,{children:s("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?s("i18n.connected"):s("i18n.notConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s("i18n.openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:o.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:o.options.map(e=>(0,r.jsx)("button",{onClick:()=>g(o.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===o.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":o.message}),"auth"===o.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:u,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f(o.token,a)},placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>f(o.token,a),disabled:!a.trim(),style:{padding:"6px 12px",background:a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()?"#fff":"var(--text-dim)",cursor:a.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:s("i18n.submit")})]})]}),"device_code"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:o.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:o.verificationUri}),o.expiresInSeconds?` Expires in ${Math.ceil(o.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o.message}),"success"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:s("i18n.connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:o.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:x?(0,r.jsx)("button",{onClick:()=>{c.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:s("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:h,style:{padding:"5px 14px",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:e.loggedIn?s("i18n.relogin"):s("i18n.login")}),e.loggedIn&&(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:s("i18n.disconnect")})]})})]})}function lN({provider:e,onRefresh:t,cwd:n}){let[o,l]=(0,i.useState)(""),[s,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,m.s)();(0,i.useEffect)(()=>{l(""),h(null),f(!1)},[e.id]);let x=(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}`):(l(""),f(!0),setTimeout(()=>f(!1),2e3),t())}catch(e){h(String(e))}finally{a(!1)}}},[o,e.id,t,n]),y=(0,i.useCallback)(async()=>{if(lL(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",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,color:e.configured?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),e.configured?g("i18n.configured"):g("i18n.notConfigured")]}),e.configured&&(0,r.jsx)("button",{onClick:y,disabled:d,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:d?"not-allowed":"pointer",fontSize:12},children:d?g("i18n.removing"):g("i18n.disconnect")})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(ly,{value:o,onChange:l,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&x()},placeholder:e.configured?g("models.replaceKeyPlaceholder"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:x,disabled:s||!o.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":o.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:o.trim()||p?"#fff":"var(--text-dim)",cursor:s||!o.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),p?g("i18n.saved"):s?g("i18n.saving"):g("models.updateKey")]})]}),u&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:u})]})}function l$({oauthProviders:e,apiKeyProviders:t,existingIds:n,onSelectOAuth:o,onSelectApiKey:l,onAddCustom:s,onClose:a}){let[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(""),{t:g}=(0,m.s)(),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>x.current?.focus(),30)},[]);let y=d.trim().toLowerCase(),v=e.filter(e=>!e.loggedIn&&(!y||e.name.toLowerCase().includes(y))),b=t.filter(e=>!e.configured&&(!y||e.displayName.toLowerCase().includes(y)||e.id.toLowerCase().includes(y))),w=!y||"custom".includes(y)||"openai-compatible".includes(y)||"anthropic-compatible".includes(y),k=v.length+b.length+ +!!w,j={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),a())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},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:{color:"var(--text-dim)",flexShrink:0},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:x,value:d,onChange:e=>c(e.target.value),placeholder:g("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===k?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:g("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[w&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:g("i18n.custom")}),w&&!u&&(0,r.jsxs)("button",{onClick:()=>h(!0),style:j,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:g("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",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",style:{color:"var(--text-dim)"},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"})]})})]}),w&&u&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=p.trim();!/^[a-z0-9][a-z0-9._-]*$/.test(t)||n.has(t)||(s(t),a())},style:{gridColumn:"1 / -1",display:"flex",flexDirection:"column",gap:8,padding:12,border:"1px solid var(--border)",borderRadius:6},children:[(0,r.jsx)("label",{htmlFor:"custom-provider-id",style:{fontSize:12},children:g("models.providerId")}),(0,r.jsx)("input",{id:"custom-provider-id",autoFocus:!0,value:p,onChange:e=>f(e.target.value),placeholder:"my-provider","aria-describedby":"custom-provider-id-hint",style:{...lx,width:"100%",boxSizing:"border-box"}}),(0,r.jsx)("span",{id:"custom-provider-id-hint",style:{fontSize:11,color:"var(--text-dim)"},children:g(n.has(p.trim())?"models.providerIdTaken":"models.providerIdFormat")}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,r.jsx)(ll,{type:"button",onClick:()=>h(!1),children:g("i18n.cancel")}),(0,r.jsx)(ll,{type:"submit",variant:"primary",disabled:!/^[a-z0-9][a-z0-9._-]*$/.test(p.trim())||n.has(p.trim()),children:g("models.createProvider")})]})]}),v.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!w,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:g("i18n.subscriptions")}),v.map(e=>(0,r.jsxs)("button",{onClick:()=>{o(e.id),a()},style:j,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(lu,{id:e.id,size:28})]},e.id)),b.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(v.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),b.map(e=>(0,r.jsxs)("button",{onClick:()=>{l(e.id),a()},style:j,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(lu,{id:e.id,size:28})]},e.id))]})})]})})}function lW({catalog:e,listedRefs:t,mode:n,providerFilter:o,saving:l,error:s,onClose:a,onApply:d,onEditModel:c}){let{t:u}=(0,m.s)(),[h,p]=(0,i.useState)(""),[f,g]=(0,i.useState)(new Set),x=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>x.current?.focus(),30)},[]);let y=h.trim().toLocaleLowerCase(),v=e.filter(e=>(!o||e.provider===o)&&!t.has(oJ(e.provider,e.id))&&(!y||e.id.toLocaleLowerCase().includes(y)||e.name?.toLocaleLowerCase().includes(y))),b=new Map;for(let e of v){let t=b.get(e.provider)??[];t.push(e),b.set(e.provider,t)}return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},children:(0,r.jsxs)("div",{style:{width:560,maxWidth:"calc(100vw - 32px)",maxHeight:"min(76vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)",display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600},children:u("models.pickModels")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)"},children:"replace"===n?u("models.pickReplaceHint"):u("models.pickAddHint")})]}),(0,r.jsx)("div",{style:{padding:"8px 14px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{ref:x,value:h,onChange:e=>p(e.target.value),placeholder:u("models.pickFilterPlaceholder"),"aria-label":u("models.pickFilter"),style:{width:"100%",boxSizing:"border-box",padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:14,display:"flex",flexDirection:"column",gap:12},children:[0===v.length?(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:u("models.noExtraModels")}):[...b.entries()].map(([e,t])=>{let n=t.map(e=>oJ(e.provider,e.id)),i=n.every(e=>f.has(e));return(0,r.jsxs)("div",{children:[(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"var(--text-dim)",marginBottom:4,cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:i,onChange:()=>g(e=>{let t=new Set(e);for(let e of n)i?t.delete(e):t.add(e);return t}),style:{width:12,height:12,accentColor:"var(--accent)",flexShrink:0}}),e]}),t.map(e=>{let t=oJ(e.provider,e.id);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"3px 8px 3px 22px"},children:[(0,r.jsx)("input",{id:t,type:"checkbox",checked:f.has(t),onChange:()=>g(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}),style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsx)("label",{htmlFor:t,style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",cursor:"pointer",fontSize:12},children:e.name&&e.name!==e.id?`${e.name} \xb7 ${e.id}`:e.id}),(0,r.jsx)("button",{type:"button",onClick:()=>c(e.provider,e.id),style:{flexShrink:0,border:0,background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:u("i18n.edit")})]},t)})]},e)}),s&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px",borderTop:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:u("models.pickSelected",{count:f.size})}),(0,r.jsxs)("span",{style:{display:"inline-flex",gap:8},children:[(0,r.jsx)(ll,{type:"button",onClick:a,children:u("i18n.cancel")}),(0,r.jsx)(ll,{type:"button",variant:"primary",disabled:0===f.size||l,onClick:()=>d([...f]),children:u("models.pickApply",{count:f.size})})]})]})]})})}function lz({title:e,hint:t,entries:n,readOnly:i,onRemove:o}){let{t:l}=(0,m.s)();return(0,r.jsxs)("div",{style:{flexShrink:0,padding:"8px 8px 0",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontWeight:600},children:e}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2,lineHeight:1.4},children:t}),n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)(o5,{className:"is-grow",style:{color:"var(--text-dim)"},children:oZ(e)?.id??e}),!i&&(0,r.jsx)("button",{type:"button",onClick:()=>o(e),style:{border:0,background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11,padding:"0 6px"},children:l("models.removeFromChat")})]},e))]})}function lP({onClose:e,embedded:t=!1,cwd:n=null,onModelsChanged:o}){var l;let s,a,{t:d}=(0,m.s)(),[c,u]=(0,i.useState)({providers:{}}),[h,p]=(0,i.useState)({providers:{}}),[f,g]=(0,i.useState)(!0),[x,y]=(0,i.useState)(!1),[v,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(lh),[E,M]=(0,i.useState)([]),[T,L]=(0,i.useState)([]),[R,N]=(0,i.useState)(!1),[$,W]=(0,i.useState)(null),[z,P]=(0,i.useState)([]),[A,D]=(0,i.useState)(null),[H,B]=(0,i.useState)(!1),[F,O]=(0,i.useState)(null),[U,_]=(0,i.useState)(null),[q,K]=(0,i.useState)(null),V=(0,i.useCallback)(()=>{fetch(`/api/auth/providers${n?`?cwd=${encodeURIComponent(n)}`:""}`).then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&M(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&L(e.apiKeyProviders)}).catch(()=>{})},[n]),J=(0,i.useCallback)(()=>{if(!n)return void P([]);let e=new URLSearchParams({cwd:n});fetch(`/api/models-config/runtime?${e}`).then(e=>e.json()).then(e=>{Array.isArray(e.catalog)&&P(e.catalog),K(e.modelError??null)}).catch(()=>{})},[n]),Y=(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?(O(null),D(t)):O(t.error??d("models.scopeError"))}).catch(()=>O(d("models.scopeError"))):D(null)},[n,d]);(0,i.useEffect)(()=>{if(!U)return;let e=setTimeout(()=>_(null),4e3);return()=>clearTimeout(e)},[U]);let Z=(0,i.useCallback)(()=>{V(),J()},[V,J]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};b(e.error??null),u(t),p(t);let n=Object.keys(t.providers??{});I(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(()=>u({providers:{}})).finally(()=>g(!1)),V()},[V]),(0,i.useEffect)(()=>{J(),Y()},[J,Y]),(0,i.useEffect)(()=>{C&&oB("models",JSON.stringify(C))},[C]);let X=(0,i.useCallback)(e=>{u(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),I({type:"provider",name:e})},[]),G=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),Q=(0,i.useCallback)(e=>{u(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),u(e=>{let t=Object.keys(e.providers??{});return I(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),ee=(0,i.useCallback)(e=>{u(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),u(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return I({type:"model",providerName:e,index:n}),t})},[]),et=(0,i.useCallback)((e,t)=>{u(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}}}})},[]),en=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),er=(0,i.useCallback)((e,t,n)=>{let r=function(e,t){let n={};for(let i of oV){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}(lp(t),{...n,id:t.id});u(n=>{var i,o;let l,s=n.providers?.[e]??{},a={...s},d=(i=s.modelOverrides,o=t.id,l={...i??{}},delete l[o],r&&(l[o]=r),Object.keys(l).length>0?l:void 0);return d?a.modelOverrides=d:delete a.modelOverrides,{...n,providers:{...n.providers??{},[e]:a}}})},[]),ei=(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]),eo=(0,i.useRef)(0),el=(0,i.useCallback)(async()=>{let e=++eo.current,t=await ei();return t&&e===eo.current&&D(t),t},[ei]),es=(0,i.useRef)(Promise.resolve()),ea=(0,i.useCallback)(e=>{if(!n)return Promise.resolve(!1);let t=es.current.then(async()=>{let t=await ei();if(!t)return O(d("models.scopeError")),!1;if(t.readOnly)return!1;let r=e(t);if(0===r.length)return O(d("models.keepOneModel")),!1;B(!0),O(null),_(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 O("untrusted"===t.code?d("models.scopeReadOnly"):t.error??d("models.scopeError")),!1;return D(t),o?.(),!0}catch{return O(d("models.scopeError")),!1}finally{B(!1)}});return es.current=t.catch(()=>!1),t},[n,ei,o,d]),ed=(0,i.useCallback)(e=>{n&&A&&W("none"===A.source?{mode:"replace",...e?{providerFilter:e}:{}}:{mode:"add",...e?{providerFilter:e}:{}})},[n,A]),ec=(0,i.useCallback)(async e=>{let t=!!A&&!oG(A?.patterns??[]);await ea(t=>(function(e){let t=oY(e.patterns);if(oG(t)){let n,r;return r=(n=e.ref.trim()).slice(n.indexOf("/")+1),oY(t).filter(e=>{let t=oZ(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=>oJ(e.provider,e.id)),pins:t.pins,ref:e}))&&t&&_(d("models.listWritten"))},[ea,A,d]),eu=(0,i.useCallback)((e,t)=>{u(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}}}}),I({type:"provider",name:e})},[]),eh=(0,i.useCallback)(async()=>{y(!0),k(null),S(!1);try{var e;let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)}),n=await t.json();if(!t.ok||n.error)return void k(n.error??`HTTP ${t.status}`);p(c),S(!0),setTimeout(()=>S(!1),2e3),J();let r=A?.defined,i=await el(),l=r&&i?(e={patterns:r.length?A?.patterns??[]:[],before:new Set(r),after:new Set(i.defined)},oY(e.patterns).filter(t=>{let n=oZ(t);return null!==n&&void 0!==n.provider&&e.before.has(n.ref)&&!e.after.has(n.ref)})):[];l.length>0&&await ea(e=>e.patterns.filter(e=>!l.includes(e)))&&_(d("models.removedWithDefinition",{count:l.length})),o?.()}catch(e){k(String(e))}finally{y(!1)}},[c,el,o,J,ea,A,d]),ep=[v,q].filter(Boolean).map(e=>String(e).split("\n")[0]).join(" \xb7 ")||null,ef=Object.entries(c.providers??{}),eg=E.filter(e=>e.loggedIn),ex=T.filter(e=>e.configured),em=JSON.stringify(c)!==JSON.stringify(h),ey=new Set([...eg.map(e=>e.id),...ex.map(e=>e.id)]),ev=(e,t)=>{let n=(c.providers?.[e]?.models??[]).findIndex(e=>e.id===t);n>=0?I({type:"model",providerName:e,index:n}):I({type:"runtime-model",providerName:e,id:t})},eb=A?.visible??[],ew=new Set(eb.map(e=>oJ(e.provider,e.id))),ek=!!A&&"none"!==A.source&&!A.readOnly,ej=A?(s=new Set((l={patterns:A.patterns,visible:[...ew]}).visible),a=new Set(l.visible.map(e=>e.slice(e.indexOf("/")+1))),oY(l.patterns).filter(e=>{let t=oZ(e);return null!==t&&(t.provider?!s.has(t.ref):!a.has(t.id))})).filter(e=>!(A.ambiguous??[]).includes(e)):[],eS=e=>{let t=c.providers?.[e]?.models??[],n=eb.filter(t=>t.provider===e),i=z.filter(t=>t.provider===e&&!ew.has(oJ(t.provider,t.id))).length;return 0===n.length&&0===i?null:(0,r.jsxs)(r.Fragment,{children:[n.map(n=>{let i=oJ(n.provider,n.id),o=z.some(t=>t.provider===e&&t.id===n.id),l=A?.pins[i];return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,r.jsxs)(o8,{className:"models-sidebar-indented-item",style:{flex:1,width:"auto"},onClick:()=>o||t.some(e=>e.id===n.id)?ev(e,n.id):void 0,children:[(0,r.jsx)(o5,{className:"is-grow",style:{color:o?"var(--text-muted)":"var(--text-dim)"},children:n.id}),l&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:d("models.thinkingPin",{level:l})})]}),ek&&(0,r.jsx)("button",{type:"button",onClick:()=>void ec(i),style:{border:0,background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11,padding:"0 6px"},children:d("models.removeFromChat")})]},i)}),i>0&&(0,r.jsx)("button",{type:"button",className:"models-sidebar-indented-item",onClick:()=>ed(e),style:{display:"block",width:"100%",padding:"6px 8px 6px 26px",border:0,background:"none",color:"var(--accent)",cursor:"pointer",fontSize:11,textAlign:"left"},children:d("models.availableMore",{count:i})})]})},eC=(()=>{var e,t;if(!C)return null;if("oauth"===C.type){let e=E.find(e=>e.id===C.providerId);if(!e)return null;let t=T.find(t=>t.id===e.id&&t.configured);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lR,{provider:e,onRefresh:Z,cwd:n},e.id),t&&(0,r.jsx)(lN,{provider:t,onRefresh:Z,cwd:n},`${e.id}-key`)]})}if("apikey"===C.type){let e=T.find(e=>e.id===C.providerId);return e?(0,r.jsx)(lN,{provider:e,onRefresh:Z,cwd:n},e.id):null}if("provider"===C.type){let t,n=c.providers?.[C.name];return n?(e=C.name,t=(0,r.jsx)(lj,{providerId:e,provider:n,usableRefs:new Set(z.map(e=>oJ(e.provider,e.id))),selectedModelIndex:C?.type==="model"&&C.providerName===e?C.index:null,onChange:t=>G(e,t),onDelete:()=>Q(e),onAddModel:()=>ee(e),onAddModels:t=>et(e,t),onSelectModel:t=>I({type:"model",providerName:e,index:t})},`${e}-json`),z.some(t=>t.provider===e)?(0,r.jsxs)("details",{children:[(0,r.jsx)("summary",{style:{cursor:"pointer",fontSize:11,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em",textTransform:"uppercase"},children:d("models.endpoint")}),(0,r.jsx)("div",{style:{marginTop:12},children:t})]}):t):null}if("runtime-model"===C.type){let e=z.find(e=>e.provider===C.providerName&&e.id===C.id);if(!e)return null;let i=c.providers?.[C.providerName]??{},o=i.modelOverrides?.[e.id],l=(t=lp(e),o?{...t,...o,id:t.id,cost:o.cost?{...t.cost,...o.cost}:t.cost}:{...t,id:t.id});return(0,r.jsx)(lT,{providerName:C.providerName,provider:i,model:l,lockId:!0,cwd:n,onChange:t=>er(C.providerName,e,t)},`${C.providerName}-${C.id}`)}let i=c.providers?.[C.providerName],o=i?.models?.[C.index];return o?(0,r.jsx)(lT,{providerName:C.providerName,provider:i,model:o,cwd:n,onChange:e=>en(C.providerName,C.index,e),onDelete:()=>eu(C.providerName,C.index)},`${C.providerName}-${C.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(oQ,{embedded:t,title:d("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:d("i18n.close"),onClose:e,children:[(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsxs)(o2,{children:[(0,r.jsxs)("div",{style:{padding:"8px 8px 4px",fontSize:11,color:"var(--text-dim)"},children:[n?A?.source==="none"?d("models.chatAll"):d("models.chatList"):d("models.scopeNoCwd"),A?.readOnly&&(0,r.jsx)("div",{style:{color:"#d97706",marginTop:4},children:d("models.scopeReadOnly")}),A?.source==="none"&&n&&!A.readOnly&&(0,r.jsx)("button",{type:"button",onClick:()=>ed(),style:{marginTop:6,padding:"4px 8px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:d("models.pickOnlyThese")}),U&&(0,r.jsx)("div",{style:{marginTop:4},children:U}),F&&(0,r.jsx)("div",{style:{color:"#f87171",marginTop:4},children:F})]}),eg.map(e=>{let t=C?.type==="oauth"&&C.providerId===e.id;return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o8,{active:t,onClick:()=>I({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(lu,{id:e.id,size:16}),(0,r.jsx)(o5,{className:"is-grow",children:e.name})]}),eS(e.id)]},e.id)}),ex.filter(e=>!eg.some(t=>t.id===e.id)).map(e=>{let t=C?.type==="apikey"&&C.providerId===e.id;return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o8,{active:t,onClick:()=>I({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(lu,{id:e.id,size:16}),(0,r.jsx)(o5,{className:"is-grow",children:e.displayName})]}),eS(e.id)]},e.id)}),(eg.length>0||ex.length>0)&&ef.some(([e])=>!ey.has(e))&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),f?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:d("i18n.loading")}):ef.filter(([e])=>!ey.has(e)).map(([e])=>{let t=C?.type==="provider"&&C.name===e;return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(o8,{onClick:()=>I({type:"provider",name:e}),active:t,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:{color:"var(--text-dim)",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"})]}),(0,r.jsx)(o5,{className:"is-grow",children:c.providers?.[e]?.name??e})]}),eS(e)]},e)}),eb.flatMap(e=>e.provider).filter((e,t,n)=>n.indexOf(e)===t&&!ey.has(e)&&!c.providers?.[e]).map(e=>(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsx)(o8,{children:(0,r.jsx)(o5,{className:"is-grow",children:e})}),eS(e)]},e))]}),ej.length>0&&(0,r.jsx)(lz,{title:d("models.unavailable",{count:ej.length}),hint:d("models.unavailableHint"),entries:ej,readOnly:!!A?.readOnly,onRemove:e=>void ea(t=>oX(t.patterns,e))}),(A?.ambiguous?.length??0)>0&&(0,r.jsx)(lz,{title:d("models.ambiguous",{count:A?.ambiguous?.length??0}),hint:d("models.ambiguousHint"),entries:A?.ambiguous??[],readOnly:!!A?.readOnly,onRemove:e=>void ea(t=>oX(t.patterns,e))}),(0,r.jsxs)("div",{className:"models-add-actions",children:[(0,r.jsx)(la,{onClick:()=>ed(),disabled:!n||!A,children:d("models.addModel")}),(0,r.jsx)(la,{className:"models-add-provider",onClick:()=>N(!0),children:d("models.addProvider")})]})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:f?null:eC??(0,r.jsx)(lr,{children:d("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(lo,{status:(w||ep)&&(0,r.jsx)("span",{style:{color:"#f87171"},title:ep??void 0,children:w||ep}),children:[!t&&(0,r.jsx)(ll,{onClick:e,children:d("i18n.cancel")}),(em||x||j)&&(0,r.jsxs)(ll,{variant:"primary",onClick:eh,disabled:x||j,className:j?"is-success":void 0,children:[j&&(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:j?d("i18n.saved"):x?d("i18n.saving"):d("models.saveModelsJson")})]})]})]}),R&&(0,r.jsx)(l$,{oauthProviders:E,apiKeyProviders:T,existingIds:new Set([...Object.keys(c.providers??{}),...E.map(e=>e.id),...T.map(e=>e.id),...z.map(e=>e.provider)]),onSelectOAuth:e=>I({type:"oauth",providerId:e}),onSelectApiKey:e=>I({type:"apikey",providerId:e}),onAddCustom:X,onClose:()=>N(!1)}),$&&(0,r.jsx)(lW,{catalog:z,listedRefs:"replace"===$.mode?new Set:ew,mode:$.mode,...$.providerFilter?{providerFilter:$.providerFilter}:{},saving:H,error:F,onClose:()=>W(null),onEditModel:(e,t)=>{W(null),ev(e,t)},onApply:e=>{let{mode:t}=$;W(null),ea(n=>"replace"===t?e:e.reduce((e,t)=>{let n,r;return n=oY(e),!(r=t.trim())||n.includes(r)?n:[...n,r]},n.patterns))}})]})}function lA(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lD(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lH(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function lB(e){return e?e.slice(0,8):"unknown"}function lF({skill:e,cwd:t,onToggle:n,toggling:i,saveError:o,updateStatus:l,checkingUpdate:s,updating:a,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:h}=(0,m.s)(),p=lD(e),f=!e.disableModelInvocation;return(0,r.jsxs)(o6,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(o3,{children:[(0,r.jsxs)(o7,{children:[(0,r.jsx)("span",{className:`config-scope-tag${"project"===p?" is-project":""}`,children:p}),(0,r.jsx)("span",{className:"config-detail-path",children:function(e){if("project"===p&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return lA(e)}(e.filePath)})]}),(0,r.jsx)(o9,{children:(0,r.jsx)(ls,{checked:f,loading:i,label:h(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>n(e)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:h("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),e.install?.skillsShUrl&&(0,r.jsx)(ln,{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)(ln,{label:"Version",children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:lB(l?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)(ll,{size:"small",onClick:c,disabled:s||a,children:h("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:lB(l.latestVersion)}),(s||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${s?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:s?h("i18n.checking"):l?.state==="up-to-date"?h("i18n.upToDate"):l?.state==="unsupported"?h("i18n.automaticChecksUnavailable"):l?.message||h("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(ll,{variant:"primary",size:"small",onClick:u,disabled:a||s,children:h(a?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)(ln,{label:"Name",children:(0,r.jsx)("span",{className:"skill-name-value",children:e.name})}),(0,r.jsx)(ln,{label:"Description",children:(0,r.jsx)("span",{className:"skill-description",children:e.description})})]})}function lO({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:o}){let{t:l}=(0,m.s)(),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(null),[b,w]=(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)}}},[]),I=(0,i.useCallback)(async t=>{x(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}`);w(e=>new Set(e).add(`${k}:${t}`)),o()}catch(e){v(String(e))}finally{x(null)}},[o,k,e]),E="global"===k?"~/.pi/agent/skills/":`${lA(e)}/.pi/skills/`;return(0,r.jsxs)(o6,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(le,{children:l("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:S,value:s,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(s)},placeholder:l("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)(ll,{variant:"primary",onClick:()=>C(s),disabled:u||!s.trim(),children:u?l("i18n.searching"):l("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:l("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:["→ ",E]})]}),p&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:p}),y&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:y})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[k].has(e.package)||b.has(`${k}:${e.package}`),i=g===e.package,o=e.package.indexOf("@"),s=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??s}),(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:s}),(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)(ll,{size:"small",onClick:()=>!n&&!i&&I(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?`✓ ${l("i18n.installed")}`:i?l("i18n.installing"):l("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 lU({cwd:e,onClose:t,embedded:n=!1}){let{t:o}=(0,m.s)(),[l,s]=(0,i.useState)([]),[a,d]=(0,i.useState)(!0),[c,u]=(0,i.useState)(null),[h,p]=(0,i.useState)(()=>oH("skills",e)),[f,g]=(0,i.useState)(new Set),[x,y]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,I]=(0,i.useState)(!1),[E,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(null),[R,N]=(0,i.useState)(!0),$=(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 s(r),N(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({}),L(null),$()},[e]),(0,i.useEffect)(()=>{h&&oB("skills",h,e)},[e,h]);let W=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(lH).filter(e=>!!e);if(0!==n.length){L(null),S(e=>new Set([...e,...n])),t||I(!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){L(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||I(!1)}}},[e,l]),z=(0,i.useCallback)(async t=>{if(!t.install)return;let n=lH(t);M(n),L(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 $();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){L(e instanceof Error?e.message:String(e))}finally{M(null)}},[e,$]),P=(0,i.useCallback)(async t=>{let n=!t.disableModelInvocation;g(e=>new Set(e).add(t.filePath)),y(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 y(i.error??`HTTP ${r.status}`);s(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:n}:e))}catch(e){y(String(e))}finally{g(e=>{let n=new Set(e);return n.delete(t.filePath),n})}},[e]),A=l.find(e=>e.filePath===h)??null;return(0,r.jsxs)(oQ,{embedded:n,title:o("common.skills"),subtitle:lA(e),closeLabel:o("i18n.close"),onClose:t,children:[!R&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:o("trust.skillsNotLoaded")}),(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{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===l.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"===lD(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===lD(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===lD(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===lD(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===lD(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!v&&h===e.filePath,l=e.disableModelInvocation;return(0,r.jsxs)(o8,{active:i,onClick:()=>{p(e.filePath),b(!1)},children:[(0,r.jsx)(ld,{active:!l}),(0,r.jsx)(o5,{className:`is-grow${l?" is-muted":""}`,children:e.name}),(n=(t=lH(e))?w[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)(o4,{children:e}),[...t.filter(e=>!e.disableModelInvocation),...t.filter(e=>e.disableModelInvocation)].map(n)]},e))})()}),(0,r.jsx)(la,{onClick:()=>b(!0),active:v,children:o("i18n.addSkill")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:v?(0,r.jsx)(lO,{cwd:e,projectResourcesLoaded:R,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{$()}}):a?null:A?(0,r.jsx)(lF,{skill:A,cwd:e,onToggle:P,toggling:f.has(A.filePath),saveError:x,updateStatus:lH(A)?w[lH(A)]:void 0,checkingUpdate:!!lH(A)&&j.has(lH(A)),updating:E===lH(A),updateError:T,onCheckUpdate:()=>void W(A),onUpdate:()=>void z(A)},A.filePath):(0,r.jsx)(lr,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(lo,{status:Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!n&&(0,r.jsx)(ll,{onClick:t,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(ll,{variant:"secondary",onClick:()=>void W(),disabled:C||null!==E,children:C?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let l_={builtin:0,global:1,workspace:2,project:3},lq=["read","bash","edit","write","grep","find","ls"],lK=["",...nE],lV={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},lJ={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"},lY={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lZ(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 lX(e){return`${e.scope}:${e.name}`}function lG(e){return"global"===e||"project"===e}function lQ(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l0({label:e,children:t}){return(0,r.jsx)(ln,{label:e,children:t})}function l1({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 l2({cwd:e,sessionId:t=null,onClose:n,onReloaded:o,embedded:l=!1}){let s=nY(),{t:a}=(0,m.s)(),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)([]),[p,f]=(0,i.useState)(!0),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(()=>oH("agents",e)),[b,w]=(0,i.useState)(lV),[k,j]=(0,i.useState)("view"),[S,C]=(0,i.useState)("global"),[I,E]=(0,i.useState)(!0),[M,T]=(0,i.useState)(!1),[L,R]=(0,i.useState)(!1),[N,$]=(0,i.useState)(!1),[W,z]=(0,i.useState)(null),[P,A]=(0,i.useState)(!0),[D,H]=(0,i.useState)(10),[B,F]=(0,i.useState)(!0),[O,U]=(0,i.useState)(!1),[_,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),Z=(0,i.useMemo)(()=>d.find(e=>lX(e)===y)??null,[d,y]),X=(0,i.useMemo)(()=>u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[u]),G=(0,i.useCallback)(async t=>{E(!0),z(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(e)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];c(i);let o=t??oH("agents",e),l=i.find(e=>lX(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;v(l?lX(l):null),l&&(w(lZ(l)),j(lG(l.scope)?"edit":"view"),lG(l.scope)&&C(l.scope))}catch(e){z(e instanceof Error?e.message:String(e))}finally{E(!1)}},[e]);(0,i.useEffect)(()=>{G()},[G]),(0,i.useEffect)(()=>{let e=new AbortController;return F(!0),q(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}`);A(n.enabled),"number"==typeof n.maxConcurrent&&H(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||F(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{y&&oB("agents",y,e)},[e,y]),(0,i.useEffect)(()=>{let t=new AbortController;return f(!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}`);h(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||f(!1)}})(),()=>t.abort()},[e]);let Q=async()=>{T(!0),z(null),R(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:S,profile:b})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await G(lX(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}},ee=async()=>{if(Z&&lG(Z.scope)&&window.confirm(a("agents.deleteConfirm",{name:Z.displayName}))){T(!0),z(null);try{let t=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Z.scope,name:Z.name})}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);await G()}catch(e){z(e instanceof Error?e.message:String(e))}finally{T(!1)}}},et="view"!==k,en="create"===k,er=!et||M||N,ei=en?S:Z?.scope,eo=en?"global"===S?`~/.pi/agent/agents/${b.name||"..."}.md`:`./.pi/agents/${b.name||"..."}.md`:Z?function(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 lQ(e.filePath)}(Z,e)??a("agents.builtinPath"):"",el=en?eo:Z?.filePath??eo,es=!b.model||u.some(e=>`${e.provider}/${e.id}`===b.model),ea=(()=>{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)}})(),ed=er?{...lJ,...lY}:lJ,ec=(e,t)=>{w(n=>({...n,[e]:t}))},eu=async t=>{if(en)return void ec("enabled",t);if(Z&&lG(Z.scope)){$(!0),z(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Z.scope,name:Z.name,enabled:t})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;c(e=>e.map(e=>lX(e)===lX(i)?i:e)),w(e=>({...e,enabled:i.enabled}))}catch(e){z(e instanceof Error?e.message:String(e))}finally{$(!1)}}},eh=async e=>{U(!0),q(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}`);A(r.enabled),V(!!t)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},ep=async e=>{H(e),q(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}`);H(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ef=async()=>{if(t){Y(!0),q(null);try{await r4(t,{type:"reload"}),V(!1),o?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(oQ,{embedded:l,title:a("common.agents"),subtitle:lQ(e),closeLabel:a("agents.close"),onClose:n,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:a("agents.builtInTitle")}),(0,r.jsx)("span",{children:a("agents.builtInDescription")}),K&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:a("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[K&&t&&(0,r.jsx)(ll,{size:"small",onClick:()=>void ef(),disabled:J||O,children:J?a("agents.reloading"):a("agents.reloadSession")}),(0,r.jsx)(ls,{checked:P,disabled:B||J,loading:O,label:a("agents.builtInTitle"),onChange:e=>void eh(e)})]})]}),(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:a("agents.maxConcurrent")}),(0,r.jsx)("span",{children:a("agents.maxConcurrentDescription")})]}),(0,r.jsx)("input",{"aria-label":a("agents.maxConcurrent"),type:"number",min:1,max:32,value:D,disabled:B||O,onChange:e=>H(Number(e.target.value)),onBlur:()=>void ep(D),style:{...lJ,width:76}})]}),(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{children:I?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:a("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=d.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(o4,{children:a(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=l_[e.scope],d.some(e=>e.name.toLowerCase()===t&&l_[e.scope]>n));return(0,r.jsxs)(o8,{active:y===lX(e)&&!en,onClick:()=>{v(lX(e)),w(lZ(e)),j(lG(e.scope)?"edit":"view"),lG(e.scope)&&C(e.scope),z(null)},children:[(0,r.jsx)(ld,{active:e.enabled}),(0,r.jsx)(o5,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:a("agents.overridden")})]},lX(e))})]},e)})}),(0,r.jsx)(la,{active:en,onClick:()=>{let e="custom-agent",t=2;for(;d.some(t=>t.name===e);)e=`custom-agent-${t++}`;v(null),w({...lV,name:e,displayName:e}),j("create"),C("global"),z(null)},children:a("agents.new")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:Z||en?(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{children:[(0,r.jsxs)(o7,{children:[ei&&(0,r.jsx)("span",{className:`config-scope-tag${"project"===ei?" is-project":""}`,children:a(`agents.scope.${ei}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:eo})]}),(0,r.jsxs)(o9,{children:[Z&&("view"===k||"edit"===k)&&(0,r.jsx)(ll,{size:"small",onClick:()=>{if(!Z)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}(Z.name,d);v(null),w({...lZ(Z),name:e,displayName:a("agents.copyName",{name:Z.displayName})}),j("create"),C(lG(Z.scope)?Z.scope:"global"),z(null)},disabled:M||N,children:a("agents.duplicate")}),Z&&lG(Z.scope)&&"edit"===k&&(0,r.jsx)(ll,{variant:"danger",size:"small",onClick:()=>void ee(),disabled:M||N,children:a("agents.delete")}),(0,r.jsx)(ls,{checked:b.enabled,disabled:er,label:b.enabled?a("agents.disable"):a("agents.enable"),onChange:e=>void eu(e)})]})]}),en&&(0,r.jsx)(l0,{label:a("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:()=>C(e),disabled:M,style:{height:28,border:"none",borderRadius:4,background:S===e?"var(--bg-selected)":"transparent",color:S===e?"var(--text)":"var(--text-muted)",cursor:M?"default":"pointer",fontSize:11,fontWeight:S===e?600:400},children:a(`agents.scope.${e}`)},e))})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(l0,{label:a("agents.name"),children:en?(0,r.jsx)("input",{"aria-label":a("agents.name"),value:b.name,disabled:er,onChange:e=>ec("name",e.target.value),style:lJ}):(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)(l0,{label:a("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":a("agents.displayName"),value:b.displayName,disabled:er,onChange:e=>ec("displayName",e.target.value),style:ed})})]}),(0,r.jsx)(l0,{label:a("agents.description"),children:(0,r.jsx)("input",{"aria-label":a("agents.description"),value:b.description,disabled:er,onChange:e=>ec("description",e.target.value),style:ed})}),(0,r.jsx)(l0,{label:a("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":a("agents.prompt"),value:b.systemPrompt,disabled:er,onChange:e=>ec("systemPrompt",e.target.value),style:{...ed,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:er?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(l0,{label:a("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:lq.map(e=>(0,r.jsx)(l1,{label:e,disabled:er,checked:b.tools.includes(e),onChange:t=>ec("tools",t?[...b.tools,e]:b.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(l0,{label:a("agents.resources"),children:(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(l1,{label:a("agents.loadSkills"),disabled:er,checked:b.loadSkills,onChange:e=>ec("loadSkills",e)}),(0,r.jsx)(l1,{label:a("agents.loadExtensions"),disabled:er,checked:b.loadExtensions,onChange:e=>ec("loadExtensions",e)})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(l0,{label:a("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(rs,{options:X,value:ea,onChange:(e,t)=>ec("model",`${e}/${t}`),onClear:()=>ec("model",void 0),emptyLabel:p?a("agents.modelsLoading"):a("agents.inherit"),selectedLabel:b.model&&!es?a("agents.modelUnavailable",{model:b.model}):void 0,disabled:er||p||0===u.length&&!b.model,ariaLabel:a("agents.model"),variant:"field",placement:"auto"}),g&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:g})]})}),(0,r.jsx)(l0,{label:a("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":a("agents.thinking"),value:b.thinking??"",disabled:er,onChange:e=>ec("thinking",e.target.value||void 0),style:ed,children:lK.map(e=>(0,r.jsx)("option",{value:e,children:e||a("agents.inherit")},e||"default"))})}),(0,r.jsx)(l0,{label:a("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":a("agents.maxTurns"),type:"number",min:1,value:b.maxTurns??"",disabled:er,onChange:e=>ec("maxTurns",e.target.value?Number(e.target.value):void 0),style:ed})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(l1,{label:a("agents.inheritContext"),disabled:er,checked:b.inheritContext,onChange:e=>ec("inheritContext",e)}),(0,r.jsx)(l1,{label:a("agents.background"),disabled:er,checked:b.runInBackground,onChange:e=>ec("runInBackground",e)})]})]}):(0,r.jsx)(lr,{children:a("agents.empty")})})})]}),(0,r.jsx)(lo,{status:(_||W)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:_||W}),children:et&&(0,r.jsxs)(ll,{variant:"primary",onClick:()=>void Q(),disabled:M||L||N||!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?a("i18n.saved"):M?a("agents.saving"):a("agents.save")})]})})]})}function l4(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l8(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function l5(e){return`${e.scope}\0${e.source}`}function l6(e){return`extension\0${e.path}`}function l3(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function l7({pkg:e}){let{t}=(0,m.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 l9({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 se({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,m.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 l=e===o,s="project"===o&&!t;return(0,r.jsx)("button",{onClick:()=>{s||n(o)},disabled:s,title:s?i("trust.projectScopeUnavailable"):void 0,style:{width:76,border:"none",borderRight:"global"===o?"1px solid var(--border)":"none",background:l?"var(--bg-selected)":"none",color:l?"var(--text)":"var(--text-muted)",cursor:s?"not-allowed":"pointer",opacity:s?.45:1,fontSize:12},children:o},o)})})}function st({cwd:e,source:t,scope:n,projectResourcesLoaded:o,busy:l,actionError:s,onSourceChange:a,onScopeChange:d,onInstall:c}){let{t:u}=(0,m.s)(),h=(0,i.useRef)(null);return(0,i.useEffect)(()=>{h.current?.focus()},[]),(0,r.jsxs)(o6,{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)(le,{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?`${l4(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsx)(ln,{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=l8(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(l8(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()&&!l&&c()}})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(se,{value:n,projectResourcesLoaded:o,onChange:d}),(0,r.jsx)(ll,{variant:"primary",onClick:c,disabled:l||!t.trim(),className:"is-pushed-right",children:u(l?"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))})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:s})]})}function sn({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:o,sessionId:l,updateStatus:s,checkingUpdate:a,updateError:d,onAction:c,onCheckUpdate:u,onReloadSession:h}){let p,{t:f}=(0,m.s)(),g=l5(e),x=n?.endsWith(g)??!1,y="reload"===n,v=!e.disabled,b=e.canCheckForUpdates,w=s?.state==="update-available";return(0,r.jsxs)(o6,{children:[(0,r.jsxs)(o3,{className:"is-top-aligned",children:[(0,r.jsxs)(o7,{children:[(0,r.jsx)(l9,{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)(o9,{children:[(0,r.jsx)(ll,{size:"small",variant:w?"primary":void 0,onClick:w||!b?()=>c("update",e):u,disabled:x||y||a,title:w?f("i18n.updateAvailable"):void 0,children:f(n===`update:${g}`?"i18n.updating":a?"i18n.checking":w||!b?"i18n.update":"i18n.check")}),(0,r.jsx)(ll,{size:"small",onClick:h,disabled:!l||y||x,title:f(l?"i18n.reloadSession":"i18n.openSessionToReload"),children:f(y?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(ll,{variant:"danger",size:"small",onClick:()=>c("remove",e),disabled:x||y,children:f(n===`remove:${g}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(ls,{checked:v,loading:x||y,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:l3(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"))}),w&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:s.displayName,children:f("i18n.updateAvailable")}),b&&(a||s&&!w)&&(0,r.jsx)("span",{className:`skill-update-status ${a?"is-checking":s?.state==="up-to-date"?"is-success":s?.state==="error"?"is-error":"is-muted"}`,children:a?f("i18n.checking"):s?.state==="up-to-date"?f("i18n.upToDate"):s?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):s?.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?l4(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:l4(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(lt,{children:f("i18n.resolvedResources")}),(0,r.jsx)(l7,{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 sr({extension:e}){let{t}=(0,m.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsxs)(o6,{children:[(0,r.jsx)(o3,{children:(0,r.jsxs)(o7,{children:[(0,r.jsx)(l9,{scope:e.scope}),(0,r.jsx)(le,{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:l4(e.path)})]})]})}function si({cwd:e,sessionId:t,onClose:n,onReloaded:o,embedded:l=!1}){let{t:s}=(0,m.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[h,p]=(0,i.useState)(null),[f,g]=(0,i.useState)(()=>oH("plugins",e)),[x,y]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[w,k]=(0,i.useState)("global"),[j,S]=(0,i.useState)(null),[C,I]=(0,i.useState)(null),[E,M]=(0,i.useState)(null),[T,L]=(0,i.useState)({}),[R,N]=(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=>l5(e)===f)??null,O=B.find(e=>l6(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),y(e=>0===n.packages.length&&0===n.standaloneExtensions.length||e),g(e=>e&&(n.packages.some(t=>l5(t)===e)||n.standaloneExtensions.some(t=>l6(t)===e))?e:n.packages[0]?l5(n.packages[0]):n.standaloneExtensions[0]?l6(n.standaloneExtensions[0]):null)}catch(e){p(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{L({}),P(null),q()},[e]),(0,i.useEffect)(()=>{f&&oB("plugins",f,e)},[e,f]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:H.filter(e=>e.canCheckForUpdates)).map(l5);if(0!==n.length){P(null),N(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}`);L(e=>{let t={...e};for(let e of r.updates??[])t[l5(e)]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{N(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),I(null),M(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),L({}),M(s("i18n.packagesUpdated")),t&&M(`${s("i18n.packagesUpdated")} ${s("agents.reloadRequired")}`)}catch(e){I(e instanceof Error?e.message:String(e))}finally{D(!1)}},[e,t,s]),J=(0,i.useCallback)(async(t,n)=>{let r=l5(n);S(`${t}:${r}`),I(null),M(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]?l5(o.packages[0]):o.standaloneExtensions[0]?l6(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&y(!0),M("Package removed."),L(e=>{let t={...e};return delete t[r],t})):(M({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&L(e=>{let t={...e};return delete t[r],t}))}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=l8(v).trim();if(!t)return;b(t);let n=`${w}\0${t}`;S(`install:${n}`),I(null),M(null);try{var r;let i,o,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:w,cwd:e})}),s=await l.json();if(!l.ok||s.error)throw Error(s.error??`HTTP ${l.status}`);d(s);let a=(r=s.packages,o=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===w&&e.source===i)??r.find(e=>e.scope===w&&e.source===`npm:${o}`)??r.find(e=>e.scope===w&&e.source.endsWith(i)));g(a?l5(a):n),y(!1),b(""),M("Package installed.")}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,w,v]),Z=(0,i.useCallback)(async()=>{if(t){S("reload"),I(null),M(null);try{await r4(t,{type:"reload"}),o?.(),await q(),M("Session reloaded.")}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(null)}}},[q,o,t]),X=j?.startsWith("install:")??!1,G=Object.values(T).filter(e=>"update-available"===e.state).length,Q=H.some(e=>e.canCheckForUpdates),ee=c||null!==j||R.size>0||A;return(0,r.jsxs)(oQ,{embedded:l,title:s("common.plugins"),subtitle:l4(e),closeLabel:s("i18n.close"),onClose:n,children:[!U&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:s("trust.pluginsNotLoaded")}),(0,r.jsxs)(o0,{children:[(0,r.jsxs)(o1,{children:[(0,r.jsx)(o2,{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)(o4,{children:s("i18n.extensions")}),B.map(e=>{let t=l6(e);return(0,r.jsxs)(o8,{active:!x&&f===t,title:e.path,onClick:()=>{g(t),y(!1),I(null),M(null)},children:[(0,r.jsx)(ld,{active:e.enabled}),(0,r.jsx)(o5,{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)(o4,{children:e.scope}),e.packages.map(e=>{let t=l5(e),n=!x&&f===t;return(0,r.jsxs)(o8,{active:n,onClick:()=>{g(t),y(!1),I(null),M(null)},children:[(0,r.jsx)(ld,{active:!e.disabled,color:l3(e.status)}),(0,r.jsx)(o5,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),T[l5(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:s("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope))]})}),(0,r.jsx)(la,{active:x,onClick:()=>{y(!0),I(null),M(null)},children:s("i18n.addPlugin")})]}),(0,r.jsx)(li,{children:(0,r.jsx)(o6,{className:"is-fill",children:x?(0,r.jsx)(st,{cwd:e,source:v,scope:w,projectResourcesLoaded:U,busy:X,actionError:C,onSourceChange:b,onScopeChange:k,onInstall:Y}):c?null:O?(0,r.jsx)(sr,{extension:O}):F?(0,r.jsx)(sn,{pkg:F,cwd:e,busyKey:j,actionError:C,actionMessage:E,sessionId:t,updateStatus:T[l5(F)],checkingUpdate:R.has(l5(F)),updateError:z,onAction:J,onCheckUpdate:()=>void K(F),onReloadSession:Z},l5(F)):(0,r.jsx)(lr,{children:s("i18n.selectPackage")})})})]}),(0,r.jsxs)(lo,{status:G>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[G," ",1===G?s("i18n.update"):s("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:[!l&&(0,r.jsx)(ll,{onClick:n,children:s("i18n.close")}),Q&&(0,r.jsx)(ll,{variant:G>0?"primary":"secondary",onClick:()=>void(G>0?V():K()),disabled:ee,title:G>0?s("i18n.updateAllPluginsHint"):void 0,children:A?s("i18n.updating"):$?s("i18n.checking"):G>0?`${s("i18n.updateAllPlugins")} (${G})`:s("i18n.checkUpdates")}),(0,r.jsx)(ll,{variant:"secondary",onClick:()=>void q(),disabled:ee,children:s("i18n.refresh")})]})]})}let so=new Set(["openai-codex","antigravity","xai"]);function sl({sessionId:e=null,onReloaded:t}){let{t:n}=(0,m.s)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(!1),[p,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(null),[y,v]=(0,i.useState)(null),[b,w]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=new AbortController;return a(!0),x(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=ss(n);l(r)}catch(e){e instanceof DOMException&&"AbortError"===e.name||x(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}`);l(ss(n)),f(!!e)},j=async e=>{c(!0),x(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){x(e instanceof Error?e.message:String(e))}finally{c(!1)}},S=async()=>{if(!b||!b.label.trim())return void w(null);c(!0),x(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:b.id,label:b.label.trim()})});await k(e),w(null)}catch(e){x(e instanceof Error?e.message:String(e))}finally{c(!1)}},C=async()=>{if(y){c(!0),x(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"edit"===y.mode?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify("edit"===y.mode?{id:y.id,label:y.label,provider:y.provider,model:y.model}:{label:y.label,provider:y.provider,model:y.model})});await k(e),v(null)}catch(e){x(e instanceof Error?e.message:String(e))}finally{c(!1)}}},I=async e=>{if(window.confirm(n("agents.deleteConfirm",{name:e.label}))){c(!0),x(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),y?.mode==="edit"&&y.id===e.id&&v(null)}catch(e){x(e instanceof Error?e.message:String(e))}finally{c(!1)}}},E=async()=>{if(e){h(!0),x(null);try{await r4(e,{type:"reload"}),f(!1),t?.()}catch(e){x(e instanceof Error?e.message:String(e))}finally{h(!1)}}},M=o?.connections.filter(e=>"custom"!==e.kind)??[],T=o?.connections.filter(e=>"custom"===e.kind)??[],L=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)("section",{className:"settings-general-section",children:[(0,r.jsx)("p",{className:"settings-general-description",children:n("settings.imagesDescription")}),(0,r.jsxs)("div",{className:"settings-image-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:n("settings.imagesEnabled")}),(0,r.jsxs)("div",{className:"settings-image-actions",children:[p&&e&&(0,r.jsx)(ll,{size:"small",onClick:()=>void E(),disabled:u||d,children:u?n("agents.reloading"):n("agents.reloadSession")}),(0,r.jsx)(ls,{checked:o?.enabled===!0,disabled:s||u||!o,loading:d&&!y&&!b,label:n("settings.imagesEnabled"),onChange:e=>void j({enabled:e})})]})]}),o?.enabled&&(0,r.jsxs)(r.Fragment,{children:[o.connections.some(e=>e.enabled)&&(0,r.jsxs)("label",{className:"settings-image-field",children:[(0,r.jsx)("span",{children:n("settings.imagesDefault")}),(0,r.jsx)("select",{value:o.defaultConnection,disabled:s||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))})]}),(0,r.jsxs)("div",{className:"settings-general-columns",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"settings-image-group",children:n("settings.imagesBuiltin")}),M.map(e=>(0,r.jsx)(sa,{connection:e,disabled:s||u||d,unsignedLabel:n("settings.imagesSignedOut"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),renaming:b?.id===e.id,renameValue:b?.id===e.id?b.label:e.label,onRenameChange:t=>w({id:e.id,label:t}),onRenameSubmit:()=>void S(),onRenameCancel:()=>w(null),onEdit:()=>{v(null),w({id:e.id,label:e.label})},editLabel:n("i18n.rename")},e.id))]}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"settings-image-group-row",children:[(0,r.jsx)("h3",{className:"settings-image-group",children:n("settings.imagesCustom")}),L.length>0&&!y&&(0,r.jsx)(ll,{size:"small",disabled:s||u||d,onClick:()=>{w(null),v({mode:"create",label:"",provider:L.find(e=>!so.has(e.id))?.id??L[0]?.id??"",model:""})},children:n("settings.imagesAddConnection")})]}),0===L.length&&(0,r.jsx)("p",{className:"settings-general-description",children:n("settings.imagesNoProviders")}),T.map(e=>(0,r.jsx)(sa,{connection:e,disabled:s||u||d,unsignedLabel:n("settings.imagesNotConfigured"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),onEdit:()=>{w(null),v({mode:"edit",id:e.id,label:e.label,provider:e.provider,model:e.model})},onDelete:()=>void I(e),editLabel:n("image.edit"),deleteLabel:n("agents.delete")},e.id)),y&&(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:y.label,onChange:e=>v({...y,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:y.provider,onChange:e=>v({...y,provider:e.target.value}),required:!0,children:L.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)(sc,{value:y.model,t:n,onChange:e=>{let t=ec.find(t=>t.model===e);v({...y,model:e,..."create"===y.mode&&!y.label.trim()&&t?{label:t.label}:{}})}},"edit"===y.mode?y.id:"create")]}),(0,r.jsxs)("div",{className:"settings-image-form-actions",children:[(0,r.jsx)(ll,{type:"submit",variant:"primary",size:"small",disabled:d||!y.label.trim()||!y.provider||!y.model.trim(),children:d?n("agents.saving"):n("agents.save")}),(0,r.jsx)(ll,{type:"button",size:"small",disabled:d,onClick:()=>v(null),children:n("trust.cancel")})]})]})]})]})]}),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})]})]})]})}function ss(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 sa({connection:e,disabled:t,unsignedLabel:n,onChange:o,onEdit:l,onDelete:s,editLabel:a,deleteLabel:d,renaming:c=!1,renameValue:u,onRenameChange:h,onRenameSubmit:p,onRenameCancel:f}){let g=(0,i.useRef)(!1),x=!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:[l&&!c?(0,r.jsx)(ll,{size:"small",disabled:t,onClick:l,children:a}):null,s?(0,r.jsx)(ll,{size:"small",disabled:t,onClick:s,children:d}):null,(0,r.jsx)(ls,{checked:e.enabled,disabled:t||x,label:e.label,onChange:o})]})]})}let sd="__other__";function sc({value:e,onChange:t,t:n}){let o=ec.some(t=>t.model===e),[l,s]=(0,i.useState)(!o),a=l||!o?sd:e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("select",{value:a,onChange:e=>{let n=e.target.value;n===sd?s(!0):(s(!1),t(n))},children:[ec.map(e=>(0,r.jsxs)("option",{value:e.model,children:[e.label," \xb7 ",e.model]},e.model)),(0,r.jsx)("option",{value:sd,children:n("settings.imagesOtherModel")})]}),a===sd?(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),required:!0}):null]})}let su=null;async function sh(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(su)return su;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 su=null,!1}})();return su=t,t.then(e=>{e||su!==t||(su=null)}),t}let sp="pi-web-sarasa-enabled";async function sf(){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(sp,"1"),await document.fonts.load('14px "Sarasa Term SC Web"')}function sg({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)(V,{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 sx({preference:e}){return"light"===e?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",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:"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)("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:"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:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}function sm({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:o}){let{locale:l,setLocale:s,supportedLocales:a,t:d}=(0,m.s)(),{preference:c,setThemePreference:u}=tO(),{width:h,setWidth:p,fontSize:f,setFontSize:g}=re(),[x,y]=(0,i.useState)(null),[v,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(!0),[E,M]=(0,i.useState)(!1),[T,L]=(0,i.useState)(null),[R,N]=(0,i.useState)(!1),[$,W]=(0,i.useState)(null),[z,P]=(0,i.useState)(!1),[A,D]=(0,i.useState)(!1),[H,B]=(0,i.useState)(""),[F,O]=(0,i.useState)("available"),[U,_]=(0,i.useState)(null);(0,i.useEffect)(()=>{S(t4()),I(oO()),M(ri())},[]),(0,i.useEffect)(()=>{fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>P(e?.enabled===!0)).catch(()=>{})},[]),(0,i.useEffect)(()=>rZ(L),[]);let q=[{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||y(n)}).catch(t=>{e||k(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let K=async n=>{b(!0),k(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}`);y(i),e&&(await r4(e,{type:"reload"}),t())}catch(e){k(e instanceof Error?e.message:String(e))}finally{b(!1)}},V=async()=>{if(!R){N(!0),W(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 sh(l))throw Error("unsupported or not permitted");W({kind:"ok",message:d("settings.pushRegistered")})}catch(e){W({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{N(!1)}}};(0,i.useEffect)(()=>{O("1"===localStorage.getItem(sp)?"cached":"available")},[]);let J=async()=>{O("loading"),_(null);try{await sf(),O("cached")}catch(e){O("error"),_(e instanceof Error?e.message:String(e))}},Y=async()=>{D(!0),B("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{B(d("auth.logoutFailed"))}finally{D(!1)}};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-general-columns",children:[(0,r.jsxs)("div",{children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:q.map(e=>{let t=c===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>u(e.id),className:"settings-theme-option",children:[(0,r.jsx)(sx,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",children:e.label})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.thinkingExpandedDefault")}),(0,r.jsx)(ls,{checked:j,label:d("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(t1,String(e)),window.dispatchEvent(new Event(t2)),S(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.autoSessionTitle")}),(0,r.jsx)(ls,{checked:C,label:d("settings.autoSessionTitle"),onChange:e=>{window.localStorage.setItem(oF,String(e)),I(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:d("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[h,"px"]}),(0,r.jsx)(ll,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("settings.resetChatContentWidth"),disabled:820===h,onClick:()=>p(820),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",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"})})})]}),(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)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:d("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[f,"px"]}),(0,r.jsx)(ll,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("settings.resetChatContentFontSize"),disabled:14===f,onClick:()=>g(14),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",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"})})})]}),(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)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.shiftEnterToSend")}),(0,r.jsx)(ls,{checked:E,label:d("settings.shiftEnterToSend"),onChange:e=>{window.localStorage.setItem(rr,String(e)),M(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(ls,{checked:n,label:d("settings.quoteSelection"),onChange:o})]}),T&&(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.browserNotifications")}),"granted"===T?(0,r.jsx)("span",{className:"settings-chat-status",children:d("settings.browserNotificationsOn")}):"denied"===T?(0,r.jsx)("span",{className:"settings-chat-status",children:d("settings.browserNotificationsBlocked")}):(0,r.jsx)(ll,{size:"small",onClick:()=>{Notification.requestPermission().then(L)},children:d("settings.browserNotificationsEnable")})]})]})]}),x?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(ls,{checked:x.powerShellEnabled,loading:v,label:d("settings.usePowerShell"),onChange:e=>void K(e)})]}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-language-options",children:a.map(e=>{let t=l===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>s(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),z&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(ll,{variant:"secondary",disabled:A,onClick:()=>void Y(),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",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),A?d("auth.loggingOut"):d("auth.logOut")]}),H&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:H})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.typography")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.typographyDescription")}),"cached"===F?(0,r.jsxs)("div",{role:"status",className:"settings-font-status",children:[(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsxs)("span",{children:[d("settings.fontCached")," \xb7 ",d("settings.fontCachedDescription")]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"settings-font-link-row",children:(0,r.jsx)(ll,{size:"small",variant:"secondary",disabled:"loading"===F,onClick:()=>void J(),children:"loading"===F?d("settings.fontDownloadLoading"):d("settings.fontDownload")})}),(0,r.jsx)("p",{role:"status",className:"error"===F?"settings-general-error":"settings-general-description",children:"error"===F?`${d("settings.fontDownloadFailed")} ${U}`:d("settings.fontNotInstalled")})]})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.pushPermissionDescription")}),(0,r.jsx)("div",{className:"settings-font-link-row",children:(0,r.jsx)(ll,{size:"small",variant:"secondary",disabled:R,onClick:()=>void V(),children:R?d("settings.pushRegisterLoading"):d("settings.pushRegister")})}),$&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===$.kind?{color:"var(--accent)"}:void 0,children:$.message})]})]})]})]})}function sy({cwd:e,sessionId:t,initialSection:n,onClose:o,onSessionReloaded:l,onModelsChanged:s,quoteSelectionEnabled:a,onQuoteSelectionChange:d}){let{t:c}=(0,m.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}];(0,i.useEffect)(()=>oD(n),[n]),(0,i.useEffect)(()=>{let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),o())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),(0,i.useEffect)(()=>{e||"skills"!==u&&"agents"!==u&&"plugins"!==u||(h("general"),f(e=>new Set(e).add("general")),oD("general"))},[e,u]);let x=e=>{f(t=>new Set(t).add(e)),h(e),oD(e)},y=(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&&o()},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=>x(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:()=>x(t.id),children:[(0,r.jsx)(sg,{section:t.id}),(0,r.jsx)("span",{children:t.label})]},t.id)})}),(0,r.jsx)("button",{type:"button",onClick:o,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:[y("general",(0,r.jsx)(sm,{sessionId:t,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),y("models",(0,r.jsx)(lP,{embedded:!0,onClose:o,cwd:e,onModelsChanged:s})),e&&y("agents",(0,r.jsx)(l2,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e)),y("images",(0,r.jsx)(sl,{sessionId:t,onReloaded:l})),e&&y("skills",(0,r.jsx)(lU,{embedded:!0,cwd:e,onClose:o},e)),e&&y("plugins",(0,r.jsx)(si,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e))]})]})})}function sv({cwd:e,busy:t,error:n,onCancel:o,onConfirm:l}){let{t:s}=(0,m.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:s("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:s("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:s("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:l,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:s(t?"trust.trusting":"trust.trustProject")})]})]})})}function sb(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function sw(e){let t=e,n=t.branchPreview,r=sb(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&sb(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function sk(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 sj({node:e,activePathIds:t,depth:n,isLast:i,parentLines:o,onSelect:l}){let{node:s,skipped:a,branchPreview:d,labelEntry:c}=sw(e),u=t.has(s.entry.id),h=t.has(e.entry.id)||t.has(s.entry.id),p=d?.text??function(e){if("message"===e.type&&sb(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:sb(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:()=>l(s.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})]}),s.children.map((e,a)=>(0,r.jsx)(sj,{node:e,activePathIds:t,depth:n+1,isLast:a===s.children.length-1,parentLines:[...o,!i],onSelect:l},e.entry.id))]})}function sS({tree:e,activeLeafId:t,onLeafChange:n,inline:o,containerRef:l,open:s,onToggle:a,hasSession:d,compact:c,hideInlineButton:u,disabled:h=!1}){let{t:p}=(0,m.s)(),[f,g]=(0,i.useState)(!1),x=void 0!==s?s:f,y=(0,i.useRef)(null),[v,b]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!x||!o)return;let e=l?.current??y.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();b({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[x,o,l]);let w=(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?sk(e)?null:p("i18n.noBranches"):p("i18n.noActiveSession"),S=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=sw(e[0]).node;return t.children.length>1?t.children:[]}(e),C=!j&&S.length>0,I=h||!C,E=(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:I?"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"})]}),M=(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:x?"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:y,disabled:I,onClick:()=>{I||(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:x?"var(--bg-selected)":"none",border:"none",cursor:I?"not-allowed":"pointer",color:I?"var(--text-dim)":x?"var(--text)":"var(--text-muted)",opacity:I?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{I||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{I||(e.currentTarget.style.color=x?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=x?"var(--bg-selected)":"none")},title:I?p("i18n.noBranches",{defaultValue:"没有分支"}):p("i18n.branches"),"aria-label":p("i18n.branches"),"aria-pressed":x,children:[E,!c&&(0,r.jsx)("span",{style:{lineHeight:1},children:p("i18n.branches")})]}),x&&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)(sj,{node:e,activePathIds:w,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:[E,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:p("i18n.branches")}),M]}),x&&(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)(sj,{node:e,activePathIds:w,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 sC({mobile:e,disabled:t,menuOpen:n,exporting:o=!1,error:l,labels:s,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?s.unsaved:s.menu,"aria-label":s.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":s.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:sI,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:s.full})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",title:s.exportMarkdownTitle,disabled:o,onClick:()=>{d()},style:{...sI,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:s.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"})]})]}),l&&(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"#dc2626",lineHeight:1.35},children:l})]})]})}let sI={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 sE({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
10
|
.system-prompt-panel {
|
|
11
11
|
display: flex;
|
|
12
12
|
height: min(600px, 75dvh);
|
|
@@ -229,4 +229,4 @@ ${t}`:e:t}function nD(e){return{data:e.data,mimeType:e.mimeType}}function nH(e,t
|
|
|
229
229
|
box-shadow: none;
|
|
230
230
|
}
|
|
231
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${tl?"":" sidebar-mobile-pending"}`,"aria-hidden":"true",onClick:ng,style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!te,pointerEvents:te?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:tp.panelRef,id:"session-sidebar",role:"navigation","aria-label":"Pi Web","aria-hidden":!!L&&!te||void 0,inert:!!L&&!te||void 0,className:`sidebar-container${te?" sidebar-open":" sidebar-closed"}${tl?"":" sidebar-mobile-pending"}${tp.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${tp.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}),te&&(0,r.jsx)("div",{...tp.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tp.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${T("layout.resizeSidebar")}: ${T("layout.resizeHint")}`}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tw,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{position:"relative"},children:[(0,r.jsx)("button",{ref:tZ,"data-dialog-focus-fallback":"true",className:"workspace-header-action",onClick:nf,title:te?T("sidebar.hide"):T("sidebar.show"),"aria-label":te?T("sidebar.hide"):T("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:te?(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"})]})}),L&&(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)]}),!L&&(0,r.jsxs)(r.Fragment,{children:[!rs&&rR&&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)(i_,{tabs:ej,activeTabId:eL??"",activePane:"primary",runningSessionIds:eo,onSelectTab:rp,onCloseTab:rf,onPinTab:rj,onNewTab:rg,onToggleSplit:rm,canSplit:rl,unifiedHeader:!0})}),te||!rR||ej.length>0?null:(0,r.jsx)("button",{type:"button",onClick:()=>nu("session"),title:rF,"aria-label":rF,"aria-pressed":"session"===nl,"aria-expanded":"session"===nl,"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"===nl?"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:rN})]})]}),!L&&rU(!1),L&&t$&&(0,r.jsx)(sS,{tree:tk,activeLeafId:tS,onLeafChange:tD,inline:!0,compact:!0,containerRef:tw,open:"branches"===nl,onToggle:()=>nu("branches"),hasSession:rR,hideInlineButton:!0}),nl&&na&&(0,r.jsxs)("div",{ref:t0,id:"workspace-top-panel",role:"region","aria-label":"agents"===nl?T("agentSwitcher.title"):"system"===nl?T("system.prompt"):"tools"===nl?T("tools.title"):T("session.title"),style:{position:"fixed",top:na.top,left:na.left,width:na.width,maxHeight:`calc(100dvh - ${na.top}px - 16px)`,overflowY:"agents"===nl?"visible":"auto",zIndex:520},children:["agents"===nl&&en&&F&&(0,r.jsx)(sP,{rootSession:en.root,subagents:en.subagents,selectedSessionId:F.id,runningSessionIds:eo,onSelectSession:nK,onOpenInNewTab:nq}),"system"===nl&&(0,r.jsx)(sE,{loading:tq,prompt:tH,translate:T}),"tools"===nl&&(0,r.jsx)(sL,{loading:tq,tools:tF,translate:T}),"session"===nl&&(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:L?"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:()=>nc(!0),title:T("i18n.close"),"aria-label":T("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"})]})})}),t8?(t=t8.totalActiveMs??0,n={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},s=(e,t)=>{let i=t7===e;return(0,r.jsx)("button",{type:"button",title:i?T("session.copied"):T(n[e]),onClick:()=>nt(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=nn??t8.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,x=a?.tokens!==null&&a?.contextWindow?Math.max(0,a.contextWindow-a.tokens):null,y=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:T("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:T("session.contextUsed")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:rn(a.tokens,M)})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.contextWindow")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:rn(a.contextWindow,M)}),null!==x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.contextRemaining")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:rn(x,M)})]})]}),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:T("chat.contextHighWarning")})]})]}):null,w=(v=t8.tokens.cacheRead+t8.tokens.cacheWrite)+t8.tokens.input>0?`${(t8.tokens.cacheRead/(v+t8.tokens.input)*100).toFixed(1)}%`:null,k=(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:T("session.cumulativeTokens")}),t8.cost>0&&(0,r.jsxs)("span",{style:{fontSize:11,fontWeight:650,color:"var(--text)"},children:["$",t8.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:T("session.total")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:rn(t8.tokens.total,M)}),(0,r.jsxs)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:[T("session.input")," / ",T("session.output")]}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:[rn(t8.tokens.input,M)," / ",rn(t8.tokens.output,M)]}),t8.tokens.cacheRead>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.cacheRead")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:rn(t8.tokens.cacheRead,M)})]}),w&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.cacheHitRate")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:w})]})]})]}),S=(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:T("session.infoSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5,fontSize:11.5},children:[t8.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:[T("session.name"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text)",fontWeight:550,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t8.sessionName})]}),F&&(j=X&&F.cwd.startsWith(X)?`~${F.cwd.slice(X.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:[T("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:j})}),F.branch&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:["\xb7 ",F.branch]}),s(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:[T("session.messages"),":"]}),(0,r.jsxs)("span",{style:{color:"var(--text-muted)",whiteSpace:"nowrap"},children:[t8.userMessages," ",T("session.user").toLowerCase()," \xb7 ",t8.assistantMessages," ",T("session.assistant").toLowerCase()," \xb7 ",t8.toolCalls," ",T("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)})`:""]})]}),t8.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:[T("session.file"),":"]}),(0,r.jsx)("span",{title:t8.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:t8.sessionFile})}),s("file",t8.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:[T("session.id"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:t8.sessionId?`${t8.sessionId.slice(0,8)}...${t8.sessionId.slice(-6)}`:"?"}),t8.sessionId&&s("id",t8.sessionId)]})]})]}),(0,r.jsxs)("div",{className:"session-stats-grid",style:{fontFamily:"var(--font-mono)",lineHeight:1.45},children:[y,k,S]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:T("session.load")})]})]})]}),L&&rR&&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)(i_,{tabs:ej,activeTabId:eL??"",activePane:"primary",runningSessionIds:eo,onSelectTab:rp,onCloseTab:rf,onPinTab:rj,onNewTab:rg,canSplit:!1,isMobile:!0})}),L&&rH(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative",display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{ref:eO,style:{flex:1,overflow:"hidden",position:"relative",display:"grid",minHeight:0,gridTemplateColumns:rs?`${100*eB}% 0 minmax(0, 1fr)`:"minmax(0, 1fr)",gridTemplateRows:rs?"auto minmax(0, 1fr)":"minmax(0, 1fr)"},children:rR?(0,r.jsxs)(r.Fragment,{children:[rs&&(0,r.jsx)("div",{style:{gridColumn:1,gridRow:1,minWidth:0,overflow:"hidden"},onPointerDownCapture:()=>rc("primary"),children:(0,r.jsx)(i_,{tabs:rt,activeTabId:eL??"",activePane:"primary"===eP?"primary":"secondary",runningSessionIds:eo,onSelectTab:ru,onCloseTab:rf,onPinTab:rj,onNewTab:()=>rg("primary"),onToggleSplit:rm,canSplit:!1})}),ej.length>0?ej.map(e=>{let t=rs?iK(e):"primary",n=e.id===("secondary"===t?e$:eL),i="secondary"===t?"secondary"===eP:ra,o=e.mountKey??e.id;return(0,r.jsx)("div",{"data-chat-pane":t,onPointerDownCapture:()=>{n&&rs&&rc(t)},style:{gridColumn:"secondary"===t?3:1,gridRow:rs?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:rs?2:1,minHeight:0,display:"flex",flexDirection:"column"},children:rS(F,rE,rM,ra,void 0,!0)}),rs&&(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*s_(e_).min),"aria-valuemax":Math.round(100*s_(e_).max),"aria-valuenow":Math.round(100*eB),tabIndex:0,title:T("chatTabs.splitView",{defaultValue:"调整分屏大小"}),onPointerDown:n3,onPointerMove:n7,onPointerUp:n9,onPointerCancel:n9,onKeyDown:re,onDoubleClick:()=>eF(.5)}),rs&&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)(i_,{tabs:rr,activeTabId:e$??"",activePane:"secondary"===eP?"primary":"secondary",runningSessionIds:eo,onSelectTab:rh,onCloseTab:rf,onPinTab:rj,onNewTab:()=>rg("secondary"),onClosePane:rm,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:T("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:E.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:T("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:E.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${tn?" is-open":""}`,onClick:()=>nm(!0)}),tn&&(0,r.jsx)("div",{...tf.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tf.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${T("layout.resizeFilePanel")}: ${T("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tf.panelRef,id:"file-panel","aria-hidden":!tn,inert:!tn||void 0,className:`right-panel-container${tn?" right-panel-open":" right-panel-closed"}${tf.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tf.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)(oL,{tabs:nI,activeTabId:nb??"",onSelectTab:nw,onCloseTab:rw})}),(0,r.jsx)("button",{type:"button",onClick:()=>nm(!0),className:"workspace-header-action right-panel-header-close","aria-controls":"file-panel",title:T("files.hidePanel"),"aria-label":T("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)(oC,{filePath:rz.filePath,cwd:rz.cwd??nM??void 0,sourceSessionId:rz.sourceSessionId,gitRefreshKey:eZ,initialDisplayMode:rz.initialDisplayMode,initialState:rz.viewerState,watchEnabled:ti,pdfPage:rz.pdfPage,onStateChange:e=>nE(rz.id,rz.viewerRevision??0,e),onMentionLines:tn?n$:void 0,onAtMention:nR,onOpenFile:e=>ry(e,b(e),{sourceSessionId:rz.sourceSessionId,cwd:rz.cwd})},`${rz.id}:${rz.viewerRevision??0}`):nk.some(e=>e.id===nb)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:T("files.noneOpen")}),nk.map(e=>(0,r.jsx)("div",{hidden:e.id!==nb,style:{width:"100%",height:"100%"},children:(0,r.jsx)(sB,{tab:e,active:tn&&e.id===nb,onRestart:()=>nj(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n,r;return t="restart"===e.closing?sO(e.cwd):null,n=nk.filter(t=>t.id!==e.id),r=oR(nI,e.id),void(nj(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nw(n=>n!==e.id?n:t?.id??r),!t&&!n.length&&!ny.length&&tr(!1))},onCloseError:()=>nj(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),eG&&(0,r.jsx)(sy,{cwd:r$,sessionId:F?.id??null,initialSection:eG,quoteSelectionEnabled:P,onQuoteSelectionChange:D,onClose:()=>{eQ(null),e1(e=>e+1)},onSessionReloaded:()=>eb(e=>e+1),onModelsChanged:()=>e1(e=>e+1)}),e8&&r$&&(0,r.jsx)(sv,{cwd:r$,busy:e6,error:e7,onCancel:()=>{e6||e5(!1)},onConfirm:()=>void rW()})]})}},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"}},94423:(e,t,n)=>{Promise.resolve().then(n.bind(n,66582)),Promise.resolve().then(n.bind(n,21278))}},e=>{e.O(0,[7523,7330,3888,5931,1278,8441,3794,7358],()=>e(e.s=94423)),_N_E=e.O()}]);
|
|
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${tl?"":" sidebar-mobile-pending"}`,"aria-hidden":"true",onClick:ng,style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!te,pointerEvents:te?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:tp.panelRef,id:"session-sidebar",role:"navigation","aria-label":"Pi Web","aria-hidden":!!L&&!te||void 0,inert:!!L&&!te||void 0,className:`sidebar-container${te?" sidebar-open":" sidebar-closed"}${tl?"":" sidebar-mobile-pending"}${tp.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${tp.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}),te&&(0,r.jsx)("div",{...tp.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tp.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${T("layout.resizeSidebar")}: ${T("layout.resizeHint")}`}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tw,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{position:"relative"},children:[(0,r.jsx)("button",{ref:tZ,"data-dialog-focus-fallback":"true",className:"workspace-header-action",onClick:nf,title:te?T("sidebar.hide"):T("sidebar.show"),"aria-label":te?T("sidebar.hide"):T("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:te?(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"})]})}),L&&(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)]}),!L&&(0,r.jsxs)(r.Fragment,{children:[!rs&&rR&&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)(i_,{tabs:ej,activeTabId:eL??"",activePane:"primary",runningSessionIds:eo,onSelectTab:rp,onCloseTab:rf,onPinTab:rj,onNewTab:rg,onToggleSplit:rm,canSplit:rl,unifiedHeader:!0})}),te||!rR||ej.length>0?null:(0,r.jsx)("button",{type:"button",onClick:()=>nu("session"),title:rF,"aria-label":rF,"aria-pressed":"session"===nl,"aria-expanded":"session"===nl,"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"===nl?"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:rN})]})]}),!L&&rU(!1),L&&t$&&(0,r.jsx)(sS,{tree:tk,activeLeafId:tS,onLeafChange:tD,inline:!0,compact:!0,containerRef:tw,open:"branches"===nl,onToggle:()=>nu("branches"),hasSession:rR,hideInlineButton:!0}),nl&&na&&(0,r.jsxs)("div",{ref:t0,id:"workspace-top-panel",role:"region","aria-label":"agents"===nl?T("agentSwitcher.title"):"system"===nl?T("system.prompt"):"tools"===nl?T("tools.title"):T("session.title"),style:{position:"fixed",top:na.top,left:na.left,width:na.width,maxHeight:`calc(100dvh - ${na.top}px - 16px)`,overflowY:"agents"===nl?"visible":"auto",zIndex:520},children:["agents"===nl&&en&&F&&(0,r.jsx)(sP,{rootSession:en.root,subagents:en.subagents,selectedSessionId:F.id,runningSessionIds:eo,onSelectSession:nK,onOpenInNewTab:nq}),"system"===nl&&(0,r.jsx)(sE,{loading:tq,prompt:tH,translate:T}),"tools"===nl&&(0,r.jsx)(sL,{loading:tq,tools:tF,translate:T}),"session"===nl&&(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:L?"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:()=>nc(!0),title:T("i18n.close"),"aria-label":T("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"})]})})}),t8?(t=t8.totalActiveMs??0,n={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},s=(e,t)=>{let i=t7===e;return(0,r.jsx)("button",{type:"button",title:i?T("session.copied"):T(n[e]),onClick:()=>nt(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=nn??t8.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,x=a?.tokens!==null&&a?.contextWindow?Math.max(0,a.contextWindow-a.tokens):null,y=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:T("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:T("session.contextUsed")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:rn(a.tokens,M)})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.contextWindow")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:rn(a.contextWindow,M)}),null!==x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.contextRemaining")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:rn(x,M)})]})]}),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:T("chat.contextHighWarning")})]})]}):null,w=(v=t8.tokens.cacheRead+t8.tokens.cacheWrite)+t8.tokens.input>0?`${(t8.tokens.cacheRead/(v+t8.tokens.input)*100).toFixed(1)}%`:null,k=(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:T("session.cumulativeTokens")}),t8.cost>0&&(0,r.jsxs)("span",{style:{fontSize:11,fontWeight:650,color:"var(--text)"},children:["$",t8.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:T("session.total")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:rn(t8.tokens.total,M)}),(0,r.jsxs)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:[T("session.input")," / ",T("session.output")]}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:[rn(t8.tokens.input,M)," / ",rn(t8.tokens.output,M)]}),t8.tokens.cacheRead>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.cacheRead")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:rn(t8.tokens.cacheRead,M)})]}),w&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:T("session.cacheHitRate")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:w})]})]})]}),S=(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:T("session.infoSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5,fontSize:11.5},children:[t8.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:[T("session.name"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text)",fontWeight:550,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t8.sessionName})]}),F&&(j=X&&F.cwd.startsWith(X)?`~${F.cwd.slice(X.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:[T("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:j})}),F.branch&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:["\xb7 ",F.branch]}),s(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:[T("session.messages"),":"]}),(0,r.jsxs)("span",{style:{color:"var(--text-muted)",whiteSpace:"nowrap"},children:[t8.userMessages," ",T("session.user").toLowerCase()," \xb7 ",t8.assistantMessages," ",T("session.assistant").toLowerCase()," \xb7 ",t8.toolCalls," ",T("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)})`:""]})]}),t8.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:[T("session.file"),":"]}),(0,r.jsx)("span",{title:t8.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:t8.sessionFile})}),s("file",t8.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:[T("session.id"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:t8.sessionId?`${t8.sessionId.slice(0,8)}...${t8.sessionId.slice(-6)}`:"?"}),t8.sessionId&&s("id",t8.sessionId)]})]})]}),(0,r.jsxs)("div",{className:"session-stats-grid",style:{fontFamily:"var(--font-mono)",lineHeight:1.45},children:[y,k,S]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:T("session.load")})]})]})]}),L&&rR&&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)(i_,{tabs:ej,activeTabId:eL??"",activePane:"primary",runningSessionIds:eo,onSelectTab:rp,onCloseTab:rf,onPinTab:rj,onNewTab:rg,canSplit:!1,isMobile:!0})}),L&&rH(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative",display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{ref:eO,style:{flex:1,overflow:"hidden",position:"relative",display:"grid",minHeight:0,gridTemplateColumns:rs?`${100*eB}% 0 minmax(0, 1fr)`:"minmax(0, 1fr)",gridTemplateRows:rs?"auto minmax(0, 1fr)":"minmax(0, 1fr)"},children:rR?(0,r.jsxs)(r.Fragment,{children:[rs&&(0,r.jsx)("div",{style:{gridColumn:1,gridRow:1,minWidth:0,overflow:"hidden"},onPointerDownCapture:()=>rc("primary"),children:(0,r.jsx)(i_,{tabs:rt,activeTabId:eL??"",activePane:"primary"===eP?"primary":"secondary",runningSessionIds:eo,onSelectTab:ru,onCloseTab:rf,onPinTab:rj,onNewTab:()=>rg("primary"),onToggleSplit:rm,canSplit:!1})}),ej.length>0?ej.map(e=>{let t=rs?iK(e):"primary",n=e.id===("secondary"===t?e$:eL),i="secondary"===t?"secondary"===eP:ra,o=e.mountKey??e.id;return(0,r.jsx)("div",{"data-chat-pane":t,onPointerDownCapture:()=>{n&&rs&&rc(t)},style:{gridColumn:"secondary"===t?3:1,gridRow:rs?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:rs?2:1,minHeight:0,display:"flex",flexDirection:"column"},children:rS(F,rE,rM,ra,void 0,!0)}),rs&&(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*s_(e_).min),"aria-valuemax":Math.round(100*s_(e_).max),"aria-valuenow":Math.round(100*eB),tabIndex:0,title:T("chatTabs.splitView",{defaultValue:"调整分屏大小"}),onPointerDown:n3,onPointerMove:n7,onPointerUp:n9,onPointerCancel:n9,onKeyDown:re,onDoubleClick:()=>eF(.5)}),rs&&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)(i_,{tabs:rr,activeTabId:e$??"",activePane:"secondary"===eP?"primary":"secondary",runningSessionIds:eo,onSelectTab:rh,onCloseTab:rf,onPinTab:rj,onNewTab:()=>rg("secondary"),onClosePane:rm,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:T("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:E.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:T("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:E.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${tn?" is-open":""}`,onClick:()=>nm(!0)}),tn&&(0,r.jsx)("div",{...tf.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tf.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${T("layout.resizeFilePanel")}: ${T("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tf.panelRef,id:"file-panel","aria-hidden":!tn,inert:!tn||void 0,className:`right-panel-container${tn?" right-panel-open":" right-panel-closed"}${tf.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tf.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)(oL,{tabs:nI,activeTabId:nb??"",onSelectTab:nw,onCloseTab:rw})}),(0,r.jsx)("button",{type:"button",onClick:()=>nm(!0),className:"workspace-header-action right-panel-header-close","aria-controls":"file-panel",title:T("files.hidePanel"),"aria-label":T("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)(oC,{filePath:rz.filePath,cwd:rz.cwd??nM??void 0,sourceSessionId:rz.sourceSessionId,gitRefreshKey:eZ,initialDisplayMode:rz.initialDisplayMode,initialState:rz.viewerState,watchEnabled:ti,pdfPage:rz.pdfPage,onStateChange:e=>nE(rz.id,rz.viewerRevision??0,e),onMentionLines:tn?n$:void 0,onAtMention:nR,onOpenFile:e=>ry(e,b(e),{sourceSessionId:rz.sourceSessionId,cwd:rz.cwd})},`${rz.id}:${rz.viewerRevision??0}`):nk.some(e=>e.id===nb)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:T("files.noneOpen")}),nk.map(e=>(0,r.jsx)("div",{hidden:e.id!==nb,style:{width:"100%",height:"100%"},children:(0,r.jsx)(sB,{tab:e,active:tn&&e.id===nb,onRestart:()=>nj(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n,r;return t="restart"===e.closing?sO(e.cwd):null,n=nk.filter(t=>t.id!==e.id),r=oR(nI,e.id),void(nj(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nw(n=>n!==e.id?n:t?.id??r),!t&&!n.length&&!ny.length&&tr(!1))},onCloseError:()=>nj(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),eG&&(0,r.jsx)(sy,{cwd:r$,sessionId:F?.id??null,initialSection:eG,quoteSelectionEnabled:P,onQuoteSelectionChange:D,onClose:()=>{eQ(null),e1(e=>e+1)},onSessionReloaded:()=>eb(e=>e+1),onModelsChanged:()=>e1(e=>e+1)}),e8&&r$&&(0,r.jsx)(sv,{cwd:r$,busy:e6,error:e7,onCancel:()=>{e6||e5(!1)},onConfirm:()=>void rW()})]})}},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=64873)),_N_E=e.O()}]);
|