@calmabacus/pi-web 1.2.2 → 1.2.3

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.
Files changed (54) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +10 -10
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/required-server-files.js +1 -1
  5. package/.next/required-server-files.json +1 -1
  6. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/server/app/_global-error.html +1 -1
  8. package/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/server/app/_not-found.html +1 -1
  14. package/.next/server/app/_not-found.rsc +4 -4
  15. package/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  16. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +4 -4
  17. package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
  18. package/.next/server/app/api/app-update/route.js +1 -1
  19. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  20. package/.next/server/app/api/sessions/route.js +1 -1
  21. package/.next/server/app/index.html +1 -1
  22. package/.next/server/app/index.rsc +6 -6
  23. package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -6
  24. package/.next/server/app/index.segments/_full.segment.rsc +6 -6
  25. package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
  26. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  27. package/.next/server/app/login.html +1 -1
  28. package/.next/server/app/login.rsc +5 -5
  29. package/.next/server/app/login.segments/_full.segment.rsc +5 -5
  30. package/.next/server/app/login.segments/_tree.segment.rsc +3 -3
  31. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +5 -5
  32. package/.next/server/app/page.js +23 -21
  33. package/.next/server/app/page_client-reference-manifest.js +1 -1
  34. package/.next/server/app-paths-manifest.json +10 -10
  35. package/.next/server/chunks/2243.js +1 -1
  36. package/.next/server/chunks/6429.js +1 -1
  37. package/.next/server/chunks/8759.js +1 -1
  38. package/.next/server/middleware-build-manifest.js +1 -1
  39. package/.next/server/pages/404.html +1 -1
  40. package/.next/server/pages/500.html +1 -1
  41. package/.next/static/chunks/1278-cee1a583acfdbbe3.js +1 -0
  42. package/.next/static/chunks/app/{layout-784aeba1512001f4.js → layout-27fe292fb4ac13b1.js} +1 -1
  43. package/.next/static/chunks/app/page-5fed5824645066c6.js +232 -0
  44. package/.next/static/css/491a0a5a0e53b1a3.css +1 -0
  45. package/.next/static/css/f8fa1f54e8c1b29d.css +1 -0
  46. package/.next/trace +7 -42
  47. package/.next/trace-build +1 -1
  48. package/package.json +1 -1
  49. package/.next/static/chunks/1278-497845aeb7531287.js +0 -1
  50. package/.next/static/chunks/app/page-3e5eeae6263d1d85.js +0 -230
  51. package/.next/static/css/64b5dad00e57cbf2.css +0 -1
  52. package/.next/static/css/b38207f874cd6169.css +0 -1
  53. /package/.next/static/{b8SGxsoAxmt_qKP0W83xq → bgANcYaziFYzUL8D6omlF}/_buildManifest.js +0 -0
  54. /package/.next/static/{b8SGxsoAxmt_qKP0W83xq → bgANcYaziFYzUL8D6omlF}/_ssgManifest.js +0 -0
@@ -1,230 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{9669:(e,t,n)=>{Promise.resolve().then(n.bind(n,40871)),Promise.resolve().then(n.bind(n,21278))},14755:(e,t,n)=>{"use strict";n.d(t,{Q8:()=>r,YO:()=>p,getPresetFromTools:()=>h,sn:()=>u,xG:()=>s});let r="configured",i=[r,"none","read-only","default","full"];function s(e){if(e!==r)return"none"===e?[...l]:"read-only"===e?[...o]:"full"===e?[...d]:[...a]}let l=[],o=["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===[...o].sort().join(",")?"read-only":t===[...a].sort().join(",")?"default":t===[...d].sort().join(",")?"full":"default"}},40871:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>o2});var r=n(95155),i=n(12115),s=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,s=r.id,l=null;for(;;){if(n.has(s)){l=n.get(s)??null;break}if(i.has(s))break;i.add(s),e.push(s);let r=t.get(s);if(!r)break;if(r.relation?.kind!=="subagent"){l=r.id;break}s=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 o="pi-web:file-explorer:open";function a(){try{return window.localStorage}catch{return null}}function d(e,t=a()){if(t)try{t.setItem(o,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 m(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=m(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(([e,{root:t}])=>({key:e,root:t}))}function f(e,t){return e.filter(e=>m(e)===t)}let x="pi-sidebar-single-project",v="pi-sidebar-single-project-changed";function y(){return"true"===window.localStorage.getItem(x)}var b=n(2730),w=n(21278);function k(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function j(e){return k(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function S(e){let t=k(e).replace(/\/+$/,"");return t.split("/").pop()??t}function C(e){let t=k(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function N(e,t){if(!t)return e;let n=k(e),r=k(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function E(e,t){return`${k(e).replace(/\/$/,"")}/${t}`}var I=n(47650);async function M(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function T(){return(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function L(){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4",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 $({onCancel:e,onSelect:t,initialPath:n,busy:s=!1,error:l}){let{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(n??""),[f,x]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await M(e),n=t.path??e??"/";u(n),p(t.parentPath??null),g(n),x(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),C(n||void 0)},[n,C]);let N=m.trim()!==c,E=!!c&&!N&&!s,R=!!h||/^[a-zA-Z]:[\\/]?$/.test(c);return a?(0,I.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":o("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||s||e()},onKeyDown:t=>{"Escape"!==t.key||s||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:600,fontSize:14},children:o("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:s,title:o("i18n.close"),"aria-label":o("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:s?"default":"pointer",opacity:s?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=m.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(h??void 0),disabled:j||!R,title:o("directoryPicker.goToParent"),"aria-label":o("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:R?"pointer":"default",opacity:R?1:.45},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:"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:o("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:m,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||!m.trim(),title:o("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||!m.trim()?"default":"pointer",opacity:j||!m.trim()?.6:1},children:o("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:o("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(L,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:o("directoryPicker.noDrives")})}):f.length>0?f.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(T,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:o("directoryPicker.noSubdirectories")}),(b||l)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:b??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:s,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:s?"default":"pointer",fontSize:12},children:o("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!E,title:o(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--primary)",color:"var(--primary-contrast)",fontSize:12,opacity:E?1:.6,cursor:E?"pointer":"default"},children:o(s?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),a):null}function R({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon":`url(/icons/catppuccin/latte/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function W({size:e=14,open:t=!1}){return(0,r.jsx)(R,{name:t?"_folder_open":"_folder",size:e})}function z({size:e=14}){return(0,r.jsx)(R,{name:"_file",size:e})}let P={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function A(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(R,{name:i,size:t});let s=P[n.split(".").pop()??""];return s?(0,r.jsx)(R,{name:s,size:t}):(0,r.jsx)(z,{size:t})}function D({open:e}){return(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.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 F(e){let t=j(e),n=await fetch(`/api/files/${t}?type=list`);if(!n.ok){let e=`Failed to load files (HTTP ${n.status})`;try{let t=await n.json();t.error&&(e=t.error)}catch{}throw Error(e)}return((await n.json()).entries??[]).map(t=>({name:t.name,fullPath:E(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function B(e){let t=new URLSearchParams({cwd:e}),n=await fetch(`/api/git/status?${t.toString()}`);if(!n.ok)throw Error(`Failed to load Git status (HTTP ${n.status})`);return n.json()}let H={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},O={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function U({status:e,t}){return(0,r.jsx)("span",{title:t(H[e.status]),"aria-label":t(H[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:O[e.status],fontFamily:"var(--font-mono)",fontSize:11},children:e.code})}function _(){return(0,r.jsxs)("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)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function q({onClick:e,title:t}){return(0,r.jsx)("button",{type:"button",onClick:e,title:t,"aria-label":t,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-muted)",cursor:"pointer"},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="none"},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:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}function K({node:e,depth:t,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:o,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p}){let m=o.has(e.fullPath),g=c.has(e.fullPath),f=k(e.fullPath),x=u.get(f),v=e.isDir&&(void 0!==x||h.has(f)),[y,b]=(0,i.useState)(e.children??[]),[w,S]=(0,i.useState)(e.loaded??!1),[C,E]=(0,i.useState)(!1),[I,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(!1),$=(0,i.useCallback)(async(t=!1)=>{if(!w||t){E(!0),M(null);try{let t=await F(e.fullPath);b(t),S(!0)}catch(e){M(e instanceof Error?e.message:String(e))}finally{E(!1)}}},[w,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&m&&w&&$(!0)},[d]);let R=(0,i.useCallback)(()=>{if(e.isDir){let t=!m;a(e.fullPath,t)}else s(e.fullPath,e.name,{cwd:n})},[n,e.isDir,e.fullPath,e.name,m,s,a]);return(0,i.useEffect)(()=>{m&&!w&&$()},[$,w,m]),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:R,onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:2,paddingLeft:2+14*t,paddingRight:8,height:28,boxSizing:"border-box",cursor:"pointer",background:T?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",display:"inline-flex"},children:(0,r.jsx)(D,{open:m})}),!e.isDir&&(0,r.jsx)("span",{style:{width:12,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",color:T?"var(--text)":"var(--text-muted)"},children:e.isDir?(0,r.jsx)(W,{size:13,open:m}):A(e.name,13)}),(0,r.jsx)("span",{style:{fontSize:12,lineHeight:1,color:T?"var(--text)":"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),g&&(0,r.jsx)("span",{title:p("files.newlyUploaded"),"aria-label":p("files.newlyUploaded"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#3b82f6"}})}),!T&&!e.isDir&&x&&(0,r.jsx)(U,{status:x,t:p}),!T&&v&&(0,r.jsx)("span",{title:p("files.containsChangedFiles"),"aria-label":p("files.containsChangedFiles"),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#d6a84b"}})}),C&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"3",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&&T&&(0,r.jsxs)("button",{onClick:t=>{t.stopPropagation(),l(N(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,whiteSpace:"nowrap"},children:[(0,r.jsx)(_,{}),p("files.mention")]}),T&&!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${j(e.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:p("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,whiteSpace:"nowrap",textDecoration:"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",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&&m&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(K,{node:e,depth:t+1,cwd:n,onOpenFile:s,onAtMention:l,expandedPaths:o,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:h,t:p},e.fullPath)),0===y.length&&w&&(0,r.jsx)("div",{style:{paddingLeft:2+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"}),I&&(0,r.jsx)("button",{type:"button",onClick:()=>void $(!0),title:I,style:{marginLeft:2+(t+1)*14,height:22,padding:0,border:0,background:"none",color:"#f87171",cursor:"pointer",fontSize:11},children:p("files.loadFailedRetry")})]})]})}function V({status:e,cwd:t,onOpenFile:n,t:s}){let[l,o]=(0,i.useState)(!1),a=S(e.filePath),d=N(e.filePath,t);return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,a,{modeHint:"diff",cwd:t}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!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)(U,{status:e,t:s}),(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",color:l?"var(--text)":"var(--text-muted)"},children:A(a,13)}),(0,r.jsx)("span",{style:{fontSize:12,lineHeight:1,color:l?"var(--text)":"var(--text-muted)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:d})]})}let J=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:s,onAtMentions:l,onUploadBusyChange:o,changesCollapsed:a,onChangesCountChange:d,fileSearchOpen:c=!1,onFileSearchOpenChange:u},h){let{t:p}=(0,w.s)(),[m,g]=(0,i.useState)([]),[f,x]=(0,i.useState)(!0),[v,y]=(0,i.useState)(null),[b,S]=(0,i.useState)(new Set),[I,M]=(0,i.useState)(0),[T,L]=(0,i.useState)(new Set),[$,R]=(0,i.useState)([]),[W,z]=(0,i.useState)({additions:0,deletions:0}),[P,A]=(0,i.useState)(null),[D,H]=(0,i.useState)(null),[U,J]=(0,i.useState)("idle"),[Y,Z]=(0,i.useState)(0),[X,G]=(0,i.useState)(null),[Q,ee]=(0,i.useState)(null),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(""),[es,el]=(0,i.useState)([]),[eo,ea]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)(!1),[eu,eh]=(0,i.useState)(new Set),ep=(0,i.useRef)(null),em=(0,i.useRef)(null),eg=(0,i.useRef)(null),ef=(0,i.useRef)(null),ex=`${n??0}:${I}`,ev="idle"!==U,ey=er.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=er.trim();if(!t){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(ex)}`,{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,ex,er]),(0,i.useEffect)(()=>{c&&ep.current?.focus()},[c]),(0,i.useEffect)(()=>{if(0===es.length)return;let t=new Set;for(let n of es){let r=n.split("/"),i="";for(let n=0;n<r.length-1;n++)i=i?`${i}/${r[n]}`:r[n],t.add(E(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,es]);let eb=(0,i.useMemo)(()=>{let t=n=>({name:n.name,fullPath:E(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,s="";for(let t=0;t<e.length;t++){s=s?`${s}/${e[t]}`:e[t];let r=n.get(s);r||(r={name:e[t],path:s,isDir:t<e.length-1,children:[]},n.set(s,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})(es).map(t)},[e,es]),ew=(0,i.useMemo)(()=>new Map($.map(e=>[k(e.filePath),e])),[$]),ek=(0,i.useMemo)(()=>{let t=new Set,n=k(e).replace(/\/$/,"");for(let e of $){let r=C(k(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=C(r);if(e===r)break;r=e}}return t},[e,$]),ej=(0,i.useCallback)((e,t)=>{S(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),eS=(0,i.useCallback)(t=>{let n=t.uploaded??[];ee({uploaded:n,skipped:t.skipped??[],errors:t.errors??[]}),n.length>0&&(L(new Set(n.map(t=>E(e,t)))),M(e=>e+1))},[e]),eC=(0,i.useCallback)(async(t,n)=>{en(null),G(null),Z(0),J("uploading");try{let{status:r,data:i}=await new Promise((r,i)=>{let s=new FormData;t.forEach(e=>s.append("files",e,e.name));let l=new XMLHttpRequest;l.open("POST",`/api/files/${j(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(s)});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]),eN=(0,i.useCallback)(async t=>{if(0!==t.length&&!ev){ee(null),L(new Set),en(null),G(null),Z(0),J("checking");try{let n=await fetch(`/api/files/${j(e)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:t.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void en({files:t,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await eC(t,"error")}catch(e){G(e instanceof Error?e.message:String(e))}finally{J("idle")}}},[e,eC,ev]),eE=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eN(t)},[eN]);(0,i.useImperativeHandle)(h,()=>({openUploadPicker(){ev||ef.current?.click()}}),[ev]),(0,i.useEffect)(()=>{o?.(ev)},[o,ev]),(0,i.useEffect)(()=>()=>o?.(!1),[o]),(0,i.useEffect)(()=>{let t=em.current!==e;em.current=e,t&&(S(new Set),L(new Set),ee(null),en(null),G(null)),x(t),y(null);let n=!1;return F(e).then(e=>{n||g(e)}).catch(e=>{n||y(e instanceof Error?e.message:String(e))}).finally(()=>{n||x(!1)}),()=>{n=!0}},[e,n,I]),(0,i.useEffect)(()=>{let t=!1;return eg.current!==e&&(A(null),R([]),z({additions:0,deletions:0})),H(null),B(e).then(n=>{t||(R(n.isGitRepository?n.files:[]),z(n.isGitRepository?{additions:n.additions,deletions:n.deletions}:{additions:0,deletions:0}),eg.current=e,A(e))}).catch(e=>{t||H(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e,n,I]),(0,i.useEffect)(()=>{d?.(P===e?$.length:0)},[e,$,P,d]);let eI=ev||null!==et||null!==X||null!==Q,eM=(0,i.useCallback)(()=>{Q&&0!==Q.uploaded.length&&l?.(Q.uploaded.map(t=>N(E(e,t),e)),e)},[e,l,Q]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:ef,type:"file",multiple:!0,hidden:!0,onChange:eE}),eI&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[ev&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===U?p("files.checking"):p("files.uploading",{progress:Y}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===U?(0,r.jsx)("svg",{width:"12",height:"12",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:"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)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===U&&(0,r.jsxs)("span",{style:{fontSize:11},children:[Y,"%"]})]}),"uploading"===U&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${Y}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),et&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, #f59e0b 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, #f59e0b 9%, var(--bg-panel))"},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:p("files.conflictSummary",{count:et.conflicts.length,countSuffix:1===et.conflicts.length?"":"s",files:et.conflicts.join(", ")})}),et.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:11,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:11},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:11},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:11},children:p("files.cancel")})]})]}),X&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"#f87171"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:X}),(0,r.jsx)(q,{onClick:()=>G(null),title:p("files.dismissError")})]}),Q&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[Q.uploaded.length>0&&(0,r.jsxs)("span",{title:`${Q.uploaded.length} uploaded`,"aria-label":`${Q.uploaded.length} uploaded`,style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"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)("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:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.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:"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)("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:eM,title:1===Q.uploaded.length?p("files.addUploadedFile"):p("files.addAllUploadedFiles"),"aria-label":1===Q.uploaded.length?p("files.addUploadedFile"):p("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,whiteSpace:"nowrap"},children:[(0,r.jsx)(_,{}),p("files.mention")]}),(0,r.jsx)(q,{onClick:()=>ee(null),title:p("files.dismissUploadResults")})]}),Q.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:11,color:"#f87171"},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:{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.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:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),ey&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[eo&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:11,color:"var(--text-dim)"},children:p("sidebar.searchingFiles")}),!eo&&ed&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:11,color:"#f87171"},children:p("i18n.networkError")}),!eo&&!ed&&0===es.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:11,color:"var(--text-dim)"},children:p("sidebar.noMatchingFiles")}),!eo&&!ed&&es.length>0&&(0,r.jsx)("div",{children:eb.map(n=>(0,r.jsx)(K,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:s,expandedPaths:eu,onToggleExpanded:(e,t)=>{eh(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:T,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},`${er}:${n.fullPath}`))})]})]}),D&&(0,r.jsx)("div",{role:"alert",title:D,style:{padding:"6px 12px",fontSize:11,color:"#f87171"},children:p("files.gitStatusFailed")}),!a&&P===e&&$.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":p("files.changeStats",{count:$.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:$.length})}),(0,r.jsxs)("span",{style:{color:O.added,fontFamily:"var(--font-mono)"},children:["+",W.additions]}),(0,r.jsxs)("span",{style:{color:O.deleted,fontFamily:"var(--font-mono)"},children:["-",W.deletions]})]}),$.map(n=>(0,r.jsx)(V,{status:n,cwd:e,onOpenFile:t,t:p},n.filePath))]}),(a||P!==e||0===$.length)&&(!c||!ey)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[f?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:v}):m.map(n=>(0,r.jsx)(K,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:s,expandedPaths:b,onToggleExpanded:ej,refreshToken:ex,highlightedPaths:T,gitStatusByPath:ew,changedDirectoryPaths:ek,t:p},n.fullPath)),!f&&!v&&0===m.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:p("files.noFiles")})]})]})});function Y({open:e,query:t,refreshKey:n,children:s,selectedSessionId:l,onSelectSession:o}){let{t:a,locale:d}=(0,w.s)(),[c,u]=(0,i.useState)({query:""}),h=t.trim(),p=c.query===h?c.response:void 0,m=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&&!m,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:m?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:s,after:a})=>(0,r.jsxs)("button",{type:"button",onClick:()=>o(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 text-text",children:e.name||e.firstMessage}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[11px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:e.cwd,children:e.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,b.fw)(e.modified,d)})]}),(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[i,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:s}),a]})]},e.id))]}):s}function Z({size:e=14,title:t,ariaLabel:n,className:i,style:s}){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,...s},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 X(e){return Math.round(264/e)/10}function G({size:e=13,className:t,style:n}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:X(e),strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:t,style:{flexShrink:0,...n},children:[(0,r.jsx)("rect",{x:"2",y:"8",width:"14",height:"14",rx:"2"}),(0,r.jsx)("path",{d:"M8 2h12a2 2 0 0 1 2 2v12"})]})}function Q({onClick:e,title:t,disabled:n,skipHover:i,color:s,background:l="none",marginRight:o,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:o,background:l,border:"none",color:s,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)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||i||(e.currentTarget.style.color=s,e.currentTarget.style.background=l)},children:c})}function ee({open:e}){return(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(D,{open:e})})}let et="pi-web:unread-session-ids",en="pi-web:last-custom-cwd",er="pi-web:workspace-expansion";function ei(){try{let e=window.localStorage.getItem(er);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 es(){try{return window.localStorage.getItem(en)??""}catch{return""}}function el(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eo({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 ea({open:e,children:t,style:n}){let[s,l]=(0,i.useState)(e),[o,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]),s)?(0,r.jsx)("div",{style:{...n,opacity:+!!o,transform:o?"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 ed({selectedSessionId:e,onSelectSession:t,onOpenSessionInNewTab:n,onPinSession:s,onNewSession:c,initialSessionId:u,skipInitialProjectSelection:h,refreshKey:p,onSessionDeleted:x,selectedCwd:b,onCwdChange:k,onOpenFile:j,onOpenTerminal:C,explorerRefreshKey:N,onExplorerRefresh:E,onAtMention:I,onAtMentions:M,onBackgroundTaskDone:T,onRunningSessionIdsChange:L,onSessionsChange:R,pinnedCwds:W,onTogglePinnedCwd:z,onHomeDirChange:P,onWorktreeInfoChange:A}){let D,F,B,{t:H}=(0,w.s)(),[O,U]=(0,i.useState)([]),[_,q]=(0,i.useState)(null),K=(0,i.useRef)(null),V=(0,i.useRef)(0),[X,G]=(0,i.useState)(!0),[ec,eu]=(0,i.useState)(null),[ep,em]=(0,i.useState)(null),[eg,ef]=(0,i.useState)(""),[ex,ev]=(0,i.useState)(!1),[ey,eb]=(0,i.useState)(""),[ew,ek]=(0,i.useState)(!1),[ej,eS]=(0,i.useState)(es),[eC,eN]=(0,i.useState)(null),[eE,eI]=(0,i.useState)(!1),[eM,eT]=(0,i.useState)(null),eL=(0,i.useRef)(null),[e$,eR]=(0,i.useState)(null),[eW,ez]=(0,i.useState)(!1),[eP,eA]=(0,i.useState)(!1),[eD,eF]=(0,i.useState)(""),[eB,eH]=(0,i.useState)(null),[eO,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(null),eJ=(0,i.useRef)(null),eY=(0,i.useRef)(null),[eZ,eX]=(0,i.useState)(!0),[eG,eQ]=(0,i.useState)(!0),[e0,e1]=(0,i.useState)(ei),[e2,e4]=(0,i.useState)({}),[e8,e3]=(0,i.useState)(0),[e6,e5]=(0,i.useState)(!1),[e7,e9]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(""),ti=te&&!!tn.trim(),[ts,tl]=(0,i.useState)(0),[to,ta]=(0,i.useState)(!0),[td,tc]=(0,i.useState)(()=>new Set),[tu,th]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(et);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),tp=(0,i.useRef)(new Set),tm=(0,i.useRef)(new Set),tg=(0,i.useRef)(new Set),tf=(0,i.useRef)(!1),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),[ty,tb]=(0,i.useState)(0),[tw,tk]=(0,i.useState)(0),[tj,tS]=(0,i.useState)(null),[tC,tN]=(0,i.useState)(null),[tE,tI]=(0,i.useState)(null),[tM,tT]=(0,i.useState)(null),[tL,t$]=(0,i.useState)(null),[tR,tW]=(0,i.useState)(null),tz=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(!1),tD=(0,i.useRef)(null),tF=(0,i.useCallback)(e=>{tN(null),tI(null);let t=e.currentTarget.scrollTop;null==tD.current&&(tD.current=requestAnimationFrame(()=>{tD.current=null,tk(t)}))},[]);(0,i.useEffect)(()=>{if(!tC&&!tE)return;let e=e=>{let t=e.target;t?.closest(".session-row-actions, .workspace-row-action")||(tN(null),tI(null))};return window.addEventListener("pointerdown",e,!0),()=>window.removeEventListener("pointerdown",e,!0)},[tC,tE]);let tB=(0,i.useCallback)((e,t)=>{if(t.target?.closest(".workspace-row-action"))return;let n=t.touches[0];tP.current={x:n.clientX,y:n.clientY},tA.current=!1,tz.current=setTimeout(()=>{tA.current=!0,tI(e),navigator.vibrate?.(15)},400)},[]),tH=(0,i.useCallback)(e=>{if(!tP.current||!tz.current)return;let t=e.touches[0];(Math.abs(t.clientX-tP.current.x)>10||Math.abs(t.clientY-tP.current.y)>10)&&(clearTimeout(tz.current),tz.current=null)},[]),tO=(0,i.useCallback)(()=>{tz.current&&clearTimeout(tz.current),tz.current=null,tP.current=null},[]);(0,i.useLayoutEffect)(()=>{let e=tv.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)tb(t.contentRect.height)});return t.observe(e),tb(e.clientHeight),tk(e.scrollTop),()=>t.disconnect()},[ti]);let tU=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++V.current;try{e&&G(!0);let r=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.json();if(n!==V.current)return;K.current=i.sessionListVersion,q(i.sessionListVersion),U(i.sessions),tf.current||(tm.current=new Set(i.completionNotificationSuppressedSessionIds??[]),tc(new Set(i.runningSessionIds??[])));let s=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));th(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>s.has(e)));return t.size===e.size?e:t}),eu(null)}catch(e){n===V.current&&eu(String(e))}finally{n===V.current&&G(!1)}},[]),t_=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!t_.current;t_.current=!0,tU(e,!e)},[tU,p]),(0,i.useEffect)(()=>{eX(function(e=a()){if(!e)return!0;try{return"false"!==e.getItem(o)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===tu.size?window.localStorage.removeItem(et):window.localStorage.setItem(et,JSON.stringify([...tu]))}catch{}},[tu]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let s=new AbortController;n?.abort(),n=s;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:s.signal});if(!t.ok)return;let r=await t.json();if(e||n!==s)return;tf.current=!0,tm.current=new Set(r.completionNotificationSuppressedSessionIds??[]),tc(new Set(r.runningSessionIds??[])),r.sessionListVersion!==K.current&&await tU()}catch{}finally{n===s&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},s=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",s),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",s)}},[tU]),(0,i.useEffect)(()=>{L?.(td)},[L,td]),(0,i.useEffect)(()=>{R?.(O)},[O,R]),(0,i.useEffect)(()=>{let t=tp.current,n=[...t].filter(t=>!td.has(t)&&t!==e),r=new Set(O.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!tg.current.has(e)&&!r.has(e)),s=[...td].filter(e=>!t.has(e));(i.length>0||s.length>0)&&th(e=>{let t=new Set(e);return td.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let l=s.some(e=>!O.some(t=>t.id===e));(n.length>0||l)&&tU(!1,!0),i.length>0&&T?.(i),tp.current=td,tg.current=new Set([...td].filter(e=>tm.current.has(e)||r.has(e)))},[td,e,O,tU,T]),(0,i.useEffect)(()=>{e&&th(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==N&&e3(e=>e+1)},[N]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&ef(e.home)}).catch(()=>{})},[]),(0,i.useEffect)(()=>{eg&&P?.(eg)},[eg,P]);let tq=(0,i.useRef)(!1),tK=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tV=(0,i.useCallback)(e=>{if(!e)return null;if(eM?.cwd===e)return tK(eM.root,eM.key);if(e$&&e$.forCwd===e||e$?.worktrees.some(t=>t.path===e))return tK(e$.projectRoot,e$.projectKey);let t=O.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tK(t.projectRoot??t.cwd,m(t)):tK(e,e)},[eM,e$,O,tK]),tJ=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tV(ep),t=tJ.current;(t?.cwd!==ep||t.key!==(e?.key??null))&&(tJ.current={cwd:ep,key:e?.key??null},k?.(ep,e?.root??null,e?.key??null))},[ep,k,tV]);let tY=(0,i.useRef)(null);(0,i.useEffect)(()=>{b&&b!==tY.current&&(tY.current=b,em(b))},[b]);let[tZ,tX]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!ep){eR(null),eV(null);return}let e=!1;return eV(ep),fetch(`/api/worktrees?cwd=${encodeURIComponent(ep)}`).then(e=>e.json()).then(t=>{if(!e){if(eV(null),t.error||!t.projectRoot)return void eR(null);eR({forCwd:ep,projectRoot:t.projectRoot,projectKey:t.projectKey??t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,currentWorktreePath:t.currentWorktreePath??null,worktrees:t.worktrees??[]})}}).catch(()=>{e||(eV(null),eR(null))}),()=>{e=!0}},[ep,tZ,p]),(0,i.useEffect)(()=>{if(A){if(!e$?.isGit)return void A(null);A({forCwd:e$.forCwd,projectRoot:e$.projectRoot,currentWorktreePath:e$.currentWorktreePath,worktrees:e$.worktrees})}},[e$,A]),(0,i.useEffect)(()=>{if(0!==O.length&&!h&&null===ep){if(u&&!tq.current){tq.current=!0;let e=O.find(e=>e.id===u);if(e){em(e.cwd),t(e,!0);return}}let e=g(O);e.length>0&&em(e[0].root)}},[O,ep,u,h,t]);let tG=e$?e$.worktrees.find(e=>e.path===ep)??(e$.forCwd===ep&&e$.currentWorktreePath?e$.worktrees.find(e=>e.path===e$.currentWorktreePath):void 0)??e$.worktrees.find(e=>e.isMain):void 0,tQ=tG?.path??null,t0=(0,i.useCallback)(async e=>{let t=(e??ej).trim();if(t&&!eE){eI(!0),eN(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 eN(r.error??`HTTP ${e.status}`);eT({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(en,n)}catch{}eS(r.cwd),W.includes(r.projectRoot)||z(r.projectRoot),e1(e=>new Set([...e??[],r.projectKey])),em(r.cwd),ek(!1),ev(!1)}catch(e){eN(e instanceof Error?e.message:String(e))}finally{eI(!1)}}},[ej,eE,z,W]),t1=(0,i.useCallback)(()=>{ek(!0),eN(null),ev(!1)},[]),t2=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(W.includes(t.cwd)||z(t.cwd),e1(e=>new Set([...e??[],t.cwd])),em(t.cwd),ek(!1),eN(null),ev(!1))}catch{}},[z,W]),t4=(0,i.useCallback)(async()=>{let e=eD.trim();if(e&&!eO&&e$){eU(!0),eH(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e$.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eH(n.error??`HTTP ${t.status}`);eA(!1),eF(""),ez(!1),eR(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),em(n.path),tX(e=>e+1)}catch(e){eH(e instanceof Error?e.message:String(e))}finally{eU(!1)}}},[eD,eO,e$]),t8=(0,i.useCallback)(async(e,t)=>{if(e$&&!eO){eU(!0),eH(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e$.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eq(e);eH(r.error??`HTTP ${n.status}`);return}eq(null),tQ===e&&em(e$.projectRoot),tX(e=>e+1)}catch(e){eH(e instanceof Error?e.message:String(e))}finally{eU(!1)}}},[e$,eO,tQ]);(0,i.useEffect)(()=>{let e=e=>{eL.current&&!eL.current.contains(e.target)&&ev(!1),eJ.current&&!eJ.current.contains(e.target)&&(ez(!1),eA(!1),eF(""),eH(null),eq(null),eb(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t3=(0,i.useCallback)((e,n,r)=>{U(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e1(t=>{let n=new Set(t??[]);return n.add(m(e)),n});let i=tV(ep)?.key;(function(e){let t=e.sessionCwd;if(!t)return!1;let n=e.selectedCwd;if(!n)return!0;if(t===n)return!1;if(e.sessionProjectKey&&e.selectedProjectKey&&e.sessionProjectKey!==e.selectedProjectKey)return!0;let r=e.worktrees;if(!r?.length)return!0;let i=e=>r.find(t=>t.path===e)?.path??null,s=i(t);return!!s&&s!==(i(n)??n)})({sessionCwd:e.cwd,selectedCwd:ep,sessionProjectKey:m(e),selectedProjectKey:i,worktrees:e$?.worktrees})&&em(e.cwd),t(e,!1,n,r)},[t,tV,ep,e$]),t6=(0,i.useCallback)(e=>{let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;c?.(t,e)},[c]),[t5,t7]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=()=>t7(y());return e(),window.addEventListener(v,e),()=>window.removeEventListener(v,e)},[]);let t9=(0,i.useMemo)(()=>g(O),[O]),ne=!ep&&!X&&!ec&&0===t9.length,nt=(0,i.useMemo)(()=>tV(ep),[tV,ep]),nn=(0,i.useMemo)(()=>{let e=[],t=new Set,n=n=>{!n||t.has(n.key)||(t.add(n.key),e.push(n))};return W.forEach(e=>n(tV(e))),t9.forEach(n),n(nt),e},[W,tV,t9,nt]),nr=(0,i.useMemo)(()=>{let t;return e?t=nt?.key:1===nn.length&&(t=nn[0]?.key),new Set(t?[t]:[])},[nt?.key,e,nn]);(0,i.useEffect)(()=>{null===e0&&0!==nn.length&&e1(nr)},[nr,e0,nn.length]),(0,i.useEffect)(()=>{null!==e0&&function(e){try{window.localStorage.setItem(er,JSON.stringify([...e]))}catch{}}(e0)},[e0]);let ni=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=m(i);if(!e)continue;let s=r.get(e);s||(s={running:0,unread:0},r.set(e,s)),t.has(i.id)&&s.running++,n.has(i.id)&&s.unread++}return r})(O,td,tu),[O,td,tu]),ns=(0,i.useMemo)(()=>{let e=0,t=0;for(let[n,r]of ni)n!==nt?.key&&(e+=r.running,t+=r.unread);return{running:e,unread:t}},[ni,nt?.key]),nl=(0,i.useCallback)(async e=>{tT(null),tW(null),t$(e.key);try{let t=await fetch("/api/projects",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key})}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);for(let t of W)tV(t)?.key===e.key&&z(t);for(let t of(nt?.key===e.key&&em(nn.find(t=>t.key!==e.key)?.root??null),n.deletedSessionIds??[]))x?.(t);tU()}catch(e){tW(e instanceof Error?e.message:String(e))}finally{t$(null)}},[tU,x,z,W,tV,nt?.key,nn]),no=!!(e$?.isGit&&e$.isTopLevel&&ep&&nt?.key===e$.projectKey),na=(0,i.useMemo)(()=>{let t=[],n=e0??nr;for(let r of t5?nn.filter(e=>e.key===(nt??nn[0])?.key):nn){let i=l(f(O,r.key));if(t.push({kind:"workspace",project:r,cwd:i[0]?.root.cwd??r.root}),t5||n.has(r.key)){let n=t5?1/0:e2[r.key]??6,s=i.slice(0,n),l=i.find(t=>t.root.id===e||t.subagents.some(t=>t.id===e));l&&!s.includes(l)&&(s=[...s.slice(0,Math.max(0,n-1)),l]),t.push(...s.map(e=>({kind:"session",family:e})));let o=i.length-s.length;o>0&&t.push({kind:"showMore",projectKey:r.key,remaining:o})}}return t},[O,nr,e0,nt,e,t5,nn,e2]),nd=function(e,t,n,r=-1){let i=Math.ceil((n||600)/28)+16,s=Math.max(0,Math.min(Math.floor(t/28)-8,e-i)),l=Math.min(e,s+i),o=Array.from({length:l-s},(e,t)=>s+t);return r>=0&&r<s&&o.unshift(r),r>=l&&r<e&&o.push(r),o}(na.length,tw,ty,na.findIndex(e=>"session"===e.kind&&e.family.root.id===tj)),nc=no&&e$?(F=(D=e$.worktrees.length>=8)&&ey.trim()?e$.worktrees.filter(e=>(e.branch??el(e.path,eg)).toLowerCase().includes(ey.trim().toLowerCase())):e$.worktrees,B=tG?tG.branch??el(tG.path,eg):"…",(0,r.jsxs)("div",{ref:eJ,className:"workspace-worktree-switcher",style:{minWidth:48,maxWidth:"60%",flex:"0 10000 auto"},children:[(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),ez(e=>!e),ev(!1)},onTouchStart:e=>e.stopPropagation(),title:tG?H("sidebar.switchWorktreeTitle",{path:tG.path}):H("sidebar.switchWorktree"),"aria-expanded":eW,"aria-haspopup":"listbox",style:{display:"flex",alignItems:"center",gap:4,height:22,maxWidth:"100%",minWidth:0,padding:"0 4px",background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:4,cursor:"pointer",fontSize:11,lineHeight:1,color:"var(--text-dim)",textAlign:"left",overflow:"hidden",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{eW||(e.currentTarget.style.background="none"),e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0,fontSize:11,lineHeight:1},children:B})]}),(0,r.jsxs)(ea,{open:eW,style:{position:"absolute",top:"calc(100% + 4px)",left:2,right:2,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[D&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px",borderBottom:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{className:"sidebar-dropdown-filter-input",value:ey,onChange:e=>eb(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eb(""),ez(!1))},placeholder:H("sidebar.filterWorktrees"),autoFocus:!0,style:{flex:1,minWidth:0,fontSize:12,fontFamily:"inherit",padding:"2px 0",border:"none",outline:"none",background:"transparent",color:"var(--text)"}}),ey&&(0,r.jsx)("button",{type:"button",onClick:()=>eb(""),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,padding:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},title:H("chat.clear"),children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",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:[F.map(e=>{let t=e.path===tQ;return e_===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:H("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void t8(e.path,!0),disabled:eO,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",fontSize:11,cursor:"pointer",flexShrink:0},children:H("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eq(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:H("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:()=>{em(e.path),ez(!1),eH(null),eb("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",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)(eo,{text:e.branch??el(e.path,eg),style:{flex:1}}),e.isMain&&(e.branch??"").toLowerCase()!==H("sidebar.main").toLowerCase()&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:H("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void t8(e.path,!1),disabled:eO,title:H("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-muted)",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-muted)",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",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),D&&0===F.length&&ey.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:H("sidebar.noMatchingWorktrees")})]}),eP?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eY,className:"sidebar-dropdown-filter-input",value:eD,onChange:e=>{eF(e.target.value),eH(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t4()),"Escape"===e.key&&(eA(!1),eF(""),eH(null))},placeholder:H("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void t4(),disabled:eO||!eD.trim(),style:{flex:1,padding:"4px 0",background:"var(--primary)",border:"none",borderRadius:4,color:"var(--primary-contrast)",fontSize:11,cursor:eO||!eD.trim()?"not-allowed":"pointer",opacity:eO||!eD.trim()?.65:1},children:eO?H("sidebar.creating"):H("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eA(!1),eF(""),eH(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:H("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eA(!0),eH(null),setTimeout(()=>eY.current?.focus(),0)},title:H("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.3",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:H("sidebar.newWorktree")})]}),eB&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eB})]})]})):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[ew&&(0,r.jsx)($,{initialPath:ej,busy:eE,error:eC,onCancel:()=>{ek(!1),eN(null)},onSelect:e=>void t0(e)}),(0,r.jsxs)("div",{ref:eL,className:"sidebar-section-row",style:{position:"relative"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eQ(e=>!e),className:"sidebar-section-label",children:[(0,r.jsx)(ee,{open:eG}),(0,r.jsx)("span",{children:H("sidebar.projects")})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[t5&&(ns.running>0||ns.unread>0)&&(0,r.jsx)("span",{role:"status",title:H("sidebar.otherProjectActivity"),"aria-label":`${H("sidebar.otherProjectActivity")} (${ns.running+ns.unread})`,style:{display:"inline-flex",alignItems:"center"},children:ns.running>0?(0,r.jsx)(Z,{size:11}):(0,r.jsx)("span",{style:{color:"#10b981",fontSize:10},children:ns.unread})}),(0,r.jsx)(Q,{onClick:()=>{ev(e=>!e),ez(!1)},title:H(t5?"sidebar.switchProject":"sidebar.addProject"),ariaPressed:ex,color:ex?"var(--accent)":"var(--text-muted)",background:ex?"var(--bg-selected)":"none",children:t5?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),(0,r.jsx)(Q,{onClick:()=>{tt(e=>{let t=!e;return t&&eQ(!0),t}),ez(!1),ev(!1)},title:H("sidebar.toggleSessionSearch"),ariaPressed:te,color:te?"var(--accent)":"var(--text-muted)",background:te?"var(--bg-selected)":"none",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})})]}),(0,r.jsxs)(ea,{open:ex,style:{position:"absolute",top:"calc(100% + 4px)",left:6,right:6,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[t5&&(0,r.jsx)("div",{style:{maxHeight:"min(50vh, 380px)",overflowY:"auto",borderBottom:"1px solid var(--border)"},children:nn.map(e=>{let t=e.key===nt?.key,n=W.includes(e.root),i=ni.get(e.key);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"true":void 0,onClick:()=>{em(e.root),ev(!1)},title:e.root,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"7px 10px",background:"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)(eo,{text:el(e.root,eg),style:{flex:1}}),i?.running?(0,r.jsx)(Z,{size:11}):null,i?.unread?(0,r.jsx)("span",{style:{color:"#10b981",fontSize:10},children:i.unread}):null]}),O.some(t=>m(t)===e.key)&&(0,r.jsx)(Q,{onClick:()=>{ev(!1),tT(e.key)},disabled:!!i?.running||tL===e.key,title:H(i?.running?"sidebar.deleteProjectSessionsRunning":"sidebar.deleteProjectSessions"),color:"var(--text-muted)",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","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}),(0,r.jsx)(Q,{onClick:()=>z(e.root),title:H(n?"sidebar.unpinDirectory":"sidebar.pinDirectory"),ariaPressed:n,color:n?"var(--text)":"var(--text-muted)",marginRight:4,children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:n?"currentColor":"none",stroke:"currentColor",strokeWidth:"2.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"})]})})]},e.key)})}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t2()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderBottom:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",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:H("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),t1()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",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:H("sidebar.customPath")})]})]})]}),te&&eG&&(0,r.jsx)("div",{style:{padding:"4px 8px 6px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tn,maxLength:200,"aria-label":H("sidebar.searchSessions"),placeholder:H("sidebar.searchSessions"),onChange:e=>tr(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),tr(""))},className:"block h-[29px] w-full min-w-0 rounded-[4px] border border-border bg-bg px-[10px] text-xs text-text focus:outline-2 focus:outline-accent"})}),(()=>{let e=tM?nn.find(e=>e.key===tM):null;if(!e)return null;let t=S(e.root),n=f(O,e.key).length;return(0,r.jsxs)("div",{role:"alertdialog","aria-labelledby":"delete-project-title","aria-describedby":"delete-project-detail",onKeyDown:e=>{"Escape"===e.key&&tT(null)},style:{margin:"4px 8px 6px",padding:"8px 10px",flexShrink:0,border:"1px solid rgba(239,68,68,0.4)",borderRadius:4,background:"rgba(239,68,68,0.06)",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{id:"delete-project-title",style:{fontWeight:600,color:"#ef4444",overflowWrap:"anywhere"},children:H("sidebar.deleteProjectSessionsConfirm",{name:t,count:n})}),(0,r.jsx)("div",{id:"delete-project-detail",style:{marginTop:4,color:"var(--text-muted)"},children:H("sidebar.deleteProjectSessionsDetail",{name:t,count:n})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:6,marginTop:8},children:[(0,r.jsx)("button",{type:"button",autoFocus:!0,onClick:()=>tT(null),style:{height:24,padding:"0 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},children:H("sidebar.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>void nl(e),style:{height:24,padding:"0 10px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},children:H("sidebar.deleteProjectSessionsAction",{count:n})})]})]})})(),(0,r.jsx)(Y,{open:te&&eG,query:tn,refreshKey:_,selectedSessionId:e,onSelectSession:t3,children:eG&&(0,r.jsxs)("div",{ref:tv,onScroll:tF,style:{flex:eZ&&(b||ep)?"1 1 0":"1 1 auto",overflowY:"auto",padding:"0",minHeight:80},children:[ec&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:ec}),tR&&(0,r.jsx)("div",{role:"alert",onClick:()=>tW(null),style:{padding:"6px 14px",color:"#f87171",fontSize:12,cursor:"pointer"},children:H("sidebar.deleteProjectSessionsFailed",{error:tR})}),!X&&!ec&&!ne&&0===nn.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:H("sidebar.noSessions")}),na.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:28*na.length},children:nd.map(t=>{let i=na[t];if("workspace"===i.kind){let e=(e0??nr).has(i.project.key),n=i.project.key===nt?.key,s=ni.get(i.project.key),l=n&&ep?ep:i.cwd,o=W.includes(i.project.root),a=tE===i.project.key,c=tM===i.project.key;return(0,r.jsxs)("div",{className:`workspace-list-row${a?" is-actions-revealed":""}`,"data-active":n?"true":"false","data-pending-delete":c?"true":void 0,onTouchStart:e=>tB(i.project.key,e),onTouchMove:tH,onTouchEnd:tO,onTouchCancel:tO,onContextMenu:e=>{tA.current&&(e.preventDefault(),e.stopPropagation())},style:{position:"absolute",top:28*t,left:4,right:4,height:28,display:"flex",alignItems:"center",WebkitTouchCallout:"none",userSelect:"none"},children:[(0,r.jsxs)("button",{type:"button","aria-current":n?"page":void 0,"aria-expanded":t5?ex:e,onMouseDown:t5?e=>e.stopPropagation():void 0,onClick:()=>{if(tA.current){tA.current=!1;return}if(t5){ev(e=>!e),ez(!1);return}e&&e4(e=>{if(!(i.project.key in e))return e;let t={...e};return delete t[i.project.key],t}),e1(e=>{let t=new Set(e??nr);return t.has(i.project.key)?t.delete(i.project.key):t.add(i.project.key),t})},title:i.project.root,style:{display:"flex",alignItems:"center",gap:4,flex:"1 1 auto",minWidth:0,height:"100%",padding:"0 4px 0 0",border:"none",background:"none",color:"inherit",cursor:"pointer",textAlign:"left",fontSize:12},children:[(0,r.jsx)(ee,{open:t5?ex:e}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:S(i.project.root)}),s?.running?(0,r.jsx)("span",{role:"status","aria-label":`${H("sidebar.agentRunning")} (${s.running})`,children:(0,r.jsx)(Z,{size:11})}):null,s?.unread?(0,r.jsx)("span",{"aria-label":`${H("sidebar.newSessionActivity")} (${s.unread})`,style:{color:"#10b981",fontSize:10},children:s.unread}):null]}),n?nc:null,(0,r.jsxs)("span",{className:"workspace-row-action",children:[(0,r.jsx)(Q,{onClick:()=>{tI(null),tT(i.project.key)},disabled:!!s?.running||tL===i.project.key,title:H(s?.running?"sidebar.deleteProjectSessionsRunning":"sidebar.deleteProjectSessions"),color:"var(--text-muted)",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:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})}),(0,r.jsx)(Q,{onClick:()=>{tI(null),em(l),eX(!0),d(!0)},title:H("sidebar.openProjectExplorer",{path:l}),color:"var(--text-muted)",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:"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)(Q,{onClick:()=>{tI(null),z(i.project.root)},title:H(o?"sidebar.unpinDirectory":"sidebar.pinDirectory"),ariaPressed:o,color:o?"var(--text)":"var(--text-muted)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:o?"currentColor":"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)(Q,{onClick:()=>{tA.current=!1,tI(null),em(l),e1(e=>new Set([...e??nr,i.project.key])),t6(l)},title:H("sidebar.newSessionTitle",{path:l}),color:"var(--text-muted)",className:"workspace-new-session",marginRight:6,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"})]})})]})]},`workspace:${i.project.key}`)}if("showMore"===i.kind)return(0,r.jsxs)("button",{type:"button",className:"workspace-show-more-button","aria-label":H("sidebar.showMoreSessionsLabel",{count:i.remaining}),onClick:()=>e4(e=>({...e,[i.projectKey]:(e[i.projectKey]??6)+Math.min(20,i.remaining)})),style:{position:"absolute",top:28*t,left:4,right:4,height:28},children:[(0,r.jsx)("span",{children:H("sidebar.showMoreSessions")}),(0,r.jsx)("span",{className:"workspace-show-more-count",children:i.remaining})]},`more:${i.projectKey}`);let l=i.family,o=[l.root,...l.subagents],a=l.latestModified===l.root.modified?l.root:{...l.root,modified:l.latestModified};return(0,r.jsx)("div",{onFocus:()=>tS(l.root.id),onBlur:()=>tS(null),style:{position:"absolute",top:28*t,left:4,right:4},children:(0,r.jsx)(eh,{session:a,indent:14,isSelected:o.some(t=>t.id===e),isRunning:o.some(e=>td.has(e.id)),isUnread:o.some(e=>tu.has(e.id)),isActionsRevealed:tC===l.root.id,onRevealActions:()=>tN(l.root.id),onDismissActions:()=>tN(e=>e===l.root.id?null:e),onClick:()=>{tN(null),t3(l.root)},onRenamed:tU,onOpenInNewTab:n?()=>{tN(null),n(l.root)}:void 0,onPin:s?()=>{tN(null),s(l.root)}:void 0,onDeleted:e=>{tN(null),x?.(e),tU()}})},l.root.id)})})]})}),(b||ep)&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:eZ?"1 1 0":"0 0 auto",minHeight:0,overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"sidebar-section-row",children:[(0,r.jsxs)("button",{onClick:()=>eX(e=>{let t=!e;return d(t),t}),className:"sidebar-section-label",children:[(0,r.jsx)(ee,{open:eZ}),(0,r.jsx)("span",{children:H("files.explorer")})]}),(0,r.jsxs)("div",{className:"sidebar-header-actions",children:[C&&(0,r.jsx)(Q,{onClick:()=>C(ep??b),title:H("terminal.open"),color:"var(--text-muted)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),eZ&&ts>0&&(0,r.jsx)(Q,{onClick:()=>ta(e=>!e),title:H("sidebar.changedFiles",{count:ts}),ariaPressed:!to,color:to?"var(--text-muted)":"var(--accent)",background:to?"none":"var(--bg-selected)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M3 12h6"}),(0,r.jsx)("path",{d:"M15 12h6"})]})}),eZ&&(0,r.jsx)(Q,{onClick:()=>{e9(e=>!e)},title:H("sidebar.searchFiles"),ariaPressed:e7,color:e7?"var(--accent)":"var(--text-muted)",background:e7?"var(--bg-selected)":"none",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]})}),eZ&&(0,r.jsx)(Q,{onClick:()=>tx.current?.openUploadPicker(),disabled:e6,title:H("sidebar.uploadFilesTitle"),color:"var(--text-muted)",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)(Q,{onClick:()=>{E?E():e3(e=>e+1)},title:H("sidebar.refreshExplorer"),color:"var(--text-muted)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]}),eZ&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(J,{ref:tx,cwd:ep??b,onOpenFile:j??(()=>{}),refreshKey:e8,onAtMention:I,onAtMentions:M,onUploadBusyChange:e5,changesCollapsed:to,onChangesCountChange:tl,fileSearchOpen:e7,onFileSearchOpenChange:e9})})]})]})}function ec(){let{t:e}=(0,w.s)();return(0,r.jsx)(Z,{size:14,title:e("sidebar.agentRunning"),ariaLabel:e("sidebar.agentRunning")})}function eu(){let{t:e}=(0,w.s)();return(0,r.jsx)("span",{title:e("sidebar.newSessionActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"5",fill:"#10b981"}),(0,r.jsx)("path",{d:"M3.6 6.2l1.6 1.6 3.2-3.4",stroke:"#ffffff",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]})})}function eh({session:e,isSelected:t,isRunning:n,isUnread:s,isActionsRevealed:l=!1,onRevealActions:o,onDismissActions:a,onClick:d,onRenamed:c,onOpenInNewTab:h,onPin:m,onDeleted:g,indent:f=0,depth:x=0,hasChildren:v=!1,collapsed:y=!1,onToggleCollapse:k}){let{locale:j,t:S}=(0,w.s)(),[C,N]=(0,i.useState)(!1),[E,I]=(0,i.useState)(!1),[M,T]=(0,i.useState)(""),[L,$]=(0,i.useState)(!1),[R,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),F=(0,i.useCallback)(t=>{if(L||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{}o?.()},400)},[L,o,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)},[]),H=(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||(T(p(e)),I(!0))},[e]),q=(0,i.useCallback)(async()=>{let t=M.trim();if(I(!1),M!==U&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[M,e.id,e.name,c,U]),K=(0,i.useCallback)(async()=>{if(!e.transient){$(!1),W(!0);try{let t=await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"});if(!t.ok)throw Error(`HTTP ${t.status}`);g?.(e.id)}catch{W(!1)}}},[e.id,e.transient,g]),V=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?K():$(!0)},[K]),J=(0,i.useCallback)(e=>{e.stopPropagation(),K()},[K]),Y=(0,i.useCallback)(e=>{e.stopPropagation(),$(!1)},[]),Z=(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?.():L||E||d()},onDoubleClick:()=>{L||E||l||e.transient||m?.()},onTouchStart:F,onTouchMove:B,onTouchEnd:H,onTouchCancel:H,onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1!==e.button||!h||L||E||(e.preventDefault(),e.stopPropagation(),h())},onContextMenu:L||E?void 0:Z,onMouseEnter:()=>N(!0),onMouseLeave:()=>{N(!1)},style:{height:28,position:"relative",display:"flex",alignItems:"center",paddingLeft:10+f+14*x,paddingRight:8,cursor:L||E?"default":"pointer",background:L?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":C?"var(--bg-hover)":"transparent",borderLeft:L?"2px solid #ef4444":"2px solid transparent",borderRadius:4,transition:"background 0.1s",opacity:R?.5:1,gap:6,overflow:"hidden",userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none"},children:L?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S("sidebar.deleteSession",{title:U.slice(0,22)+(U.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:J,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:24,padding:"0 8px",background:"#ef4444",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},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:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),S("sidebar.delete")]}),(0,r.jsx)("button",{onClick:Y,style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},children:S("sidebar.cancel")})]})]}):E?(0,r.jsx)("input",{ref:z,value:M,onChange:e=>T(e.target.value),onBlur:q,onKeyDown:e=>{"Enter"===e.key&&q(),"Escape"===e.key&&I(!1)},autoFocus:!0,className:"session-rename-input",style:{flex:1,minWidth:0,fontSize:12,fontFamily:"inherit",lineHeight:1.4,padding:"1px 6px",border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg)",color:"var(--text)",height:24,boxSizing:"border-box"}}):(0,r.jsxs)(r.Fragment,{children:[x>0&&(0,r.jsx)(G,{size:13,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:12,lineHeight:1.4,color:t||C?"var(--text)":"var(--text-muted)"},title:e.name||O||e.id,children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:U})})}),e.isWorktree&&e.branch&&(0,r.jsxs)("span",{title:`Worktree: ${e.branch}
2
- ${e.cwd}`,style:{display:"flex",alignItems:"center",gap:3,maxWidth:82,color:"var(--text-dim)",flexShrink:1,fontSize:10,fontFamily:"var(--font-mono)",lineHeight:1},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e.branch})]}),v&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),k?.()},title:S(y?"sidebar.expandSubagents":"sidebar.collapseSubagents"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:y?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",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)(ec,{}):s?(0,r.jsx)(eu,{}):(0,r.jsx)("span",{title:e.modified,children:(0,b.wA)(e.modified,j)})}),!e.transient&&(0,r.jsxs)("div",{className:"session-row-actions",style:{display:"flex",alignItems:"center",gap:2,position:"absolute",right:6,top:0,height:"100%",background:t?"var(--bg-selected)":C?"var(--bg-hover)":"var(--bg-panel)",paddingLeft:4,borderRadius:4},children:[h&&(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),a?.(),h()},title:S("chatTabs.openInNewTab",{defaultValue:"在新标签页打开"}),"aria-label":S("chatTabs.openInNewTab",{defaultValue:"在新标签页打开"}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background=t?"var(--bg-hover)":"var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"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:"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"})]})}),m&&(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),a?.(),m()},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:"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:"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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:e=>{a?.(),V(e)},title:S("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.12)",e.currentTarget.style.color="#ef4444"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",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 ep({src:e,alt:t="",children:n,className:s,style:l}){let{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(!1),c=(0,i.useRef)(null),u=(0,i.useRef)(null),h=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!a)return;let e=u.current;if(!e)return;let t=c.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),h.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[a]);let p=()=>{u.current?.open&&u.current.close(),d(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:c,type:"button",className:s,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...l},onClick:()=>d(!0),"aria-label":o("chat.previewImage"),"aria-haspopup":"dialog","aria-expanded":a,title:o("chat.previewImage"),children:n}),a&&(0,r.jsxs)("dialog",{ref:u,className:"image-preview-dialog","aria-label":o("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":o("chat.close"),title:o("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}let em="pi-image-result",eg=[{model:"gpt-image-2.5-flare",label:"Flare"},{model:"gpt-image-2.5-sunburst",label:"Sunburst"},{model:"grok-imagine-image-2.0",label:"Grok"}],ef=["1:1","16:9","9:16","4:3","3:4","3:2","2:3"];function ex(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 ev=/@"([^"]+)"|@([^\s"]+)/g,ey=/\.(?:png|jpe?g|webp)$/i;function eb(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ew(e){if(!eb(e)||![em,"pi-web:image"].includes(e.type)||1!==e.version)return null;let t=e.type===em;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:em}:null}function ek(e,t,n){if("generate_image"!==e)return null;let r=ew(n);return r?r.source?"edit":"generate":eb(t)&&!0===t.new_image?"generate":eb(t)&&("string"==typeof t.target&&t.target||!0===t.use_last_attachment)?"edit":null}function ej(e,t){return`/api/files/${j(e)}?type=${t}`}function eS(e,t){return e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:t?E(t,e):e}function eC({path:e,cwd:t,onRemove:n}){let{t:i}=(0,w.s)(),s=ej(eS(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:s,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:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})}):null]})}function eN(e,t){return{aspectRatio:`${e} / ${t}`,width:`min(100%, calc(28rem * ${e/t}))`}}function eE({value:e,cwd:t,onEdit:n,onMention:s,showPrompt:l=!1,createdAt:o}){let a,d,c,u,{t:h,locale:p}=(0,w.s)(),m=ew(e),[g,f]=(0,i.useState)(!1);if(!m)return null;let x=eS(m.path,t),v=ej(x,"read"),y=(c=[(a=function(e,t){if(e<=0||t<=0)return ex(e,t);let n=e/t,r=ef[0],i=1/0;for(let e of ef){let[t,s]=e.split(":").map(Number),l=Math.abs(n-t/s)/(t/s);l<i&&(r=e,i=l)}return i<=.03?r:ex(e,t)}(m.width,m.height),d=`${m.width}\u00d7${m.height}`,a===`${m.width}:${m.height}`?d:`${a}(${d})`)],m.resolution&&c.push(m.resolution.toUpperCase()),(u="low"===m.quality?h("image.qualityLow"):"medium"===m.quality?h("image.qualityMedium"):"high"===m.quality?h("image.qualityHigh"):"auto"===m.quality?h("image.qualityAuto"):m.quality)&&c.push(u),c.join(" \xb7 ")),b=[m.label?m.label:m.model.includes("sunburst")?"Sunburst":m.model.includes("flare")?"Flare":m.model.includes("grok-imagine")?"Grok":m.model.includes("flash-image")?"Banana 2":m.model,o?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 s=n.toLocaleDateString(t,{month:"short",day:"numeric",year:n.getFullYear()!==r.getFullYear()?"numeric":void 0});return`${s} ${i}`}(o,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:eN(m.width,m.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)(ep,{src:v,alt:m.prompt,className:"block h-full w-full",children:(0,r.jsx)("img",{src:v,alt:m.prompt,loading:"lazy",onError:()=>f(!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(m)},title:h("image.edit"),className:"h-7 rounded-full px-2.5 text-[11px] 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,s?(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),s(m.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:ej(x,"download"),download:!0,title:h("i18n.downloadFile"),"aria-label":h("i18n.downloadFile"),onClick:e=>e.stopPropagation(),className:"inline-flex h-7 w-7 items-center justify-center rounded-full text-white/95 hover:bg-white/15",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m7 10 5 5 5-5M12 15V3"})]})})]})})]}),l&&m.prompt?(0,r.jsx)("p",{className:"mt-1.5 line-clamp-3 text-[12px] leading-snug text-text-muted",title:m.prompt,children:m.prompt}):null,y||b?(0,r.jsxs)("div",{className:`${l&&m.prompt?"mt-1":"mt-1.5"} max-w-full text-[11px] leading-snug tracking-wide text-text-muted`,title:m.model,children:[y,y&&b?" \xb7 ":null,b]}):null]})}function eI({prompt:e,size:t,width:n,height:i,previewUrl:s}){let{t:l}=(0,w.s)(),{w:o,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:eN(o,a),children:[s?(0,r.jsx)("img",{src:s,alt:"",className:"absolute inset-0 h-full w-full object-cover opacity-35"}):null,(0,r.jsx)("div",{className:"image-pending-sheen","aria-hidden":"true"})]}),e?(0,r.jsx)("p",{className:"mt-1.5 line-clamp-3 text-[12px] leading-snug text-text-muted",children:e}):null]})}let eM=["off","minimal","low","medium","high","xhigh","max"],eT=RegExp(`:(${eM.join("|")})$`),eL=new Map;function e$(e){return`pi-chat-draft:${encodeURIComponent(e)}`}function eR(){try{return window.sessionStorage}catch{return null}}function eW(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function ez(e){return!e.value&&0===e.images.length}function eP(e){let t=eL.get(e)??function(e){try{let t=eR()?.getItem(e$(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 eW(n)}catch{return null}}(e);return t&&!eL.has(e)&&eL.set(e,t),t?eW(t):null}function eA(e,t){if(ez(t))return eD(e),!0;let n=eW(t);eL.set(e,n);let r=eR();if(!r)return!1;try{return r.setItem(e$(e),JSON.stringify(n)),!0}catch{return r.removeItem(e$(e)),!1}}function eD(e){eL.delete(e);try{eR()?.removeItem(e$(e))}catch{}}function eF(e,t){return e.trim()?t.trim()?`${e}
3
-
4
- ${t}`:e:t}function eB(e){return{data:e.data,mimeType:e.mimeType}}function eH(e,t,n,r){return{value:eF(e,n),images:[...t??[],...r].map(eB)}}function eO(e,t,n){if(e===t)return n?eW(n):eP(t);let r=eP(e),i=n&&!ez(n)?eW(n):r??(n?eW(n):null),s=eP(t);if(eD(e),!i)return s;let l=s?eH(s.value,s.images,i.value,i.images):i;return eA(t,l),eW(l)}function eU(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 e_(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function eq(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 eK(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function eV({active:e,size:t=13,className:n,style:i}){return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"2.4 2.4 19.2 19.2",fill:"none",stroke:"currentColor",strokeWidth:.8*X(t),strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:n,style:{flexShrink:0,color:e?"var(--accent)":"currentColor",display:"block",...i},children:[(0,r.jsx)("path",{d:"M9.5 4a3.5 3.5 0 0 0-3.5 3.5c0 .34.05.67.14.98A4 4 0 0 0 4 12c0 1.9 1.3 3.5 3.1 3.9A3.5 3.5 0 0 0 10.5 19h1"}),(0,r.jsx)("path",{d:"M14.5 4a3.5 3.5 0 0 1 3.5 3.5c0 .34-.05.67-.14.98A4 4 0 0 1 20 12c0 1.9-1.3 3.5-3.1 3.9A3.5 3.5 0 0 1 13.5 19h-1"}),(0,r.jsx)("path",{d:"M12 4v16"})]})}let eJ="(max-width: 640px)",eY=e=>(function(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)})(eJ,e),eZ=()=>!!window.matchMedia&&window.matchMedia(eJ).matches;function eX(){return!1}function eG(){return(0,i.useSyncExternalStore)(eY,eZ,eX)}let eQ="pi-chat-content-width",e0="pi-chat-content-font-size",e1={width:820,fontSize:14},e2=null,e4=new Set;function e8(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function e3(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function e6(e){try{return window.localStorage.getItem(e)}catch{return null}}function e5({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 e7(){return e2||e5(e2={width:e8(e6(eQ)),fontSize:e3(e6(e0))}),e2}function e9(e){return e4.add(e),()=>{e4.delete(e)}}function te(e,t){let n="width"===e?e8(t):e3(t);e5(e2={...e7(),[e]:n});try{window.localStorage.setItem("width"===e?eQ:e0,String(n))}catch{}e4.forEach(e=>e())}let tt=e=>te("width",e),tn=e=>te("fontSize",e);function tr(){return{...(0,i.useSyncExternalStore)(e9,e7,()=>e1),setWidth:tt,setFontSize:tn}}var ti=n(14755);function ts(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 tl="pi-shift-enter-to-send";function to(){try{return"true"===window.localStorage.getItem(tl)}catch{return!1}}let ta=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function td(e,t){return ta.compare(e.name||e.modelId,t.name||t.modelId)||ta.compare(e.provider,t.provider)||ta.compare(e.modelId,t.modelId)}function tc({options:e,value:t,onChange:n,onClear:s,emptyLabel:l,selectedLabel:o,disabled:a=!1,busy:d=!1,isAutoSelection:c=!1,ariaLabel:u,variant:h="toolbar",placement:p="up"}){let m,g,f,x,v,y,b,w,k=eG(),j=(0,i.useRef)(null),S=(0,i.useRef)(null),C=(0,i.useRef)(null),N=(0,i.useId)(),[E,I]=(0,i.useState)(!1),[M,T]=(0,i.useState)(0),[L,$]=(0,i.useState)(null),R=a||d,W=(0,i.useMemo)(()=>[...e].sort(td),[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=o??(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)(()=>s?[null,...W]:W,[s,W]),D=A.findIndex(e=>null!==e?e.modelId===t?.modelId&&e.provider===t?.provider:!t),F=A.length?Math.min(M,A.length-1):0,B=A.length?`${N}-option-${F}`:void 0,H=(0,i.useCallback)(()=>{let e=S.current?.getBoundingClientRect();e&&$({top:e.top,right:e.right,bottom:e.bottom,left:e.left,width:e.width})},[]);(0,i.useEffect)(()=>{let e=e=>{j.current&&!j.current.contains(e.target)&&C.current&&!C.current.contains(e.target)&&I(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{R&&I(!1)},[R]),(0,i.useEffect)(()=>{if(!E)return;H();let e=window.visualViewport;return window.addEventListener("scroll",H,!0),window.addEventListener("resize",H),e?.addEventListener("scroll",H),e?.addEventListener("resize",H),()=>{window.removeEventListener("scroll",H,!0),window.removeEventListener("resize",H),e?.removeEventListener("scroll",H),e?.removeEventListener("resize",H)}},[E,H]),(0,i.useEffect)(()=>{E&&T(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:R?"var(--bg-panel)":"var(--bg)",color:R?"var(--text-dim)":"var(--text)",cursor:R?"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:R?"not-allowed":"pointer",fontSize:12,lineHeight:1.25,opacity:R?.5:1,transition:"background 0.12s, color 0.12s"},U=e=>{let r=e.modelId===t?.modelId&&e.provider===t?.provider;I(!1),(!r||c)&&n(e.provider,e.modelId)};return(0,r.jsxs)("div",{ref:j,className:`model-selector is-${h}${R?" 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(),I(!1))},children:[(0,r.jsxs)("button",{ref:S,type:"button",role:"combobox","aria-label":u,"aria-haspopup":"listbox","aria-controls":N,"aria-activedescendant":E?B:void 0,"aria-expanded":E,onKeyDown:e=>{if("Escape"===e.key&&E){e.preventDefault(),I(!1);return}if("ArrowDown"===e.key||"ArrowUp"===e.key){if(e.preventDefault(),!E){H(),T(D>=0?D:0),I(!0);return}let t="ArrowDown"===e.key?1:-1;T(e=>A.length?(e+t+A.length)%A.length:0);return}if(E&&A.length){if("Home"===e.key||"End"===e.key)e.preventDefault(),T("Home"===e.key?0:A.length-1);else if("Enter"===e.key||" "===e.key){e.preventDefault();let t=A[F];null===t?(I(!1),s?.()):t&&U(t)}}},"aria-busy":d||void 0,disabled:R,title:d?"Switching model":R?P:W.length>0||s?"Change model":"No available models",style:O,onClick:()=>{H(),I(e=>!e)},onMouseEnter:e=>{R||k&&"toolbar"===h||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(R){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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:"13",height:"13",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&&L&&(m=window.visualViewport?.height??window.innerHeight,g=window.visualViewport?.width??window.innerWidth,f=L.top-8,x=m-L.bottom-8,y=Math.max(120,Math.min((v="up"===p||f>x)?f:x,.6*m)),b=v?{bottom:m-L.top+6}:{top:L.bottom+6},w=k?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:L.left,width:"max-content",minWidth:L.width,maxWidth:Math.max(L.width,g-L.left-8)},(0,r.jsx)("div",{ref:C,id:N,role:"listbox","aria-label":u,"aria-activedescendant":B,style:{position:"fixed",...b,...w,zIndex:500,display:"flex",flexDirection:"column",maxHeight:y,overflow:"hidden",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:v?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[s&&(0,r.jsx)(tu,{id:`${N}-option-0`,active:!t,highlighted:0===F,label:l??"Default",onActive:()=>T(0),onClick:()=>{I(!1),s()}}),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||s?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,letterSpacing:0,textTransform:"uppercase"},children:e.provider}),e.options.map(e=>(0,r.jsx)(tu,{id:`${N}-option-${A.indexOf(e)}`,active:e.modelId===t?.modelId&&e.provider===t?.provider,highlighted:F===A.indexOf(e),label:e.name,onActive:()=>T(A.indexOf(e)),onClick:()=>U(e)},`${e.provider}:${e.modelId}`))]},e.provider))]})}))]})}function tu({id:e,active:t,highlighted:n,label:i,onActive:s,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,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{s?.(),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:"1.3",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 th=["configured","chat-only","read-only","default","full"],tp={configured:ti.Q8,"chat-only":"none","read-only":"read-only",default:"default",full:"full"},tm=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function tg(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 s=e.parentElement,l=s?.parentElement,o="u">typeof ResizeObserver&&s?new ResizeObserver(i):null;s&&o?.observe(s),l&&o?.observe(l);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{o?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let tf=["auto",...eM],tx={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},tv=[{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 ty(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return tv.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}function tb(e,t){return`${t.map(e=>eK(e,!1)).join("")}${e.trim()}`.trim()}let tw=["builtin","extension","prompt","skill"],tk={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},tj={builtin:0,extension:1,prompt:2,skill:3};function tS(e,t,n){let r=e.name.toLowerCase(),i=tC(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function tC(e,t){return"builtin"===e.source?t(e.description):e.description??""}function tN(e,t){requestAnimationFrame(()=>{let n=e.current;n&&(n.focus(),n.setSelectionRange(t,t))})}let tE={name:"<session-title>",session:"[session-id]",clone:"[new-title]"};function tI(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function tM(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 s=i.getContext("2d");if(!s)return t();s.fillStyle="#fff",s.fillRect(0,0,i.width,i.height),s.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 tT(e){return{data:e.data,mimeType:e.mimeType}}function tL(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function t$(e){return(e??[]).map(tL)}function tR(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function tW({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 tz({tone:e,title:t,body:n,onClose:i}){let s="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(${s},0.3)`,borderRadius:4,background:`rgba(${s},0.07)`,color:`rgb(${s})`,fontSize:11,lineHeight:1.45},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:{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:12,lineHeight:1},children:"\xd7"})]})}function tP({error:e}){let{t}=(0,w.s)();return e?(0,r.jsx)(tz,{tone:"error",title:t("chat.modelError"),body:e}):null}function tA({warnings:e}){let{t}=(0,w.s)();return e&&0!==e.length?(0,r.jsx)(tz,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let tD=(0,i.forwardRef)(function({onSend:e,onOpenImageGeneration:t,onAbort:n,onSteer:s,onFollowUp:l,isStreaming:o,disabled:a=!1,model:d,isAutoModelSelection:c,modelNames:u,modelList:h,modelError:p,modelScopeWarnings:m,onModelChange:g,modelSwitching:f,onCompact:x,onAbortCompaction:v,isCompacting:y,compactError:b,compactResult:k,toolPreset:j,onToolPresetChange:S,contextUsage:C,cacheHitRate:N,onOpenSessionStats:E,thinkingLevel:I,onThinkingLevelChange:M,availableThinkingLevels:T,thinkingLevelMap:L,retryInfo:$,queuedMessages:R,inputHistory:z=[],onRecallQueue:P,slashCommands:D,slashCommandsLoading:F,onLoadSlashCommands:B,onBuiltinCommand:H,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,es,el,{t:eo}=(0,w.s)(),{fontSize:ea}=tr(),ed=eG(),ec=(0,i.useId)(),[eu,eh]=(0,i.useState)(()=>K?eP(K)?.value??"":""),[ep,em]=(0,i.useState)(!1),[eg,ef]=(0,i.useState)(!1),[ex,ev]=(0,i.useState)(!1),[ey,eb]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(!1),[ej,eS]=(0,i.useState)([]),eN=(0,i.useRef)([]);eN.current=ej;let[eE,eI]=(0,i.useState)(()=>K?t$(eP(K)?.images):[]),eM=eu.trimStart(),eT=0===eE.length&&eM.startsWith("!"),eL=eT&&eM.startsWith("!!"),[e$,eR]=(0,i.useState)(!1),[eW,ez]=(0,i.useState)(null),[eB,eK]=(0,i.useState)(0),[eJ,eY]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useState)(null),[e4,e8]=(0,i.useState)(0),[e3,e6]=(0,i.useState)(!1),[e5,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(0),tl=(0,i.useRef)(null),[ta,td]=(0,i.useState)(!1),[tu,tL]=(0,i.useState)(null),[tD,tF]=(0,i.useState)(!1),[tB,tH]=(0,i.useState)(null),[tO,tU]=(0,i.useState)(null),t_=Y&&tO?.cwd===Y?tO.values:{},tq=(0,i.useRef)(null),tK=(0,i.useRef)(null),tV=(0,i.useRef)(null),tJ=(0,i.useRef)(null),tY=(0,i.useRef)(null),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tG=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(0),t4=(0,i.useRef)(!1),t8=(0,i.useRef)(null),t3=(0,i.useRef)([]),t6=(0,i.useRef)(null),t5=(0,i.useRef)([]),t7=(0,i.useRef)(!1),t9=(0,i.useRef)([]),ne=(0,i.useRef)(null),nt=(0,i.useRef)(null),nn=(0,i.useRef)(0),nr=(0,i.useRef)(K),ni=(0,i.useRef)(eu),ns=(0,i.useRef)(eE),nl=(0,i.useRef)(0);ni.current=eu,ns.current=eE,(0,i.useImperativeHandle)(X,()=>({insertIfEmpty(e){let t=tq.current;(t?t.value:eu).trim()||(ni.current=e,eh(e),eX(null),requestAnimationFrame(()=>{t&&t.focus()}))},replaceMessage(e){var t,n,r;let i=tq.current;if(t=i?i.value:eu,n=ns.current.length,r=nl.current,t.trim()||0!==n||0!==r)return;let s="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),l=t$("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return!function(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}(r)?[]:[r]}));ni.current=s,ns.current=l,eh(s),eX(null),te(!1),eI(e=>(e.forEach(tR),l)),requestAnimationFrame(()=>{i&&i.focus()})},prependText(e){if(!e.trim())return;let t=tq.current,n=[e,t?t.value:eu].filter(e=>e.trim()).join("\n\n");ni.current=n,eh(n),eX(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length))})},rekeyDraft(e,t){if(e===t)return;if(nr.current!==e)return void eO(e,t);let n={value:ni.current,images:ns.current.map(tT)},r=eO(e,t,n)??{value:"",images:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType);if(nr.current=t,i)return;let s=t$(r.images);ni.current=r.value,ns.current=s,eh(r.value),eI(e=>(e.forEach(tR),s)),eX(null),te(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=nr.current,i=n??r,s=i===r,l=!s&&i?eP(i):null,o=eH(e,t,s?ni.current:l?.value??"",s?ns.current.map(tT):l?.images??[]);if(i&&eA(i,o),!s)return;let a=t$(o.images);ni.current=o.value,ns.current=a,eh(t=>{let n=eF(e,t);return ni.current=n,n}),eX(null),te(!1),eI(e=>(e.forEach(tR),ns.current=a,a)),requestAnimationFrame(()=>{let e=tq.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))})},insertText(e){let t=tq.current;if(!t)return void eh(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),s=t.value.slice(r),l=i.length>0&&!i.endsWith(" ")?" ":"",o=i+l+e+s;ni.current=o,eh(o),eX(null),requestAnimationFrame(()=>{if(!t)return;let r=n+l.length+e.length;t.setSelectionRange(r,r),t.focus()})},addImages(e){no(e)},mentionImage(e){eS(t=>t.includes(e)?t:[...t,e]),requestAnimationFrame(()=>tq.current?.focus())},removeAttachedImage(e){let t=ns.current.findIndex(t=>t.data===e);t>=0&&na(t)}}));let no=(0,i.useCallback)(async e=>{if(Z)return;let t=Math.max(0,10-ns.current.length-nl.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(!n.length)return;let r=nn.current;nl.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await tM(e),previewUrl:URL.createObjectURL(e)})));eI(t=>{if(r!==nn.current)return e.forEach(tR),t;let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(tR);let i=[...t,...n];return ns.current=i,i})}finally{nl.current-=n.length}},[Z]),na=(0,i.useCallback)(e=>{eI(t=>{let n=[...t],[r]=n.splice(e,1);return r&&tR(r),ns.current=n,n})},[]),nd=(0,i.useCallback)(()=>{ns.current=[],eI(e=>(e.forEach(tR),[]))},[]),nc=(0,i.useCallback)(()=>{nn.current+=1,tl.current=null,ni.current="",eh(""),eX(null),te(!1),K&&eD(K),nr.current&&nr.current!==K&&eD(nr.current),nd(),eN.current=[],eS([])},[nd,K]);(0,i.useEffect)(()=>{K&&nr.current===K&&(td(!eA(K,{value:eu,images:eE.map(tT)})),V?.(K,eu,eE.length))},[eE,K,V,eu]),(0,i.useEffect)(()=>{let e=nr.current;if(e===K)return;e&&eA(e,{value:ni.current,images:ns.current.map(tT)});let t=K?eP(K):null;nr.current=K;let n=t?.value??"",r=t$(t?.images);nn.current+=1,ni.current=n,ns.current=r,eh(n),eX(null),te(!1),eI(e=>(e.forEach(tR),r)),K&&V?.(K,n,r.length)},[K,V]);let nu=(0,i.useCallback)(()=>{let e=tq.current;if(!e||(e.style.overflowY="hidden",e.style.height="auto",!e.value))return;let t=e.scrollHeight;e.style.height=`${Math.min(t,200)}px`,t>200&&(e.style.overflowY="auto")},[]);(0,i.useLayoutEffect)(nu,[eu,ea,nu]),(0,i.useEffect)(()=>{let e=tq.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,nu())});return n.observe(e),()=>n.disconnect()},[nu]),(0,i.useEffect)(()=>()=>{nn.current+=1,ns.current.forEach(tR)},[]);let nh=(0,i.useCallback)(async e=>{if(eE.length||!e.startsWith("/")||!H)return!1;if(t7.current)return!0;t7.current=!0,e6(!0);try{var t,n;let r=await H(e);if(!r.handled)return!1;return r.error||(t=ni.current,n=ns.current.length,0!==n||t.trim()!==e)||nc(),!0}finally{t7.current=!1,e6(!1)}},[eE.length,nc,H]),np=(0,i.useCallback)(async()=>{if(a)return;let t=eu.trim();if(eE.length>10)return;let n=tb(t,ej);if(!n&&!eE.length||(_?.(),(!o||ty(t))&&await nh(t)||o))return;let r=eE.length?eE:void 0;nc(),e(n,r)},[a,eu,eE,ej,o,nh,e,nc,_]),nm=!Z&&eu.startsWith("/")&&!/\s/.test(eu.slice(1))?eu.slice(1).toLowerCase():null,ng=null===nm?[]:[...o?tv.filter(e=>e.availableWhileStreaming):tv,...D??[]].filter(e=>{let t=e.name.toLowerCase(),n=tC(e,eo).toLowerCase();return t.includes(nm)||n.includes(nm)}).sort((e,t)=>{let n=tS(e,nm,eo)-tS(t,nm,eo);return 0!==n?n:tj[e.source]-tj[t.source]||tm.compare(e.name,t.name)}),{commands:nf,groups:nx}=(G=0,{commands:(Q=tw.map(e=>{let t=ng.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!tI(e,t_)),...t.filter(e=>tI(e,t_))]:t;return{source:e,items:n.map(e=>({command:e,index:G++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:Q}),nv=(()=>{if(Z)return null;let e=eW??eu.length,t=eu.slice(0,e);if(t.includes("\n"))return null;let n=/^\/([^\s]+)\s(.*)$/.exec(t);return n&&tE[n[1]]?{command:n[1],signature:tE[n[1]],hasArgument:n[2].trim().length>0}:null})(),ny=1===ng.length?eo(nm?"chat.match":"chat.command"):eo(nm?"chat.matches":"chat.commands",{count:ng.length}),nb=!!eu.trim(),nw=eE.length>10,nk=!nw&&(nb||eE.length>0||ej.length>0),nj=!a&&!nw&&(nb||eE.length>0||ej.length>0),nS=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)&&!e5;(0,i.useEffect)(()=>{0===eE.length&&e7(!1)},[eE.length]);let nC=(0,i.useCallback)((e,t)=>{if(!Y)return void eX(null);let n=t??e.length;eX(eU(e.slice(0,n)))},[Y]),nN=eZ?.query??null,nE=i.useMemo(()=>null!==nN&&tu&&tu.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:eq(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:eq(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||e_(e.entry.path)-e_(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tu.entries,nN):[],[nN,tu,Y]),nI=!!(nN&&tu?.clientTruncated&&tu.cwd===Y);(0,i.useEffect)(()=>{if(!nI||!Y||!nN)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(Y)}&q=${encodeURIComponent(nN)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tH({cwd:Y,query:nN,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nI,nN,Y]);let nM=nI&&null!==tB&&tB.cwd===Y&&tB.query===nN,nT=nM?tB.matches:nE,nL=null===eZ?null:`${eZ.start}:${+!!eZ.quoted}:${eZ.query}`;(0,i.useEffect)(()=>{if(null===nL){e0(!1),e8(0);return}e0(!0),e8(0)},[nL]);let n$=null!==eZ;(0,i.useEffect)(()=>{if(!n$||!Y)return;let e=ne.current;e&&e.cwd===Y&&Date.now()-e.fetchedAt<1e4||nt.current===Y||(nt.current=Y,tF(!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=>{tL({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)=>e_(e.path)-e_(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),clientTruncated:!!e.clientTruncated,serverHardTruncated:!!e.serverHardTruncated}),ne.current={cwd:Y,fetchedAt:Date.now()}}).catch(()=>{ne.current=null}).finally(()=>{nt.current=null,tF(!1)}))},[n$,Y]);let nR=(0,i.useCallback)(e=>{if(!eZ)return;let t=tq.current,n=t?.selectionStart??eu.length,r=eu.slice(0,eZ.start),i=eu.slice(n);eZ.quoted&&i.startsWith('"')&&(i=i.slice(1));let s=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 s=i?`@"${r}" `:`@${r} `;return{text:s,cursorOffset:s.length}}(e.path,e.isDir,eZ.quoted),l=r+s.text+i,o=r.length+s.cursorOffset;ni.current=l,eh(l),ez(o),eX(eU(l.slice(0,o))),tN(tq,o)},[eZ,eu]);(0,i.useEffect)(()=>{e4>=nT.length&&e8(Math.max(0,nT.length-1))},[nT.length,e4]),(0,i.useEffect)(()=>{t5.current.length=nT.length},[nT.length]),(0,i.useEffect)(()=>{eQ&&t5.current[e4]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e4,eQ]),(0,i.useEffect)(()=>{tt>=z.length&&tn(Math.max(0,z.length-1))},[z.length,tt]),(0,i.useEffect)(()=>{t9.current.length=z.length},[z.length]),(0,i.useEffect)(()=>{e9&&t9.current[tt]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tt,e9]);let nW=(0,i.useCallback)(()=>{let e=tl.current;tl.current=null,e&&(ni.current=e.text,eh(e.text)),te(!1)},[]),nz=(0,i.useCallback)(e=>{tl.current=null,ni.current=e,eh(e),ez(e.length),te(!1),tn(0),eX(null),tN(tq,e.length)},[]),nP=(0,i.useCallback)(e=>{let t=`/${e.name} `;ni.current=t,eh(t),ez(t.length),eR(!1),eK(0),tN(tq,t.length)},[]),nA=(0,i.useCallback)(e=>{let t=eu.trim();if(eE.length>10)return;let n=tb(t,ej);if(!n&&!eE.length)return;if(_?.(),!eE.length&&H&&ty(t))return void nh(t);let r=eE.length?eE:void 0;if(t.startsWith("/")&&q){nc(),q(t,"steer"===e?"steer":"followUp",r);return}nc(),"steer"===e&&s?s(n,r):"followup"===e&&l&&l(n,r)},[eu,eE,ej,H,q,s,l,nc,_,nh]),nD=(0,i.useCallback)(e=>{let t=e.nativeEvent,r=!ed&&to(),i="Enter"===e.key&&e.shiftKey===r&&(!ed||e.ctrlKey||e.metaKey),a=Date.now()-t2.current<100,d=t1.current||t.isComposing||229===t.keyCode;if(i&&(d||a)){a&&e.preventDefault();return}if(e9&&!d){if("ArrowDown"===e.key){e.preventDefault(),tn(e=>Math.min(Math.max(0,z.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tn(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),nW();return}if(("Tab"===e.key||i)&&z[tt]){e.preventDefault(),nz(z[tt]);return}}if(e$&&null!==nm&&!d){if("ArrowDown"===e.key){e.preventDefault(),eK(e=>0===nf.length?0:(e+1)%nf.length);return}if("ArrowUp"===e.key){e.preventDefault(),eK(e=>0===nf.length?0:(e-1+nf.length)%nf.length);return}if("Escape"===e.key){e.preventDefault(),eR(!1);return}let t=nf[eB];if("Tab"===e.key&&t){e.preventDefault(),nP(t);return}if(i&&t)return void((e.preventDefault(),o&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||eu.trim()!==`/${t.name}`)?nP(t):(eR(!1),np()))}if(eQ&&null!==eZ&&!d){if("ArrowDown"===e.key){e.preventDefault(),e8(e=>0===nT.length?0:(e+1)%nT.length);return}if("ArrowUp"===e.key){e.preventDefault(),e8(e=>0===nT.length?0:(e-1+nT.length)%nT.length);return}if("Escape"===e.key){e.preventDefault(),e0(!1);return}if(("Tab"===e.key||i)&&nT[e4]){e.preventDefault(),nR(nT[e4]);return}}if("ArrowUp"===e.key&&!eu&&!d&&!o&&z.length>0){e.preventDefault(),eR(!1),e0(!1),tl.current={text:eu},tn(z.length-1),te(!0);return}if("Escape"===e.key&&ey){e.preventDefault(),eb(!1);return}if("Escape"===e.key&&!d&&o&&n){e.preventDefault(),n();return}i&&(e.preventDefault(),o&&(s||l)?nA(e.altKey&&l||!s?"followup":"steer"):np())},[ed,o,s,l,n,ey,e$,nm,nf,eB,nP,nA,np,eQ,eZ,nT,e4,nR,e9,z,tt,nz,nW,eu]),nF=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!Z&&t.length){e.preventDefault(),no(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"),s=function(e,t){let n="",r=0,i=!1;for(let{label:s,href:l,occurrence:o}of t){if(!s||!l)continue;let t=0;for(let n=0;n<=o&&!((t=e.indexOf(s,n?t+s.length:0))<0);n++);if(t<r)continue;let a=s.replace(/([\\[\]])/g,"\\$1"),d=l.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+s.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===s)return;let l=e.currentTarget,o=l.selectionStart,a=l.value.slice(0,o)+s+l.value.slice(l.selectionEnd);e.preventDefault(),ni.current=a,eh(a),te(!1),nC(a,o+s.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(o+s.length,o+s.length)})},[Z,no,nC]);(0,i.useEffect)(()=>{if(null===nm){eR(!1),eK(0),t4.current=!1;return}eR(!0),eK(0),!t4.current&&B&&(t4.current=!0,Promise.resolve(B()).catch(()=>{t4.current=!1}))},[nm,B]),(0,i.useEffect)(()=>{if(!e$||!Y)return;let e=!1;return tU({cwd:Y,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(Y)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;tU({cwd:Y,values:n})}).catch(()=>{e||tU({cwd:Y,values:{}})}),()=>{e=!0}},[e$,Y]),(0,i.useEffect)(()=>{eB>=nf.length&&eK(Math.max(0,nf.length-1))},[nf.length,eB]),(0,i.useEffect)(()=>{t3.current.length=nf.length},[nf.length]),(0,i.useEffect)(()=>{e$&&t3.current[eB]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eB,e$]),(0,i.useLayoutEffect)(()=>{if(!e$||null===nm)return void eY(null);let e=t8.current;if(e)return tg(e,e=>{eY(t=>t===e?t:e)})},[e$,nm]),(0,i.useLayoutEffect)(()=>{if(!eQ||null===eZ)return void e2(null);let e=t6.current;if(e)return tg(e,e=>{e2(t=>t===e?t:e)})},[eQ,eZ]);let nB=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})),nH=k?Math.max(0,k.tokensBefore-k.estimatedTokensAfter):0,nO=k?`${k.reason&&"manual"!==k.reason?`${k.reason[0].toUpperCase()}${k.reason.slice(1)} `:eo("chat.compacted")} ${ts(k.tokensBefore)} -> ${ts(k.estimatedTokensAfter)} tokens (${eo("chat.tokensSaved",{saved:ts(nH)})})`:null,nU="auto"!==(ee=I??"auto")&&L?L[ee]??ee:ee,n_=Object.entries(tp).find(([,e])=>e===(j??ti.Q8))?.[0]??"configured",nq="chat-only"===n_?eo("chat.chatOnly"):n_,nK=C?.percent??null,nV=[nU,null!=nK&&nK>=70?`${Math.round(nK)}%`:null].filter(Boolean).join(" \xb7 ");(0,i.useEffect)(()=>{let e=e=>{let t=e.target;tK.current&&!tK.current.contains(t)&&em(!1),tV.current&&!tV.current.contains(t)&&ef(!1),tJ.current&&!tJ.current.contains(t)&&eb(!1),tY.current&&!tY.current.contains(t)&&ek(!1),tG.current&&!tG.current.contains(t)&&ev(!1),!t8.current||t8.current.contains(t)||tq.current?.contains(t)||eR(!1),!t6.current||t6.current.contains(t)||tq.current?.contains(t)||e0(!1),!tQ.current||tQ.current.contains(t)||tq.current?.contains(t)||nW()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[nW]),(0,i.useEffect)(()=>{ed||ek(!1)},[ed]);let nJ=e=>{if(!C||C.contextWindow<=0)return null;let t=C.contextWindow,n=C.tokens,i=C.percent??(null!==n?n/t*100:null),s=null!==i?Math.min(100,Math.max(0,i)):0,l=null!==i&&i>=85,o=null!==i&&i>=70&&i<85,a=null!==n?`${ts(n)}/${ts(t)}`:`?/${ts(t)}`,d=null!==n?Math.max(0,t-n):null,c=[`${eo("chat.contextUsage")}: ${null!==n?ts(n):"?"} / ${ts(t)} (${null!==i?i.toFixed(1):"?"}%)`,null!==d?`${eo("chat.contextRemaining")}: ${ts(d)}`:null,null!=N?`${eo("session.cacheHitRate")}: ${N.toFixed(1)}%`:null,l?`⚠️ ${eo("chat.contextHighWarning")}`:null].filter(Boolean).join("\n");return(0,r.jsxs)("button",{ref:tG,type:"button",onClick:()=>{ev(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:ex?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":o?"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||ex||(t.currentTarget.style.background=l?"rgba(239,68,68,0.12)":"var(--bg-hover)")},onMouseLeave:t=>{e||!E||ex||(t.currentTarget.style.background=l?"rgba(239,68,68,0.06)":"none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",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:"6",stroke:"currentColor",strokeWidth:"1.33",opacity:"0.3"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"6",pathLength:"100",stroke:"currentColor",strokeWidth:"1.33",strokeLinecap:"round",strokeDasharray:`${s} 100`,style:{transition:"stroke-dasharray 0.3s ease"}})]}),(0,r.jsx)("span",{style:{letterSpacing:"-0.01em",lineHeight:1},children:a}),null!=N&&(0,r.jsxs)("span",{style:{lineHeight:1},children:[N.toFixed(0),"%"]})]})};(0,i.useLayoutEffect)(()=>{if(!ed||!ew)return;let e=tX.current;if(e)return e.style.height="32px",()=>{e.style.height=""}},[ed,ew]),(0,i.useEffect)(()=>{o&&(ef(!1),em(!1),eb(!1))},[o]);let nY=`${ec}-history`,nZ=`${ec}-slash`,nX=`${ec}-files`,nG=e9&&z.length>0?nY:e$&&null!==nm?nZ:eQ&&null!==eZ?nX:void 0,nQ=nG===nY&&void 0!==z[tt]?`${nY}-${tt}`:nG===nZ&&nf[eB]?`${nZ}-${eB}`:nG===nX&&nT[e4]?`${nX}-${e4}`:void 0;return(0,r.jsxs)("fieldset",{disabled:e3,"aria-busy":e3,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:e3?.5:1,transition:"opacity 0.15s"},children:[!Z&&(0,r.jsx)("input",{ref:t0,type:"file",accept:"image/*",multiple:!0,disabled:a,style:{display:"none"},onChange:e=>{no(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)(tP,{error:p}),(0,r.jsx)(tA,{warnings:m}),nw&&(0,r.jsx)(tz,{tone:"error",title:eo("chat.tooManyImagesTitle"),body:eo("chat.tooManyImagesBody",{count:eE.length,max:10})}),nS&&(et=h?.find(e=>e.provider===d?.provider&&e.id===d?.modelId),(0,r.jsx)(tz,{tone:"warning",title:eo("chat.imageNotSupportedTitle"),body:eo("chat.imageNotSupportedBody",{model:et?.name||d?.modelId||""}),onClose:()=>e7(!0)})),(R?.steering.length??0)+(R?.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:eo("chat.queued",{count:(R?.steering.length??0)+(R?.followUp.length??0)})}),P&&(0,r.jsxs)("button",{onClick:P,title:eo("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"})]}),eo("chat.recall")]})]}),R?.steering.map((e,t)=>(0,r.jsx)(tW,{kind:"steer",text:e},`steer-${t}`)),R?.followUp.map((e,t)=>(0,r.jsx)(tW,{kind:"follow-up",text:e},`followup-${t}`))]}),$&&(0,r.jsxs)("div",{className:"chat-input-feedback chat-input-feedback-warning",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:{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"})]}),eo("chat.retrying",{attempt:$.attempt,max:$.maxAttempts}),$.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",$.errorMessage]})]}),nO&&(0,r.jsxs)("div",{className:"chat-input-feedback chat-input-feedback-success",children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nO]}),b&&(0,r.jsx)("div",{role:"alert",className:"chat-input-feedback chat-input-feedback-error chat-input-feedback-detail",style:{whiteSpace:"pre-wrap"},children:b}),(ta||J)&&(0,r.jsx)("div",{role:"status",className:"chat-input-feedback chat-input-feedback-warning chat-input-feedback-draft",children:eo("chat.draftPageOnly")}),(eE.length>0||ej.length>0)&&(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:8,flexWrap:"wrap",padding:"0 2px"},children:[ej.map(e=>(0,r.jsx)(eC,{path:e,cwd:Y??void 0,onRemove:()=>eS(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:()=>na(t),title:eo("i18n.close"),"aria-label":eo("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:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},t))]}),(0,r.jsxs)("div",{ref:tZ,style:{position:"relative",minWidth:0},children:[nv&&!e$&&(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,lineHeight:1,color:"var(--text-dim)",opacity:nv.hasArgument?.45:1,pointerEvents:"none"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:"Usage:"}),(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["/",nv.command]}),(0,r.jsx)("span",{children:nv.signature})]}),e9&&z.length>0&&(0,r.jsxs)("div",{ref:tQ,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:eo("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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 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:nY,role:"listbox",style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:z.map((e,t)=>{let n=t===tt;return(0,r.jsxs)("button",{ref:e=>{t9.current[t]=e},type:"button",id:`${nY}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nz(e)},onMouseEnter:()=>tn(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,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}`)})})]}),e$&&null!==nm&&(0,r.jsxs)("div",{ref:t8,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eJ?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eJ}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:F?eo("chat.loadingCommands"):eo("chat.slashCommands",{label:ny})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nZ,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:6},children:F||0!==ng.length?nx.map(e=>(0,r.jsxs)("section",{style:{marginBottom:8},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-6,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 8px 3px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,letterSpacing:"0.04em",textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eo(tk[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},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===eB,i=tI(e,t_);return(0,r.jsxs)("button",{ref:e=>{t3.current[t]=e},type:"button",id:`${nZ}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nP(e)},onMouseEnter:()=>eK(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,fontFamily:"var(--font-mono)",whiteSpace:"nowrap",color:n?"var(--text)":i?"var(--text-dim)":"var(--text)"},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)"},children:e.slice(n,n+t.length)}),e.slice(n+t.length)]})}(e.name,nm),"builtin"===e.source&&tE[e.name]&&(0,r.jsx)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11,fontWeight:400},children:tE[e.name]}),i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eo("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:tC(e,eo)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"4px 8px",fontSize:12,color:"var(--text-dim)"},children:eo("chat.noCommands")})})]}),eQ&&null!==eZ&&(en=tD&&(!tu||tu.cwd!==Y),er=1===nT.length?eo("chat.match"):eo("chat.matches",{count:nT.length}),ei=tu?.serverHardTruncated?eo("chat.serverIndexTruncated"):tu?.clientTruncated&&!nM?eZ.query?eo("chat.searchingAll"):eo("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:t6,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===e1?"min(48vh, 400px)":`min(48vh, 400px, ${e1}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:en?eo("chat.loadingFiles"):eo("chat.files",{label:er,hint:ei})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eo("chat.tabEnter")})]}),(0,r.jsx)("div",{id:nX,role:"listbox",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:en||0!==nT.length?nT.map((e,t)=>{let n=t===e4,i=e.path.split("/").pop()??e.path,s=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{t5.current[t]=e},type:"button",id:`${nX}-${t}`,role:"option","aria-selected":n,tabIndex:-1,onMouseDown:t=>{t.preventDefault(),nR(e)},onMouseEnter:()=>e8(t),style:{width:"100%",height:30,display:"flex",alignItems:"center",gap:8,padding:"0 8px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12,fontFamily:"var(--font-mono)",transition:"background 0.08s ease"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(W,{size:13}):A(i,13)}),(0,r.jsxs)("span",{style:{flexShrink:0,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"},children:e.slice(n,n+t.length)}),e.slice(n+t.length)]})}(i,eZ?.query??null),e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]}),s&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:s})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:nI&&!nM?eo("chat.searching"):eo("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-input-composer${eT?" is-bash-mode":""}`,style:{minWidth:0,display:"flex",flexDirection:Z?"column":"row",gap:8,alignItems:Z?"stretch":"center",background:eT?"color-mix(in srgb, var(--bg-panel) 75%, var(--bg))":"var(--bg)",border:Z?"none":`1px solid ${eT?eL?"rgba(100,116,139,0.45)":"color-mix(in srgb, var(--accent) 45%, var(--border))":o&&(s||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":eT?"0 0 0 1px rgba(37,99,235,0.12)":"0 1px 2px rgba(15,23,42,0.04)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[eT&&(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2px 6px",borderRadius:4,background:eL?"rgba(100,116,139,0.12)":"rgba(37,99,235,0.12)",color:eL?"var(--text-muted)":"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11,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"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}),(0,r.jsx)("span",{style:{lineHeight:1},children:eL?"Local":"Shell"})]}),(0,r.jsx)("textarea",{ref:tq,className:"chat-input-textarea",role:"combobox","aria-autocomplete":"list","aria-haspopup":"listbox","aria-expanded":!!nG,"aria-controls":nG,"aria-activedescendant":nQ,"aria-label":Z?eo("chat.quoteQuestion"):eo("chat.message"),disabled:a,placeholder:a?eo("agentSwitcher.status.queued"):void 0,value:eu,onChange:e=>{ni.current=e.target.value,eh(e.target.value),ez(e.target.selectionStart),tl.current=null,te(!1),nC(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;ez(t.selectionStart),nC(t.value,t.selectionStart)},onKeyDown:nD,onCompositionStart:()=>{t1.current=!0},onCompositionEnd:e=>{t1.current=!1,t2.current=Date.now();let t=e.currentTarget;ez(t.selectionStart),nC(t.value,t.selectionStart)},onPaste:nF,rows:1,style:{flex:Z?"none":1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:"var(--chat-content-font-size, 14px)",lineHeight:1.5,padding:0,fontFamily:eT?"var(--font-mono)":"var(--font-chat)",minHeight:Z?96:24,maxHeight:200}}),o?nk?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[(0,r.jsx)("button",{type:"button",className:"chat-input-action","aria-label":eo("chat.stop"),title:eo("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":eo("chat.followUp"),onClick:()=>nA("followup"),title:`${eo("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:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,letterSpacing:"-0.01em",lineHeight:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg)"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:eo("chat.followUp")})]}),s&&(0,r.jsxs)("button",{className:"chat-input-action","aria-label":eo("chat.steer"),onClick:()=>nA("steer"),title:eo("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:"var(--primary)",border:"none",borderRadius:5,color:"var(--primary-contrast)",cursor:"pointer",fontSize:12,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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:eo("chat.steer")})]})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":eo("chat.stop"),title:eo("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,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:eo("chat.stop")})]}):(0,r.jsxs)("button",{className:"chat-input-action","aria-label":eo("chat.send"),title:nw?eo("chat.tooManyImagesTitle"):eo("chat.send"),onClick:np,disabled:!nj,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:5,height:ed?32:28,padding:"0 10px",background:nj?"var(--primary)":"none",border:"none",borderRadius:5,color:nj?"var(--primary-contrast)":"var(--text-dim)",opacity:nj?1:.45,cursor:nj?"pointer":"not-allowed",fontSize:12,letterSpacing:"-0.01em",lineHeight:1,transition:"background 0.15s, color 0.15s, opacity 0.15s, filter 0.15s"},onMouseEnter:e=>{nj&&(e.currentTarget.style.filter="brightness(1.08)")},onMouseLeave:e=>{nj&&(e.currentTarget.style.filter="none")},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:eo("chat.send")})]})]})]}),eT&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eL?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eo("chat.shell")," \xb7 ",eL?eo("chat.outputLocal"):eo("chat.outputModel")]}),!Z&&(0,r.jsxs)("div",{className:"chat-input-toolbar",style:{marginTop:4*!ed,padding:ed?0:"0 2px",display:ed?"grid":"flex",gridTemplateColumns:ed?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:4},children:[(0,r.jsxs)("div",{style:{flex:ed?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:1},children:[(0,r.jsxs)("div",{ref:tJ,style:{position:"relative",display:"flex",alignItems:"center"},children:[(0,r.jsx)("button",{type:"button",disabled:a,onClick:()=>{t?eb(e=>!e):t0.current?.click()},title:t?`${eo("chat.attachImage")} / ${eo("image.title")}`:eo("chat.attachImage"),"aria-label":t?`${eo("chat.attachImage")} / ${eo("image.title")}`:eo("chat.attachImage"),"aria-expanded":t?ey:void 0,"aria-haspopup":t?"menu":void 0,style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",height:ed?32:28,padding:"0 4px",background:ey?"var(--bg-hover)":"none",border:"none",borderRadius:4,color:eE.length?"var(--accent)":ey?"var(--text)":"var(--text-muted)",cursor:a?"not-allowed":"pointer",opacity:a?.45:1,lineHeight:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{ed||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=eE.length?"var(--accent)":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=ey?"var(--bg-hover)":"none",e.currentTarget.style.color=eE.length?"var(--accent)":ey?"var(--text)":"var(--text-muted)")},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),ey&&t&&(0,r.jsxs)("div",{role:"menu",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),eb(!1))},style:{position:"absolute",bottom:"calc(100% + 6px)",left:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 4px 20px rgba(0,0,0,0.15), 0 1px 4px rgba(0,0,0,0.08)",overflow:"hidden",minWidth:120},children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{eb(!1),t0.current?.click()},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:"none",border:"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("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:eo("chat.attachImage")})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{eb(!1);let[e]=1===ns.current.length?ns.current:[];t(e?tT(e):void 0)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:"none",border:"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"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:eo("image.title")})]})]})]}),(nB.length>0||d||p)&&g&&(0,r.jsx)(tc,{options:nB,value:d,onChange:g,disabled:o,busy:f,isAutoSelection:c})]}),!ed&&(0,r.jsx)("div",{style:{flex:1}}),ed&&ew&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent"},onClick:()=>{em(!1),ef(!1),ek(!1)}}),ed&&(ew||ep||eg||ey)&&(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:55,background:"transparent",WebkitTapHighlightColor:"transparent"},onClick:()=>{em(!1),ef(!1),eb(!1),ek(!1),ev(!1)},"aria-hidden":"true"}),(0,r.jsxs)("div",{ref:tY,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ed?0:"auto",zIndex:ed&&ew?60:void 0},children:[ed&&nJ(!0),ed&&(es=!!(null!=nK&&nK>=85),(0,r.jsxs)("button",{type:"button",title:ew?eo("chat.collapseControls"):eo("chat.moreControls"),"aria-label":eo("chat.moreControls"),"aria-expanded":ew,onClick:()=>{ew?(em(!1),ef(!1),ek(!1)):ek(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,maxWidth:"min(48vw, 200px)",height:32,padding:"0 6px",background:ew?es?"rgba(239,68,68,0.12)":"var(--bg-hover)":es?"rgba(239,68,68,0.06)":"none",border:es?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:es?"#ef4444":null!=nK&&nK>=70&&nK<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)(eV,{size:13,style:{display:"block"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:nV})]})),(0,r.jsxs)("div",{ref:tX,className:"chat-input-toolbar-controls",style:{display:ed?ew?"flex":"none":"flex",alignItems:"center",gap:1,...ed?{position:"absolute",right:0,bottom:"100%",height:32,zIndex:60,boxSizing:"border-box",padding:"1px 2px",width:"max-content",maxWidth:"calc(100vw - 32px)",overflow:"visible",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",boxShadow:"0 4px 16px rgba(0,0,0,0.12), 0 1px 3px rgba(0,0,0,0.06)"}:null},children:[M&&(0,r.jsxs)("div",{ref:tV,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!o&&(em(!1),ef(e=>!e)),disabled:o,title:eo("chat.changeReasoning",{level:nU}),"aria-label":eo("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:o?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||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)(eV,{size:13,style:{display:"block"}}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:nU})]}),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:tf.filter(e=>!T||"auto"===e||T.includes(e)).map(e=>{let t=(I??"auto")===e,n=eo(tx[e]),i="auto"!==e&&L?L[e]:void 0,s=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{ef(!1),ed&&ek(!1),t||M(e)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",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:"1.3",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:[s,l&&(0,r.jsxs)("span",{style:{fontSize:11,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&&nJ(!1),!o&&S&&(0,r.jsxs)("div",{ref:tK,style:{position:ed?"static":"relative",display:"flex",alignItems:"center"},children:[(0,r.jsxs)("button",{onClick:()=>!o&&(ef(!1),em(e=>!e)),disabled:o,title:eo("chat.changeToolPreset")+`: ${nq}`,"aria-label":eo("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:o?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:o?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{o||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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:n_})]}),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:th.map(e=>{let t,n=tp[e],i=(j??ti.Q8)===n;return t="configured"===e?eo("chat.configuredTools"):"chat-only"===e?eo("chat.chatOnly"):"read-only"===e?eo("chat.readOnlyTools",{count:4}):"default"===e?eo("chat.builtInTools",{count:4}):eo("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{em(!1),ed&&ek(!1),i||S(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",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:"1.3",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)})})]}),!o&&x&&(el=!!(C?.percent&&C.percent>=85),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center"},children:(0,r.jsx)("button",{onClick:()=>{ed&&ek(!1),y?v?.():x?.()},disabled:o&&!y,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 4px",width:ed?"auto":void 0,height:ed?32:28,background:y?"rgba(239,68,68,0.08)":el?"rgba(239,68,68,0.06)":"none",border:el&&!y?"1px solid rgba(239,68,68,0.25)":"none",borderRadius:4,color:y||el?"#ef4444":"var(--text-muted)",cursor:o&&!y?"not-allowed":"pointer",fontSize:12,lineHeight:1,opacity:o&&!y?.5:1,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{ed||o&&!y||(e.currentTarget.style.background=y?"rgba(239,68,68,0.16)":el?"rgba(239,68,68,0.12)":"var(--bg-hover)",e.currentTarget.style.color=y||el?"#ef4444":"var(--text)")},onMouseLeave:e=>{ed||(e.currentTarget.style.background=y?"rgba(239,68,68,0.08)":el?"rgba(239,68,68,0.06)":"none",e.currentTarget.style.color=y||el?"#ef4444":"var(--text-muted)")},title:y?eo("chat.stopCompaction"):el?`${eo("chat.compactContext")} (${eo("chat.contextHighWarning")})`:eo("chat.compactContext"),"aria-label":y?eo("chat.stopCompaction"):eo("chat.compactContext"),children:y?(0,r.jsxs)(r.Fragment,{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:"6",y:"6",width:"12",height:"12",rx:"2",fill:"currentColor"})}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:eo("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{display:"block",flexShrink:0},children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(!ed||ew)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap",lineHeight:1},children:eo("chat.compact")})]})})})),void 0!==U&&(0,r.jsx)("button",{onClick:()=>{ed&&ek(!1),U?.()},title:O?eo("chat.disableSound"):eo("chat.enableSound"),"aria-label":O?eo("chat.disableSound"):eo("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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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 tF(e,t,n,r){let i=e?.capabilities[t];if(r&&i?.includes(r))return r;let s=e?.defaults?.[n];return s&&i?.includes(s)?s:i?.includes("auto")?"auto":i?.[0]??""}function tB({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:"3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})]})}function tH({config:e,edit:t,editPreviewUrl:n,initialSourceImage:s,onClose:l,onSubmit:o}){let{t:a}=(0,w.s)(),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),[h,p]=(0,i.useState)(""),m=e.connections.filter(e=>!0===e.capabilities.editing),[g,f]=(0,i.useState)(()=>t||!m.length?void 0:s),x=!!(t||g),v=x?m:e.connections,[y,b]=(0,i.useState)(()=>t?.connection&&e.connections.some(e=>e.id===t.connection)?t.connection:e.defaultConnection);(0,i.useEffect)(()=>{v.some(e=>e.id===y)||b(v.some(t=>t.id===e.defaultConnection)?e.defaultConnection:v[0]?.id??"")},[e.defaultConnection,v,y]);let k=v.find(e=>e.id===y)??v[0],j=!t&&m.length>0,S=e=>{let t=Array.from(e).find(e=>e.type.startsWith("image/"));return!!t&&(tM(t).then(f,e=>console.error("Failed to read source image:",e)),!0)},[C,N]=(0,i.useState)(()=>tF(k,"sizes","size",t?.size)),[E,I]=(0,i.useState)(()=>tF(k,"resolutions","resolution",t?.resolution)),[M,T]=(0,i.useState)(()=>tF(k,"qualities","quality",t?.quality)),L=k?.capabilities.sizes??[],$=k?.capabilities.resolutions??[],R=k?.capabilities.qualities??[],W=v.length>1,z=t?n:g?`data:${g.mimeType};base64,${g.data}`:void 0;(0,i.useLayoutEffect)(()=>{let e=c.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`)},[h]),(0,i.useEffect)(()=>{let e=document.activeElement;return window.matchMedia("(max-width: 640px)").matches||c.current?.focus(),()=>{e?.isConnected&&e.focus()}},[]),(0,i.useEffect)(()=>{let e=t&&k?.id===t.connection?t:void 0;N(tF(k,"sizes","size",e?.size)),I(tF(k,"resolutions","resolution",e?.resolution)),T(tF(k,"qualities","quality",e?.quality))},[k,t]);let P=()=>{if(!h.trim()||!k)return;let e={prompt:h.trim(),connection:k.id,...C?{size:C}:{},...E?{resolution:E}:{},...M?{quality:M}:{},...t?{target:t.path}:g?{}:{new_image:!0}};l(),o(e,t?void 0:g)};return(0,r.jsx)("div",{role:"presentation",className:"fixed inset-0 z-[1100] flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4",onClick:e=>{e.target===e.currentTarget&&l()},children:(0,r.jsxs)("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"image-generation-title",tabIndex:-1,onDragOver:e=>{j&&e.dataTransfer.types.includes("Files")&&e.preventDefault()},onDrop:e=>{j&&S(e.dataTransfer.files)&&e.preventDefault()},className:"flex max-h-[min(92dvh,100%)] w-full max-w-full flex-col overflow-hidden rounded-t-[16px] border border-border/80 bg-bg-panel shadow-2xl sm:max-h-[calc(100dvh-2rem)] sm:w-[480px] sm:rounded-[12px]",onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),l();return}if((e.metaKey||e.ctrlKey)&&"Enter"===e.key){e.preventDefault(),P();return}if("Tab"!==e.key)return;let t=Array.from(d.current?.querySelectorAll("button:not(:disabled), textarea:not(:disabled), select:not(:disabled), input:not(:disabled)")??[]).filter(e=>null!==e.offsetParent);if(!t.length)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n.focus())},children:[(0,r.jsx)("div",{className:"flex justify-center pt-2 sm:hidden","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-1 w-10 rounded-full bg-border"})}),(0,r.jsxs)("header",{className:"flex h-10 shrink-0 items-center px-4 sm:h-11",children:[(0,r.jsx)("h2",{id:"image-generation-title",className:"text-[14px] font-semibold text-text",children:x?a("image.editTitle"):a("image.title")}),(0,r.jsx)("button",{type:"button",onClick:l,className:"ml-auto inline-flex h-7 w-7 items-center justify-center rounded-md border-0 bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",title:a("trust.cancel"),"aria-label":a("trust.cancel"),children:(0,r.jsx)("svg",{width:"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:"M18 6 6 18M6 6l12 12"})})})]}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:z?"flex flex-col gap-3 sm:flex-row sm:items-start":void 0,children:[z?(0,r.jsxs)("div",{className:"relative overflow-hidden rounded-[10px] sm:shrink-0",children:[(0,r.jsx)("img",{src:z,alt:t?.prompt??a("image.editSource"),className:"block h-auto w-full sm:h-28 sm:w-auto sm:max-w-[7.5rem]"}),t?null:(0,r.jsx)("button",{type:"button",onClick:()=>f(void 0),className:"absolute right-1 top-1 inline-flex h-6 w-6 items-center justify-center rounded-full border-0 bg-black/60 text-white hover:bg-black/80",title:a("image.removeSource"),"aria-label":a("image.removeSource"),children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]}):null,(0,r.jsx)("textarea",{ref:c,id:"image-prompt",rows:2,value:h,maxLength:32e3,"aria-label":a("image.prompt"),onChange:e=>p(e.target.value),onPaste:e=>{j&&S(e.clipboardData.files)&&e.preventDefault()},placeholder:x?a("image.editPromptPlaceholder"):a("image.promptPlaceholder"),className:`image-generation-prompt w-full resize-none rounded-[10px] border-0 bg-bg px-3 py-2.5 leading-[1.5] text-text outline-none ring-1 ring-inset ring-transparent placeholder:text-text-dim focus:ring-accent/50 ${z?"sm:min-h-28 sm:flex-1":""}`,style:{fontFamily:"var(--font-chat)",fontSize:"var(--chat-content-font-size, 14px)"}})]})}),(0,r.jsxs)("footer",{className:"flex shrink-0 items-center gap-2 px-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-3",children:[(0,r.jsxs)("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-x-1 gap-y-0.5",children:[j&&!g?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",onClick:()=>u.current?.click(),className:"inline-flex h-7 w-7 flex-none items-center justify-center rounded-md border-0 bg-transparent text-text-muted hover:bg-bg-hover hover:text-text",title:a("image.addSource"),"aria-label":a("image.addSource"),children:(0,r.jsxs)("svg",{width:"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)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),(0,r.jsx)("input",{ref:u,type:"file",accept:"image/*",hidden:!0,onChange:e=>{S(e.target.files??[]),e.target.value=""}})]}):null,W?(0,r.jsx)(tB,{value:y,label:a("image.connection"),onChange:b,children:e.connections.map(e=>(0,r.jsx)("option",{value:e.id,children:e.label},e.id))}):null,L.length?(0,r.jsx)(tB,{value:C,label:a("image.aspect"),onChange:N,children:L.map(e=>{let t,n,i;return(0,r.jsx)("option",{value:e,children:"auto"===(t="auto"===(i=e.trim())?"auto":(n=function(e){let t=/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(e.trim())??/^(\d+)x(\d+)$/.exec(e.trim());if(!t)return null;let n=Number(t[1]),r=Number(t[2]);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?null:{width:n,height:r}}(i))?n.width===n.height?"square":n.width>n.height?"landscape":"portrait":null)?a("image.aspectAuto"):"square"===t?`${a("image.aspectSquare")} ${e}`:"portrait"===t?`${a("image.aspectPortrait")} ${e}`:"landscape"===t?`${a("image.aspectLandscape")} ${e}`:e},e)})}):null,$.length?(0,r.jsx)(tB,{value:E,label:a("image.resolution"),onChange:I,children:$.map(e=>(0,r.jsx)("option",{value:e,children:e.toUpperCase()},e))}):null,R.length?(0,r.jsx)(tB,{value:M,label:a("image.quality"),onChange:T,children:R.map(e=>(0,r.jsx)("option",{value:e,children:"auto"===e?a("image.qualityAuto"):"low"===e?a("image.qualityLow"):"medium"===e?a("image.qualityMedium"):"high"===e?a("image.qualityHigh"):e},e))}):null]}),(0,r.jsx)("button",{type:"button",disabled:!h.trim(),onClick:P,className:"h-8 shrink-0 rounded-md border-0 bg-[var(--primary)] px-3 text-[12px] text-[var(--primary-contrast)] disabled:cursor-not-allowed disabled:opacity-50",children:x?a("image.edit"):a("image.generate")})]})]})})}let tO=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,tU=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,t_=/\x1B_pi:c\x07/g;function tq(e){return e.replace(t_,"").replace(tO,"")}function tK(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(tU);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 tV(e,t){let n=tK(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function tJ(e){return tK(e)[0]?.char}let tY={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:""},tZ={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function tX(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function tG(e){return"custom"===e.role&&"pi-web:subagent-notification"===e.customType}function tQ(e){return tX(e)||tG(e)}function t0(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function t1(e,t={}){return(e.content??[]).filter(e=>!t0(e,t)&&!function(e,t={}){return"text"===e.type&&!t.isStreaming&&""===e.text.trim()}(e,t))}function t2(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function t4(e,t={}){return"image"===e.type||"text"===e.type&&(t.isStreaming?e.text.length>0:e.text.trim().length>0)}function t8(e,t={}){let n=t1(e,t),r=n.findLastIndex(e=>!t4(e,t));return -1===r?{answerBlocks:n,processBlocks:[]}:{processBlocks:n.slice(0,r+1),answerBlocks:n.slice(r+1)}}function t3(e,t={}){return t8(e,t).answerBlocks.some(e=>t4(e,t))}function t6(e){return e.filter(e=>"toolCall"===e.type).length}function t5(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 t7(e,t={}){let n=function(e,t={}){let{processBlocks:n,answerBlocks:r}=t8(e,t),i=[],s=[];for(let e of n)"text"===e.type&&e.text.trim().length>400?s.push(e):i.push(e);return{answerBlocks:[...s,...r],processBlocks:i}}(e,t),r=t3(e,t),i=!!t2(e,t),s=n.answerBlocks.length>0?t5(e,n.answerBlocks,{omitError:!r}):null;return{processMessage:t1({...e,content:n.processBlocks},t).length>0||i&&!r?t5(e,n.processBlocks,{omitUsage:!!s&&!t.isStreaming,omitError:r}):null,answerMessage:s}}let t9=/^\*\*\* (Add|Update|Delete) File: (.+)$/,ne=/^\*\*\* Move to: (.+)$/;function nt(){return{lineNo:null,text:"",type:"empty"}}function nn(e){if(!e.includes("*** Begin Patch"))return null;let t=[],n=null,r=!1,i=[],s=[],l=()=>{if(!n){i=[],s=[];return}let e=Math.max(i.length,s.length);for(let t=0;t<e;t+=1){let e=i[t]?{lineNo:i[t].lineNo,text:i[t].text,type:"removed"}:nt(),r=s[t]?{lineNo:s[t].lineNo,text:s[t].text,type:"added"}:nt();n.rows.push({type:"line",left:e,right:r})}i=[],s=[]};for(let o of e.split(/\r?\n/)){if(o.startsWith("*** Begin Patch")||o.startsWith("*** End Patch")){l(),r=!1;continue}let e=o.match(t9);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=o.match(ne);if(a){n.moveTo=a[1].trim();continue}if(o.startsWith("@@")){l(),r=!0,n.rows.push({type:"hunk",text:o});continue}if(o.startsWith("*** "))return null;if(""===o){l();continue}if(!r&&"update"===n.operation)continue;let d=o[0]??"",c=o.slice(1);"+"===d?s.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 nr(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function ni(e){try{return decodeURIComponent(e)}catch{return e}}function ns(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function nl(e){let t=ns(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,s=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){s.length>0&&".."!==s[s.length-1]?s.pop():i||n||r||s.push(e);continue}s.push(e)}let l=s.join("/");return n?l:r?`//${l}`:i?`/${l}`:l}function no(e,t){if(!e)return null;let n=e.split("#",1)[0].split("?",1)[0].trim();if(!n)return null;let r=null,i=ni(n),s=i.startsWith("\\\\"),l=ns(i),o=l.toLowerCase();if(o.startsWith("/api/")||o.startsWith("/_next/")||!s&&l.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(l)&&!o.startsWith("file:")&&!/^[a-zA-Z]:\//.test(l))return null;if(o.startsWith("file:"))r=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=ni(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}}(n);else if(/^[a-zA-Z]:\//.test(l))r=l;else if(l.startsWith("/"))r=l;else t&&!(l.startsWith("#")||l.startsWith("?"))&&(l.startsWith("./")||l.startsWith("../")||l.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(l))&&(r=`${ns(t).replace(/\/+$/,"")}/${l}`);return r?nl(r).replace(/:\d+(?::\d+)?$/,""):null}function na(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}function nd(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 nc(e){let t=e.toLowerCase();return"apply_patch"===t||t.endsWith(".apply_patch")||t.endsWith("/apply_patch")||t.endsWith("_apply_patch")}function nu(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
5
-
6
- ${r}
7
-
8
- ${n}`}function nh(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))),s=r-i;return{startIndex:Math.max(0,s-n),endIndex:s}}function np(e,t,n,r=8){return e+t>=n-r}class nm extends Error{constructor(e,t){super(t),this.name="OutlineLocateError",this.reason=e}}function ng(e,t){return e.entry.id===t||!!e.compressedEntryIds?.includes(t)}function nf(e,t){if(!e)return null;let n=new Map,r=[];for(let t=e.length-1;t>=0;t--)n.set(e[t],null),r.push(e[t]);for(;r.length>0;){let e=r.pop();if(ng(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 nx(e,t,n,r){let i=t,s=new Set;for(;;){if(r.throwIfAborted(),i.entryIds.includes(e))return;let t=i.oldestEntryId;if(!i.hasMore||!t)throw new nm("exhausted","Question is no longer in this branch. Refresh the outline and try again.");if(s.has(t))throw new nm("stalled","History did not advance. Please try again.");s.add(t);let l=await n(t);if(r.throwIfAborted(),!l)throw new nm("load_failed","Could not load this question. Please try again.");if(l.entryIds.includes(e))return;if(l.oldestEntryId===t||null!==l.oldestEntryId&&s.has(l.oldestEntryId))throw new nm("stalled","History did not advance. Please try again.");i=l}}function nv(e,t){return t.aborted||e instanceof DOMException&&"AbortError"===e.name||e instanceof Error&&"AbortError"===e.name}var ny=n(32316),nb=n(88374),nw=n(5924),nk=n(94764),nj=n(63835),nS=n(23135),nC=n(54152),nN=n(84678),nE=n(98164);let nI={...nk.j,attributes:{...nk.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...nk.j.protocols,href:[...nk.j.protocols?.href??[],"file"]},strip:[...nk.j.strip||[],"iframe","object","style","form"]};function nM(e){return/^file:/i.test(e)?e:(0,ny.Lv)(e)}let nT=/(?<![\\`])`((?:[^`\n]|\\`)+?)(?<![\\`])`(?!`)/g;function nL(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,s=0,l=null,o=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},s=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),s=0,r.push(t);continue}if(""===t.trim()||/^(?: {4}|\t)/.test(t)&&!/^[ \t]*\$\$/.test(t)||a.has(e)){s=0,r.push(t);continue}if(s||(t=t.replace(nT,(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}`})),s||t.includes("`")){s=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,s),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 m=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(m){let e=m[2].trim();if(d=e,/\\[A-Za-z]+/.test(d)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(d)){r.push(`${m[1]}$$`,`${m[1]}${e}`,`${m[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=>nz(e,g[1])),`${g[1]}$$`),e=t;continue}}let f=t.match(/^([ \t]*)\$\$(.+)\$\$[ \t]*$/);if(f){let e=f[2].trim();if(e){r.push(`${f[1]}$$`,`${f[1]}${e}`,`${f[1]}$$`);continue}}let x=t.match(/^([ \t]*)\$\$(.+)$/);if(x){let i=x[1],s=x[2].trimEnd();if(s&&!s.includes("$$")){let l=n$(n,e+1,i,o);if(l){r.push(`${i}$$`,`${i}${s}`);for(let t=e+1;t<l.index;t++)r.push(nz(n[t],i));l.content&&r.push(`${i}${l.content}`),r.push(`${i}$$`),e=l.index;continue}r.push(nR(t));continue}}let v=t.match(/^([ \t]*)\$\$\s*$/);if(v){let i=v[1],s=n$(n,e+1,i,o);if(s&&(s.glued||""!==i)){r.push(`${i}$$`);for(let t=e+1;t<s.index;t++)r.push(nz(n[t],i));s.content&&r.push(`${i}${s.content}`),r.push(`${i}$$`),e=s.index;continue}if(s){a.add(s.index),r.push(t);continue}r.push(nR(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 n$(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 s,l;let t=e[i];if(function(e,t){if(""===t)return/^ {0,3}\$\$\s*$/.test(e);let n=nW(e,t);return null!==n&&/^\$\$\s*$/.test(n)}(t,n))return{index:i,content:"",glued:!1};if(s=t,/^ {0,3}(`{3,}|~{3,})/.test(s)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(s)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(s)||/^ {0,3}>/.test(s)||/<(code|pre|script|style)\b/i.test(s)||(l=t,/^[ \t]*\$\$(?:\S|[ \t]+\S)/.test(l)))return r.set(n,i),null;let o=function(e,t){let n=nW(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!==o)return{index:i,content:o,glued:!0}}return r.set(n,e.length),null}function nR(e){return e.replace(/^([ \t]*)\$\$/,(e,t)=>`${t}\\$\\$`)}function nW(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 nz(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 nP={singleTilde:!1},nA=[[nC.A,["yaml"]],[nN.A,nP],nE.A,nS.A],nD=[[nC.A,["yaml"]],[nN.A,nP],nE.A,nS.A],nF=[nw.A,[nj.A,nI],[nb.A,{throwOnError:!1,strict:!1}]],nB=[nw.A,[nj.A,nI],[nb.A,{throwOnError:!1,strict:!1}]];var nH=n(7644);let nO="pi-theme",nU=["light","dark","auto"],n_={preference:"auto",theme:"light"},nq=new Set,nK=null,nV=!1;function nJ(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function nY(e){return"auto"===e?nJ():e}let nZ={light:"#f5f5f5",dark:"#242424"};function nX(e){"u">typeof document&&(document.documentElement.classList.toggle("dark","dark"===e),function(e){if("u"<typeof document)return;let t=nZ[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 nG(){if(nK)return nK;let e=function(){try{let e=localStorage.getItem(nO);if("light"===e||"dark"===e||"auto"===e)return e}catch{}return"auto"}(),t=nY(e);return nX(t),nK={preference:e,theme:t}}function nQ(e,t,n){if(nX(t),n)try{localStorage.setItem(nO,e)}catch{}nK={preference:e,theme:t},nq.forEach(e=>e())}function n0(){let e=nG();if("auto"!==e.preference)return;let t=nJ();t!==e.theme&&nQ("auto",t,!1)}function n1(e){return nq.add(e),nG(),nV||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",n0),window.addEventListener("focus",n0),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&n0()}),nV=!0),n0(),()=>{nq.delete(e)}}function n2(){return nG()}function n4(){return n_}function n8(){let e=(0,i.useSyncExternalStore)(n1,n2,n4),t=(0,i.useCallback)((e,t)=>{if(nG().preference===e)return;let n=nY(e),r=()=>{nQ(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let s=t?.x??window.innerWidth/2,l=t?.y??window.innerHeight/2,o=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(l,window.innerHeight-l));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${l}px)`,`circle(${o}px at ${s}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=nG().preference,r=nU.indexOf(n),nU[(r+1)%nU.length]),e)},[t]);return{theme:e.theme,preference:e.preference,setThemePreference:t,toggleTheme:n,isDark:"dark"===e.theme}}function n3(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 n6=n(65063);function n5({code:e,isStreaming:t,defaultPreview:s=!1}){let{isDark:l}=n8(),{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(s),[c,u]=(0,i.useState)(null),[h,p]=(0,i.useState)(!1),m=(0,i.useRef)(null),g=`${l?"dark":"light"}
9
- ${e}`,f=a&&!t;(0,i.useEffect)(()=>{if(!f)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)}`,s=await r.render(i,e);t||u({key:g,status:"ready",svg:s.svg})})().catch(()=>{t||u({key:g,status:"error"})}),()=>{t=!0}},[e,g,l,f]);let x=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?o("i18n.previewAfterStreaming"):f?o("i18n.showMermaidSource"):o("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?o("i18n.source"):o("i18n.preview")}),[t,f,o]);if(!f)return(0,r.jsx)(n9,{code:e,lang:"mermaid",headerAction:x,isStreaming:t});let v=c?.key===g&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:o("i18n.invalidMermaid")}):c?.key!==g||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":o("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!h&&(0,r.jsx)("button",{ref:m,type:"button",className:"mermaid-block mermaid-preview-button",title:o("i18n.openMermaidViewer"),"aria-label":o("i18n.openMermaidViewer"),onClick:()=>p(!0),dangerouslySetInnerHTML:{__html:c.svg}}),h&&(0,r.jsx)(n7,{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:`${o("i18n.downloadFile")} (SVG)`,"aria-label":`${o("i18n.downloadFile")} (SVG)`,onClick:()=>{let e,t,n,r=m.current?.querySelector("svg");r&&(e=new XMLSerializer().serializeToString(r),t=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),(n=document.createElement("a")).href=t,n.download="mermaid-diagram.svg",n.click(),setTimeout(()=>URL.revokeObjectURL(t),0))},children:"SVG"}),x]})]}),v]})}function n7({svg:e,onClose:t}){let{t:n}=(0,w.s)(),s=(0,i.useRef)(null),[l,o]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=s.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:s,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:()=>o(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:()=>o(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:()=>o(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 n9=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:s}){let{isDark:l}=n8(),{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsxs)("button",{type:"button",onClick:()=>{n3(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",title:o(a?"i18n.copied":"i18n.copy"),"aria-label":o(a?"i18n.copied":"i18n.copy"),children:[a?(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:"2.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:o(a?"i18n.copied":"i18n.copy")})]})]})]}),s?(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)(n6.A,{language:t||"text",style:l?nH.xJ:nH.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",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 re({children:e,className:t,isStreaming:n,cwd:s,onOpenFile:l}){let o=(0,i.useMemo)(()=>nL(e),[e]),a=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let s=e?.replace("language-","").toLowerCase()??"",l=String(t);return e?.includes("language-")||l.includes("\n")?"mermaid"===s?(0,r.jsx)(n5,{code:l.replace(/\n$/,""),isStreaming:n,defaultPreview:!0}):(0,r.jsx)(n9,{code:l.replace(/\n$/,""),lang:s,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?no(e,s):null;if(!i||!l)return(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t});let o=na(e);return(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(!nr(e))return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),l(i,o??void 0))},children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?no(e,s):null,l=i?`/api/files/${j(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})})}),[s,n,l]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(ny.oz,{remarkPlugins:nA,rehypePlugins:nF,urlTransform:l?nM:void 0,components:a,children:o})})}function rt({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:"currentColor",strokeWidth:X(n),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:X(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 15 10 9 4 3"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"20",y2:"17"})]}):"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:X(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",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:X(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",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:X(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",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)(G,{size:n,className:"shrink-0",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:X(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",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:X(n),strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",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 rn=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,rr=/(?:\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 ri(e){let t,n=[],r=null,i=0,s=0,l=0,o=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||o>0)){if(c.startsWith("--- ")){u(),t=rs(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:rs(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]),s=Number(e[3]),l=void 0===e[2]?1:Number(e[2]),o=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:s++,text:p,type:"context"}}),l>0&&l--,o>0&&o--):"-"===h?(a.push({lineNo:i++,text:p}),l>0&&l--):"+"===h?(d.push({lineNo:s++,text:p}),o>0&&o--):""!==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 rs(e){return e.split(" ")[0].trim()}let rl="pi-thinking-expanded",ro="pi-thinking-expanded-changed";function ra(){return"true"===window.localStorage.getItem(rl)}function rd({files:e,onOpenFile:t}){let{t:n}=(0,w.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=S(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:5,padding:"2.5px 7px",minHeight:22,fontSize:"calc(11px + 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},children:A(i,12)}),(0,r.jsx)("span",{style:{lineHeight:1},children:i})]},e)})})}let rc=new Map;function ru({children:e,className:t,...n}){let{t:s}=(0,w.s)(),[l,o]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(re,{className:t,...n,children:e});if(!l){var a;return(0,r.jsxs)("button",{onClick:()=>o(!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:["⚠ ",s("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 rh(e,t){if("number"!=typeof e||"number"!=typeof t)return;let n=Math.round((t-e)/1e3);return n>0?n:void 0}function rp(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 s=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${s} ${i}`}let rm=(0,i.memo)(function({message:e,modelName:t,isStreaming:n,toolResults:i,cwd:s,onOpenFile:l,onOpenSession:o,entryId:a,searchBlock:d,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:m,isTurnEnd:g,sessionId:f,writtenFiles:x,isProcess:v,runningToolIds:y}){return"user"===e.role?(0,r.jsx)(rx,{message:e,cwd:s,onOpenFile:l,entryId:a,onFork:c,forking:u,onNavigate:h,prevAssistantEntryId:p,onEditContent:m}):"assistant"===e.role?(0,r.jsx)(rv,{message:e,modelName:t,isStreaming:n,toolResults:i,cwd:s,onOpenFile:l,onOpenSession:o,isTurnEnd:g,sessionId:f,entryId:a,searchBlock:d,writtenFiles:x,isProcess:v,runningToolIds:y}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(rW,{message:e}):tG(e)?(0,r.jsx)(rA,{message:e,cwd:s,onOpenFile:l}):(0,r.jsx)(rD,{message:e,cwd:s,onOpenFile:l}):"bashExecution"===e.role?(0,r.jsx)(rO,{message:e,sessionId:f}):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 rg({text:e,cwd:t,onOpenFile:n}){let i=function(e){let t=[],n=0;for(let r of e.matchAll(ev)){let i=function(e){let t=(e[1]??e[2]??"").replace(/[),.;]+$/,"");if(!(!ey.test(t)||t.split(/[\\/]/).includes("..")))return t}(r),s=r.index??0;i&&(s>n&&t.push({type:"text",value:e.slice(n,s)}),t.push({type:"mention",path:i}),n=s+r[0].length)}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length?t:[{type:"text",value:e}]}(e),s=i.filter(e=>"mention"===e.type),l=i.filter(e=>"text"===e.type).map(e=>e.value).join("").trim();return s.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!l},children:s.map(e=>(0,r.jsx)(eC,{path:e.path,cwd:t},e.path))}),l?(0,r.jsx)(ru,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:l}):null]}):(0,r.jsx)(ru,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:e})}let rf=/^\[Image(?:: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by \d+\.\d{2} to map to original image\.| converted from \S+ to \S+\.)\]$/;function rx({message:e,cwd:t,onOpenFile:n,entryId:s,onFork:l,forking:o,onNavigate:a,prevAssistantEntryId:d,onEditContent:c}){let{t:h}=(0,w.s)(),[p,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),y=function(e){let t=e.split("\n"),n=t.length;for(;n>0&&(""===t[n-1].trim()||rf.test(t[n-1].trim()));)n-=1;return t.slice(0,n).join("\n")}("string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")),b="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),k=u(y),j=k?.search(/\s/)??-1,S=k?-1===j?k:k.slice(0,j):"",C=k&&-1!==j?k.slice(j+1):"",N=rp(e.timestamp),E=!!s&&!!l,I=k??y,M=k?function(e,t){if("string"==typeof e.content)return{...e,content:t};let n=[],r=!1;for(let i of e.content){if("text"!==i.type){n.push(i);continue}r||(n.push({...i,text:t}),r=!0)}return r||n.unshift({type:"text",text:t}),{...e,content:n}}(e,k):e,T=b.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!y},children:b.map((e,t)=>{let n=e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:"";return(0,r.jsx)(ep,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:8,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t)})}),L=!!d&&!!a;return(0,r.jsxs)("div",{style:{marginBottom:10,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"min(85%, 680px)"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid var(--user-border, var(--border))",borderRadius:6,padding:"6px 11px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.58,color:"var(--text)",wordBreak:"break-word",maxHeight:480,overflowY:"auto"},children:k?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[T,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>v(e=>!e),title:h(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(12px + 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:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),C&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.58,whiteSpace:"pre-wrap",wordBreak:"break-word",flex:"1 0 auto",width:"max-content",maxWidth:"100%"},children:C})]}),x&&(0,r.jsx)(re,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:y})]}):(0,r.jsxs)(r.Fragment,{children:[T,y&&(0,r.jsx)(rg,{text:y,cwd:t,onOpenFile:n})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:2},children:[(0,r.jsx)("div",{className:"message-action-group",style:{opacity:+!!p,pointerEvents:p?"auto":"none"},children:(0,r.jsx)("button",{type:"button",className:"message-action-button","data-copied":g?"true":void 0,onClick:()=>{n3(I).then(()=>{f(!0),setTimeout(()=>f(!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:"2.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"})]})})}),(E||L)&&(0,r.jsxs)("div",{className:"message-action-group",style:{opacity:p||o?1:0,pointerEvents:p||o?"auto":"none"},children:[L&&(0,r.jsx)("button",{type:"button",className:"message-action-button",onClick:()=>{a(d),c?.(M)},title:h("i18n.editFromHereTitle"),"aria-label":h("i18n.editFromHere"),children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",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(s)},disabled:o,title:h(o?"i18n.creatingSession":"i18n.newSessionTitle"),"aria-label":h(o?"i18n.creating":"i18n.newSession"),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","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"})]})})]}),N&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",userSelect:"none"},children:N})]})]})}function rv({message:e,modelName:t,isStreaming:n,toolResults:s,cwd:l,onOpenFile:o,onOpenSession:a,isTurnEnd:d,sessionId:c,entryId:u,searchBlock:h,writtenFiles:p,isProcess:m,runningToolIds:g}){let{t:f}=(0,w.s)(),[x,v]=(0,i.useState)(!1),y=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!t0(e,{isStreaming:n})),[e.content,n]),b=(0,i.useMemo)(()=>y.map(({block:e})=>e),[y]),k=e.completedAt??e.timestamp,j=(0,i.useMemo)(()=>{let t=new Map;if(!s||void 0===k)return t;for(let n of e.content){if("toolCall"!==n.type)continue;let e=s.get(n.toolCallId),r=rh(k,e?.timestamp);void 0!==r&&t.set(n.toolCallId,r)}return t},[e.content,s,k]),S=t2(e,{isStreaming:n}),C=function(e,t={}){return!t.isStreaming&&"length"===e.stopReason}(e,{isStreaming:n}),N=b.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),E=d&&!n?rp(e.timestamp):null,I=d&&!n&&(t||e.model)||null,M=d&&!n&&!!(I||N||E);return 0!==b.length||n||S||C?(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":u,style:{marginBottom:d?16:8},children:[(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:y.map(({block:t,originalIndex:i},d)=>{let p="thinking"===t.type?t:null,m=p?p.startedAt??e.timestamp:void 0,f=p?rh(m,p.endedAt??e.completedAt):void 0,x=!!(n&&p&&d===y.length-1&&void 0===f&&"number"==typeof m);return(0,r.jsx)(rw,{block:t,searchTarget:t===h,toolResults:s,isStreaming:n,streamingDuration:f,startTime:"toolCall"===t.type?k:m,live:x||"toolCall"===t.type&&!!g?.has(t.toolCallId),toolCallDurations:j,cwd:l,onOpenFile:o,onOpenSession:a,sessionId:c,entryId:u,blockIndex:i},`${u??"stream"}-${i}`)})}),S&&(m?(0,r.jsx)("div",{style:{marginTop:4*(b.length>0)},children:(0,r.jsx)(ry,{error:S})}):(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(b.length>0),padding:"7px 10px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,background:"rgba(239,68,68,0.07)",color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Error: ",S]})),C&&(0,r.jsx)("div",{role:"status",style:{marginTop:8*(b.length>0),padding:"7px 10px",border:"1px solid rgba(234,179,8,0.35)",borderRadius:6,background:"rgba(234,179,8,0.08)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:f("chat.truncatedByOutputLimit")}),p&&p.length>0&&(0,r.jsx)(rd,{files:p,onOpenFile:o}),M&&(0,r.jsxs)("div",{"data-answer-footer":!0,style:{display:"flex",alignItems:"center",gap:6,marginTop:2},children:[I&&(0,r.jsx)("div",{"data-answer-model":!0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-ui)"},children:I}),(N||E)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginLeft:"auto",flexShrink:0},children:[N&&(0,r.jsx)("button",{type:"button",className:"answer-copy-button message-action-button","data-copied":x?"true":void 0,onClick:()=>{n3(N).then(()=>{v(!0),setTimeout(()=>v(!1),1500)})},title:f(x?"i18n.copied":"i18n.copyMessage"),"aria-label":f(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:"2.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"})]})}),E&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)",userSelect:"none"},children:E})]})]})]}):null}function ry({error:e}){let{t}=(0,w.s)(),[n,s]=(0,i.useState)(!1),l=(0,i.useId)(),o=(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(11px + 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:()=>s(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},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#f87171",strokeWidth:"2.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)",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,lineHeight:1.35},children:o}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",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 rb({seconds:e,startTime:t,live:n}){let{t:s}=(0,w.s)(),[l,o]=(0,i.useState)(Date.now);(0,i.useEffect)(()=>{if(!n)return;let e=setInterval(()=>o(Date.now()),500);return()=>clearInterval(e)},[n]);let a=n&&void 0!==t?Math.max(0,Math.round((l-t)/1e3)):e;if(void 0===a)return null;let d=void 0!==t?s("chat.stepStartedAt",{time:new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):void 0;return(0,r.jsx)("span",{title:d,style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums",lineHeight:1.35},children:(0,b.a3)(a,s)})}function rw({block:e,searchTarget:t,toolResults:n,isStreaming:i,streamingDuration:s,startTime:l,live:o,toolCallDurations:a,cwd:d,onOpenFile:c,onOpenSession:u,sessionId:h,entryId:p,blockIndex:m}){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)(rk,{block:e,isStreaming:i,cwd:d,onOpenFile:c})}):null}if("image"===e.type){let n=rH(e);return n?(0,r.jsx)("div",{"data-search-target":t||void 0,style:{margin:"8px 0"},children:(0,r.jsx)(ep,{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)(rj,{block:e,duration:s,startTime:l,live:o,sessionId:h,entryId:p,blockIndex:m});if("toolCall"===e.type){let t=n?.get(e.toolCallId),i=a?.get(e.toolCallId);return(0,r.jsx)(rS,{block:e,result:t,duration:i,startTime:l,live:o,onOpenSession:u})}return null}function rk({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(ru,{className:"markdown-assistant-message",isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rj({block:e,duration:t,startTime:n,live:s,sessionId:l,entryId:o,blockIndex:a}){var d;let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(ra),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),y=(0,i.useRef)(c);y.current=c;let b=(d=e.thinking,d.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>h(ra());return window.addEventListener(ro,e),()=>window.removeEventListener(ro,e)},[]),(0,i.useEffect)(()=>{if(!u||!e.deferred||null!==p)return;if(!l||!o)return void v(y.current("i18n.thinkingUnavailable"));let t=!1;return f(!0),v(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=rc.get(r);if(i)return rc.delete(r),rc.set(r,i),i;let s=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 rc.delete(r),e});if(rc.set(r,s),rc.size>100){let e=rc.keys().next().value;e&&rc.delete(e)}return s})(l,o,a).then(e=>{t||(m(e),f(!1))}).catch(e=>{t||(v(e instanceof Error?e.message:String(e)),f(!1))}),()=>{t=!0}},[u,e.deferred,p,l,o,a]),(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",border:"1px solid var(--border)",background:"var(--bg-subtle)",transition:"border-color 0.15s ease"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:(0,r.jsxs)("button",{type:"button","aria-expanded":u,"data-step-trigger":"","aria-label":`${c("i18n.thinking")}${b?`: ${b}`:""}`,title:c("i18n.thinking"),onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0},children:(0,r.jsx)(eV,{active:u,size:12})}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-ui)",fontSize:11,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,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0,lineHeight:1.35},children:b?(0,r.jsx)(ny.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:b}):"..."}),u&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsx)(rb,{seconds:t,startTime:n,live:s}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.4,display:"block",transform:u?"rotate(180deg)":"none",transition:"transform 0.15s, opacity 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})}),u&&(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.55,color:x?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:g?c("i18n.loadingThinking"):x??(e.deferred?p:e.thinking)})]})}function rS({block:e,result:t,duration:n,startTime:s,live:l,onOpenSession:o}){var a,d;let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(!1),p=(d=e).rawInput??JSON.stringify(d.input,null,2),m=void 0!==e.rawInput,g=nd(e.toolName),f=nc(e.toolName),x=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,v=ek(e.toolName,e.input,t?.details),y="edit"===v?c("image.edit"):"generate"===v?c("image.generate"):e.toolName,b=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,k=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,j=rB(t?.content??[]),S=null!==k&&("(no output)"===k.trim()||""===k.trim()),C=t?.isError??!1,N=(a=t?.details)&&"object"==typeof a&&"pi-web-subagent"===a.kind&&"string"==typeof a.sessionId?t.details:null;return(0,r.jsxs)("div",{"data-step-card":"",style:{borderRadius:6,overflow:"hidden",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",border:C?"1px solid rgba(248,113,113,0.45)":"1px solid var(--border)",background:C?"rgba(248,113,113,0.05)":"var(--bg-subtle)",transition:"border-color 0.15s ease"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":u,"data-step-trigger":"",onClick:()=>h(e=>!e),style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,padding:"3px 8px",minHeight:24,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:"inherit",textAlign:"left"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:C?"#f87171":void 0},children:(0,r.jsx)(rt,{toolName:e.toolName,isError:C,size:12})}),(0,r.jsx)("span",{style:{color:C?"#f87171":"var(--text)",fontFamily:"var(--font-mono)",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,lineHeight:1.35},children:m?c("chat.generatingToolInput"):function(e){let t=e.input;if(!t||"object"!=typeof t)return"";let n=Object.keys(t);return 0===n.length?"":"command"in t?String(t.command).slice(0,120):"path"in t?String(t.path).slice(0,120):"file_path"in t?String(t.file_path).slice(0,120):"pattern"in t?String(t.pattern).slice(0,120):"query"in t?String(t.query).slice(0,120):String(t[n[0]]).slice(0,120)}(e)}),(0,r.jsx)(rb,{seconds:n,startTime:s,live:l}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",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"})})]}),N&&o&&(0,r.jsx)("button",{type:"button",onClick:()=>o(N.sessionId),title:c("subagent.open"),"aria-label":c("subagent.open"),style:{width:30,display:"grid",placeItems:"center",border:"none",borderLeft:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsxs)("svg",{width:"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)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})})]}),u&&(m||!g)&&!f&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg)",borderTop:C?"1px solid rgba(239,68,68,0.25)":"1px solid color-mix(in srgb, var(--border) 80%, transparent)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:p}),u&&f&&void 0!==x&&(0,r.jsx)("div",{style:{borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)(rI,{patch:x})}),u&&f&&void 0===x&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",background:"var(--bg)",borderTop:"1px solid color-mix(in srgb, var(--border) 80%, transparent)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:c("chat.generatingToolInput")}),u&&t&&!(f&&void 0!==x)&&(b?(0,r.jsx)(rN,{diff:b}):(0,r.jsx)(rR,{text:k??"",images:j,isEmpty:S,isError:C})),!u&&j.length>0&&(0,r.jsx)("div",{style:{padding:"6px 10px 8px",borderTop:C?"1px solid rgba(239,68,68,0.25)":"1px solid color-mix(in srgb, var(--border) 80%, transparent)",background:"var(--bg)"},children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:(0,r.jsx)(rC,{images:j,thumbnails:!0})})})]})}function rC({images:e,thumbnails:t=!1}){return(0,r.jsx)(r.Fragment,{children:e.map((e,n)=>{let i=rH(e);return i?(0,r.jsx)(ep,{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 rN({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(rE,{text:e.text})})}function rE({text:e}){let t=(0,i.useMemo)(()=>ri(e),[e]);return t?(0,r.jsx)(rM,{files:t}):(0,r.jsx)(r$,{text:e})}function rI({patch:e}){let t=(0,i.useMemo)(()=>nn(e),[e]);return t?(0,r.jsx)(rM,{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)(r$,{text:e})}function rM({files:e}){let{t}=(0,w.s)(),n=e.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:e.map((e,i)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===i?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(rT,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(rT,{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)(rL,{cell:e.left,side:"left"}),(0,r.jsx)(rL,{cell:e.right,side:"right"})]},t))})]},i))})}function rT({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 rL({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?"-":" ",s="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:s,userSelect:"none",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 r$({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 rR({text:e,images:t,isEmpty:n,isError:i}){let{t:s}=(0,w.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)(rC,{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"},children:n?s("i18n.noOutput"):e})]})}function rW({message:e}){let{t}=(0,w.s)(),n=rF(e.content),s=(0,i.useMemo)(()=>{let e,t,r,i,s;return e=[],t=[],r=n.match(rr),i=r?.[1]??"",s=r?.index===void 0?n:n.slice(0,r.index),i.replace(rn,(n,r,i)=>{let s=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...s):t.push(...s),""}),{body:s.trim(),readFiles:e,modifiedFiles:t}},[n]),l=rp(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},children:"compaction"}),l&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:11},children:l})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",fontWeight:600,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")}),s.body?(0,r.jsx)(re,{className:"markdown-compaction-message",children:s.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(rz,{readFiles:s.readFiles,modifiedFiles:s.modifiedFiles})]})]})})}function rz({readFiles:e,modifiedFiles:t}){let{t:n}=(0,w.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(rP,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(rP,{title:n("i18n.readFiles"),files:e})]})}function rP({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 rA({message:e,cwd:t,onOpenFile:n}){let{t:s}=(0,w.s)(),[l,o]=(0,i.useState)(!1),a=(e.details?.sessionIds??[]).length||1,d=1===a?s("subagent.notificationSingle"):s("subagent.notificationMany",{count:a}),c=rF(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:()=>o(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)(G,{size:12})}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11},children:d}),(0,r.jsx)("svg",{"data-step-chevron":"",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",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)(ru,{className:"markdown-subagent-notification",cwd:t,onOpenFile:n,children:c})})]})}function rD({message:e,cwd:t,onOpenFile:n}){let s,{t:l}=(0,w.s)(),o=!1===e.display,[a,d]=(0,i.useState)(!o),[c,u]=(0,i.useState)(!1),[h,p]=(0,i.useState)(!1),m=rF(e.content),g=rB(e.content),f=void 0!==e.details,x=f?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",v=e.customType||"extension",y=rp(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:o?"var(--bg-subtle)":"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)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:v}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:11},children:y})]}),a?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!m},children:g.map((e,t)=>{let n=rH(e);return n?(0,r.jsx)(ep,{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})}),m?(0,r.jsx)(re,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:m}):(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:m?(s=m.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"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:[m||x?(0,r.jsx)("button",{onClick:()=>{n3(m||x).then(()=>{p(!0),setTimeout(()=>p(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(h?"i18n.copied":"i18n.copy")}):null,(f||o)&&(0,r.jsx)("button",{onClick:()=>{o?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(o?a?"i18n.collapse":"i18n.expand":c?"i18n.hideDetails":"i18n.showDetails")})]}),f&&(o&&a||!o&&c)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:x})]})})}function rF(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function rB(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function rH(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}function rO({message:e,sessionId:t}){let[n,s]=(0,i.useState)(null),[l,o]=(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,m=n??e.output;async function g(){if(h){o(!0),d(null);try{let e=await fetch(h),t=await e.json();t.success?s(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{o(!1)}}}let f=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:f,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:f,content:m?[{type:"text",text:m}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rS,{block:x,result:v}),e.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[p&&(0,r.jsx)("button",{onClick:g,disabled: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,")"]})]})]})}function rU(e,t){let n=new Set(e),r=new Map,i=t.find(e=>n.has(e)),s=void 0===i?e.length:e.indexOf(i),l=e[s-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 r_(e,t,n){return n-t>0&&e+t>=n-8?1/0:e+48}function rq(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 rK=n(88576),rV=n.n(rK);function rJ({items:e,activeEntryId:t,onJumpToEntry:n,label:s,left:l,top:o,maxHeight:a=360,width:d=310}){var c,u;let h,p,m,{t:g}=(0,w.s)(),f=(0,i.useRef)(null),x=(0,i.useRef)(null),[v,y]=(0,i.useState)(!1),[b,k]=(0,i.useState)(0),[j,S]=(0,i.useState)(0),[C,N]=(0,i.useState)(null),E=(0,i.useRef)(0),I=(0,i.useRef)(null),M=(0,i.useRef)(!1),T=(0,i.useRef)(null),L=(0,i.useRef)(null),$=(0,i.useRef)(null),R=(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((m=Math.max(0,Math.min(b,28*u-p)))/28)-1),end:Math.min(u,Math.ceil((m+p)/28)+1)});(0,i.useEffect)(()=>()=>{E.current++,T.current&&clearTimeout(T.current),L.current&&clearTimeout(L.current),$.current&&clearTimeout($.current)},[]);let F=(0,i.useCallback)(()=>{T.current&&clearTimeout(T.current),L.current&&clearTimeout(L.current),$.current&&clearTimeout($.current),I.current=null,y(!1)},[]),B=(0,i.useCallback)(()=>{L.current&&(clearTimeout(L.current),L.current=null),v||(T.current=setTimeout(()=>{y(!0)},100))},[v]),H=(0,i.useCallback)(e=>{T.current&&(clearTimeout(T.current),T.current=null);let t=document.activeElement;t instanceof HTMLElement&&e.currentTarget.contains(t)&&t.matches(":focus-visible")||(L.current=setTimeout(()=>{F()},150))},[F]);async function O(e){let t=++E.current;N({entryId:e,state:"loading"});try{await n(e),E.current===t&&(N(null),$.current&&clearTimeout($.current),$.current=setTimeout(()=>{F()},160))}catch(n){if(E.current!==t)return;if(n&&"object"==typeof n&&"name"in n&&"AbortError"===n.name)return void N(null);N({entryId:e,state:"error",message:n instanceof Error?n.message:String(n)})}}function U(t){let n=Math.max(0,Math.min(e.length-1,t));I.current=n,S(n);let r=x.current;if(r){var i;let e;i=r.scrollTop,r.scrollTop=(e=28*n)<i?e:e+28>i+P?e+28-P:i,k(r.scrollTop);let t=r.querySelector(`[data-outline-index="${n}"]`);t&&(I.current=null,t.focus({preventScroll:!0}))}y(!0)}return((0,i.useLayoutEffect)(()=>{if(!v){M.current=!1;return}let e=x.current;if(e){if(!M.current){let t=Math.max(0,W);e.scrollTop=Math.max(0,(t+.5)*28-P/2),S(t),M.current=!0}k(e.scrollTop)}},[v,W,P]),(0,i.useLayoutEffect)(()=>{if(!v||null===I.current)return;let e=x.current?.querySelector(`[data-outline-index="${I.current}"]`);e&&(I.current=null,e.focus({preventScroll:!0}))}),e.length)?(0,r.jsxs)("div",{className:rV().minimap,style:{left:l,top:o},onMouseEnter:B,onMouseLeave:H,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||F()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),F(),f.current?.focus({preventScroll:!0}))},children:[(0,r.jsx)("button",{ref:f,type:"button",className:rV().trigger,style:{height:Math.min(a,Math.max(20,(z.end-z.start)*8+6))},"aria-label":s,"aria-expanded":v,"aria-controls":v?R:void 0,"aria-busy":C?.state==="loading"||void 0,onClick:e=>{0===e.detail?U(Math.max(0,W)):(T.current&&clearTimeout(T.current),L.current&&clearTimeout(L.current),y(e=>!e))},onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),U(Math.max(0,W)))},children:e.slice(z.start,z.end).map((e,n)=>(0,r.jsx)("span",{className:rV().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:rV().panel,style:{width:d},children:(0,r.jsxs)("nav",{id:R,className:rV().menu,"aria-label":s,children:[(0,r.jsx)("div",{ref:x,className:rV().list,style:{height:P},onScroll:e=>k(e.currentTarget.scrollTop),children:(0,r.jsx)("div",{className:rV().track,style:{height:28*e.length},children:e.slice(A,D).map((n,i)=>{let s=A+i;return(0,r.jsx)("button",{type:"button",className:rV().row,style:{top:28*s},"data-outline-index":s,"aria-current":t===n.entryId?"location":void 0,"aria-label":n.preview,tabIndex:s===(j>=A&&j<D?j:A)?0:-1,onFocus:()=>S(s),onKeyDown:t=>{let n={ArrowDown:s+1,ArrowUp:s-1,Home:0,End:e.length-1,PageDown:s+Math.max(1,Math.floor(P/28)),PageUp:s-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:rV().rowText,children:n.preview})},n.entryId)})})}),C?.state==="error"&&(0,r.jsxs)("div",{className:rV().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 rY({items:e,scrollContainer:t,contentContainer:n,loadedEntryIds:s,onJumpToEntry:l,label:o}){let[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),h=(0,i.useMemo)(()=>rU(e.map(e=>e.entryId),s),[e,s]);return((0,i.useEffect)(()=>{let r=t.current,i=n.current;if(!r||!i)return;let s=0,l=!0,o=[],a=[],c=new ResizeObserver(()=>m()),p=()=>{s||(s=requestAnimationFrame(g))},m=()=>{l=!0,p()};function g(){if(s=0,l){l=!1;let t=r.getBoundingClientRect(),n=Math.max(0,t.top),s=Math.min(window.innerHeight,t.bottom),d=Math.min(window.innerWidth,t.right),p=Math.max(0,Math.min(360,s-n-16)),m={left:d-26,top:(n+s-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===m.left&&e.top===m.top&&e.maxHeight===p&&e.width===m.width?e:m);let g=Array.from(i.children).filter(e=>e instanceof HTMLElement&&e.hasAttribute("data-entry-id"));o=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 f=new Set(g),x=new Set(a);for(let e of a)f.has(e)||c.unobserve(e);for(let e of g)x.has(e)||c.observe(e);a=g}d(rq(o,r_(r.scrollTop,r.clientHeight,r.scrollHeight)))}c.observe(r),c.observe(i);let f=new MutationObserver(m);f.observe(i,{subtree:!0,childList:!0,characterData:!0,attributes:!0}),r.addEventListener("scroll",p,{passive:!0}),window.addEventListener("resize",m);let x=e=>{e.target!==r&&e.target instanceof Node&&e.target.contains(r)&&m()};return window.addEventListener("scroll",x,!0),p(),()=>{cancelAnimationFrame(s),c.disconnect(),f.disconnect(),r.removeEventListener("scroll",p),window.removeEventListener("resize",m),window.removeEventListener("scroll",x,!0)}},[e.length,h,t,n]),!c||c.maxHeight<52||c.width<80)?null:(0,I.createPortal)((0,r.jsx)(rJ,{items:e,activeEntryId:a,onJumpToEntry:l,label:o,...c}),document.body)}function rZ(e,t,n){let r=JSON.stringify([e,t]),[s,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 s=i.toString();return fetch(`/api/sessions/${encodeURIComponent(e)}/outline${s?`?${s}`:""}`,{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&&s?.key===r)?s.items:[]}function rX({sessionId:e,leafId:t,outlineRevision:n,...i}){let{t:s}=(0,w.s)(),l=rZ(e,t,n);return e&&l.length?(0,r.jsx)(rY,{...i,items:l,label:s("chatMinimap.userOutline")},JSON.stringify([e,t])):null}function rG({sessionId:e,leafId:t,outlineRevision:n,scrollContainer:s,contentContainer:l,loadedEntryIds:o,onJumpToEntry:a}){let{t:d}=(0,w.s)(),c=rZ(e,t,n),[u,h]=(0,i.useState)(!1),[p,m]=(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||!s?.current||!l?.current)return;let e=s.current,t=l.current,n=rU(c.map(e=>e.entryId),o??[]),r=e.getBoundingClientRect(),i=[];for(let s of t.children)if(s instanceof HTMLElement&&s.dataset.entryId){let t=n.get(s.dataset.entryId);t&&i.push({userId:t,top:s.getBoundingClientRect().top-r.top-e.clientTop+e.scrollTop})}i.sort((e,t)=>e.top-t.top),m(rq(i,r_(e.scrollTop,e.clientHeight,e.scrollHeight)))},[u,c,o,s,l]),(0,i.useEffect)(()=>{u&&g.current&&g.current.scrollIntoView({block:"center"})},[u,p]),u&&c.length&&!("u"<typeof document))?(0,I.createPortal)((0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"fixed inset-0 z-[120] bg-black/50 transition-opacity",onClick:()=>h(!1),"aria-hidden":"true"}),(0,r.jsx)("section",{className:"fixed bottom-0 left-0 right-0 z-[121] flex max-h-[72dvh] flex-col overflow-hidden rounded-t-[16px] border-t border-[var(--border)] bg-[var(--bg-panel)] shadow-2xl pb-[max(12px,env(safe-area-inset-bottom))]",role:"dialog","aria-modal":"true","aria-label":d("i18n.outline")||"目录",children:(0,r.jsx)("div",{className:"flex-1 overflow-y-auto overscroll-contain px-2 py-2.5 space-y-0.5",children:c.map((e,t)=>{let n=p===e.entryId;return(0,r.jsxs)("button",{ref:n?g:void 0,type:"button",className:`relative flex w-full items-start gap-2.5 rounded-[4px] py-2 pl-2.5 pr-2 text-left transition-colors [-webkit-tap-highlight-color:transparent] ${n?"bg-[var(--bg-selected)] 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-[12px] leading-5 select-none ${n?"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-[12px] leading-5",style:{hangingPunctuation:"first"},children:e.preview})]},e.entryId)})})})]}),document.body):null}var rQ=n(42790);function r0({text:e}){let t=(0,i.useMemo)(()=>new rQ.v().ansi_to_html(e),[e]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:t}})}let r1="/icons/icon-192.png";function r2(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function r4(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 r8(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 r3(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,icon:r1,badge:r1,...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 r6(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r5(e,t={}){if("assistant"!==e.role)return e;let n=e.content;if(!Array.isArray(n))return e;let r=n.map(e=>(function(e,t={}){if(!r6(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=r6(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=r6(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 r7 extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function r9(e){return e instanceof r7&&"prompt_rejected"===e.code&&!1===e.accepted}async function ie(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 r7(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let it=["off","minimal","low","medium","high","xhigh","max"],ir="pi-tool-preset";function ii(){try{return window.localStorage}catch{return null}}function is(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 il(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,is(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),is(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function io(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function ia(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(io).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class id 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 ic{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 id("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof id?"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 id("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 id("closed");if(this.current!==t){if(this.current?.sessionId===e)continue;throw new id("closed")}if(1===t.source.readyState)return;this.discard(t,new id("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new id("closed"));try{t=this.options.createSource(e)}catch(e){throw new id("closed",e instanceof Error?e.message:String(e))}let i=!1,s=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(a,new id("ready_timeout"))},this.options.readinessTimeoutMs),o={promise:s,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a={sessionId:e,source:t,attempt:o};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)o.ready=!0,o.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(a,new id("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new id("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 iu(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 ih={isStreaming:!1,streamingMessage:null};function ip(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],s=n(i[t]);return s?(i[t]=s,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function im(e,t){switch(t.type){case"text_start":return ip(e,t.contentIndex,()=>({type:"text",text:""}));case"text_delta":return ip(e,t.contentIndex,e=>e?.type==="text"?{...e,text:e.text+t.delta}:null);case"text_end":return ip(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 ip(e,t.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+t.delta,startedAt:e.startedAt??Date.now()}:null);case"thinking_end":return ip(e,t.contentIndex,e=>({...e?.type==="thinking"?e:{startedAt:Date.now()},type:"thinking",thinking:t.content,endedAt:Date.now()}));case"toolcall_start":return ip(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 ip(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 ip(e,t.contentIndex,()=>({type:"toolCall",toolCallId:t.toolCall.id,toolName:t.toolCall.name,input:t.toolCall.arguments}));default:return e}}function ig(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=r5(t.message,{includeStreamingRawInput:!0});if("assistant"!==n.role)return e;let r="number"==typeof n.timestamp?n.timestamp:Date.now(),i=e.streamingMessage,s=n.content.map((e,t)=>{if("thinking"!==e.type)return e;let n=i?.content[t],s=e.startedAt??(n?.type==="thinking"?n.startedAt:void 0)??r,l=e.endedAt??(n?.type==="thinking"?n.endedAt:void 0);return e.startedAt===s&&e.endedAt===l?e:{...e,startedAt:s,..."number"==typeof l?{endedAt:l}:{}}});return{isStreaming:!0,streamingMessage:{...n,timestamp:r,content:s}}}case"delta":return im(e,t.event);case"deltas":return t.events.reduce(im,e);case"end":return ih;default:return e}}class ix{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 iv(e,t,n,r){return e===t&&"string"==typeof n&&n.length>0&&n===r}async function iy(e){let{gate:t,runId:n}=e;t.begin(n);let r=()=>!(!t.isCancelled(n)||t.wasDispatched(n))&&(e.abandonUnsent(),!0),i=null,s=!1;try{if(r()||(i=await e.prepare(),r()))return{status:"abandoned"};if(!i)throw Error("No active session for the prompt");if(s=!0,t.markDispatched(n),e.onDispatched?.(),await e.send(i),!t.isCancelled(n))return{status:"sent",sessionId:i};if(e.promptPending()&&iv(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:s};if(!s)return e.abandonUnsent(),{status:"abandoned"};if(e.promptPending()&&iv(n,e.currentRunId(),i,e.currentSessionId()))return{status:"cancelled_after_dispatch",sessionId:i};return{status:"stale"}}finally{t.forget(n)}}async function ib(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 iw(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 ik=new Map,ij=new Map;function iS(e){return"string"==typeof e?e:e?.text??""}function iC(e){return{steering:(e?.steering??[]).map(iS),followUp:(e?.followUp??[]).map(iS)}}function iN(e,t){return e===t||null!==e&&null!==t&&e.tokens===t.tokens&&e.percent===t.percent&&e.contextWindow===t.contextWindow?e:t}let iE=[2e3,5e3,1e4];function iI(e){return new Promise(t=>setTimeout(t,e))}function iM(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iT(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:iM(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iM(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=iM(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function iL(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 i$(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 iR({showCurrentVersion:e=!1}){let{t}=(0,w.s)(),[n,s]=(0,i.useState)(null),[l,o]=(0,i.useState)(!1),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)("idle"),[h,p]=(0,i.useState)(null),m=(0,i.useRef)(!1),g=n?.currentVersion;(0,i.useEffect)(()=>{let e;if("waiting"!==c||!g)return;let t=new AbortController,n=!1,r=setTimeout(()=>{n=!0,t.abort(),clearTimeout(e),u("timeout")},18e4),i=async()=>{try{let e=await fetch("/api/app-update?status=1",{cache:"no-store",signal:t.signal});if(e.ok){let t=await e.json();if(!n&&t.currentVersion&&t.currentVersion!==g){n=!0,clearTimeout(r),window.location.reload();return}}}catch{}n||(e=setTimeout(()=>{i()},2e3))};return i(),()=>{n=!0,t.abort(),clearTimeout(r),clearTimeout(e)}},[c,g]);let f=async()=>{if(!m.current&&window.confirm(t("appUpdate.confirm"))){m.current=!0,p(null),u("requesting");try{let e=await fetch("/api/app-update",{method:"POST"});if(202!==e.status){let n=await e.json().catch(()=>null);throw Error(n?.error||t("appUpdate.failed"))}u("waiting")}catch(e){p(e instanceof Error?e.message:t("appUpdate.failed")),u("idle"),m.current=!1}}},x=(0,i.useCallback)(async(e,t)=>{try{let n=await fetch(e?"/api/app-update?force=1":"/api/app-update",{cache:"no-store",signal:t});if(!n.ok)throw Error(`HTTP ${n.status}`);s(await n.json()),o(!1)}catch{t?.aborted||o(!0)}},[]);(0,i.useEffect)(()=>{let e=new AbortController;x(!1,e.signal);let t=()=>{"visible"===document.visibilityState&&x(!1,e.signal)};return document.addEventListener("visibilitychange",t),()=>{e.abort(),document.removeEventListener("visibilitychange",t)}},[x]);let v=async()=>{d(!0),o(!1),await x(!0),d(!1)},y=n?.updateAvailable&&n.latestVersion&&n.releaseUrl;if(!e&&!y)return null;let b=t("appUpdate.releaseNotes",{version:n?.latestVersion??""});return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:e?"flex-start":"center",gap:6},children:[e&&(0,r.jsxs)("p",{style:{fontSize:12},children:[t("appUpdate.currentVersion",{version:n?.currentVersion??"1.2.2"??"dev"}),!y&&(0,r.jsxs)("span",{role:"status",style:{color:"var(--text-muted)"},children:[" \xb7 ",t(!a&&(n||l)?l?"appUpdate.checkFailed":n?.releaseUrl?"appUpdate.upToDate":"appUpdate.checkDisabled":"appUpdate.checking")]}),(l||n?.releaseUrl)&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsx)("button",{type:"button",disabled:a||"idle"!==c,onClick:()=>{v()},title:t("appUpdate.checkNow"),"aria-label":t("appUpdate.checkNow"),style:{color:"var(--text-muted)",display:"inline-flex",alignItems:"center",height:"1lh",verticalAlign:"top",cursor:a?"default":"pointer"},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 12a9 9 0 1 1-3-6.7L21 8"}),(0,r.jsx)("path",{d:"M21 3v5h-5"})]})})]})]}),y&&n&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("a",{href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:b,"aria-label":b,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,lineHeight:1.2,textDecoration:"none",transition:"background 0.12s",whiteSpace:"nowrap"},children:[(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:["v",n.latestVersion]}),(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]}),n.canUpdate&&(0,r.jsx)("button",{type:"button",disabled:"idle"!==c,onClick:()=>{f()},style:{color:"var(--accent)",fontSize:12,cursor:"idle"===c?"pointer":"default"},children:t("appUpdate.updateAndRestart")})]}),e&&y&&!n?.canUpdate&&(n?.manualCommand?(0,r.jsxs)("p",{style:{color:"var(--text-muted)",fontSize:12},children:[t("appUpdate.manualCommand"),(0,r.jsx)("br",{}),(0,r.jsx)("code",{children:n.manualCommand})]}):(0,r.jsx)("p",{style:{color:"var(--text-muted)",fontSize:12},children:t("appUpdate.manualUpdate")})),("requesting"===c||"waiting"===c)&&(0,r.jsx)("p",{role:"status",style:{color:"var(--text-muted)",fontSize:12},children:t("appUpdate.waiting")}),h&&(0,r.jsx)("p",{role:"alert",style:{color:"var(--text-muted)",fontSize:12},children:h}),"timeout"===c&&(0,r.jsxs)("div",{role:"alert",style:{color:"var(--text-muted)",fontSize:12,textAlign:"center"},children:[(0,r.jsx)("p",{children:t("appUpdate.timeout")}),(0,r.jsx)("code",{children:"npm install -g @calmabacus/pi-web@latest"}),(0,r.jsx)("p",{children:t("appUpdate.thenStart")}),(0,r.jsx)("code",{children:"pi-web"})]})]})}function iW(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 iz({label:e}){return(0,r.jsx)("div",{role:"status","aria-label":e,className:"flex h-[28px] items-center",style:{marginBottom:8},children:(0,r.jsx)(Z,{size:12})})}function iP({cwd:e,onChange:t,recentPaths:n,pinnedPaths:s,onTogglePinnedCwd:l,homeDir:o,worktreeInfo:a}){let{t:d}=(0,w.s)(),c=(0,i.useRef)(null),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(null),k=[...s.map(e=>({path:e,pinned:!0})),...n.filter(e=>!s.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),m(!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),N=C?.branch??null,E=j?.projectRoot??e,I=o&&E.startsWith(o)?`~${E.slice(o.length)}`:E,M=()=>{h(!1),m(!1)},T=n=>{n===e?M():(v(!0),t(n).then(M).finally(()=>v(!1)))};return(0,r.jsxs)("div",{ref:c,style:{position:"relative",marginTop:10,maxWidth:"100%",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",title:d("chat.changeWorkingDirectory"),"aria-label":`${d("chat.changeWorkingDirectory")}: ${E}`,"aria-expanded":u,onClick:()=>{h(e=>!e),m(!1)},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},style:{maxWidth:"min(80vw, 360px)",border:"none",background:"none",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.4,padding:0,cursor:"pointer"},children:(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"center"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:I})})}),N&&(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")}: ${N}`,"aria-expanded":p,onClick:()=>{m(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:N})]}),u&&(0,r.jsxs)("div",{role:"listbox","aria-label":d("chat.changeWorkingDirectory"),style:{position:"absolute",top:"calc(100% + 6px)",left:"50%",transform:"translateX(-50%)",width:"max-content",minWidth:200,maxWidth:"min(90vw, 260px)",zIndex:50,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden",textAlign:"left"},children:[(0,r.jsx)("div",{style:{maxHeight:280,overflowY:"auto"},children:k.map(({path:t,pinned:n})=>{let i=t===e||!!(j?.projectRoot&&t===j.projectRoot);return(0,r.jsxs)("div",{className:"project-pin-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":i,disabled:x,onClick:()=>T(t),title:t,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"8px 10px",background:"var(--bg)",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:x?"default":"pointer",fontSize:11,fontFamily:"var(--font-mono)",textAlign:"left"},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",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:o&&t.startsWith(o)?`~${t.slice(o.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:"12",height:"12",viewBox:"0 0 24 24",fill:n?"currentColor":"none",stroke:"currentColor",strokeWidth:"2.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"})]})})]},t)})}),(0,r.jsx)("button",{type:"button",onClick:()=>{h(!1),f(!0),b(null)},style:{display:"block",width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,textAlign:"left"},children:d("sidebar.customPath")})]}),p&&S.length>0&&(0,r.jsx)("div",{role:"listbox","aria-label":d("sidebar.switchWorktree"),style:{position:"absolute",top:"calc(100% + 6px)",left:"50%",transform:"translateX(-50%)",width:"max-content",minWidth:180,maxWidth:"min(90vw, 260px)",zIndex:50,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:4,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden",textAlign:"left"},children:(0,r.jsx)("div",{style:{maxHeight:280,overflowY:"auto"},children:S.map(t=>{let n=t.path===e||t.path===j?.currentWorktreePath;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":!!n,disabled:x,onClick:()=>T(t.path),title:t.path,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"var(--bg)",border:"none",borderBottom:"1px solid var(--border)",color:n?"var(--text)":"var(--text-muted)",cursor:x?"default":"pointer",fontSize:11,fontFamily:"var(--font-mono)",textAlign:"left"},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"1.3",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)($,{initialPath:e,busy:x,error:y,onCancel:()=>{f(!1),b(null)},onSelect:e=>{v(!0),b(null),t(e).then(()=>f(!1),e=>b(e instanceof Error?e.message:String(e))).finally(()=>v(!1))}})]})}function iA(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&t3(r))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}function iD(e){return e?.content.at(-1)}function iF(e,t,n,r,i=!1){if(!e)return!1;if(r?.kind==="running_tools")return!0;let s=iD(n);return!!t&&(s?.type==="thinking"||s?.type==="toolCall")||!i}function iB(e,t,n){if(!e)return null;let r=ek(e,t);return"edit"===r?n("image.edit"):"generate"===r?n("image.generate"):null}function iH(e,t,n){if(t?.kind==="running_tools"){let e=t.tools[t.tools.length-1]?.name??null;return iB(e,void 0,n)??e}let r=iD(e);return r?.type==="thinking"?n("chat.thinking"):r?.type==="toolCall"?iB(r.toolName,r.input,n)??r.toolName??null:null}function iO(e,t,n,r){return t?(e&&(n.current=e),n.current??r):(n.current=null,null)}function iU(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 i_({startTime:e,t}){let[n,s]=(0,i.useState)(()=>Math.max(0,Math.round((Date.now()-e)/1e3)));return(0,i.useEffect)(()=>{let t=setInterval(()=>{s(Math.max(0,Math.round((Date.now()-e)/1e3)))},500);return()=>clearInterval(t)},[e]),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--accent)",fontVariantNumeric:"tabular-nums",flexShrink:0},children:(0,b.a3)(n,t)})}function iq({messageCount:e,toolCallCount:t,durationSeconds:n,startTime:s,defaultExpanded:l=!1,reveal:o=!1,isMobile:a=!1,activeStepSummary:d=null,isStreaming:c=!1,children:u,t:h}){let[p,m]=(0,i.useState)(l),g=(0,i.useRef)(null),f=(0,i.useRef)(!1),x=(0,i.useRef)(!1);(0,i.useLayoutEffect)(()=>{x.current||m(l)},[l]);let v=p||o,y=h(1===t?"chat.step":"chat.steps"),w=void 0!==n&&n>0?(0,b.a3)(n,h):null,k=w?t>0?h("chat.workedForSteps",{duration:w,count:t,steps:y}):h("chat.workedFor",{duration:w}):t>0?`${t} ${y}`:h("chat.processDetails");return(0,i.useLayoutEffect)(()=>{if(!v){f.current=!1;return}let e=g.current;!e||f.current||e.scrollHeight<=e.clientHeight+1||(e.scrollTop=e.scrollHeight)},[v,e,t]),(0,r.jsxs)("div",{style:{marginBottom:v?8:2},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":v,onClick:()=>{x.current=!0,m(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,fontFamily:"var(--font-ui)",fontWeight:400,textAlign:"left",transition:"color 0.12s ease"},title:h(v?"chat.collapseProcess":"chat.expandProcess"),children:[c?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Z,{size:12}),s&&(0,r.jsx)(i_,{startTime:s,t:h}),(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,minWidth:0,fontSize:11,color:"var(--accent)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"\xb7"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d||h("chat.thinking")})]})]}):(0,r.jsx)("span",{"data-summary-label":"",style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:400,color:"inherit",lineHeight:1.35,transition:"color 0.12s ease"},children:k}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block",transform:v?"rotate(90deg)":"none",transition:"transform 0.15s ease"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"3.5 2 6.5 5 3.5 8"})})]}),v&&(0,r.jsx)("div",{ref:g,onScroll:()=>{let e=g.current;e&&(f.current=!(e.scrollTop+e.clientHeight>=e.scrollHeight-20))},className:"process-details-list",style:{display:"flex",flexDirection:"column",gap:1,margin:"0 -8px",padding:"2px 8px 4px",maxHeight:a?220:280,overflowY:"auto",overflowX:"hidden",overscrollBehavior:"contain",overflowAnchor:"none"},children:u})]})}function iK({session:e,searchTarget:t,onSearchTargetHandled:s,initialScrollPosition:l,onScrollPositionChange:o,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onDraftChange:u,onKeepTabOpen:h,onNewSessionCwdChange:p,recentProjectPaths:m=[],pinnedCwds:g=[],onTogglePinnedCwd:f,homeDir:x="",worktreeInfo:v=null,draftPersistenceWarning:y=!1,onAgentEnd:b,onAttentionNeeded:k,onSessionCreated:S,onSessionForked:C,modelsRefreshKey:N,chatInputRef:M,isFocusedPane:T=!1,isVisiblePane:L=T,onBranchDataChange:$,onSystemPromptChange:R,onSystemToolsChange:W,onSystemInfoLoaderChange:z,onSessionStatsChange:P,onSessionStatsPanelOpen:A,onContextUsageChange:D,onOpenFile:F,onOpenSession:B,onAskInNewChat:H,quoteSelectionEnabled:O=!1,initialPrompt:U,onInitialPromptConsumed:_,soundEnabled:q=!0,onSoundToggle:K,playDoneSound:V=()=>{},unlockAudio:J}){var Y;let Z,{t:X}=(0,w.s)(),G=eG(),Q=e?.relation?.kind!=="subagent",ee=(0,i.useRef)(V);ee.current=V;let et=(0,i.useRef)(q);et.current=q;let en=(0,i.useRef)(e);en.current=e;let er=(0,i.useRef)(null),ei=(0,i.useCallback)(e=>{let t=er.current;er.current=e,M&&(e?M.current=e:M.current===t&&(M.current=null))},[M]),es=(0,i.useRef)(null),el=(0,i.useCallback)(()=>{Q&&et.current&&ee.current(),b?.(en.current)},[Q,b]),eo=(0,i.useCallback)(e=>{k?.(e,en.current)},[k]),ea=(0,i.useCallback)(e=>{C?.(e,en.current?.id??null)},[C]),ed=(0,i.useCallback)((e,t)=>{F?.(e,en.current?.id??null,t)},[F]),ec=(0,i.useCallback)(()=>{let e=en.current?.id;e&&h?.(e)},[h]),eu=(0,i.useCallback)(e=>{er.current?.replaceMessage(e)},[]),eh=(0,i.useRef)(t?null:l??null),[ep,eg]=(0,i.useState)(()=>{let e=eh.current;return e&&!e.atBottom?e:null}),[ef,ex]=(0,i.useState)(!1),{data:ev,loading:ey,error:eb,messages:ek,activeToolResults:ej,entryIds:eS,historyCursor:eC,hasEarlierMessages:eN,streamState:eM,agentRunning:eT,directImageRunning:eL,bashRunning:e$,pendingBash:eR,modelNames:eW,modelList:ez,modelError:eD,modelScopeWarnings:eF,modelThinkingLevels:eB,modelThinkingLevelMaps:eU,toolPreset:e_,thinkingLevel:eq,retryInfo:eK,contextUsage:eV,forkingEntryId:eJ,isCompacting:eY,compactError:eZ,compactResult:eX,displayModel:eQ,modelSwitching:e0,sessionStats:e1,slashCommands:e2,slashCommandsLoading:e4,queuedMessages:e8,notices:e3,extensionDialog:e6,extensionCustomUi:e5,respondToExtensionUi:e7,sendExtensionCustomInput:e9,addNotice:te,setNoticePaused:tt,isAutoModelSelection:tn,agentPhase:tr,isNew:ts,sessionIdRef:tl,scrollContainerRef:to,handleSend:ta,handleDirectImageGeneration:td,abortDirectImageGeneration:tc,handleAbort:tu,handleFork:th,handleNavigate:tp,handleModelChange:tm,handleCompact:tg,handleSteer:tf,handleFollowUp:tx,handlePromptWithStreamingBehavior:tv,handleAbortCompaction:ty,handleRecallQueue:tb,handleBuiltinSlashCommand:tw,handleToolPresetChange:tk,handleThinkingLevelChange:tj,loadSlashCommands:tS,loadContext:tC,activeLeafId:tN,scrollToBottom:tE,scrollToMessage:tI}=function(e){let{session:t,sessionRunning:r,newSessionCwd:s,newSessionDraftKey:l,onAgentEnd:o,onAttentionNeeded:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:h,onSystemPromptChange:p,onSystemToolsChange:m,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:f,isVisiblePane:x=!1}=e,v=null===t&&null!==s,y=s??t?.cwd??"",b=y?`/api/models?cwd=${encodeURIComponent(y)}`:"/api/models",w=ik.get(b)?.data,k=v?i$(w):null,j=k?w?.thinkingLevelPins?.[`${k.provider}/${k.modelId}`]:void 0,[S,C]=(0,i.useState)(null),[N,E]=(0,i.useState)(!v),[I,M]=(0,i.useState)(null),[T,L]=(0,i.useState)(null),[$,R]=(0,i.useState)([]),[W,z]=(0,i.useState)(new Map),[P,A]=(0,i.useState)([]),[D,F]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),O=(0,i.useRef)({messages:$,entryIds:P,oldestEntryId:D,hasMore:B});O.current={messages:$,entryIds:P,oldestEntryId:D,hasMore:B};let[U,_]=(0,i.useReducer)(ig,ih),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??{}),[es,el]=(0,i.useState)(()=>w?.modelList??[]),[eo,ea]=(0,i.useState)(()=>w?.modelError??null),[ed,ec]=(0,i.useState)(()=>w?.modelScopeWarnings??[]),[eu,eh]=(0,i.useState)(()=>w?.thinkingLevels??{}),[ep,em]=(0,i.useState)(()=>w?.thinkingLevelMaps??{}),[eg,ef]=(0,i.useState)(()=>w?.thinkingLevelPins??{}),[ex,ev]=(0,i.useState)(null),[ey,eb]=(0,i.useState)(k),[ew,ek]=(0,i.useState)(ti.Q8),[ej,eS]=(0,i.useState)(j??"auto"),[eC,eN]=(0,i.useState)(null),[eE,eI]=(0,i.useState)(null),[eM,eT]=(0,i.useState)(null),[eL,e$]=(0,i.useState)(null),[eR,eW]=(0,i.useState)(null),[ez,eD]=(0,i.useState)(null),[eF,eB]=(0,i.useState)(!1),[eU,e_]=(0,i.useState)(!1),[eq,eK]=(0,i.useState)(!0),[eV,eJ]=(0,i.useState)(null),[eY,eZ]=(0,i.useState)(null),[eX,eG]=(0,i.useState)(null),[eQ,e0]=(0,i.useState)([]),[e1,e2]=(0,i.useState)(!1),[e4,e8]=(0,i.useReducer)(iT,{visible:[],pending:[]}),[e3,e6]=(0,i.useState)(null),[e5,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)({steering:[],followUp:[]}),tr=(0,i.useRef)(null),ts=(0,i.useRef)(null),tl=(0,i.useRef)(0),to=(0,i.useRef)(!1),ta=(0,i.useRef)(!1),td=(0,i.useRef)(t?.id??null),tc=(0,i.useRef)(t?.id??null),tu=(0,i.useRef)(!!r),th=(0,i.useRef)(x),tp=(0,i.useRef)(!1),tm=(0,i.useRef)(!1),tg=(0,i.useRef)(!1),tf=(0,i.useRef)(-1),tx=(0,i.useRef)(!1),tv=(0,i.useRef)(!1),ty=(0,i.useRef)(0),tb=(0,i.useRef)(null),tw=(0,i.useRef)(!!e.deferInitialScroll),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(!0),tS=(0,i.useRef)(0),tC=(0,i.useRef)(null),tN=(0,i.useRef)([]),tE=(0,i.useRef)(void 0),tI=(0,i.useRef)(null),tM=(0,i.useRef)(null),tT=(0,i.useRef)(!1),tL=(0,i.useRef)(null),t$=(0,i.useRef)(null),tR=(0,i.useRef)(0),tW=(0,i.useRef)(new ix),tz=(0,i.useRef)(null),tP=(0,i.useRef)(!1),tA=(0,i.useRef)(null),tD=(0,i.useRef)(!1),tF=(0,i.useRef)(u),tB=(0,i.useRef)(new Map),tH=(0,i.useRef)(!0);tc.current=t?.id??null,tu.current=!!r,th.current=x,tr.current||(tr.current=new ic({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tb.current?.(e),shouldMaintain:e=>tH.current&&td.current===e&&(th.current||tp.current||to.current||tc.current===e&&tu.current),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let tO=e.setToolPreset??ek,tU=t?.id;(0,i.useLayoutEffect)(()=>{(tU||v&&!td.current)&&tO(function(e=ii()){if(!e)return ti.Q8;try{let t=e.getItem(ir);return(0,ti.sn)(t)?t:ti.Q8}catch{return ti.Q8}}())},[tU,v,tO]);let t_=(0,i.useCallback)((e="instant")=>{let t=tI.current;t&&(tj.current=!0,t.scrollTo({top:Math.max(0,t.scrollHeight-t.clientHeight),behavior:e}),tS.current=t.scrollTop)},[]),tq=eR??S?.context.model??ez??null,tK=v?ex??ey:tq,tV=t?.id??l??void 0,tJ=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tB.current.get(t);if(!e)break;t=e}return t},[]),tY=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),s=tJ(r);if(!tH.current&&!tT.current&&r===l)return;let o=e.chatInputRef?.current;if(o)o.restoreSubmission(t,i,s);else{let e,n;s&&(n=eH(t,i,(e=eP(s)??{value:"",images:[]}).value,e.images),eA(s,n))}},[l,e.chatInputRef,tJ]),tZ=(0,i.useMemo)(()=>{if(e3)return{...e3,totalActiveMs:S?.totalActiveMs,...eE?{contextUsage:eE}:{}};let e=S?.stats,n=function(e,t,n){let r=il(n);if(!e)return r;let i=il(t),s=(e,t)=>Math.max(0,e-t),l={input:e.tokens.input+s(r.tokens.input,i.tokens.input),output:e.tokens.output+s(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+s(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+s(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return l.total=l.input+l.output+l.cacheRead+l.cacheWrite,{userMessages:e.userMessages+s(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+s(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+s(r.toolCalls,i.toolCalls),toolResults:e.toolResults+s(r.toolResults,i.toolResults),totalMessages:e.totalMessages+s(r.totalMessages,i.totalMessages),tokens:l,cost:e.cost+s(r.cost,i.cost)}}(e,S?.context.messages??[],$);return 0!==n.tokens.total||0!==$.length||e?{sessionFile:S?.filePath||void 0,sessionId:td.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:S?.totalActiveMs,...eE?{contextUsage:eE}:{}}:null},[$,e3,eE,S?.context.messages,S?.filePath,S?.totalActiveMs,S?.stats,t?.id,t?.name]),tX=(0,i.useCallback)(async(e,t=!1,n=!1)=>{let r=!1;try{t&&E(!0);let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});n&&i.set("force","1");let s=await fetch(`/api/sessions/${encodeURIComponent(e)}?${i}`);if(404===s.status)return t&&(C(null),L(null),R([]),A([]),F(null),H(!1),eI(null),M(null)),null;if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json();if(td.current!==e)return null;let o={messages:l.context.messages,entryIds:l.context.entryIds??[],oldestEntryId:l.context.oldestEntryId,hasMore:l.context.hasMore},a=t?o: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,o);if(C({...l,context:{...l.context,...a}}),L(l.leafId),R(a.messages),A(a.entryIds),F(a.oldestEntryId),H(a.hasMore),ta.current=void 0!==l.toolNames,tO(void 0!==l.toolNames?(0,ti.YO)(l.toolNames):ti.Q8),eW(e=>tD.current?e:null),M(null),l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&eS(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(td.current!==e)return null;let r=n.state;return r?(void 0!==r.contextUsage&&eI(r.contextUsage??null),void 0!==r.systemPrompt&&eT(r.systemPrompt??null),void 0!==r.thinkingLevel&&eS(r.thinkingLevel??"auto"),void 0!==r.queuedMessages&&tn(iC(r.queuedMessages))):n.running||tn({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return M(String(e)),null}finally{t&&!r&&E(!1)}},[tO]),tG=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let s=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,l=await fetch(s,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let o=await l.json();if(td.current!==e||r?.signal?.aborted||!tH.current)return;return F(o.context.oldestEntryId),H(o.context.hasMore),C(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...o.context.messages,...t.context.messages],entryIds:[...o.context.entryIds,...t.context.entryIds],oldestEntryId:o.context.oldestEntryId,hasMore:o.context.hasMore}:o.context;return{...t,context:r}}),n?(R(e=>[...o.context.messages,...e]),A(e=>[...o.context.entryIds,...e])):(R(o.context.messages),A(o.context.entryIds??[])),o.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),tQ=(0,i.useCallback)(async e=>{try{let t=await ie(e,{type:"get_tools"});if(!t||!tH.current||td.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return tO(ta.current?r(t):ti.Q8),m?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[m,tO]),t0=(0,i.useCallback)((t=0,n="(no messages)")=>{let r=td.current;if(v&&s&&r&&!tT.current&&(tT.current=!0,l)){if(l!==r){tB.current.set(l,r);let t=e.chatInputRef?.current;t?t.rekeyDraft(l,r):eO(l,r)}d?.({id:r,path:"",cwd:s,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},l)}},[v,s,l,d,e.chatInputRef]),t1=(0,i.useCallback)(e=>{e instanceof id||console.error("Failed to maintain the agent event stream:",e)},[]),t2=(0,i.useCallback)(async()=>{if(td.current||!v||!s)return td.current;if(tM.current)return tM.current;let e=(async()=>{let e=tL.current,t=t$.current;e&&eD(e);let n=(0,ti.xG)(ew);ta.current=void 0!==n;let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:s,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 td.current=l,th.current&&tr.current?.ensureConnected(l).catch(t1),void 0!==i.contextUsage&&eI(i.contextUsage??null),i.model&&tL.current===e&&(eD(i.model),e||eb(i.model)),i.thinkingLevel&&t$.current===t&&eS(i.thinkingLevel),l})();tM.current=e;try{return await e}finally{tM.current=null}},[t1,v,s,ew]),t4=(0,i.useCallback)(async()=>{let e=td.current??await t2();if(!e)return;let[t]=await Promise.all([ie(e,{type:"get_state"}),tQ(e)]);tH.current&&td.current===e&&eT(t.systemPrompt??"")},[t2,tQ]),t8=(0,i.useCallback)(async()=>{let e=td.current??await t2();if(!e)return e0([]),[];e2(!0);try{let t=await ie(e,{type:"get_commands"}),n=t?.commands??[];return e0(n),n}catch(e){return console.error("Failed to load slash commands:",e),e0([]),[]}finally{e2(!1)}},[t2]),t3=(0,i.useCallback)(()=>{tl.current+=1,to.current=!1,ts.current&&(clearTimeout(ts.current),ts.current=null)},[]),t6=(0,i.useCallback)(()=>{tr.current?.close()},[]),t5=(0,i.useCallback)(e=>tr.current.ensureConnected(e),[]),t7=(0,i.useCallback)(e=>{tr.current.maintain(e)},[]),t9=(0,i.useCallback)(e=>{tr.current?.reconnect(e).catch(t1)},[t1]);(0,i.useEffect)(()=>{if(t?.id&&r)return t7(t.id),()=>{td.current!==t.id||tp.current||to.current||th.current||tc.current===t.id&&tu.current||tr.current?.close()}},[t7,t?.id,r]),(0,i.useEffect)(()=>{if(!x){tp.current||tu.current||to.current||t6();return}let e=t?.id??td.current??null;e&&(t3(),tr.current?.ensureConnected(e).catch(t1))},[t3,t6,t1,x,t?.id]);let ne=(0,i.useCallback)(async(e,t)=>{let n=td.current;if(e7(t=>t?.id===e.id?null:t),n)try{await ie(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),nt=(0,i.useCallback)(async(e,t)=>{let n=td.current;if(n)try{await ie(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nn=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e8({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),nr=(0,i.useCallback)(t=>{switch(r8(t)&&a?.(t),t.method){case"select":case"confirm":case"input":case"editor":e7(t);break;case"notify":nn({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":te(e=>t.closed?e?.id===t.id?null:e:t)}},[nn,a,e.chatInputRef]),ni=(0,i.useCallback)(()=>{null!==tC.current&&(cancelAnimationFrame(tC.current),tC.current=null);let e=tN.current;0!==e.length&&(tN.current=[],_({type:"deltas",events:e}))},[]),ns=(0,i.useCallback)(e=>{tN.current.push(e),null===tC.current&&(tC.current=requestAnimationFrame(()=>{tC.current=null,ni()}))},[ni]),nl=(0,i.useCallback)(()=>{ni();let e=tp.current;return tp.current=!1,V(!1),eG(null),eN(null),z(new Map),_({type:"end"}),e},[ni]),no=(0,i.useCallback)(e=>tf.current!==e&&(tf.current=e,o?.(),!0),[o]),na=(0,i.useCallback)(e=>{if(th.current&&td.current===e)return void t3();t3(),to.current=!0;let t=tl.current,n=async()=>{if(t===tl.current&&td.current===e&&to.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!==tl.current||td.current!==e||!to.current)return;let s=i.state;if(i.running&&s&&(s.isStreaming||s.isPromptRunning)){to.current=!1,ts.current=null,tm.current=!!s?.isStreaming,tg.current=!!s?.isPromptRunning,tp.current=!0,V(!0),eG(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&s?.isCompacting){e_(!0),ts.current=setTimeout(()=>void n(),600);return}to.current=!1,ts.current=null,t6()}catch{if(t!==tl.current||td.current!==e||!to.current)return;ts.current=setTimeout(()=>void n(),600)}};ts.current=setTimeout(()=>void n(),3e4)},[t3,t6]),nd=(0,i.useCallback)(async(e=td.current,t=tR.current)=>{if(tR.current===t)try{e&&await tX(e)}finally{if(tR.current!==t)return;let n=tg.current,r=tm.current;tg.current=!1,tm.current=!1,tA.current=null;let i=nl();n?no(t):r&&i&&o?.(),e&&na(e)}},[tX,no,o,na,nl]),nc=(0,i.useCallback)(async(e,t)=>{await iI(800);let n=Date.now();for(;tp.current&&Date.now()-n<2e4;){if(void 0!==t&&tR.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await nd(e,t)}}catch{}await iI(600)}},[nd]),nu=(0,i.useCallback)(async e=>{let t=ty.current+1;for(ty.current=t;tx.current&&ty.current===t&&td.current===e;){await iI(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await tX(e),ty.current!==t||td.current!==e)return;tx.current=!1,Y(!1),X(null);return}catch{}}},[tX]),nh=(0,i.useCallback)(async e=>{if(!tp.current||td.current!==e)return;let t=tR.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(td.current!==e||tR.current!==t)return;let i=r.state;if(e_(i?.isCompacting??!1),tn(iC(i?.queuedMessages)),"boolean"==typeof i?.autoCompactionEnabled&&eK(i.autoCompactionEnabled),i?.contextUsage!==void 0&&eI(e=>iN(e,i.contextUsage??null)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){tm.current=!!i.isStreaming,tg.current=!!i.isPromptRunning;return}if(!tp.current)return;i&&void 0!==i.systemPrompt&&eT(i.systemPrompt??null),await nd(e,t)}catch{}},[nd]);(0,i.useEffect)(()=>{if(!K)return;let e=()=>{let e=td.current;e&&nh(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,nh]),(0,i.useEffect)(()=>{let e=()=>{let e=td.current;if(e&&"hidden"!==document.visibilityState){if(th.current)return void t9(e);(tp.current||to.current||tc.current===e&&tu.current)&&t7(e)}},t=()=>{"visible"===document.visibilityState&&e()};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener("pageshow",e)}},[t7,t9]),(0,i.useEffect)(()=>{tp.current=K},[K]),tb.current=(0,i.useCallback)(e=>{switch("message_update"!==e.type&&ni(),e.type){case"connected":{let t=td.current;t&&tX(t),_({type:!0===e.isStreaming?"resume":"end"}),!0===e.isStreaming&&(t3(),tm.current=!0,tp.current=!0,V(!0),eG({kind:"waiting_model"}));break}case"agent_start":t3(),tm.current=!0,tp.current=!0,V(!0),eG({kind:"waiting_model"}),_({type:"start"});break;case"agent_end":if(!tp.current)break;eG(null),eN(null),_({type:"end"}),td.current&&(tX(td.current),fetch(`/api/agent/${encodeURIComponent(td.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&eI(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eT(e.state.systemPrompt??null),tn(iC(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=tm.current;if(tm.current=!1,!e||tg.current)break;let t=td.current,n=nl();e_(!1),t&&(tX(t),na(t)),n&&o?.();break}case"prompt_done":{let e=tR.current,t=tg.current;tg.current=!1,tA.current=null;let n=no(e);if(!t&&!n)break;let r=td.current;r&&tX(r),!tm.current&&(nl(),r&&na(r))}break;case"prompt_error":nn({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":nn({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tp.current||iu(e))break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(_({type:"snapshot",message:t}),t.content.length>0&&eG(null)):t&&eG(null)}else{let t=e.assistantMessageEvent;t&&(ns(t),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eG(null))}break;case"message_end":{if(!tp.current||iu(e))break;let t=e.message;if(t&&"user"===t.role){let e=r5(t),n=ia(e),r=tA.current;tA.current=null,R(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ia(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else if(t){let e=r5(t);if("assistant"===e.role){let t=function(e){if("assistant"!==e.role||"aborted"===e.stopReason||"error"===e.stopReason)return null;let t=e.usage;if(!t)return null;let n=t.totalTokens,r=n&&n>0?n:t.input+t.output+t.cacheRead+t.cacheWrite;return r>0?r:null}(e);null!==t&&eI(e=>{let n=e?.contextWindow??0;return n<=0?e:iN(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 s=t.content[i],l=(s?.type==="thinking"?s.startedAt:void 0)??e.startedAt??t.timestamp,o=(s?.type==="thinking"?s.endedAt:void 0)??e.endedAt??n;return e.startedAt===l&&e.endedAt===o?e:(r=!0,{...e,..."number"==typeof l?{startedAt:l}:{},..."number"==typeof o?{endedAt:o}:{}})});return r?{...e,content:i}:e}({...e,completedAt:n},q.current.streamingMessage,n);R(e=>[...e,r])}else"system"!==e.role&&R(t=>[...t,e])}_({type:"end"}),eG({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;eG(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":{let t=e.toolCallId,n=e.toolName,r=e.partialResult,i=r?.content;("bash"===n||"powershell"===n)&&Array.isArray(i)&&z(e=>{let s=new Map(e);return s.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),s}),eG(e=>{let r=e?.kind==="running_tools"?e.tools:[],i=r.find(e=>e.id===t),s=n||i?.name||"tool";return i?.name===s?e:{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),{id:t,name:s}]}});break}case"tool_execution_end":{let t=e.toolCallId;z(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),eG(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"queue_update":tn({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":eN({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eN(null);break;case"auto_compaction_start":case"compaction_start":e_(!0),eJ(null),eZ(null);break;case"auto_compaction_end":case"compaction_end":e_(!1),e.errorMessage?(eJ(e.errorMessage),eZ(null)):!e.aborted&&(eZ(iL(e.result,e.reason??"auto")),td.current&&tX(td.current));break;case"extension_ui_request":nr(e);break;case"extension_ui_closed":e7(t=>t?.id===e.id?null:t)}},[nn,t3,ni,nr,tX,no,o,ns,na,nl]);let nm=(0,i.useCallback)(async(e,n)=>{let r=e.trim();if(!r&&!n?.length)return;if(tp.current||tx.current)return void tY(e,n,tV);let i=!n?.length&&r.startsWith("/");if(!n?.length&&r.startsWith("!")){let t=r.startsWith("!!"),i=(t?r.slice(2):r.slice(1)).trim();return i?void await tE.current?.(i,t):void tY(e,n,tV)}let l=tR.current+1;t3(),tg.current=!0;let o=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:o?.length?[...e.trim()?[{type:"text",text:e}]:[],...o]:e,timestamp:Date.now()};R(e=>[...e,a]),tA.current=ia(a),tR.current=l,tp.current=!0,V(!0),eG(i?{kind:"running_command"}:{kind:"waiting_model"}),_({type:"start"}),tk.current=!0,tz.current={runId:l,message:e,images:n,userMsg:a};let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=!1;tW.current.begin(l);let u=async e=>{try{await ie(e,{type:"abort"})}catch(e){nn({type:"error",message:e instanceof Error?e.message:String(e)})}},h=await iy({gate:tW.current,runId:l,currentRunId:()=>tR.current,currentSessionId:()=>td.current,promptPending:()=>tg.current,abandonUnsent:()=>{tz.current?.runId===l&&(tz.current=null,tg.current=!1,R(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tY(e,n,tV),tA.current=null,tR.current===l&&(tp.current=!1,V(!1),eG(null),_({type:"end"})))},onDispatched:()=>{tz.current?.runId===l&&(tz.current=null)},abort:u,prepare:async()=>{if(v&&s){let e=td.current??await tM.current;if(tW.current.isCancelled(l))return null;let t=e??await t2();if(tW.current.isCancelled(l))return null;if(!t)throw Error("Unable to create a session for the prompt");if(ex&&(eD(ex),e)){let e=await ie(t,{type:"set_model",provider:ex.provider,modelId:ex.modelId});if(e?.thinkingLevel&&"off"!==e.thinkingLevel&&eS(e.thinkingLevel),tW.current.isCancelled(l))return null}return(await t5(t),tW.current.isCancelled(l))?null:t}if(t)return(await t5(t.id),tW.current.isCancelled(l))?null:t.id;throw Error("No active session for the prompt")},send:async t=>{let n=await ie(t,{type:"prompt",message:e,...d?.length?{images:d}:{}});c=n?.subagentAction==="steered"||n?.subagentAction==="resumed"}});if("abandoned"!==h.status&&"aborted"!==h.status&&"stale"!==h.status){if("cancelled_after_dispatch"===h.status)return void nc(h.sessionId,l);if("failed"===h.status){let t=h.error,r=h.sessionId,i=h.requestStarted;return(console.error("Failed to send message:",t),!(!i||r9(t))&&r)?void nc(r,l):(tg.current=!1,tz.current?.runId===l&&(tz.current=null),R(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),nn({type:"error",message:t instanceof Error?t.message:String(t)}),tY(e,n,tV),tA.current=null,r)?void nh(r):(tp.current=!1,t6(),V(!1),eG(null),void _({type:"end"}))}if(v&&s&&t0(1,e),c&&h.sessionId){tg.current=!1,nc(h.sessionId,l);return}i&&h.sessionId&&nc(h.sessionId,l)}},[v,s,ex,t,t2,t5,t0,nc,nn,t3,t6,tV,nh,tY]),ng=(0,i.useCallback)(async(e,n)=>{if(tp.current||tx.current||ee.current)throw Error("Cannot generate an image while the session is busy");let r=crypto.randomUUID();ee.current=!0,et.current=r,en.current=!1,Q(!0);try{let i=t?.id??(v&&s?await t2():null);if(!i)throw Error("No active session for image generation");if(en.current)throw new DOMException("Image generation cancelled","AbortError");let l=await ie(i,{type:"generate_image_direct",requestId:r,arguments:e,...n?{sourceImage:n}:{}});return await tX(i),v&&s&&t0(1,e.prompt),l}finally{et.current===r&&(ee.current=!1,et.current=null,en.current=!1,Q(!1))}},[t2,v,tX,s,t0,t?.id]),nf=(0,i.useCallback)(async()=>{en.current=!0;let e=td.current,t=et.current;e&&t&&await ie(e,{type:"abort_image_generation",requestId:t})},[]);tE.current=(0,i.useCallback)(async(e,n)=>{if(tp.current||tx.current)return;let r=`${n?"!!":"!"}${e}`;tP.current=!1,tx.current=!0,X({command:e,excludeFromContext:n}),Y(!0);try{let i=await ib({abortRequested:()=>tP.current,prepare:async()=>td.current??t?.id??await t2(),send:async t=>{await ie(t,{type:"bash",command:e,excludeFromContext:n})},loadResults:async e=>{td.current===e&&await tX(e)},restoreUnsent:()=>tY(r,void 0,tV)});("completed"===i.status||"cancelled_after_dispatch"===i.status)&&t0(1,r)}catch(e){console.error("Failed to execute shell command:",e),nn({type:"error",message:e instanceof Error?e.message:String(e)}),tY(r,void 0,tV)}finally{tx.current=!1,X(null),Y(!1)}},[nn,tV,t2,tX,t0,tY,t]);let nx=(0,i.useCallback)(async()=>{var e;let n=tR.current,r=td.current,i=async e=>{if(r&&!tv.current){tv.current=!0;try{await ie(r,{type:e})}catch(e){console.error("Failed to abort:",e),nn({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tv.current=!1}}};if(tx.current){tP.current=!0,await i("abort_bash");return}let s=tz.current;(tW.current.isInFlight(n)||s?.runId===n)&&tW.current.cancel(n);let l=!!(s&&s.runId===n&&tW.current.shouldAbandonUnsent(n));if(l&&s){tz.current=null,tg.current=!1,R(e=>{let t=e.lastIndexOf(s.userMsg);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tY(s.message,s.images,tV),tA.current=null,tp.current=!1,V(!1),eG(null),_({type:"end"});return}let o=(e={bashRunning:!1,hasSessionId:!!r,localUnsent:l,agentRunning:tp.current||tg.current}).bashRunning?e.hasSessionId?"abort_bash":"none":!e.agentRunning||e.localUnsent?"none":e.hasSessionId?"abort":"none";t?.relation?.kind==="subagent"&&"queued"===t.relation.status&&r?await i("abort"):"none"!==o&&r&&await i("abort_bash"===o?"abort_bash":"abort")},[nn,tV,tY,t]),nv=(0,i.useCallback)(async e=>{if(tx.current)return;let t=td.current;if(t){e$(e);try{let{cancelled:n,newSessionId:r}=await ie(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e)}finally{e$(null)}}},[c]),ny=(0,i.useCallback)(async e=>{if(tx.current)return;let t=td.current;t&&(ie(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),L(e),await tG(t,e))},[tG]),nb=(0,i.useCallback)(async e=>{if(tx.current)return;L(e);let t=td.current;t&&(await tG(t,e),e&&ie(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tG]),nw=(0,i.useCallback)(async(e,t)=>{if(v){let n={provider:e,modelId:t};tL.current=n,ev(n),eD(n);let r=td.current??await tM.current;if(!r){let n=eg[`${e}/${t}`];n&&null===t$.current?eS(n):eS(function(e,t){if(!e?.length||e.includes(t)||"auto"===t)return t;let n=it.indexOf(t);if(-1===n)return e[0];for(let t=n+1;t<it.length;t++)if(e.includes(it[t]))return it[t];for(let t=n-1;t>=0;t--)if(e.includes(it[t]))return it[t];return e[0]}(eu[`${e}:${t}`],ej));return}try{let n=await ie(r,{type:"set_model",provider:e,modelId:t});n?.thinkingLevel&&"off"!==n.thinkingLevel&&eS(n.thinkingLevel)}catch(e){console.error("Failed to set model:",e)}return}let n=td.current;if(n&&!tD.current){tD.current=!0,eW({provider:e,modelId:t}),eB(!0);try{await ie(n,{type:"set_model",provider:e,modelId:t}),tD.current=!1,await tX(n)}catch(e){console.error("Failed to set model:",e),tD.current=!1,eW(eR),nn({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await tX(n)}finally{tD.current=!1,eB(!1)}}},[nn,eR,v,tX,eg,eu,ev,ej]),nk=(0,i.useCallback)(async()=>{let e=td.current;if(e&&!eU){e_(!0),eJ(null),eZ(null);try{let t=await ie(e,{type:"compact"});eZ(iL(t,"manual")),await tX(e,!0)}catch(e){eJ(e instanceof Error?e.message:String(e)),eZ(null)}finally{e_(!1)}}},[eU,tX]),nj=(0,i.useCallback)(async(e,t=!1,n)=>{let r;try{r=await function(e,t,n={}){let r=ik.get(e);if(!n.force&&r&&r.loadedAt+6e4>Date.now())return Promise.resolve(r.data);let i=ij.get(e);if(i&&(!n.force||i.forced&&i.refreshToken===n.refreshToken))return i.promise;let s=(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(ik.delete(e),ik.set(e,{data:t,loadedAt:Date.now()});ik.size>32;){let e=ik.keys().next().value;if(void 0===e)break;ik.delete(e)}return t}).finally(()=>{ij.get(e)?.promise===s&&ij.delete(e)});return ij.set(e,{promise:s,forced:!0===n.force,...void 0!==n.refreshToken?{refreshToken:n.refreshToken}:{}}),s}(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??{}),em(r.thinkingLevelMaps??{}),ef(r.thinkingLevelPins??{}),el(r.modelList??[]),v&&!td.current){let e=i$(r);eb(e);let t=e&&r.thinkingLevelPins?.[`${e.provider}/${e.modelId}`];null===t$.current&&eS(t??"auto")}},[v,b]),nS=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),s=td.current??await t2(),l=e=>(e.handled&&(e.error?nn({type:"error",message:e.error}):"openSessionStats"!==e.action&&nn({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!s||eU)return l({handled:!0,error:"No active session to compact"});e_(!0),eJ(null),eZ(null);let e=await ie(s,{type:"compact",...i?{customInstructions:i}:{}});return eZ(iL(e,"manual")),await tX(s,!0)&&t0(),l({handled:!0,message:"Compacted context"})}case"reload":if(!s)return l({handled:!0,error:"No active session to reload"});return await ie(s,{type:"reload"}),await Promise.all([tX(s,!1,!0),tQ(s),t8(),nj(void 0,!0)]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!s)return l({handled:!0,error:"No active session to name"});if(!i)return l({handled:!0,error:"Usage: /name <name>"});return await ie(s,{type:"set_session_name",name:i}),await tX(s)&&t0(),l({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!s)return l({handled:!0,error:"No active session"});let e=await ie(s,{type:"get_session_stats"});return e&&e6(e),f?.(),l({handled:!0,action:"openSessionStats"})}case"copy":{if(!s)return l({handled:!0,error:"No active session"});let e=await ie(s,{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(!s)return l({handled:!0,error:"No active session"});let e=await ie(s,{type:"get_state"}),t=!("boolean"!=typeof e?.autoCompactionEnabled||e.autoCompactionEnabled);return await ie(s,{type:"set_auto_compaction",enabled:t}),eK(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"clone":{if(!s)return l({handled:!0,error:"No active session to clone"});if(tp.current||tx.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=await ie(s,{type:"clone",leafId:T});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(!s)return l({handled:!0,error:"No active session to report"});if(tp.current||tx.current)return l({handled:!0,error:"Cannot report a bug while the session is running"});let e=await ie(s,{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&&e_(!1)}},[T,nn,t2,eU,nj,tX,t8,tQ,t0,c,f]),nC=(0,i.useCallback)(async(e,t,n)=>{let r=td.current;if(!r){tY(e,n,tV),nn({type:"error",message:"No active session for the queued message"});return}let i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await ie(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),r9(t)&&tY(e,n,tV),nn({type:"error",message:t instanceof Error?t.message:String(t)})}},[nn,tV,tY]),nN=(0,i.useCallback)(async(e,t)=>{await nC(e,"steer",t)},[nC]),nE=(0,i.useCallback)(async(e,t,n)=>{await nC(e,t,n)},[nC]),nI=(0,i.useCallback)(async(e,t)=>{await nC(e,"followUp",t)},[nC]),nM=(0,i.useCallback)(async()=>{let e=td.current;if(e)try{await ie(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nT=(0,i.useCallback)(async()=>{let e=td.current;if(e)try{let t=await ie(e,{type:"clear_queue"});tn({steering:[],followUp:[]});let n=[...iw(t?.steering),...iw(t?.followUp)];if(0===n.length)return;tY(n.map(e=>e.text).filter(Boolean).join("\n\n"),n.flatMap(e=>e.images).map(e=>({...e,previewUrl:""})),tV)}catch(e){console.error("Failed to recall queued messages:",e),nn({type:"error",message:e instanceof Error?e.message:"Failed to recall queued messages"})}},[nn,tV,tY]),nL=(0,i.useCallback)(async e=>{if(eS(e),v&&!td.current&&(t$.current="auto"===e?null:e),"auto"===e)return;let t=td.current??await tM.current;if(t)try{await ie(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[v]),n$=(0,i.useCallback)(async e=>{let t=(0,ti.xG)(e);!function(e,t=ii()){if(t)try{t.setItem(ir,e)}catch{}}(e),tO(e);let n=td.current??await tM.current;if(!n){ta.current=void 0!==t;return}try{let e=await ie(n,{type:"set_tools",...void 0!==t?{toolNames:t}:{}});ta.current=void 0!==t;let r=e?.sessionId??n,i=e?.recreated===!0;r!==n&&(t3(),t6(),td.current=r),e0([]),th.current&&(i||r!==n)&&t9(r);let[s]=await Promise.all([ie(r,{type:"get_state"}),tQ(r)]);tH.current&&td.current===r&&eT(s.systemPrompt??"")}catch(e){console.error("Failed to set tools:",e)}},[t3,t6,tQ,t9,tO]),nR=(0,i.useCallback)((e,t=16)=>{let n=tI.current;n&&(tw.current=!0,tk.current=!1,tj.current=!1,n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tS.current=n.scrollTop)},[]),nW=(0,i.useCallback)(()=>{let e=tI.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tp.current,s=tj.current,l=function(e,t,n,r,i,s=96){return!!np(n,r,i)||!(n<t)&&(!!(!e&&n>t&&np(n,r,i,s))||e)}(s,tS.current,t,n,r,i?96:8);tj.current=l,tS.current=t,!s&&l&&i&&t_("instant")}},[t_]);(0,i.useEffect)(()=>(tH.current=!0,t&&(td.current=t.id,tX(t.id,!0,!0).then(e=>{e?.running&&(tQ(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(tm.current=!!e.state.isStreaming,tg.current=!!e.state.isPromptRunning,tp.current=!0,V(!0),eG(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),_({type:"resume"}),t7(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nc(t.id)),e.state?.isBashRunning&&(tx.current=!0,Y(!0),nu(t.id))),e?.state&&(void 0!==e.state.isCompacting&&e_(e.state.isCompacting),"boolean"==typeof e.state.autoCompactionEnabled&&eK(e.state.autoCompactionEnabled),void 0!==e.state.contextUsage&&eI(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eT(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&eS(e.state.thinkingLevel??"auto"),void 0!==e.state.queuedMessages&&tn(iC(e.state.queuedMessages)))})),()=>{tH.current=!1,null!==tC.current&&cancelAnimationFrame(tC.current),tC.current=null,tN.current=[],ty.current+=1,t3(),t6()}),[]),(0,i.useEffect)(()=>{p?.(eM)},[eM,p]),(0,i.useEffect)(()=>(g?.(t4),()=>g?.(null)),[t4,g]),(0,i.useEffect)(()=>{h&&h(S?.tree??[],T,nb)},[S?.tree,T,nb,h]),(0,i.useEffect)(()=>{let e=tI.current;if(e)return tS.current=e.scrollTop,e.addEventListener("scroll",nW,{passive:!0}),()=>{e.removeEventListener("scroll",nW)}},[$.length,N,nW]),(0,i.useLayoutEffect)(()=>{$.length>0&&(tk.current?(tk.current=!1,tw.current=!0,t_("instant")):tw.current?tj.current&&t_("instant"):(tw.current=!0,t_("instant")))},[$.length,K,t_,U.streamingMessage]),(0,i.useEffect)(()=>{let e=new AbortController,t=tF.current!==u;return tF.current=u,(async()=>{for(let n=0;;n++)try{await nj(e.signal,t,u);return}catch(t){if(e.signal.aborted||t instanceof DOMException&&"AbortError"===t.name||n>=iE.length||(await iI(iE[n]),e.signal.aborted))return}})(),()=>e.abort()},[nj,u]),(0,i.useEffect)(()=>{if(!eY)return;let e=setTimeout(()=>eZ(null),6e3);return()=>clearTimeout(e)},[eY]);let[nz,nP]=(0,i.useState)(null),nA=(0,i.useRef)(5e3),nD=(0,i.useRef)(null),nF=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===e4.visible.length){nF.current=null;return}let e=e4.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e8({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=e4.visible[0];if(!t||(nF.current!==t.id&&(nF.current=t.id,nA.current=5e3),e4.visible.some(e=>e.id===nz)))return;nD.current=Date.now();let n=setTimeout(()=>{e8({type:"mark_oldest_exiting"})},nA.current);return()=>{clearTimeout(n),null!==nD.current&&(nA.current=Math.max(0,nA.current-(Date.now()-nD.current)),nD.current=null)}},[e4.visible,nz]),(0,i.useEffect)(()=>{e6(null)},[$.length,eE?.tokens,eE?.percent,eE?.contextWindow]),{data:S,loading:N,error:I,activeLeafId:T,messages:$,activeToolResults:W,entryIds:P,historyCursor:D,hasEarlierMessages:B,streamState:U,agentRunning:K,directImageRunning:G,modelNames:er,modelList:es,modelError:eo,modelScopeWarnings:ed,modelThinkingLevels:eu,modelThinkingLevelMaps:ep,newSessionModel:ex,toolPreset:ew,thinkingLevel:ej,retryInfo:eC,contextUsage:eE,systemPrompt:eM,forkingEntryId:eL,isCompacting:eU,autoCompactionEnabled:eq,compactError:eV,compactResult:eY,currentModel:tq,displayModel:tK,modelSwitching:eF,sessionStats:tZ,slashCommands:eQ,slashCommandsLoading:e1,queuedMessages:tt,notices:e4.visible,extensionDialog:e5,extensionCustomUi:e9,respondToExtensionUi:ne,sendExtensionCustomInput:nt,isAutoModelSelection:v&&null===ex,agentPhase:eX,isNew:v,sessionIdRef:td,scrollContainerRef:tI,initialScrollDoneRef:tw,handleSend:nm,handleDirectImageGeneration:ng,abortDirectImageGeneration:nf,handleAbort:nx,handleFork:nv,handleNavigate:ny,handleModelChange:nw,handleCompact:nk,handleSteer:nN,handleFollowUp:nI,handlePromptWithStreamingBehavior:nE,handleAbortCompaction:nM,handleRecallQueue:nT,handleBuiltinSlashCommand:nS,addNotice:nn,setNoticePaused:nP,handleToolPresetChange:n$,handleThinkingLevelChange:nL,loadTools:tQ,loadSlashCommands:t8,setActiveLeafId:L,setData:C,setMessages:R,loadContext:tG,scrollToBottom:t_,scrollToMessage:nR,dispatch:_,setAgentRunning:V,setForkingEntryId:e$,bashRunning:J,pendingBash:Z,handleAgentEventRef:tb}}({session:e,sessionRunning:a,newSessionCwd:d,newSessionDraftKey:c,onAgentEnd:el,onAttentionNeeded:eo,onSessionCreated:S,onSessionForked:ea,modelsRefreshKey:N,chatInputRef:er,onBranchDataChange:$,onSystemPromptChange:R,onSystemToolsChange:W,onSystemInfoLoaderChange:z,onSessionStatsPanelOpen:A,deferInitialScroll:!!ep,isVisiblePane:L}),tM=eT||eL||e$,tT=(0,i.useCallback)(()=>eL?tc():tu(),[tc,eL,tu]),tL=(0,i.useRef)(null),t$=e1?e1.tokens.input+e1.tokens.cacheRead+e1.tokens.cacheWrite:0,tR=e1&&t$>0?e1.tokens.cacheRead/t$*100:null,[tW,tz]=(0,i.useState)(null),tP=ts&&0===ek.length&&!eM.isStreaming&&!tM&&null===tW,[tA,tF]=(0,i.useState)(!1),[tB,tO]=(0,i.useState)(null),[tU,t_]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(void 0),[tY,tZ]=(0,i.useState)(0),[t0,t4]=(0,i.useState)(null),[t8,t3]=(0,i.useState)(!1),[t5,t9]=(0,i.useState)(!1),[ne,nt]=(0,i.useState)(null),nr=(0,i.useRef)(null),ni=(0,i.useRef)(null),ns=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/image-generation",{signal:e.signal}).then(async e=>{let t=await e.json();e.ok&&t.available&&t.config?.connections.length?tO(t.config):(tO(null),t_(!1),tK(null))}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load image generation config:",e)}),()=>e.abort()},[tY,N]);let no=(0,i.useCallback)(async(t,n)=>{ec();let r=null;for(let e=ek.length-1;e>=0;e--){let t=ew(ek[e].details);if(t){r=t;break}}let i=e?.cwd??d,s=t.target,l=s&&(s.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(s)?s:i?E(i,s):s);tz({prompt:t.prompt,size:t.size,width:n?void 0:r?.width,height:n?void 0:r?.height,previewUrl:n?`data:${n.mimeType};base64,${n.data}`:l?`/api/files/${j(l)}?type=read`:void 0});try{await td(t,n),n&&er.current?.removeAttachedImage(n.data)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return;te({type:"error",message:e instanceof Error?e.message:String(e)})}finally{tz(null)}},[te,td,ec,ek,d,e?.cwd]),na=(0,i.useCallback)(async e=>{let t=await tw(e);return!("error"in t)&&/^\/reload(?:\s|$)/.test(e.trim())&&tZ(e=>e+1),t},[tw]),ny=(0,i.useCallback)(()=>{t4(null),t3(!1),nt(null)},[]);(0,i.useEffect)(()=>{O||ny()},[O,ny]);let nb=(0,i.useCallback)(e=>{let t=ns.current;if(t&&!(null!=e&&Math.hypot(e.clientX-t.x,e.clientY-t.y)>4)||!O||t8)return;let n=window.getSelection(),r=n?.rangeCount?n.getRangeAt(0):null,i=n$.current;if(!n||n.isCollapsed||!r||!i||!i.contains(r.commonAncestorContainer))return void t4(null);let s=n.toString().trim();if(!s)return void t4(null);let l=r.getBoundingClientRect(),o=[r.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?r.commonAncestorContainer:r.commonAncestorContainer.parentElement,r.startContainer.nodeType===Node.ELEMENT_NODE?r.startContainer:r.startContainer.parentElement,r.endContainer.nodeType===Node.ELEMENT_NODE?r.endContainer:r.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);t4({text:s,top:Math.min(window.innerHeight-44,l.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,l.left+l.width/2)),sourceEntryId:o})},[O,t8]);(0,i.useEffect)(()=>{t8&&t0&&ni.current?.insertIfEmpty(nu(t0.text,X("chat.quoteIntro"),X("chat.quoteQuestion")))},[t8,t0,X]),(0,i.useLayoutEffect)(()=>{let e=nr.current;if(!e||!t0)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(t0.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(t0.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)}},[t0,t8,ne]),(0,i.useEffect)(()=>{if(!t0)return;let e=e=>{if(t8||nr.current?.contains(e.target))return;ns.current={x:e.clientX,y:e.clientY};let t=()=>{document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),queueMicrotask(()=>{ns.current=null})};document.addEventListener("pointerup",t),document.addEventListener("pointercancel",t),ny()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),t5||ny())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[t0,t8,t5,ny]);let nw=(0,i.useCallback)(()=>{t0&&(er.current?.insertText(nu(t0.text,X("chat.quoteIntro"),X("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),ny())},[t0,ny,X]),nk=(0,i.useCallback)(async t=>{let n=tl.current??e?.id;if(!t5&&t.trim()&&t0?.sourceEntryId&&n&&H){t9(!0),nt(null),J?.();try{await H(t,n,t0.sourceEntryId),ny()}catch(e){ni.current?.restoreSubmission(t),nt(e instanceof Error?e.message:String(e))}finally{t9(!1)}}},[H,t0,t5,e?.id,tl,ny,J]),nj=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(ey||eb||!U||nj.current)return;let t=tl.current??e?.id;t&&(nj.current=!0,_?.(t),ec(),ta(U))},[U,ey,eb,ta,_,ec,e?.id,tl]),(0,i.useEffect)(()=>{Q&&e6&&es.current!==e6.id&&(es.current=e6.id,ee.current())},[Q,e6]);let[nS,nC]=(0,i.useState)(0),[nN,nE]=(0,i.useState)(50),nI=(0,i.useRef)(null),nM=(0,i.useRef)(null),nT=(0,i.useRef)({startIndex:0,endIndex:0,totalCount:0}),nL=(0,i.useRef)(null),n$=(0,i.useRef)(null),nR=(0,i.useRef)(null),nW=(0,i.useRef)(!1),nz=(0,i.useRef)(null),[nP,nA]=(0,i.useState)(null),nD=(0,i.useRef)(!1),nF=(0,i.useRef)(tN),nB=(0,i.useRef)(ep);nB.current=ep;let[nH,nO]=(0,i.useState)(null),nU=ek[eS.indexOf(nH?.entryId??"")],n_=nU?.role==="assistant"?nH?.blockIndex===void 0?nU.content.find(e=>"text"===e.type):nU.content[nH.blockIndex]:void 0,nq=(0,i.useRef)({entryIds:eS,historyCursor:eC,hasEarlierMessages:eN});nq.current={entryIds:eS,historyCursor:eC,hasEarlierMessages:eN},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=to.current,r=n$.current;if(t&&o&&n&&r)return()=>{if(nB.current)return;if(np(n.scrollTop,n.clientHeight,n.scrollHeight))return void o(t,{atBottom:!0});let e=n.getBoundingClientRect().top,i=iW(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&&o(t,{atBottom:!1,...i,oldestEntryId:nq.current.historyCursor})}},[ey,o,to,e?.id]),(0,i.useEffect)(()=>{t&&eg(null)},[t]);let nK=(0,i.useCallback)(async(e,t,n)=>{do await new Promise(e=>requestAnimationFrame(()=>e())),n.throwIfAborted();while(nW.current);nW.current=!0;try{let r=nq.current;await nx(e,{entryIds:r.entryIds,oldestEntryId:r.historyCursor,hasMore:r.hasEarlierMessages},e=>tC(t,tN,e,{signal:n}),n)}finally{nW.current=!1}},[tN,tC]),nV=(0,i.useRef)(nK);nV.current=nK;let nJ=(0,i.useCallback)(()=>{let e=nT.current;nC(e.totalCount-e.endIndex),nE(50)},[]);(0,i.useEffect)(()=>{let n=e?.id;if(!ep||!n||ey||t||nD.current)return;nD.current=!0,nz.current?.abort();let r=new AbortController;nz.current=r,nA(null),nO(null);let i=()=>{ex(!1),eg(null)};return(async()=>{try{if(await nV.current(ep.anchorEntryId,n,r.signal),r.signal.aborted)return void i();ex(!0)}catch(e){if(nv(e,r.signal))return void i();tE("instant"),eg(null)}})(),()=>{r.abort(),nz.current===r&&(nz.current=null),eg(null),ex(!1)}},[ey,ep,tE,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=n$.current;if(!ep||!e||t)return;let n=e.querySelector(`[data-entry-id="${CSS.escape(ep.anchorEntryId)}"]`);if(n){nJ(),tI(n,ep.anchorOffset),eg(null);return}ef&&(tE("instant"),eg(null))},[eS,nJ,ep,ef,tE,tI,t,nN,nS]),(0,i.useEffect)(()=>{if(!t||ey)return;nz.current?.abort();let e=new AbortController;nz.current=e,nA(null),nO(null);let n=t.sessionId;return(async()=>{try{if(await nV.current(t.entryId,n,e.signal),e.signal.aborted)return;nR.current=null,nO(t)}catch(n){if(nv(n,e.signal))return;te({type:"warning",message:"other_branch"===(n instanceof nm&&"exhausted"===n.reason?function(e,t,n){if(!t||!n)return"not_found";let r=nf(t,n);return!r||r.some(t=>ng(t,e))?"not_found":nf(t,e)?"other_branch":"not_found"}(t.entryId,ev?.tree,tN):"not_found")?X("chat.locateOtherBranch"):n instanceof nm&&"stalled"===n.reason?X("chat.locateHistoryStalled"):n instanceof nm&&"load_failed"===n.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")}),s?.(t)}})(),()=>{e.abort(),nz.current===e&&(nz.current=null)}},[tN,te,ev?.tree,ey,s,t,X]),(0,i.useLayoutEffect)(()=>{var e;let n=nH?`[data-entry-id="${CSS.escape(nH.entryId)}"]`:null,r=n?to.current?.querySelector(nU?.role==="user"?n:`${n} [data-search-target]`)??to.current?.querySelector(n):null,i=(e={pending:nH??null,searchTarget:t??null,elementFound:!!r}).pending?e.pending!==e.searchTarget?"clear-stale":e.elementFound?"commit":"retry":"ignore";"ignore"===i||"retry"===i||("clear-stale"===i?nO(null):r&&nH&&(nJ(),tI(r),r.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500}),nO(null),s?.(nH)))},[eS,nJ,ek.length,nN,nH,t,nU,to,tI,s,nS]),(0,i.useEffect)(()=>{nC(0),nE(50)},[e?.id]),(0,i.useEffect)(()=>{let e=to.current;e&&(tM||eM.isStreaming)&&np(e.scrollTop,e.clientHeight,e.scrollHeight)&&nC(0)},[tM,eM.isStreaming,to]),(0,i.useEffect)(()=>{let e=to.current;if(!e)return void tF(!1);let t=()=>{let t=e.scrollHeight-e.scrollTop-e.clientHeight;tF(nS>0||t>160)},n=()=>{t(),nz.current||nS>0||np(e.scrollTop,e.clientHeight,e.scrollHeight)&&(nC(0),nE(50))};t();let r=new ResizeObserver(t);return r.observe(e),n$.current&&r.observe(n$.current),e.addEventListener("scroll",n,{passive:!0}),()=>{r.disconnect(),e.removeEventListener("scroll",n)}},[tP,ey,to,e?.id,nS]);let nY=(0,i.useCallback)(()=>{if(nW.current||nz.current)return;let t=to.current;if(nT.current.startIndex>0){let e=n$.current;if(e&&t){let n=t.getBoundingClientRect().top;nL.current=iW(Array.from(e.children).flatMap((e,t)=>{if(!(e instanceof HTMLElement))return[];let n=e.dataset.entryId||e.dataset.slotIndex||`slot-${t}`,r=e.getBoundingClientRect();return[{entryId:n,top:r.top,bottom:r.bottom}]}),n)}nC(e=>e+25),nE(50);return}if(!eN||!eC)return;let n=e?.id??tl.current;n&&(nW.current=!0,t&&(nR.current=t.scrollHeight-t.scrollTop),tC(n,tN,eC).finally(()=>{nW.current=!1}))},[eC,eN,e,tN,tC,tl,to]);(0,i.useEffect)(()=>{let e=nI.current,t=to.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nY()},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nY,to]),(0,i.useEffect)(()=>{let e=nM.current,t=to.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&!nz.current&&nC(e=>Math.max(0,e-25))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nS,to]),(0,i.useLayoutEffect)(()=>{let e=nL.current,t=n$.current;if(!e||!t)return;let n=Array.from(t.children).find((t,n)=>t instanceof HTMLElement&&(t.dataset.entryId||t.dataset.slotIndex||`slot-${n}`)===e.anchorEntryId);n instanceof HTMLElement&&tI(n,e.anchorOffset),nL.current=null},[nS,tI]),(0,i.useEffect)(()=>{if(null==nR.current)return;let e=to.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nR.current),nR.current=null}},[ek.length,to]);let nZ=e1?[e1.sessionId,e1.sessionFile??"",e1.sessionName??"",e1.userMessages,e1.assistantMessages,e1.toolCalls,e1.toolResults,e1.totalMessages,e1.tokens.input,e1.tokens.output,e1.tokens.cacheRead,e1.tokens.cacheWrite,e1.tokens.total,e1.cost??0,e1.totalActiveMs??0,e1.contextUsage?.percent??"null",e1.contextUsage?.contextWindow??"",e1.contextUsage?.tokens??"null"].join("|"):null,nX=(0,i.useRef)(e1);nX.current=e1,(0,i.useEffect)(()=>{ey||P?.(nX.current)},[ey,nZ,P]),(0,i.useEffect)(()=>()=>{P?.(null)},[P]);let nG=eV?`${eV.percent??"null"}|${eV.contextWindow}|${eV.tokens??"null"}`:null,nQ=(0,i.useRef)(eV);nQ.current=eV,(0,i.useEffect)(()=>{ey||D?.(nQ.current)},[nG,ey,D]),(0,i.useEffect)(()=>()=>{D?.(null)},[D]);let{isDragOver:n0,handleDragEnter:n1,handleDragOver:n2,handleDragLeave:n4,handleDrop:n8}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),s=(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:s,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)},[])),n3=e?.cwd??d??void 0,n6=(0,i.useMemo)(()=>ek.filter(e=>tQ(e)||"assistant"===e.role||"toolResult"===e.role&&!e.isError&&ew(e.details)),[ek]),n5=(0,i.useMemo)(()=>{let e=new Map(ej);for(let t of ek)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ej,ek]),n7=(0,i.useMemo)(()=>new Set(tr?.kind==="running_tools"?tr.tools.map(e=>e.id):[]),[tr]),n9=(0,i.useMemo)(()=>ek.map(e=>"assistant"===e.role?t7(e):null),[ek]),re=(0,i.useMemo)(()=>{let e=new Map;for(let t=0;t<ek.length;){let n=tQ(ek[t])?t:-1,r=n>=0?t+1:t;for(;r<ek.length&&!tQ(ek[r]);)r+=1;let i=iA(ek,n,r);if(i>=0&&n9[i]?.answerMessage){let t=[];for(let e=n+1;e<=i;e+=1){let n=ek[e];n?.role==="assistant"&&t.push(...n.content)}e.set(i,function(e,t,n){let r=new Set,i=[];for(let s of e){if("toolCall"!==s.type||!function(e){let t;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||nd(e)||nc(e)}(s.toolName))continue;let e=t?.get(s.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=nn(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):[]}(s.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,s=i(e),l=t?i(t).replace(/\/+$/,""):void 0,o=/^[a-zA-Z]:\//.test(s),a=s.startsWith("//");if(o||a)n=s;else if(s.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${s}`:s}else{if(!l)return null;n=`${l}/${s}`}return nl(n)}(e,n);t&&(r.has(t)||(r.add(t),i.push({filePath:t})))}}return i}(t,n5,n3))}t=r}return e},[n9,n3,ek,n5]),rt=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ek.length-1;n>=0;n-=1){let r=function(e){if("user"!==e.role)return null;if("string"==typeof e.content){let t=e.content.trim();return t.length>0?t:null}let t=e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim();return t.length>0?t:null}(ek[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ek]),rn=(Y=n6.length,(Z=(0,i.useRef)([])).current=Array(Y).fill(null).map((e,t)=>Z.current[t]??null),Z),rr=(0,i.useMemo)(()=>{for(let e=ek.length-1;e>=0;e--)if(ek[e]?.role==="user")return eS[e]??"";return""},[eS,ek]);(0,i.useEffect)(()=>{let e=nF.current;nF.current=tN,null!==e&&e!==tN&&(nz.current?.abort(),nB.current&&(eg(null),ex(!1)))},[tN]),(0,i.useEffect)(()=>()=>{nz.current?.abort()},[e?.id]);let ri=(0,i.useCallback)(async t=>{let n=e?.id??tl.current;if(!n)return;nz.current?.abort();let r=new AbortController;nz.current=r,nA(null),nO(null);try{nR.current=null,nL.current=null,await nK(t,n,r.signal),r.signal.throwIfAborted(),await new Promise((e,n)=>{r.signal.addEventListener("abort",()=>n(r.signal.reason),{once:!0}),nA({entryId:t,signal:r.signal,resolve:e})})}catch(e){if(nv(e,r.signal))return;te({type:"warning",message:e instanceof nm&&"stalled"===e.reason?X("chat.locateHistoryStalled"):e instanceof nm&&"load_failed"===e.reason?X("chat.locateLoadFailed"):X("chat.locateNotFound")})}finally{nA(e=>e?.signal===r.signal?null:e),nz.current===r&&(nz.current=null)}},[te,nK,e?.id,tl,X]);(0,i.useLayoutEffect)(()=>{if(!nP||nP.signal.aborted)return;let e=n$.current?.querySelector(`[data-entry-id="${CSS.escape(nP.entryId)}"]`);e&&(nJ(),tI(e),nP.resolve())},[nP,eS,nJ,ek.length,nN,nS,tI]);let rs=!!eM.streamingMessage?.content.length,rl=(0,i.useMemo)(()=>{let e=-1;for(let t=ek.length-1;t>=0;t--)if(tQ(ek[t])){e=t;break}let t=e>=0&&tG(ek[e])?e:e+1;for(let e=t;e<ek.length;e++){let t=ek[e];if("custom"===t.role||"assistant"===t.role&&(t1(t).length>0||t2(t)))return!0}return!1},[ek]),ro=eM.streamingMessage?.role==="assistant"?eM.streamingMessage:null,ra=ro?t7(ro,{isStreaming:!0}):{processMessage:null,answerMessage:null},rd=(0,i.useRef)(T);(0,i.useLayoutEffect)(()=>{let e=rd.current;rd.current=T,!e&&T&&tM&&!tA&&tE("instant")},[T,tM,tA,tE]);let rc=eQ?eB[`${eQ.provider}:${eQ.modelId}`]??null:null,ru=eQ?eU[`${eQ.provider}:${eQ.modelId}`]??null:null,rh=(0,i.useCallback)(async(e,t)=>{ec(),nz.current?.abort(),nA(null),nO(null),nC(0),nE(50),await ta(e,t)},[ta,ec]),rp=(0,i.useCallback)(e=>(ec(),th(e)),[th,ec]),rg=(0,i.useCallback)((e,t)=>(ec(),tf(e,t)),[tf,ec]),rf=(0,i.useCallback)((e,t)=>(ec(),tx(e,t)),[tx,ec]),rx=(0,i.useCallback)((e,t,n)=>(ec(),tv(e,t,n)),[tv,ec]),rv=!ts&&ey,ry=e?.relation?.kind==="subagent"&&"queued"===e.relation.status,rb=(0,r.jsx)(tD,{ref:ei,onSend:rh,onOpenImageGeneration:!tB||rv||tM||ry?void 0:e=>{tK(null),tJ(e),tZ(e=>e+1),t_(!0)},onAbort:tT,onSteer:eT?rg:void 0,onFollowUp:eT?rf:void 0,onPromptWithStreamingBehavior:eT?rx:void 0,isStreaming:tM||ry,disabled:ry,model:rv?null:eQ,isAutoModelSelection:!rv&&tn,modelNames:eW,modelList:ez,modelError:rv?null:eD,modelScopeWarnings:rv?[]:eF,onModelChange:rv||ry?void 0:tm,modelSwitching:e0,onCompact:!ry&&(e||ts)?tg:void 0,onAbortCompaction:ty,isCompacting:eY,compactError:eZ,compactResult:eX,contextUsage:rv?null:eV,cacheHitRate:tR,onOpenSessionStats:A,toolPreset:e_,onToolPresetChange:!ry&&(e||ts)?tk:void 0,thinkingLevel:rv?void 0:eq,onThinkingLevelChange:rv||ry?void 0:e||ts?tj:void 0,availableThinkingLevels:rc,thinkingLevelMap:ru,retryInfo:eK,queuedMessages:e8,inputHistory:rt,onRecallQueue:tb,slashCommands:e2,slashCommandsLoading:e4,onLoadSlashCommands:tS,onBuiltinCommand:na,soundEnabled:q,onSoundToggle:K,onAudioUnlock:J,draftKey:e?.id??c??void 0,onDraftChange:u,draftPersistenceWarning:y,cwd:e?.cwd??d});return ey?(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[(0,r.jsx)("div",{className:"relative flex min-h-0 min-w-0 flex-1 items-center justify-center",children:(0,r.jsx)("div",{className:"text-sm text-text-muted",children:X("chat.loadingSession")})}),(0,r.jsx)("div",{className:"relative shrink-0",children:rb})]}):eb?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children: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)"},onDragEnter:n1,onDragOver:n2,onDragLeave:n4,onDrop:n8,children:[n0&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[rgba(37,99,235,0.06)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[rgba(37,99,235,0.5)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"drop-shadow-[0_6px_18px_rgba(37,99,235,0.18)]",children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"rgba(37,99,235,0.08)",stroke:"rgba(37,99,235,0.50)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"rgba(37,99,235,0.16)",stroke:"rgba(37,99,235,0.40)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"rgba(37,99,235,0.22)",stroke:"rgba(37,99,235,0.55)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),(0,r.jsx)("div",{className:"notice-shelf-wrapper",style:{position:"absolute",top:12,left:0,right:0,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(iJ,{notices:e3,floating:!0,onPauseChange:tt})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[tU&&tB&&(0,r.jsx)(tH,{config:tB,edit:tq,initialSourceImage:tV,editPreviewUrl:tq?`/api/files/${j(tq.path.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(tq.path)?tq.path:n3?E(n3,tq.path):tq.path)}?type=read`:void 0,onClose:()=>{t_(!1),tK(null)},onSubmit:no}),e6&&(0,r.jsx)(iY,{request:e6,onRespond:e7},e6.id),e5&&(0,r.jsx)(iZ,{request:e5,onInput:e9},e5.id),!tP&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:to,className:"min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",style:{overflowAnchor:"none",overscrollBehaviorY:"contain",visibility:ep?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:n$,onPointerUp:nb,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var n,i;let s=-1;for(let e=ek.length-1;e>=0;e--)if(tQ(ek[e])){s=e;break}let l=new Map,o=0;ek.forEach((e,t)=>{let n=("toolResult"!==e.role||e.isError)&&("custom"!==e.role||e.customType!==em)?null:ew(e.details);(tQ(e)||"assistant"===e.role||n)&&l.set(t,o++)});let a=(t,n={})=>{var i,s;let o,a,d,c=n.messageOverride??ek[t],u="user"===c.role&&t>0&&"assistant"===ek[t-1].role?eS[t-1]:void 0,h=("toolResult"!==c.role||c.isError)&&("custom"!==c.role||c.customType!==em)?null:ew(c.details),p=tQ(c)||"assistant"===c.role||!!h,m=l.get(t),g=n.keyPrefix??"message",f=eS[t]??t,x=h?(0,r.jsx)(eE,{value:h,cwd:n3,onEdit:tB&&!tM&&tB.connections.some(e=>e.id===h.connection&&!0===e.capabilities.editing)?e=>{tK(e),tZ(e=>e+1),t_(!0)}:void 0,onMention:tB?e=>{er.current?.mentionImage(e)}:void 0,showPrompt:"custom"===c.role,createdAt:c.timestamp},`${g}-image-${f}`):(0,r.jsx)(rm,{message:c,modelName:n.isTurnEnd&&"assistant"===c.role?(i=c.provider??"",s=c.model??"",o=i.toLowerCase(),a=s.toLowerCase(),d=Object.entries(eW??{}).flatMap(([e,t])=>{let n=e.indexOf(":");return n>0&&e.slice(0,n).toLowerCase()===o?[{id:e.slice(n+1).toLowerCase(),name:t}]:[]}),d.find(e=>e.id===a)?.name??d.find(e=>a.endsWith(`/${e.id}`))?.name??Object.entries(eW??{}).find(([e])=>e.toLowerCase()===a)?.[1]??(i&&s?`${i}/${s}`:s)):void 0,toolResults:n5,cwd:n3,onOpenFile:ed,onOpenSession:B,entryId:eS[t],searchBlock:eS[t]===nH?.entryId?n_:void 0,onFork:tM||ts?void 0:rp,forking:eJ===eS[t],onNavigate:tM?void 0:tp,prevAssistantEntryId:tM?void 0:u,onEditContent:eu,isTurnEnd:n.isTurnEnd,sessionId:e?.id??tl.current??void 0,writtenFiles:n.writtenFiles,isProcess:n.isProcess,runningToolIds:"assistant"===c.role&&c.content.some(e=>"toolCall"===e.type&&n7.has(e.toolCallId))?n7:void 0},`${g}-view-${f}`);return p?(0,r.jsx)("div",{"data-entry-id":eS[t],"data-slot-index":`msg-${t}`,ref:!1===n.attachRef||void 0===m?void 0:e=>{rn.current[m]=e},children:x},`${g}-${f}`):x},d=(n={outline:nP?{entryId:nP.entryId,aborted:nP.signal.aborted}:null,search:nH?{entryId:nH.entryId,matchesTarget:nH===t}:null,restore:ep?{entryId:ep.anchorEntryId}:null}).outline&&!n.outline.aborted?n.outline.entryId:n.search&&n.search.matchesTarget?n.search.entryId:n.restore?n.restore.entryId:null,c=[],u=-1,h=e=>{var t,n;t=u,n=c.length,u=d&&e.includes(d)?n:t},p=0;for(let e=0;e<ek.length;){let t,n,i,o=tQ(ek[e]),u=tX(ek[e]),m=o?e:-1,g=m>=0&&tG(ek[m]),f=o?e+1:e;for(;f<ek.length&&!tQ(ek[f]);)f+=1;let x=o?m:e,v=g?m:m+1,y=iA(ek,m,f),b=(tM||eM.isStreaming)&&f===ek.length&&m===s;if(b&&(p=f-x),-1===y&&!g){for(let e=x;e<f;e++)h([eS[e]]),c.push(a(e));if(b&&ra.processMessage){h([]);let e=iF(!0,eM.isStreaming,ro,tr,!!ra.answerMessage),t=m>=0&&"number"==typeof ek[m]?.timestamp&&Number.isFinite(ek[m].timestamp)?ek[m].timestamp:ra.processMessage.timestamp,n=iU(t,ra.processMessage.completedAt);c.push((0,r.jsx)("div",{children:(0,r.jsx)(iq,{messageCount:1,toolCallCount:t6(ra.processMessage.content??[]),durationSeconds:n,startTime:t,defaultExpanded:!0,isMobile:G,activeStepSummary:iO(iH(ra.processMessage,tr,X),e,tL,X("chat.thinking")),isStreaming:e,t:X,children:(0,r.jsx)(rm,{message:ra.processMessage,isStreaming:!0,isProcess:!0,toolResults:n5,cwd:n3,onOpenFile:ed,onOpenSession:B},"streaming-process-view")})},`process-group-${eS[x]??x}`))}e=f;continue}u&&(h([eS[m]]),c.push(a(m)));let w=n9[y],k=w?.answerMessage??null,j=y>=0?y:f-1,S=[],C=[],N=[],E=0,I=!1;for(let e=v;e<=j;e++){let r=ek[e];if("number"==typeof r.timestamp&&Number.isFinite(r.timestamp)&&(n=void 0===n?r.timestamp:Math.min(n,r.timestamp),i=void 0===i?r.timestamp:Math.max(i,r.timestamp)),"assistant"===r.role&&"number"==typeof r.completedAt&&Number.isFinite(r.completedAt)&&(i=void 0===i?r.completedAt:Math.max(i,r.completedAt)),"custom"===r.role){t??=l.get(e),I||=!!(d&&d===eS[e]),eS[e]&&C.push(eS[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",isProcess:!0}));continue}if("assistant"!==r.role)continue;let s=n9[e];e!==y&&s?.answerMessage&&N.push({idx:e,message:s.answerMessage});let o=s?.processMessage;if(!o)continue;let c=t1(o),u=!!t2(o);(0!==c.length||u)&&(t??=l.get(e),E+=t6(c),I||=!!(d&&eS[e]===d&&(!n_||nH?.entryId!==d||c.includes(n_))),eS[e]&&C.push(eS[e]),S.push(a(e,{attachRef:!1,keyPrefix:"process",messageOverride:o,isTurnEnd:!1,isProcess:!0})))}b&&ra.processMessage&&(E+=t6(ra.processMessage.content??[]),S.push((0,r.jsx)(rm,{message:ra.processMessage,isStreaming:!0,isProcess:!0,toolResults:n5,cwd:n3,onOpenFile:ed,onOpenSession:B},"streaming-process-view")));let M=!!(k||ra.answerMessage),T=iF(b,eM.isStreaming,ro,tr,M),L=iO(iH(ro,tr,X),T,tL,X("chat.thinking")),$=m>=0&&"number"==typeof ek[m]?.timestamp&&Number.isFinite(ek[m].timestamp)?ek[m].timestamp:n,R=iU($??n,i);S.length>0&&(h(C),c.push((0,r.jsx)("div",{"data-entry-id":eS[v],ref:void 0===t?void 0:e=>{rn.current[t]=e},children:(0,r.jsx)(iq,{messageCount:S.length,toolCallCount:E,durationSeconds:R,startTime:$??n,defaultExpanded:!k&&f===ek.length,reveal:I,isMobile:G,activeStepSummary:L,isStreaming:T,t:X,children:S})},`process-group-${eS[x]??x}`)));for(let e=x;e<=j;e++){let t=ek[e];"toolResult"===t.role&&!t.isError&&ew(t.details)&&(h([eS[e]]),c.push(a(e)))}for(let e of N)h([eS[e.idx]]),c.push(a(e.idx,{keyPrefix:"promoted",messageOverride:e.message}));if(k&&(h([eS[y]]),c.push(a(y,{isTurnEnd:!0,messageOverride:k,writtenFiles:re.get(y)}))),y>=0)for(let e=y+1;e<f;e++)h([eS[e]]),c.push(a(e));e=f}let m=Math.max(nN,50+p),{startIndex:g,endIndex:f}=u>=0?nh(i=c.length,i-Math.max(0,u-5)-50):nh(c.length,nS,m);nT.current={startIndex:g,endIndex:f,totalCount:c.length};let x=g>0||eN;return(0,r.jsxs)(r.Fragment,{children:[x&&(0,r.jsx)("button",{type:"button",ref:nI,onClick:nY,className:"w-full cursor-pointer py-3 text-center text-xs text-text-muted transition-colors hover:text-text focus-visible:outline-2 focus-visible:outline-accent",children:X("chat.loadEarlier")}),c.slice(g,f),f<c.length&&(0,r.jsx)("div",{ref:nM,className:"py-3 text-center text-xs text-text-muted"})]})})(),eM.isStreaming&&ra.answerMessage&&(0,r.jsx)(rm,{message:ra.answerMessage,isStreaming:!0,cwd:n3,onOpenFile:ed,onOpenSession:B}),eT&&!rs&&!rl&&(0,r.jsx)(iz,{label:X("chat.agentWorking")}),e$&&!eR&&(0,r.jsx)(iz,{label:X("chat.agentWorking")}),eR&&(0,r.jsx)(rm,{message:{role:"bashExecution",command:eR.command,output:"",excludeFromContext:eR.excludeFromContext},sessionId:e?.id??tl.current??void 0,onOpenSession:B}),tW&&(0,r.jsx)(eI,{prompt:tW.prompt,size:tW.size,width:tW.width,height:tW.height,previewUrl:tW.previewUrl})]})})}),tA&&!ep&&(0,r.jsx)("button",{type:"button",onClick:()=>{nz.current?.abort(),nA(null),nO(null),nC(0),nE(50),requestAnimationFrame(()=>tE("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:"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:"m7 10 5 5 5-5"})})}),G&&L&&(0,r.jsx)(rG,{sessionId:e?.id??tl.current,leafId:tN,outlineRevision:rr,scrollContainer:to,contentContainer:n$,loadedEntryIds:eS,onJumpToEntry:ri}),!L||G||ep?null:(0,r.jsx)(rX,{sessionId:e?.id??tl.current,leafId:tN,outlineRevision:rr,scrollContainer:to,contentContainer:n$,loadedEntryIds:eS,onJumpToEntry:ri})]})]}),O&&t0&&(0,I.createPortal)((0,r.jsx)("div",{ref:nr,role:t8?"dialog":"toolbar","aria-label":X(t8?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:t0.top,left:t0.left,zIndex:130,display:"flex",flexWrap:"wrap",gap:2,width:t8?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:t8?12:2,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)"},children:t8?(0,r.jsxs)("fieldset",{disabled:t5,"aria-busy":t5,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:t5,onClick:ny,style:{border:"none"},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 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(tD,{ref:ni,compact:!0,onSend:nk,onAbort:ny,isStreaming:!1}),ne&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:ne})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[4px] border-0 bg-transparent px-2 text-[11px] text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text)] focus-visible:outline-2 focus-visible:outline-[var(--accent)]",title:X("chat.askInCurrent"),"aria-label":X("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:nw,children:[(0,r.jsx)("span",{"aria-hidden":"true",children:"@"}),(0,r.jsx)("span",{children:X("chat.askInCurrent")})]}),H&&t0.sourceEntryId&&!tM&&(0,r.jsxs)("button",{type:"button",className:"inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[4px] border-0 bg-transparent px-2 text-[11px] 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:()=>{t3(!0),window.getSelection()?.removeAllRanges()},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","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M6 3v12M18 9a9 9 0 0 1-9 9"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"})]}),(0,r.jsx)("span",{children:X("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[tP&&(0,r.jsxs)("div",{className:"mx-auto mb-6 flex select-none flex-col items-center justify-center text-center",style:{maxWidth:"var(--chat-content-max-width, 820px)",padding:"0 16px"},children:[(0,r.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:10,lineHeight:1},children:[(0,r.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 82 32",width:"82",height:"32",fill:"currentColor",role:"img","aria-label":"Pi Web",style:{color:"var(--text)",flexShrink:0,display:"block"},children:(0,r.jsx)("path",{d:"M0 0H24V16H16V8H0ZM0 8H8V16H16V24H8V32H0ZM24 16H32V32H24ZM44 16H46V26H44ZM46 26H48V32H46ZM48 22H50V26H48ZM50 26H52V32H50ZM52 16H54V26H52ZM60 16H68V18H60ZM58 18H60V30H58ZM60 22H66V24H60ZM60 30H68V32H60ZM72 16H80V18H74V22H80V24H74V30H80V32H72ZM80 18H82V22H80ZM80 24H82V30H80Z"})}),(0,r.jsx)(iR,{})]}),d&&p&&(0,r.jsx)(iP,{cwd:d,onChange:p,recentPaths:m,pinnedPaths:g,onTogglePinnedCwd:f,homeDir:x,worktreeInfo:v})]}),rb]}),tP&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function iV({type:e}){return"success"===e?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"#10b981",strokeWidth:"2",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:"13",height:"13",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:"13",height:"13",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:"13",height:"13",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 iJ({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,s)=>(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*(s!==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:12,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)(iV,{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 iY({request:e,onRespond:t}){let{t:n}=(0,w.s)(),[s,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[o,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 m=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:s})};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:o?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:o?(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,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:12,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}),m,(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:600},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")}),m]})]}),(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.3",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)(re,{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:12,overflowWrap:"anywhere"},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(re,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:s,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:12}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:s,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(--primary)",background:"var(--primary)",color:"var(--primary-contrast)",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(--primary)",background:"var(--primary)",color:"var(--primary-contrast)",cursor:"pointer"},children:n("chat.submit")}):null]})]})})}function iZ({request:e,onInput:t}){let{t:n}=(0,w.s)(),s=(0,i.useRef)(null),l=(0,i.useRef)(!1),[o,a]=(0,i.useState)(!1),d=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(t_,""),i=tq(e).trimEnd();if(t.test(i))continue;let s=e,l=tJ(s);("│"===l||"┃"===l)&&" "===tJ(s=tV(s,0))&&(s=tV(s,0));let o=function(e){let t=tK(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(s),a=o>=0?tK(s)[o]?.char:void 0;("│"===a||"┃"===a)&&(s=tV(s,o)),n.push(function(e){let t=e;for(;;){let e=tK(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(s))}for(;n.length>0&&""===tq(n[0]).trim();)n.shift();for(;n.length>0&&""===tq(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)(()=>{o||s.current?.focus()},[o]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:o?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:o?(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,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:12,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")||s.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:s,"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=tZ[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":" ":tY[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:14,fontWeight:600},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.3",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)(r0,{text:d.join("\n")})})]})})}function iX({tabs:e,activeTabId:t,splitTabId:n=null,activePane:s="primary",runningSessionIds:l,onSelectTab:o,onCloseTab:a,onPinTab:d,onNewTab:c,onToggleSplit:u,onClosePane:h,canSplit:p=!0,isSecondaryPane:m=!1,unifiedHeader:g=!1,isMobile:f=!1}){let{t:x}=(0,w.s)(),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(!1),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)({top:0,left:0,width:320}),E=(0,i.useRef)(null),M=(0,i.useRef)(null),T=(0,i.useRef)(null),L=(0,i.useRef)(null);(0,i.useEffect)(()=>{E.current&&E.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),(0,i.useEffect)(()=>{let e=M.current;if(!e)return;let t=()=>k(e.scrollWidth>e.clientWidth+1);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[e]),(0,i.useEffect)(()=>{if(!j)return;let e=e=>{let t=e.composedPath();L.current&&t.includes(L.current)||T.current&&t.includes(T.current)||S(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),S(!1),T.current?.focus())},n=()=>S(!1);return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),window.addEventListener("resize",n),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0),window.removeEventListener("resize",n)}},[j]),(0,i.useEffect)(()=>{b||S(!1)},[b]);let $=!!(n&&!f),R=e=>{let t=e?Array.from(document.querySelectorAll("[data-chat-tab-id]")).find(t=>t.dataset.chatTabId===e):null,n=E.current??document.querySelector('[data-chat-tab="true"][tabindex="0"]'),r=Array.from(document.querySelectorAll(".chat-input-textarea")).find(e=>e.getClientRects().length>0);(t??n??r)?.focus()};return(0,r.jsxs)("div",{role:"tablist","aria-label":x("chatTabs.label",{defaultValue:"对话标签"}),style:{display:"flex",alignItems:"stretch",background:g?"transparent":"var(--bg-panel)",borderBottom:g?"none":"1px solid var(--border)",height:"var(--workspace-header-height, 30px)",minHeight:"var(--workspace-header-height, 30px)",maxHeight:"var(--workspace-header-height, 30px)",width:g?"auto":"100%",maxWidth:"100%",minWidth:0,flex:g?"0 1 auto":"0 0 auto",flexShrink:0,overflow:"hidden",position:"relative"},children:[(0,r.jsx)("div",{ref:M,onWheel:e=>{e.deltaY&&!e.deltaX&&(e.currentTarget.scrollLeft+=e.deltaY)},style:{display:"flex",alignItems:"stretch",flex:"0 1 auto",minWidth:0,overflowX:"auto",overflowY:"hidden",scrollbarWidth:"none",WebkitOverflowScrolling:"touch",touchAction:"pan-x",overscrollBehaviorX:"contain"},children:e.map((i,c)=>{let u=i.id===t,h=i.id===n,p=u||h,m=u&&"primary"===s||h&&"secondary"===s,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?E:void 0,role:"tab","aria-label":i.dirty?`${i.title}, ${x("chatTabs.unsentDraft")}`:i.title,"aria-selected":p,tabIndex:m||!t&&0===c?0:-1,onClick:()=>o(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(),o(i.id);else if(["ArrowLeft","ArrowRight"].includes(t.key)){t.preventDefault();let n=(c+("ArrowRight"===t.key?1:-1)+e.length)%e.length;o(e[n].id),t.currentTarget.parentElement?.children[n]?.focus()}else if("Delete"===t.key){if(t.preventDefault(),!1===a(i.id))return;requestAnimationFrame(()=>{R()})}}},style:{display:"flex",alignItems:"center",gap:f?4:6,height:"100%",paddingLeft:f?8:10,paddingRight:f?p?4:8:4,borderRight:f&&c===e.length-1?"none":"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:f?130:200,minWidth:f?70:84,flexShrink:0,userSelect:"none",WebkitUserSelect:"none",touchAction:"pan-x",position:"relative",transition:"background 0.12s, color 0.12s",boxShadow:m?"inset 0 -2px 0 var(--accent)":void 0},title:i.preview?`${i.title} \xb7 ${x("chatTabs.previewTabHint",{defaultValue:"预览标签,双击固定"})}`:i.title,children:[(g||"draft"===i.kind)&&(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:g?"var(--accent)":p?"var(--text)":"var(--text-dim)"},children:g?(0,r.jsx)(Z,{size:12,ariaLabel:"Running"}):(0,r.jsxs)("svg",{width:"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)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,textDecoration:i.preview?"underline dotted":void 0,textDecorationColor:"var(--text-dim)",textUnderlineOffset:5,paddingBlock:5},children:i.title}),"draft"===i.kind&&i.dirty&&(0,r.jsx)("span",{title:x("chatTabs.unsentDraft"),"aria-hidden":"true",style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",flexShrink:0}}),(!f||p)&&(0,r.jsx)("button",{type:"button",tabIndex:-1,onClick:e=>{e.stopPropagation(),a(i.id)},onDoubleClick:e=>e.stopPropagation(),onMouseEnter:()=>y(i.id),onMouseLeave:()=>y(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:f?22:20,height:f?22:20,background:v===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:3,color:v===i.id?"var(--text)":"var(--text-muted)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:x("chatTabs.closeTab",{defaultValue:"关闭标签"}),"aria-label":`${x("chatTabs.closeTab",{defaultValue:"关闭标签"})}: ${i.title}`,children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.3",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)"},children:[b&&!f&&(0,r.jsx)("button",{ref:T,type:"button",onClick:()=>{if(j)return void S(!1);let e=T.current.getBoundingClientRect(),t=Math.min(320,window.innerWidth-16);N({top:e.bottom+4,left:Math.max(8,Math.min(e.right-t,window.innerWidth-t-8)),width:t}),S(!0)},"aria-expanded":j,title:x("chatTabs.allTabs"),"aria-label":x("chatTabs.allTabs"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",padding:0,border:"none",background:j?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 6h13M8 12h13M8 18h13"}),(0,r.jsx)("path",{d:"M3 6h.01M3 12h.01M3 18h.01"})]})}),(0,r.jsx)("button",{type:"button",onClick:c,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:x("chatTabs.newTab",{defaultValue:"新建对话标签"}),"aria-label":x("chatTabs.newTab",{defaultValue:"新建对话标签"}),onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="transparent"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),!m&&p&&!f&&u&&(0,r.jsx)("button",{type:"button",onClick:u,"aria-pressed":$,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:$?"var(--bg-selected)":"transparent",border:"none",color:$?"var(--accent)":"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:$?x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):x("chatTabs.splitView",{defaultValue:"向右分屏"}),"aria-label":$?x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}):x("chatTabs.splitView",{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)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"12",y1:"3",x2:"12",y2:"21"})]})}),m&&h&&(0,r.jsx)("button",{type:"button",onClick:h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:"100%",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",padding:0,transition:"color 0.12s, background 0.12s"},title:x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),"aria-label":x("chatTabs.closeSplit",{defaultValue:"关闭分屏"}),onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="transparent"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),j&&(0,I.createPortal)((0,r.jsx)("div",{ref:L,role:"dialog","aria-label":x("chatTabs.allTabs"),style:{position:"fixed",top:C.top,left:C.left,width:C.width,zIndex:700,padding:6,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",boxShadow:"0 8px 24px rgba(0,0,0,0.16)"},children:(0,r.jsx)("div",{style:{maxHeight:"min(50vh, 360px)",overflowY:"auto"},children:e.map((e,i)=>{let s=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:s?"var(--bg-selected)":"transparent",borderRadius:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{S(!1),o(e.id),requestAnimationFrame(()=>R(e.id))},style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,height:30,padding:"0 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12},children:[d?(0,r.jsx)("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:12,height:12,flexShrink:0},children:(0,r.jsx)(Z,{size:10})}):(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",flexShrink:0,background:e.dirty?"var(--accent)":"transparent"}}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title})]}),(0,r.jsx)("button",{type:"button","data-tab-menu-close":e.id,onClick:()=>{!1!==a(e.id)&&requestAnimationFrame(()=>{let e=M.current;if(e&&e.scrollWidth>e.clientWidth+1){let e=L.current?.querySelectorAll("[data-tab-menu-close]"),t=e?.[Math.min(i,e.length-1)];if(t)return void t.focus()}S(!1),R()})},title:`${x("chatTabs.closeTab")}: ${e.title}`,"aria-label":`${x("chatTabs.closeTab")}: ${e.title}`,style:{width:28,height:28,padding:0,border:"none",background:"transparent",color:"var(--text-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.3",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M2 2l6 6M8 2 2 8"})})})]},e.id)})})}),document.body)]})}function iG(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 iQ(e){return e.pane??"primary"}function i0(e,t){return e.filter(e=>iQ(e)===t)}function i1(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 s=e.findIndex(e=>!0===e.preview&&iQ(e)===n);if(s>=0){let r=[...e];return r[s]={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 i2(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 i4(e,t){let n=[...i0(e,"primary"),...i0(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 i8(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 i3(e,t,n,r="新会话",i="primary"){let s=`draft:${n}`;return e.find(e=>e.id===s)?{tabs:e,tabId:s}:{tabs:[...e,{id:s,kind:"draft",title:r,session:null,newSessionCwd:t,newSessionDraftKey:n,projectKey:t,dirty:!1,pane:i}],tabId:s}}function i6(e,t,n,r=null){let i=e.findIndex(e=>e.id===t);if(-1===i)return{tabs:e,nextActiveTabId:n,nextSplitTabId:r};let s=e.filter(e=>e.id!==t),l=iQ(e[i]),o=i0(e,l),a=i0(s,l),d=a[Math.min(o.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:i4(s,e),nextActiveTabId:e,nextSplitTabId:null}}return{tabs:s,nextActiveTabId:c,nextSplitTabId:u}}var i5=n(50640);let i7={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"},i9={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"},se={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function st(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function sn(e){return null!==(i7[st(e)]??null)}function sr(e){return null!==(i9[st(e)]??null)}function si(e){return null!==(se[st(e)]??null)}function ss(e){let t;return null!==("pdf"===(t=st(e))||"docx"===t?t:null)}let sl=new Set(["md","mdx","markdown","html","htm"]);var so=n(73620);let sa=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function sd(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 sc(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 su=/^ {0,3}(`{3,}|~{3,})/,sh=/^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*#*[ \t]*$/,sp=["tags","categories","keywords","tag","category"];function sm({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,s=sp.find(t=>Array.isArray(e[t])),l=s?e[s].map(sd).filter(Boolean):[],o=n.filter(([e])=>e!==s&&("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}`))}),o.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:o.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=sd(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 sg({items:e,scrollRoot:t}){let{t:n}=(0,w.s)(),s=(0,i.useId)(),l=(0,i.useRef)(null),[o,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(!o)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)}},[o]),0===e.length)return null;let h=e.map(()=>!1);if(u)for(let t=0;t<e.length;t++){let n=sc(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":o,"aria-haspopup":"menu","aria-controls":s,"aria-label":n("i18n.outline"),title:n("i18n.outline"),onClick:()=>a(e=>!e),style:{background:o?"var(--bg-selected)":"transparent",color:o?"var(--text)":"var(--text-muted)"},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:"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"})]})}),o&&(0,r.jsx)("div",{className:`file-outline-menu${u?" is-collapsible":""}`,id:s,role:"menu",children:e.map((n,i)=>{if(u&&3===n.level){let t=sc(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:"3",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,s=0;for(let t of e.querySelectorAll(".markdown-file-preview :is(h1, h2, h3)"))if(t.textContent?.replace(/\s+/g," ").trim()===r.text){if(s===i)return void t.scrollIntoView({block:"start",inline:"nearest"});s++}}(t.current,e,i),a(!1)},children:n.text})]},`${n.level}-${i}-${n.text}`)})})]})}function sf(e,t,n){var r;return r=n??(sl.has(st(e))?"preview":void 0),t?.displayMode??r??"source"}let sx={fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",lineHeight:1.6},sv={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 sy(){return(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:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function sb(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function sw(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=sb(n.startContainer),i=sb(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let s=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(s)||!Number.isInteger(l))return null;if(s<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]")&&(s=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 s>l?null:{startLine:s,endLine:l}}function sk({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,s)=>{let l=e.children??[],o=l[0]?.properties?.className,a=Array.isArray(o)&&o.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":s+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,i5.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${s}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,i5.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${s}-${r}`}))})]},`source-line-${s}`)})}function sj(e,t,n,r={}){let i=j(e),s=new URLSearchParams({type:t});for(let[e,t]of(n&&s.set("sessionId",n),Object.entries(r)))void 0!==t&&s.set(e,String(t));return`/api/files/${i}?${s.toString()}`}function sS({filePath:e,sourceSessionId:t}){let{t:n}=(0,w.s)();return(0,r.jsx)("a",{href:sj(e,"download",t),download:S(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"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)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function sC(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function sN({patch:e}){let{t}=(0,w.s)(),n=(0,i.useMemo)(()=>{let t;return(t=ri(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]),s=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 s.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%",...sx},children:[s.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?"-":" ",s="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:{...sv,width:40,minWidth:40,paddingInline:6},children:e.oldLineNo}),(0,r.jsx)("span",{style:{...sv,width:40,minWidth:40,paddingInline:6},children:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0},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 sE({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0}){let{t:l}=(0,w.s)(),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),m(null),f(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),x.current&&(x.current.close(),x.current=null),!s)return;let t=!0,r=!1,i=new EventSource(sj(e,"watch",n));x.current=i,i.addEventListener("connected",()=>{var i;let s;a(!0),i=r,s=++v.current,fetch(sj(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===v.current){if(e.error)return void f(e.error);"number"==typeof e.size&&h(e.size),m(null),f(null),i&&c(e=>e+1)}}).catch(e=>{t&&s===v.current&&f(String(e))}),r=!0}),i.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),f(null),c(e=>e+1)});let l=()=>{a(!1)};return i.addEventListener("error",l),i.onerror=l,()=>{t=!1,i.close(),x.current===i&&(x.current=null)}},[e,n,s]);let b=sj(e,"read",n,d?{v:d}:void 0),k=null!=u?sC(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:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),k&&(0,r.jsx)("span",{children:k}),(0,r.jsxs)("span",{title:l(o?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:o?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:o?"#4ade80":"var(--border)",display:"inline-block",boxShadow:o?"0 0 4px #4ade80":"none"}}),o?"live":"static"]}),(0,r.jsx)(sS,{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:12},children:g}):(0,r.jsx)("img",{src:b,alt:e,onLoad:e=>{let t=e.currentTarget;m({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function sI(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 sM({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0}){let{t:l}=(0,w.s)(),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),m(null),f(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),x.current&&(x.current.close(),x.current=null),!s)return;let t=!0,r=!1,i=new EventSource(sj(e,"watch",n));x.current=i,i.addEventListener("connected",()=>{var i;let s;a(!0),i=r,s=++v.current,fetch(sj(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===v.current){if(e.error)return void f(e.error);"number"==typeof e.size&&h(e.size),m(null),f(null),i&&c(e=>e+1)}}).catch(e=>{t&&s===v.current&&f(String(e))}),r=!0}),i.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),f(null),c(e=>e+1)});let l=()=>{a(!1)};return i.addEventListener("error",l),i.onerror=l,()=>{t=!1,i.close(),x.current===i&&(x.current=null)}},[e,n,s]);let b=sj(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:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=p&&(0,r.jsx)("span",{children:sI(p)}),null!=u&&(0,r.jsx)("span",{children:sC(u)}),(0,r.jsxs)("span",{title:l(o?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:o?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:o?"#4ade80":"var(--border)",display:"inline-block",boxShadow:o?"0 0 4px #4ade80":"none"}}),o?"live":"static"]}),(0,r.jsx)(sS,{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:12,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:b,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>f("Failed to load audio"),style:{width:"100%"}},b)]})})]})}function sT({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0}){let{t:l}=(0,w.s)(),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(0),y=S(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),h(null),m(null),f(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),x.current&&(x.current.close(),x.current=null),!s)return;let t=!0,r=!1,i=new EventSource(sj(e,"watch",n));x.current=i,i.addEventListener("connected",()=>{var i;let s;a(!0),i=r,s=++v.current,fetch(sj(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===v.current){if(e.error)return void f(e.error);"number"==typeof e.size&&h(e.size),m(null),f(null),i&&c(e=>e+1)}}).catch(e=>{t&&s===v.current&&f(String(e))}),r=!0}),i.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&h(t.size)}catch{}m(null),f(null),c(e=>e+1)});let l=()=>{a(!1)};return i.addEventListener("error",l),i.onerror=l,()=>{t=!1,i.close(),x.current===i&&(x.current=null)}},[e,n,s]);let b=sj(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:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=p&&(0,r.jsx)("span",{children:sI(p)}),null!=u&&(0,r.jsx)("span",{children:sC(u)}),(0,r.jsxs)("span",{title:l(o?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:o?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:o?"#4ade80":"var(--border)",display:"inline-block",boxShadow:o?"0 0 4px #4ade80":"none"}}),o?"live":"static"]}),(0,r.jsx)(sS,{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:12,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:b,onLoadedMetadata:e=>m(e.currentTarget.duration),onError:()=>f("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},b)]})})]})}function sL({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:s=!0,pdfPage:l}){let{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),f=(0,i.useRef)(null),x=(0,i.useRef)(0),v=st(e),y="pdf"===v,b=y?sj(e,"read",n,c?{v:c}:void 0)+(l?`#page=${l}`:""):sj(e,"preview",n,c?{v:c}:void 0);return(0,i.useEffect)(()=>{u(0),p(null),g(null),d(!1);let t=!0,r=++x.current;return fetch(sj(e,"meta",n)).then(e=>e.json()).then(e=>{t&&r===x.current&&(e.error&&g(e.error),"number"==typeof e.size&&(p(e.size),!y&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===x.current&&g(String(e))}),()=>{t=!1}},[e,y,n]),(0,i.useEffect)(()=>{if(d(!1),f.current&&(f.current.close(),f.current=null),!s)return;let t=!0,r=!1,i=new EventSource(sj(e,"watch",n));f.current=i,i.addEventListener("connected",()=>{var i;let s;d(!0),i=r,s=++x.current,fetch(sj(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&s===x.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(p(e.size),!y&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),i&&u(e=>e+1)}}).catch(e=>{t&&s===x.current&&g(String(e))}),r=!0}),i.addEventListener("change",e=>{x.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(p(t.size),!y&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),u(e=>e+1)});let l=()=>{d(!1)};return i.addEventListener("error",l),i.onerror=l,()=>{t=!1,i.close(),f.current===i&&(f.current=null)}},[e,y,n,s]),(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:N(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===v?"docx preview":"pdf"}),null!=h&&(0,r.jsx)("span",{children:sC(h)}),(0,r.jsx)(sS,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:o(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:m?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:12,textAlign:"center"},children:m}):(0,r.jsx)("iframe",{src:b,sandbox:y?void 0:"allow-same-origin",title:o("i18n.previewFile",{file:S(e)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},b)})]})}function s$({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u=!0,pdfPage:h}){let p="diff"===sf(e,d,a);return!p&&sn(e)?(0,r.jsx)(sE,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&sr(e)?(0,r.jsx)(sM,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&si(e)?(0,r.jsx)(sT,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):!p&&ss(e)?(0,r.jsx)(sL,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u,pdfPage:h}):(0,r.jsx)(sR,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u})}function sR({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:s,onMentionLines:l,onAtMention:o,gitRefreshKey:a,initialDisplayMode:d,initialState:c,onStateChange:u,watchEnabled:h=!0}){let{isDark:p}=n8(),{t:m}=(0,w.s)(),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(!1),[k,j]=(0,i.useState)(!1),[S,E]=(0,i.useState)(null),[I,M]=(0,i.useState)(!0),[T,L]=(0,i.useState)(!1),[$,R]=(0,i.useState)(null),W=sf(e,c,d),z="diff"===W&&(sn(e)||sr(e)||si(e)||ss(e)),P=c?.wrapLines??!1,A=c?.scrollByMode?.[W],D=A?.scrollTop??c?.scrollTop??0,F=A?.scrollLeft??c?.scrollLeft??0,B=c?.loadedBytes??0,[H,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:F,loadedBytes:B,scrollByMode:{...c?.scrollByMode}}),ei=(0,i.useRef)(u),[es,el]=(0,i.useState)(null);ei.current=u;let eo=(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)(()=>()=>{ei.current?.({...er.current})},[]);let ed=(0,i.useCallback)(async(e,t=0)=>{let r=++J.current,i=async t=>(await fetch(sj(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 R(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 R(n.error),null}return R(null),Y.current=n.version,Z.current=n.nextOffset,er.current.loadedBytes=n.nextOffset,f(t=>e&&t?{...n,content:t.content+n.content}:n),n}catch(e){if(r!==J.current)return null;return R(String(e)),null}},[n]),ec=(0,i.useCallback)(async(e,t)=>{let n=await ed(e);for(;n?.truncated&&n.nextOffset<t;)n=await ed(e,n.nextOffset);return n},[ed]),eu=4194304*!!sl.has(st(e)),eh=(0,i.useCallback)(async e=>{let n=++Q.current;if(b(!0),E(null),!t){v(null),b(!1),j(!0);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),s=await i.json();if(n!==Q.current)return;i.ok||E(s.error??`Failed to load diff (HTTP ${i.status})`),v(i.ok&&s.supported&&"string"==typeof s.patch?s:null)}catch(e){n===Q.current&&(v(null),E(e instanceof Error?e.message:String(e)))}finally{n===Q.current&&(b(!1),j(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;if(M(!0),R(null),f(null),v(null),j(!1),E(null),K(!1),Y.current=null,Z.current=0,G.current=!1,z)return M(!1),X.current=null,()=>{t=!1,J.current+=1};let n=ec(e,Math.max(B,eu));return X.current=n,n.finally(()=>{X.current===n&&(X.current=null),t&&M(!1)}),()=>{t=!1,J.current+=1}},[eu,e,ec,B,z,n]),(0,i.useEffect)(()=>{if(K(!1),V.current&&(V.current.close(),V.current=null),!h)return;let t=new EventSource(sj(e,"watch",n));V.current=t,t.addEventListener("connected",n=>{K(!0);let r=G.current;if(G.current=!0,r&&eh(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&&(ec(e,Math.max(er.current.loadedBytes??0,eu)),eh(e))})}),t.addEventListener("change",()=>{z||ec(e,Math.max(er.current.loadedBytes??0,eu)),eh(e)});let r=()=>{K(!1)};return t.addEventListener("error",r),t.onerror=r,()=>{t.close(),V.current===t&&(V.current=null)}},[eu,e,eh,ec,z,n,h]),(0,i.useEffect)(()=>{eh(e)},[eh,e,a]);let ep=x?.supported===!0&&"string"==typeof x.patch,em=ep&&"deleted"===x.status;(0,i.useEffect)(()=>{k&&!ep&&"diff"===H&&eo("source")},[H,k,ep,eo]),(0,i.useEffect)(()=>{"diff"===W&&ep&&!et.current&&(et.current=!0,eo("diff"))},[W,ep,eo]);let eg=(0,i.useMemo)(()=>g?.language==="markdown"?nL(g.content):"",[g]),ef=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=sa.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,so.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]),ex=(0,i.useMemo)(()=>(function(e){let t=[],n=null;for(let r of e.split(/\r?\n/)){let e=su.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=sh.exec(r);if(!i)continue;let s=i[2].replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").trim();s&&t.push({level:i[1].length,text:s})}return t})(ef?.rest??""),[ef]),ev=g?.content??"",ey=(0,i.useMemo)(()=>ev.split("\n"),[ev]),eb=g?.language??"text",ew="html"===eb,ek="markdown"===eb,ej=!g?.truncated&&(ew||ek),eS=em?"diff":"preview"!==H||ej?H:"source",eC=(ey.length>1e3||(g?.size??0)>131072)&&!("diff"===eS&&ep)&&!("preview"===eS&&ej),eN=!eC&&!("diff"===eS&&ep)&&!("preview"===eS&&ej),eE=(0,i.useMemo)(()=>eN?(0,r.jsx)(n6.A,{className:U?"file-source-view is-wrapped":"file-source-view",language:"text"===eb?"plaintext":eb,style:p?nH.xJ:nH.vs,showLineNumbers:!0,lineNumberStyle:{...sv},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...sx,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)(sk,{...e,wrapLines:U}),wrapLongLines:U,children:ev}):null,[p,eb,eN,ev,U]),eI=(0,i.useMemo)(()=>eC?ey.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:sv,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,[ey,eC,U]);(0,i.useEffect)(()=>{let e=()=>{let e=ee.current;el(t=>{let n=l&&"source"===H&&e?sw(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"===H)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[g?.content,H,l]);let eM=(0,i.useCallback)(n=>{l&&n&&l(N(e,t),n.startLine,n.endLine,t)},[t,e,l]);if((0,i.useEffect)(()=>{if(!l||"source"!==H)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?sw(n,window.getSelection()):null;r&&(e.preventDefault(),eM(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[H,eM,l]),(0,i.useEffect)(()=>{if(!en.current||I||$&&!em||"diff"===W&&!k||"diff"===W&&ep&&"diff"!==H)return;let e=ee.current;e&&(e.scrollTop=er.current.scrollTop,e.scrollLeft=er.current.scrollLeft,en.current=!1)},[g?.content,H,$,k,ep,em,I,W]),(0,i.useLayoutEffect)(()=>{if(en.current)return;let e=ee.current;if(!e)return;let t=er.current.scrollByMode?.[eS];e.scrollTop=t?.scrollTop??0,e.scrollLeft=t?.scrollLeft??0},[eS]),I||"diff"===W&&y&&!k)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:12},children:m("i18n.loading")});if("diff"===W&&k&&S)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:12,textAlign:"center"},children:S});if($&&!("diff"===eS&&ep))return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:8,color:"#f87171",fontSize:12},children:[$,"Binary file, preview not available"===$&&(0,r.jsx)(sS,{filePath:e,sourceSessionId:n})]});if(!g&&!("diff"===eS&&ep))return null;let eT=C(e),eL=!g||em?["diff"]:["source",...ej?["preview"]:[],...ep?["diff"]:[]],e$=em?m("files.deleted"):g?`${eb} \xb7 ${ey.length} lines \xb7 ${sC(g.size)}`:m("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:N(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:e$,children:e$}),g&&!em&&(0,r.jsx)("span",{title:q?m("i18n.liveSync"):m("i18n.notWatching"),"aria-label":q?m("i18n.liveSync"):m("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:[eL.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":m("i18n.fileViewMode"),children:eL.map(e=>{let t=eS===e;return(0,r.jsx)("button",{type:"button",onClick:()=>eo(e),title:"diff"===e?m("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?m("i18n.source"):"preview"===e?m("i18n.preview"):m("i18n.diff")},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[ek&&"preview"===eS&&(0,r.jsx)(sg,{items:ex,scrollRoot:ee}),(o||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{es&&l?eM(es):o?.(N(e,t),!1,t)},title:es&&l?`${m("i18n.mentionSelectedLines")} (L${es.startLine}${es.startLine!==es.endLine?`-L${es.endLine}`:""})`:m("files.insertPath"),"aria-label":m("files.mention"),disabled:!o&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(sy,{})}),"source"===eS&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:ea,title:U?m("i18n.disableWrap"):m("i18n.enableWrap"),"aria-label":U?m("i18n.disableWrap"):m("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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 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"})]})})})]}),!em&&(0,r.jsx)(sS,{filePath:e,sourceSessionId:n})]})]}),g?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",children:[(0,r.jsxs)("span",{children:[sC(g.nextOffset)," / ",sC(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:T,onClick:()=>{L(!0),ed(e,g.nextOffset).finally(()=>L(!1))},children:T?m("i18n.loading"):m("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,[eS]:t}},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:g?.truncated?48:void 0},children:"diff"===eS&&ep?(0,r.jsx)(sN,{patch:x.patch}):ew&&"preview"===eS?(0,r.jsx)("iframe",{srcDoc:ev,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:m("i18n.htmlPreview")}):ek&&"preview"===eS?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[ef?.data&&(0,r.jsx)(sm,{data:ef.data}),(0,r.jsx)(ny.oz,{remarkPlugins:nD,rehypePlugins:nB,urlTransform:s?nM:void 0,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===i?(0,r.jsx)(n5,{code:s.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(n9,{code:s.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:t,...n}){if(delete n.node,e?.startsWith("#"))return(0,r.jsx)("a",{href:e,...n,onClick:t=>{t.preventDefault();let n=decodeURIComponent(e.slice(1)),r=t.currentTarget.closest(".markdown-file-preview"),i=[...r?.querySelectorAll("h1, h2, h3, h4, h5, h6")??[]],s=r?.querySelector(`[id="user-content-${CSS.escape(n)}"]`)??i[function(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r].trim().toLowerCase().replace(/[^\p{L}\p{M}\p{N}\p{Pc}\- ]/gu,"").replace(/ /g,"-"),s=n.get(i)??0;if(n.set(i,s+1),(s?`${i}-${s}`:i)===t)return r}return -1}(i.map(e=>e.textContent??""),n)];s?.scrollIntoView({block:"start",inline:"nearest"})},children:t});let i=s?no(e,eT):null;return i&&s?(0,r.jsx)("a",{href:e,...n,onClick:t=>{nr(t)&&(t.preventDefault(),s(i,na(e)??void 0))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...i}){delete i.node;let s="string"==typeof e?no(e,eT):null,l=s?sj(s,"read",n):e;return(0,r.jsx)("img",{src:l,alt:t??"",loading:"lazy",...i})}},children:eg})]}):eC?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:U?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...sx},children:eI}):eE})]})}function sW(e,t){if(t<=0)return"";let n=Math.max(0,e.length-1-t);return e.slice(n,-1).join("/")||e[0]||""}function sz(e,t){return t?`${e} \xb7 ${t}`:e}function sP(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return t}function sA({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:s}){let{t:l}=(0,w.s)(),[o,a]=(0,i.useState)(null),d=(0,i.useRef)(null),c=(0,i.useRef)(!1),u=(0,i.useMemo)(()=>(function(e){let t=new Map,n=new Map;for(let t of e){let e=function(e){let t=e.label?.trim();return t||S(e.path)||e.path}(t),r=n.get(e);r?r.push(t):n.set(e,[t])}for(let[e,r]of n){if(1===r.length){t.set(r[0].id,e);continue}let n=r.map(e=>(function(e){let t=k(e).replace(/\/+$/,"");return t?/^[a-zA-Z]:$/.test(t)?[t]:t.split("/").filter((e,t)=>e.length>0||0===t):[]})(e.path)),i=n.map(e=>Math.max(0,e.length-1)),s=r.map(()=>0),l=!0;for(;l;){l=!1;let t=r.map((t,r)=>sz(e,sW(n[r],s[r]))),o=sP(t);for(let e=0;e<r.length;e+=1)!((o.get(t[e])??0)<=1)&&(s[e]>=i[e]||(s[e]+=1,l=!0))}let o=r.map((t,r)=>sz(e,sW(n[r],s[r]))),a=sP(o);r.forEach((n,r)=>{t.set(n.id,(a.get(o[r])??0)>1?e:o[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),s="Home"===t.key?0:"End"===t.key?e.length-1:(r+("ArrowRight"===t.key?1:-1)+e.length)%e.length;n(e[s].id),t.currentTarget.parentElement?.children[s]?.focus()}}},onClick:()=>n(i.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),i.closing||s(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,display:"inline-flex",alignItems:"center"},children:"terminal"===i.kind?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]}):A(i.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,lineHeight:1},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,s(i.id)},onMouseEnter:()=>a(i.id),onMouseLeave:()=>a(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,background:o===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:o===i.id?"var(--text)":"var(--text-muted)",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.3",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 sD(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 sF=["general","models","agents","images","skills","plugins"],sB="pi-web:settings-navigation",sH=new Set(["skills","agents","plugins"]);function sO(){try{return window.localStorage}catch{return null}}function sU(e){let t=e.getItem(sB);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 s_(e,t=sO()){if(t)try{let n=sU(t);n.section=e,t.setItem(sB,JSON.stringify(n))}catch{}}let sq="pi-auto-session-title";function sK(){try{return"false"!==window.localStorage.getItem(sq)}catch{return!0}}let sV=["input","output","cacheRead","cacheWrite"];function sJ(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 sY(e){if(!sZ(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),s=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==s)return{input:n,output:r,cacheRead:i,cacheWrite:s}}function sZ(e){return sV.some(t=>""!==e[t].trim())}let sX=["name","reasoning","thinkingLevelMap","input","contextWindow","maxTokens","cost","headers","compat"];function sG(e,t){return`${e}/${t}`}function sQ(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function s0(e,t){let n=sQ(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function s1(e){let t=e.trim(),n=t.match(eT),r=n?t.slice(0,-n[0].length):t,i=n?.[1];if(!r||/[*?\[]/.test(r))return null;let s=r.indexOf("/");return s===r.length-1?null:s<=0?{id:r,...i?{pin:i}:{},ref:r}:{provider:r.slice(0,s),id:r.slice(s+1),...i?{pin:i}:{},ref:r}}function s2(e,t){let n=t.trim();return sQ(e).filter(e=>e!==n)}function s4(e){let t=sQ(e);return t.length>0&&t.every(e=>null!==s1(e))}function s8({embedded:e,title:t,subtitle:n,closeLabel:i="Close",onClose:s,children:l,width:o=900,height:a="78vh"}){let d=e?void 0:{"--config-panel-width":`${o}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||s()},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:s,title:i,"aria-label":i,children:"\xd7"})]}),l]})})}function s3({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 s6({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function s5({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 s7({title:e,action:t,children:n}){return(0,r.jsxs)("section",{className:"settings-group",children:[(e||t)&&(0,r.jsxs)("div",{className:"settings-group-header",children:[e&&(0,r.jsx)("h3",{className:"settings-group-title",children:e}),t]}),(0,r.jsx)("div",{className:"settings-group-rows",children:n})]})}function s9({label:e,description:t,htmlFor:n,stacked:i=!1,title:s,children:l}){return(0,r.jsxs)("div",{className:`settings-row${i?" is-stacked":""}`,title:s,children:[(0,r.jsxs)("div",{className:"settings-row-copy",children:[n?(0,r.jsx)("label",{htmlFor:n,className:"settings-row-label",children:e}):(0,r.jsx)("span",{className:"settings-row-label",children:e}),t&&(0,r.jsx)("p",{className:"settings-row-description",children:t})]}),l&&(0,r.jsx)("div",{className:"settings-row-control",children:l})]})}function le({label:e,description:t,muted:n=!1,title:i,onOpen:s,children:l}){return(0,r.jsxs)("div",{className:"settings-row is-link",children:[(0,r.jsxs)("button",{type:"button",className:"settings-row-copy settings-row-open",title:i,onClick:s,children:[(0,r.jsx)("span",{className:`settings-row-label${n?" is-dim":""}`,children:e}),t&&(0,r.jsx)("span",{className:"settings-row-description is-clamped",children:t})]}),l&&(0,r.jsx)("div",{className:"settings-row-control",children:l})]})}function lt({label:e,onClick:t}){return(0,r.jsxs)("button",{type:"button","data-settings-back":!0,className:"settings-back-link",onClick:t,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:"m15 18-6-6 6-6"})}),e]})}function ln({value:e,onChange:t,placeholder:n}){return(0,r.jsxs)("label",{className:"settings-search-field",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-3.5-3.5"})]}),(0,r.jsx)("input",{type:"search",value:e,onChange:e=>t(e.target.value),placeholder:n,"aria-label":n})]})}function lr({label:e,count:t}){return(0,r.jsxs)(r.Fragment,{children:[e,(0,r.jsx)("span",{className:"settings-group-count",children:t})]})}function li({title:e,meta:t,description:n,children:i}){return(0,r.jsxs)("div",{className:"settings-detail-page",children:[(0,r.jsxs)("header",{className:"settings-detail-header",children:[(0,r.jsx)("h2",{className:"settings-detail-title",children:e}),t&&(0,r.jsx)("div",{className:"settings-detail-meta",children:t}),n&&(0,r.jsx)("p",{className:"settings-detail-description",children:n})]}),i]})}function ls({label:e,options:t,value:n,onChange:i,disabled:s=!1}){return(0,r.jsx)("div",{role:"radiogroup","aria-label":e,className:"settings-segmented",children:t.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":n===e.value,className:"settings-segmented-option",disabled:s||e.disabled,title:e.title,onClick:()=>i(e.value),children:e.label},e.value))})}function ll({children:e}){return(0,r.jsx)("dl",{className:"settings-properties",children:e})}function lo({label:e,mono:t=!1,children:n}){return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{className:t?"is-mono":void 0,children:n})]})}function la({variant:e="secondary",size:t="default",className:n,children:i,...s}){return(0,r.jsx)("button",{type:"button",...s,className:["config-button",`config-button-${e}`,`config-button-${t}`,n].filter(Boolean).join(" "),children:i})}function ld({checked:e,disabled:t=!1,loading:n=!1,label:i,onChange:s}){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:()=>s(!e),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function lc({tone:e,title:t}){return(0,r.jsx)("span",{role:"img","aria-label":t,title:t,className:`config-status-dot is-${e}`})}let lu={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 lh({id:e,size:t}){let n=lu[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:{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:600,lineHeight:1},children:i})}function lp({value:e,onChange:t,placeholder:n,mono:i,disabled:s,id:l}){return(0,r.jsx)("input",{id:l,className:`models-input${i?" is-mono":""}`,value:e,onChange:e=>t(e.target.value),placeholder:n,disabled:s})}function lm({value:e,onChange:t,placeholder:n,mono:s,onKeyDown:l}){let[o,a]=(0,i.useState)(!1),{t:d}=(0,w.s)();return(0,i.useEffect)(()=>{e||a(!1)},[e]),(0,r.jsxs)("div",{className:"models-secret",children:[(0,r.jsx)("input",{type:o?"text":"password",className:`models-input${s?" is-mono":""}`,value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:n,autoComplete:"off",spellCheck:!1}),(0,r.jsx)("button",{type:"button",className:"models-secret-toggle",onClick:()=>a(e=>!e),"aria-label":d(o?"i18n.hideDetails":"i18n.showDetails"),title:d(o?"i18n.hideDetails":"i18n.showDetails"),children:o?(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:"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:"13",height:"13",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 lg({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",className:"models-input",value:e,onChange:e=>t(e.target.value),placeholder:n})}function lf({value:e,onChange:t,options:n,required:i}){let{t:s}=(0,w.s)();return(0,r.jsxs)("select",{className:"models-input",value:e,onChange:e=>t(e.target.value),children:[!i&&(0,r.jsx)("option",{value:"",children:s("models.useDefault")}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function lx({label:e,description:t,checked:n,onChange:i}){return(0,r.jsx)(s9,{label:e,description:t,children:(0,r.jsx)(ld,{checked:n,label:e,onChange:i})})}function lv({title:e,hint:t,actions:n}){return(0,r.jsxs)("div",{className:"models-section-header",children:[(0,r.jsxs)("div",{className:"models-section-heading",children:[(0,r.jsx)("h3",{className:"settings-group-title",children:e}),t&&(0,r.jsx)("p",{className:"settings-row-description",children:t})]}),n&&(0,r.jsx)("span",{className:"models-form-actions",children:n})]})}function ly({children:e}){return(0,r.jsx)("span",{className:"models-hint",children:e})}function lb({tone:e="info",children:t,action:n}){return(0,r.jsxs)("div",{className:`models-notice is-${e}`,role:"danger"===e?"alert":"status",children:[(0,r.jsx)("div",{className:"models-notice-body",children:t}),n]})}function lw({headers:e,onChange:t}){let{t:n}=(0,w.s)(),[s,l]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),o=(0,i.useRef)(s.length),a=e=>{l(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},d=(e,t)=>{a(s.map(n=>n.id===e?{...n,...t}:n))};return(0,r.jsxs)("div",{className:"models-header-list",children:[s.map(e=>(0,r.jsxs)("div",{className:"models-header-row",children:[(0,r.jsx)("input",{className:"models-input is-mono",value:e.name,onChange:t=>d(e.id,{name:t.target.value}),placeholder:"Header-Name"}),(0,r.jsx)("input",{className:"models-input is-mono",value:e.value,onChange:t=>d(e.id,{value:t.target.value}),placeholder:"value"}),(0,r.jsx)("button",{type:"button",className:"models-icon-button is-danger",onClick:()=>{var t;return t=e.id,void a(s.filter(e=>e.id!==t))},"aria-label":n("i18n.remove"),title:n("i18n.remove"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.id)),(0,r.jsx)(la,{size:"small",className:"models-self-start",onClick:()=>l(e=>[...e,{id:o.current++,name:"",value:""}]),children:n("models.addHeader")})]})}function lk({value:e,onChange:t}){let{t:n}=(0,w.s)(),i=e??{},s=(e,n)=>{let r={...i};"omit"===n?delete r[e]:r[e]=n,t(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{className:"models-thinking-map",children:eM.map(e=>{let t=i[e],l=e in i?null===t?"null":"string":"omit",o="string"==typeof t?t:"";return(0,r.jsxs)("div",{className:`models-thinking-row is-${l}`,children:[(0,r.jsx)("span",{className:"models-thinking-level",children:e}),(0,r.jsxs)("div",{className:"models-segmented",role:"radiogroup","aria-label":e,children:[(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"omit"===l,onClick:()=>s(e,"omit"),children:n("models.levelDefault")}),(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"null"===l,className:"is-danger",onClick:()=>s(e,null),children:n("models.levelDisabled")}),(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":"string"===l,onClick:()=>s(e,o||e),children:n("models.levelCustom")})]}),(0,r.jsx)("input",{className:"models-input is-mono models-thinking-input",value:o,onChange:t=>s(e,t.target.value),onFocus:()=>{"string"!==l&&s(e,o||e)},placeholder:e,maxLength:10,"aria-label":`${e} ${n("models.levelCustom")}`})]},e)})})}function lj({title:e,description:t,width:n=560,onClose:i,children:s,footer:l,header:o}){return(0,r.jsx)("div",{className:"models-dialog-backdrop",onClick:e=>{e.target===e.currentTarget&&i()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),i())},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":e,className:"models-dialog",style:{width:n},children:[o??(0,r.jsxs)("div",{className:"models-dialog-header",children:[(0,r.jsx)("strong",{children:e}),t&&(0,r.jsx)("span",{children:t})]}),(0,r.jsx)("div",{className:"models-dialog-body",children:s}),l&&(0,r.jsx)("div",{className:"models-dialog-footer",children:l})]})})}function lS(e,t){return window.confirm(e("models.disconnectConfirm",{name:t}))}function lC({tone:e,children:t}){return(0,r.jsxs)("span",{className:`models-status is-${e}`,children:[(0,r.jsx)("span",{className:"models-status-dot","aria-hidden":"true"}),t]})}function lN({provider:e,onRefresh:t,cwd:n}){let[s,l]=(0,i.useState)({phase:"idle"}),{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(""),c=(0,i.useRef)(null),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>u.current?.focus(),50)},[s.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:o("models.loginConnectionLost")})}},[e.id,t,n,o]),p=(0,i.useCallback)(async()=>{lS(o,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,o,n]),m=(0,i.useCallback)(async(t,n,r)=>{l({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));l({phase:"error",message:e.error??`HTTP ${r.status}`});return}d("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e.id]),g=(e,t)=>{t.trim()&&m(e,t.trim(),o("models.loginVerifying"))},f="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{className:"models-auth",children:[(0,r.jsxs)("div",{className:"models-auth-row",children:[(0,r.jsxs)("div",{className:"models-auth-copy",children:[(0,r.jsx)("strong",{children:o("models.oauthTitle")}),(0,r.jsx)(lC,{tone:e.loggedIn?"success":"muted",children:e.loggedIn?o("i18n.connected"):o("i18n.notConnected")})]}),(0,r.jsx)("div",{className:"models-auth-actions",children:f?(0,r.jsx)(la,{size:"small",onClick:()=>{c.current?.close(),l({phase:"idle"})},children:o("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[e.loggedIn&&(0,r.jsx)(la,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:p,children:o("i18n.disconnect")}),(0,r.jsx)(la,{size:"small",variant:e.loggedIn?"secondary":"primary",onClick:h,children:e.loggedIn?o("i18n.relogin"):o("i18n.login")})]})})]}),"idle"===s.phase&&!e.loggedIn&&(0,r.jsx)("p",{className:"models-muted",children:o("models.oauthConnectHint",{name:e.name})}),"connecting"===s.phase&&(0,r.jsx)("p",{className:"models-muted",children:o("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:s.message}),(0,r.jsx)("div",{className:"models-auth-options",children:s.options.map(e=>(0,r.jsx)(la,{className:"models-auth-option",onClick:()=>void m(s.token,e.id,o("models.loginContinuing")),children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:"auth"===s.phase?o("models.oauthPasteRedirect"):s.message}),"auth"===s.phase&&(0,r.jsxs)("p",{className:"models-hint",children:[o("models.oauthBrowserNotOpened")," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"models-link",children:o("models.oauthOpenLoginPage")})]}),(0,r.jsxs)("div",{className:"models-inline-form",children:[(0,r.jsx)("input",{ref:u,className:"models-input is-mono",value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&g(s.token,a)},placeholder:"auth"===s.phase?"http://localhost:1455/auth/callback?code=…":s.placeholder??o("models.enterValue")}),(0,r.jsx)(la,{variant:"primary",size:"small",onClick:()=>g(s.token,a),disabled:!a.trim(),children:o("i18n.submit")})]})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{className:"models-auth-flow",children:[(0,r.jsx)("p",{className:"models-muted",children:o("models.deviceCodeHint")}),(0,r.jsx)("div",{className:"models-device-code",children:s.userCode}),(0,r.jsxs)("p",{className:"models-hint",children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"models-link",children:s.verificationUri}),s.expiresInSeconds?` \xb7 ${o("models.deviceCodeExpires",{minutes:Math.ceil(s.expiresInSeconds/60)})}`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{className:"models-muted",children:s.message}),"success"===s.phase&&(0,r.jsx)(lb,{tone:"success",children:o("i18n.connectedSuccessfully")}),"error"===s.phase&&(0,r.jsx)(lb,{tone:"danger",children:s.message})]})}function lE({provider:e,onRefresh:t,cwd:n}){let[s,l]=(0,i.useState)(""),[o,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(null),[p,m]=(0,i.useState)(!1),{t:g}=(0,w.s)();(0,i.useEffect)(()=>{l(""),h(null),m(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(s.trim()){a(!0),h(null),m(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:s.trim(),cwd:n})}),i=await r.json();!r.ok||i.error?h(i.error??`HTTP ${r.status}`):(l(""),m(!0),setTimeout(()=>m(!1),2e3),t())}catch(e){h(String(e))}finally{a(!1)}}},[s,e.id,t,n]),x=(0,i.useCallback)(async()=>{if(lS(g,e.displayName)){c(!0),h(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:n})}),i=await r.json();!r.ok||i.error?h(i.error??`HTTP ${r.status}`):t()}catch(e){h(String(e))}finally{c(!1)}}},[e.id,e.displayName,t,g,n]);return(0,r.jsxs)("div",{className:"models-auth",children:[(0,r.jsxs)("div",{className:"models-auth-row",children:[(0,r.jsxs)("div",{className:"models-auth-copy",children:[(0,r.jsx)("strong",{children:g("models.apiKeyTitle")}),(0,r.jsx)(lC,{tone:e.configured?"success":"muted",children:e.configured?g("i18n.configured"):g("i18n.notConfigured")})]}),e.configured&&(0,r.jsx)("div",{className:"models-auth-actions",children:(0,r.jsx)(la,{size:"small",variant:"ghost",className:"models-danger-ghost",onClick:x,disabled:d,children:d?g("i18n.removing"):g("i18n.disconnect")})})]}),(0,r.jsxs)("div",{className:"models-inline-form",children:[(0,r.jsx)(lm,{value:s,onChange:l,onKeyDown:e=>{"Enter"===e.key&&s.trim()&&f()},placeholder:e.configured?g("models.replaceKeyPlaceholder"):"sk-…",mono:!0}),(0,r.jsx)(la,{variant:"primary",size:"small",onClick:f,disabled:o||!s.trim()||p,className:p?"is-success":void 0,children:p?g("i18n.saved"):o?g("i18n.saving"):e.configured?g("models.updateKey"):g("models.saveKey")})]}),u&&(0,r.jsx)(lb,{tone:"danger",children:u})]})}let lI=/^[a-z0-9][a-z0-9._-]*$/;function lM(){let e=(0,i.useRef)(null);return(0,i.useEffect)(()=>{setTimeout(()=>e.current?.focus(),30)},[]),e}function lT({oauthProviders:e,apiKeyProviders:t,existingIds:n,onSelectOAuth:s,onSelectApiKey:l,onAddCustom:o,onClose:a}){let[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(""),{t:g}=(0,w.s)(),f=lM(),x=d.trim().toLowerCase(),v=e.filter(e=>!e.loggedIn&&(!x||e.name.toLowerCase().includes(x))),y=t.filter(e=>!e.configured&&(!x||e.displayName.toLowerCase().includes(x)||e.id.toLowerCase().includes(x))),b=!x||"custom".includes(x)||"openai-compatible".includes(x)||"anthropic-compatible".includes(x),k=v.length+y.length+ +!!b,j=p.trim(),S=lI.test(j)&&!n.has(j),C=(e,t,n,i,s)=>(0,r.jsxs)("button",{type:"button",className:"models-card",onClick:s,children:[(0,r.jsxs)("span",{className:"models-card-copy",children:[(0,r.jsx)("strong",{children:t}),(0,r.jsx)("span",{children:n})]}),i]},e);return(0,r.jsx)(lj,{title:g("models.addProviderTitle"),width:820,onClose:a,header:(0,r.jsxs)("div",{className:"models-dialog-search",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:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:f,value:d,onChange:e=>c(e.target.value),placeholder:g("i18n.searchProviders"),"aria-label":g("i18n.searchProviders")})]}),children:0===k?(0,r.jsx)("p",{className:"models-empty",children:g("i18n.noProviders")}):(0,r.jsxs)("div",{className:"models-card-grid",children:[b&&(0,r.jsx)("div",{className:"models-card-group",children:g("i18n.custom")}),b&&!u&&C("custom",g("models.customCompatible"),g("i18n.customEndpoint"),(0,r.jsx)("span",{className:"models-card-plus","aria-hidden":"true",children:"+"}),()=>h(!0)),b&&u&&(0,r.jsxs)("form",{className:"models-custom-form",onSubmit:e=>{e.preventDefault(),S&&(o(j),a())},children:[(0,r.jsx)("label",{htmlFor:"custom-provider-id",className:"config-field-label",children:g("models.providerId")}),(0,r.jsx)("input",{id:"custom-provider-id",autoFocus:!0,className:"models-input is-mono",value:p,onChange:e=>m(e.target.value),placeholder:"my-provider","aria-describedby":"custom-provider-id-hint"}),(0,r.jsx)("span",{id:"custom-provider-id-hint",children:(0,r.jsx)(ly,{children:n.has(j)?g("models.providerIdTaken"):g("models.providerIdFormat")})}),(0,r.jsxs)("div",{className:"models-form-actions",children:[(0,r.jsx)(la,{size:"small",onClick:()=>h(!1),children:g("i18n.cancel")}),(0,r.jsx)(la,{size:"small",type:"submit",variant:"primary",disabled:!S,children:g("models.createProvider")})]})]}),v.length>0&&(0,r.jsx)("div",{className:"models-card-group",children:g("i18n.subscriptions")}),v.map(e=>C(e.id,e.name,g("models.kindOAuth"),(0,r.jsx)(lh,{id:e.id,size:28}),()=>{s(e.id),a()})),y.length>0&&(0,r.jsx)("div",{className:"models-card-group",children:g("models.kindApiKey")}),y.map(e=>C(e.id,e.displayName,g("models.modelCount",{count:e.modelCount}),(0,r.jsx)(lh,{id:e.id,size:28}),()=>{l(e.id),a()}))]})})}function lL({catalog:e,listedRefs:t,mode:n,providerLabel:s,saving:l,error:o,onClose:a,onApply:d}){let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(""),[p,m]=(0,i.useState)(new Set),g=lM(),f=u.trim().toLocaleLowerCase(),x=e.filter(e=>!f||e.id.toLocaleLowerCase().includes(f)||e.name?.toLocaleLowerCase().includes(f)),v=e=>t.has(sG(e.provider,e.id)),y=new Map;for(let e of x){let t=y.get(e.provider)??[];t.push(e),y.set(e.provider,t)}return(0,r.jsxs)(lj,{title:c("models.pickModels"),description:"replace"===n?c("models.pickReplaceHint"):c("models.pickAddHint"),onClose:a,footer:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"models-hint",children:c("models.pickSelected",{count:p.size})}),(0,r.jsxs)("span",{className:"models-form-actions",children:[(0,r.jsx)(la,{onClick:a,children:c("i18n.cancel")}),(0,r.jsx)(la,{variant:"primary",disabled:0===p.size||l,onClick:()=>d([...p]),children:c("models.pickApply",{count:p.size})})]})]}),children:[(0,r.jsx)("input",{ref:g,className:"models-input",value:u,onChange:e=>h(e.target.value),placeholder:c("models.pickFilterPlaceholder"),"aria-label":c("models.pickFilter")}),!x.some(e=>!v(e))&&(0,r.jsx)("p",{className:"models-empty",children:c("models.noExtraModels")}),[...y.entries()].map(([e,t])=>{let n=t.filter(e=>!v(e)).map(e=>sG(e.provider,e.id)),i=n.length>0&&n.every(e=>p.has(e));return(0,r.jsxs)("section",{className:"models-picker-group",children:[(0,r.jsxs)("label",{className:"models-picker-head",children:[(0,r.jsx)("input",{type:"checkbox",checked:i,disabled:0===n.length,onChange:()=>m(e=>{let t=new Set(e);for(let e of n)i?t.delete(e):t.add(e);return t})}),(0,r.jsx)(lh,{id:e,size:12}),(0,r.jsx)("span",{children:s(e)}),(0,r.jsx)("span",{className:"models-count",children:t.length})]}),t.map(e=>{let t=sG(e.provider,e.id),n=v(e);return(0,r.jsxs)("label",{className:`models-row${n?" is-disabled":""}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:n||p.has(t),disabled:n,onChange:()=>m(e=>{let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n})}),(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsx)("span",{className:"models-row-title",children:e.name||e.id}),e.name&&e.name!==e.id&&(0,r.jsx)("code",{className:"models-row-sub",children:e.id})]}),n&&(0,r.jsx)("span",{className:"models-tag",children:c("models.alreadyInChat")})]},t)})]},e)}),o&&(0,r.jsx)(lb,{tone:"danger",children:o})]})}let l$=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function lR(e){return{id:e.id,name:e.name,api:e.api,reasoning:e.reasoning,thinkingLevelMap:e.thinkingLevelMap,input:e.input,contextWindow:e.contextWindow,maxTokens:e.maxTokens,cost:e.cost,headers:e.headers,compat:e.compat}}function lW({providerId:e,provider:t,builtIn:n,namePlaceholder:i,onChange:s}){let{t:l}=(0,w.s)(),o=(e,n)=>s({...t,[e]:n});return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsxs)(s3,{label:l("models.displayName"),children:[(0,r.jsx)(lp,{value:t.name??"",onChange:e=>o("name",e.trim()||void 0),placeholder:i}),(0,r.jsx)(ly,{children:l("models.providerIdHint",{id:e})})]}),(0,r.jsx)(s3,{label:l("models.apiProtocol"),children:n?(0,r.jsx)(lf,{value:t.api??"",onChange:e=>o("api",e||void 0),options:l$}):(0,r.jsx)(lf,{value:t.api??"openai-completions",onChange:e=>o("api",e),options:l$,required:!0})})]}),(0,r.jsx)(s3,{label:l("models.baseUrl"),children:(0,r.jsx)(lp,{value:t.baseUrl??"",onChange:e=>o("baseUrl",e||void 0),placeholder:n?l("models.builtInDefault"):"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(s3,{label:l("models.apiKeyTitle"),children:[(0,r.jsx)(lm,{value:t.apiKey??"",onChange:e=>o("apiKey",e||void 0),placeholder:l(n?"models.builtInKeyPlaceholder":"models.endpointKeyPlaceholder"),mono:!0}),(0,r.jsx)(ly,{children:l("models.endpointKeyHint")})]}),(0,r.jsxs)(s3,{label:l("models.headers"),children:[(0,r.jsx)(lw,{headers:t.headers,onChange:e=>o("headers",e)}),(0,r.jsx)(ly,{children:l("models.providerHeadersHelp")})]})]})}function lz({providerId:e,provider:t,onAddModels:n,onClose:s}){let{t:l}=(0,w.s)(),[o,a]=(0,i.useState)({phase:"idle"}),[d,c]=(0,i.useState)(""),[u,h]=(0,i.useState)([]),p=(0,i.useRef)(0),m=(0,i.useRef)(null),g=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim())return;let n=++p.current;a({phase:"loading"}),h([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==p.current)return;if(!r.ok||i.error||!i.models)return void a({phase:"error",message:i.error??`HTTP ${r.status}`});a({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==p.current)return;a({phase:"error",message:e instanceof Error?e.message:String(e)})}},[e,t]);(0,i.useEffect)(()=>{g()},[e,t.baseUrl,t.api,t.apiKey]);let f=new Set((t.models??[]).map(e=>e.id)),x="success"===o.phase?o.models:[],v=d.trim().toLocaleLowerCase(),y=x.filter(e=>!v||e.id.toLocaleLowerCase().includes(v)||e.name?.toLocaleLowerCase().includes(v)),b=y.slice(0,300),k=b.filter(e=>!f.has(e.id)).map(e=>e.id),j=u.filter(e=>!f.has(e)).length,S=k.length>0&&k.every(e=>u.includes(e)),C=!S&&k.some(e=>u.includes(e));return(0,i.useEffect)(()=>{m.current&&(m.current.indeterminate=C)},[C]),(0,r.jsxs)("div",{className:"models-discovery",children:[(0,r.jsxs)("div",{className:"models-discovery-header",children:[(0,r.jsx)("strong",{children:l("models.discoveryTitle")}),(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:s,children:l("i18n.close")})]}),"loading"===o.phase&&(0,r.jsx)("p",{className:"models-muted",children:l("models.discoveryFetching")}),"error"===o.phase&&(0,r.jsx)(lb,{tone:"danger",action:(0,r.jsx)(la,{size:"small",onClick:()=>void g(),children:l("models.retry")}),children:o.message}),"success"===o.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{className:"models-input",value:d,onChange:e=>c(e.target.value),placeholder:l("models.discoveryFilterPlaceholder",{count:o.models.length}),"aria-label":l("models.discoveryFilter")}),(0,r.jsxs)("div",{className:"models-list models-discovery-list",children:[(0,r.jsxs)("label",{className:"models-row models-discovery-all",children:[(0,r.jsx)("input",{ref:m,type:"checkbox",checked:S,disabled:0===k.length,onChange:()=>{let e=new Set(k);h(t=>S?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...k])))}}),l("models.discoverySelectShown")]}),0===b.length?(0,r.jsx)("div",{className:"models-row models-muted",children:l("models.discoveryNoMatches")}):b.map(e=>{let t=f.has(e.id);return(0,r.jsxs)("label",{className:`models-row${t?" is-disabled":""}`,children:[(0,r.jsx)("input",{type:"checkbox",checked:u.includes(e.id)||t,disabled:t,onChange:()=>{var t;return t=e.id,void h(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])}}),(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsx)("span",{className:"models-row-title",children:e.name??e.id}),e.name&&(0,r.jsx)("code",{className:"models-row-sub",children:e.id})]}),t&&(0,r.jsx)("span",{className:"models-tag",children:l("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{className:"models-discovery-footer",children:[(0,r.jsx)("span",{className:"models-hint",title:o.endpoint,children:y.length>b.length?l("models.discoveryShowing",{shown:b.length,total:y.length}):l("models.discoveryFetched",{count:o.models.length})}),(0,r.jsx)(la,{size:"small",variant:"primary",onClick:()=>{if("success"!==o.phase)return;let e=new Set(u),t=o.models.filter(t=>e.has(t.id)&&!f.has(t.id));0!==t.length&&(n(t),h([]))},disabled:0===j,children:j?l("models.discoveryAddSelectedCount",{count:j}):l("models.discoveryAddSelected")})]})]})]})}let lP={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function lA(e){return e.compat?.thinkingFormat==="deepseek"}function lD({providerName:e,provider:t,model:n,onChange:s,onDelete:l,lockId:o=!1,cwd:a=null,shadowsBuiltIn:d=!1}){let[c,u]=(0,i.useState)({phase:"idle"}),{t:h}=(0,w.s)(),[p,m]=(0,i.useState)({phase:"idle"}),[g,f]=(0,i.useState)(!1),[x,v]=(0,i.useState)(()=>sJ(n.cost)),y=(0,i.useRef)(x),[b,k]=(0,i.useState)(!1),j=(0,i.useRef)(0),S=(0,i.useRef)(null),C=(0,i.useRef)(n.cost),N=(e,t)=>s({...n,[e]:t}),E=(()=>{if("idle"===c.phase||"testing"===c.phase)return null;let e=[void 0!==c.latencyMs?`${c.latencyMs}ms`:null,void 0!==c.status?`HTTP ${c.status}`:null].filter(Boolean);return"success"===c.phase?[h("i18n.connected"),...e,c.responseText||null].filter(Boolean).join(" \xb7 "):[h("i18n.failed"),...e,c.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{u({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{j.current+=1,m({phase:"idle"}),S.current=null},[e,t.baseUrl,n.id]);let I=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==c.phase){u({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n,cwd:a??void 0})}),i=await r.json();if(!r.ok||!i.ok)return void u({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});u({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){u({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,c.phase,a]),M=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===p.phase)return;let i=++j.current;m({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 o=await fetch(`/api/models-config/catalog?${l}`),d=await o.json();if(i!==j.current)return;if(!o.ok||d.error||!d.recommendation)return void m({phase:"error",message:d.error??`HTTP ${o.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??{}},s=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],s+=1);let l=sY(sJ(i));s>0&&l&&(n.cost={...i,...l},r+=s)}return{model:n,appliedCount:r}}(n,d.recommendation.preset);c.appliedCount>0&&(S.current=n,s(c.model)),f(!1),m({phase:"success",recommendation:d.recommendation,appliedCount:c.appliedCount})}catch(e){if(i!==j.current)return;m({phase:"error",message:e instanceof Error?e.message:String(e)})}},[p.phase,n,s,t.baseUrl,e,a]),T=(()=>{if("success"!==p.phase)return null;let{recommendation:t,appliedCount:n}=p,r=n>0?h("models.catalogFilled",{count:n}):h("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?h("models.catalogNoExactMatch"):h("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?h("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?h("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):h("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),L="error"===p.phase?p.message:T,$="error"===p.phase?"danger":"success"===p.phase&&"unreliable"===p.recommendation.price.status?"warning":"info",R=[{key:"input",label:h("models.costInput")},{key:"output",label:h("models.costOutput")},{key:"cacheRead",label:h("models.costCacheRead")},{key:"cacheWrite",label:h("models.costCacheWrite")}],W=new Set(Object.keys(n.compat??{})),z=0;lA(n)&&(z+=1,W.delete("thinkingFormat"),W.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&(z+=1,W.delete("supportsDeveloperRole")),z+=W.size;let P=[n.api?`API: ${n.api}`:null,Object.keys(n.headers??{}).length?h("models.headersSummary",{count:Object.keys(n.headers??{}).length}):null,z?h("models.compatSummary",{count:z}):null,Object.keys(n.thinkingLevelMap??{}).length?h("models.thinkingSummary",{count:Object.keys(n.thinkingLevelMap??{}).length}):null].filter(e=>!!e),A=P.length?P.join(" \xb7 "):h("models.providerDefaults");return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("header",{className:"settings-detail-header",children:[(0,r.jsx)("h2",{className:"settings-detail-title",children:n.name||n.id||h("models.untitledModel")}),(0,r.jsx)("div",{className:"settings-detail-meta",children:(0,r.jsx)("span",{className:"config-scope-tag",children:o?h("models.kindOverride"):h("models.kindDefinition")})})]}),d&&l&&(0,r.jsx)(lb,{tone:"warning",action:(0,r.jsx)(la,{size:"small",onClick:l,children:h("models.restoreBuiltIn")}),children:h("models.replacesBuiltInHint")}),E&&(0,r.jsx)(lb,{tone:"success"===c.phase?"success":"danger",children:(0,r.jsx)("span",{className:"models-ellipsis",title:E,children:E})}),(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsx)(s3,{label:h("models.modelId"),children:(0,r.jsx)(lp,{value:n.id,onChange:e=>N("id",e),placeholder:"model-id",mono:!0,disabled:o})}),(0,r.jsx)(s3,{label:h("models.displayName"),children:(0,r.jsx)(lp,{value:n.name??"",onChange:e=>N("name",e||void 0),placeholder:n.id||h("models.displayName")})})]}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(s9,{label:h("models.catalogFill"),description:(0,r.jsxs)(r.Fragment,{children:[h("models.catalogFillDescription")," ",(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",className:"settings-link",children:"models.dev ↗"})]}),children:(0,r.jsx)(la,{size:"small",onClick:()=>void M(),disabled:!n.id.trim()||"loading"===p.phase,children:"loading"===p.phase?h("models.catalogFilling"):h("models.catalogFillAction")})}),(0,r.jsx)(s9,{label:h("i18n.testConnection"),description:h("models.testDescription"),children:(0,r.jsx)(la,{size:"small",onClick:I,disabled:!n.id.trim()||"testing"===c.phase,children:"testing"===c.phase?h("i18n.checking"):h("models.testAction")})})]}),L&&(0,r.jsx)(lb,{tone:$,action:S.current&&(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>{let e=S.current;e&&(S.current=null,s(e),m({phase:"idle"}))},children:h("models.catalogUndo")}),children:(0,r.jsx)("span",{className:"models-ellipsis",title:L,children:L})}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(lv,{title:h("models.capabilities")}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(lx,{label:h("models.reasoning"),description:h("models.reasoningDescription"),checked:n.reasoning??!1,onChange:e=>N("reasoning",e||void 0)}),(0,r.jsx)(lx,{label:h("models.imageInput"),description:h("models.imageInputDescription"),checked:n.input?.includes("image")??!1,onChange:e=>N("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(lv,{title:h("models.modelSpecs")}),(0,r.jsxs)("div",{className:"models-form-grid",children:[(0,r.jsx)(s3,{label:h("models.contextWindow"),children:(0,r.jsx)(lg,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>N("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(s3,{label:h("models.maxOutputTokens"),children:(0,r.jsx)(lg,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>N("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{className:"models-section-header",children:[(0,r.jsx)("span",{className:"config-field-label",children:h("models.costPerMillion")}),(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>{if(g)return void f(!1);C.current=n.cost;let e=sJ(n.cost);y.current=e,v(e),f(!0)},"aria-expanded":g,children:g?h("models.finishEditingCosts"):h("models.editCosts")})]}),g?(0,r.jsxs)("div",{className:"models-cost-grid",children:[R.map(({key:e,label:t})=>(0,r.jsx)(s3,{label:t,children:(0,r.jsx)(lg,{value:x[e],onChange:t=>{let r,i,l;return i=sY(r={...y.current,[e]:t}),l={...n},void(y.current=r,v(r),i?(l.cost={...C.current??{},...i},C.current=l.cost):delete l.cost,s(l))},placeholder:"0"})},e)),sZ(x)&&!sY(x)&&(0,r.jsx)("p",{"aria-live":"polite",className:"models-hint is-warning models-grid-full",children:h("models.costAllRequired")})]}):(0,r.jsx)("div",{className:"models-cost-grid",children:R.map(({key:e,label:t})=>{let i;return(0,r.jsxs)("div",{className:"models-cost-cell",children:[(0,r.jsx)("span",{className:"models-hint",children:t}),(0,r.jsx)("span",{className:`models-cost-value${n.cost?.[e]===void 0?" is-missing":""}`,children:void 0===(i=n.cost?.[e])?h("models.notProvided"):`$${String(i)}`})]},e)})})]}),(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsxs)("button",{type:"button",className:"models-disclosure",onClick:()=>k(e=>!e),"aria-expanded":b,"aria-controls":"model-advanced-settings",children:[(0,r.jsxs)("span",{className:"models-disclosure-copy",children:[(0,r.jsx)("strong",{children:h("models.advancedSettings")}),(0,r.jsx)("span",{children:A})]}),(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"models-disclosure-chevron",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),b&&(0,r.jsxs)("div",{id:"model-advanced-settings",className:"models-form",children:[!o&&(0,r.jsx)(s3,{label:h("models.apiOverride"),children:(0,r.jsx)(lf,{value:n.api??"",onChange:e=>N("api",e||void 0),options:l$})}),(0,r.jsxs)(s3,{label:h("models.headers"),children:[(0,r.jsx)(lw,{headers:n.headers,onChange:e=>N("headers",e)}),(0,r.jsx)(ly,{children:h("models.headersHelp")})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lv,{title:h("models.compatibility")}),(0,r.jsxs)("div",{className:"models-switch-list",children:[(0,r.jsx)(lx,{label:h("models.deepSeekThinkingCompat"),checked:lA(n),onChange:e=>s(function(e,t){if(t)return{...e,compat:{...e.compat??{},...lP}};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)(lx,{label:h("models.developerRole"),checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>s({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})})]}),(0,r.jsx)(lv,{title:h("models.thinkingLevelMap"),actions:n.thinkingLevelMap&&(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>N("thinkingLevelMap",void 0),children:h("models.clearAll")})}),(0,r.jsx)(lk,{value:n.thinkingLevelMap,onChange:e=>N("thinkingLevelMap",e)})]})]})]}),l&&(0,r.jsx)(s7,{children:(0,r.jsx)(s9,{label:h("models.deleteDefinition"),description:h("models.deleteDefinitionDescription"),children:(0,r.jsx)(la,{size:"small",variant:"danger",onClick:l,children:h("i18n.delete")})})})]})}function lF({onClose:e,embedded:t=!1,cwd:n=null,onModelsChanged:s,onDirtyChange:l}){var o;let a,d,{t:c}=(0,w.s)(),[u,h]=(0,i.useState)({providers:{}}),[p,m]=(0,i.useState)({providers:{}}),[g,f]=(0,i.useState)(!0),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(null),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[N,E]=(0,i.useState)({provider:null}),[I,M]=(0,i.useState)([]),[T,L]=(0,i.useState)([]),[$,R]=(0,i.useState)(!1),[W,z]=(0,i.useState)(null),[P,A]=(0,i.useState)(null),[D,F]=(0,i.useState)([]),[B,H]=(0,i.useState)(new Set),[O,U]=(0,i.useState)(null),[_,q]=(0,i.useState)(!1),[K,V]=(0,i.useState)(null),[J,Y]=(0,i.useState)(null),[Z,X]=(0,i.useState)(null),[G,Q]=(0,i.useState)({}),ee=(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]),et=(0,i.useCallback)(()=>{if(!n)return void F([]);let e=new URLSearchParams({cwd:n});return fetch(`/api/models-config/runtime?${e}`).then(e=>e.json()).then(e=>{Array.isArray(e.catalog)&&F(e.catalog),Array.isArray(e.builtIn)&&H(new Set(e.builtIn)),X(e.modelError??null)}).catch(()=>{})},[n]),en=(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?(V(null),U(t)):V(t.error??c("models.scopeError"))}).catch(()=>V(c("models.scopeError"))):void U(null),[n,c]);(0,i.useEffect)(()=>{if(!J)return;let e=setTimeout(()=>Y(null),4e3);return()=>clearTimeout(e)},[J]);let er=(0,i.useCallback)(()=>{ee(),et(),en()},[ee,et,en]);(0,i.useEffect)(()=>{let e=!1;return f(!0),Promise.all([fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};b(e.error??null),h(t),m(t)}).catch(e=>b(String(e))),ee(),et(),en()]).finally(()=>{e||f(!1)}),()=>{e=!0}},[ee,et,en]);let ei=JSON.stringify(u)!==JSON.stringify(p);(0,i.useEffect)(()=>{l?.(ei)},[ei,l]),(0,i.useEffect)(()=>{if(!ei)return;let e=e=>e.preventDefault();return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[ei]);let es=(0,i.useCallback)((e,t)=>{E({provider:e,...t?{model:t}:{}})},[]),el=(0,i.useCallback)(e=>{h(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),es(e)},[es]),eo=(0,i.useCallback)((e,t)=>{h(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),ea=(0,i.useCallback)(e=>{h(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),es(null)},[es]),ed=(0,i.useCallback)(e=>{let t=u.providers?.[e]?.models?.length??0;h(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),es(e,{kind:"definition",index:t})},[u.providers,es]),ec=(0,i.useCallback)((e,t)=>{h(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],s=new Set(i.map(e=>e.id));for(let e of t)s.has(e.id)||(s.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),eu=(0,i.useCallback)((e,t,n)=>{h(r=>{let i=r.providers?.[e]??{},s=[...i.models??[]];return s[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:s}}}})},[]),eh=(0,i.useCallback)((e,t,n)=>{let r=function(e,t){let n={};for(let i of sX){let s=t[i];if(void 0!==s){var r;r=e[i],JSON.stringify(s)!==JSON.stringify(r)&&(n[i]=s)}}return Object.keys(n).length>0?n:void 0}(lR(t),{...n,id:t.id});h(n=>{var i,s;let l,o=n.providers?.[e]??{},a={...o},d=(i=o.modelOverrides,s=t.id,l={...i??{}},delete l[s],r&&(l[s]=r),Object.keys(l).length>0?l:void 0);return d?a.modelOverrides=d:delete a.modelOverrides,{...n,providers:{...n.providers??{},[e]:a}}})},[]),ep=(0,i.useCallback)((e,t)=>{h(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}}}}),es(e)},[es]),em=(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]),eg=(0,i.useRef)(0),ef=(0,i.useCallback)(async()=>{let e=++eg.current,t=await em();return t&&e===eg.current&&U(t),t},[em]),ex=(0,i.useRef)(Promise.resolve()),ev=(0,i.useCallback)(e=>{if(!n)return Promise.resolve(!1);let t=ex.current.then(async()=>{let t=await em();if(!t)return V(c("models.scopeError")),!1;if(t.readOnly)return!1;let r=e(t);if(0===r.length)return V(c("models.keepOneModel")),!1;q(!0),V(null),Y(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 V("untrusted"===t.code?c("models.scopeReadOnly"):t.error??c("models.scopeError")),!1;return U(t),s?.(),!0}catch{return V(c("models.scopeError")),!1}finally{q(!1)}});return ex.current=t.catch(()=>!1),t},[n,em,s,c]),ey=(0,i.useCallback)(()=>{n&&O&&A("none"===O.source?"replace":"add")},[n,O]),eb=(0,i.useCallback)(async e=>{let t=!!O&&!s4(O?.patterns??[]);await ev(t=>(function(e){let t=sQ(e.patterns);if(s4(t)){let n,r;return r=(n=e.ref.trim()).slice(n.indexOf("/")+1),sQ(t).filter(e=>{let t=s1(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=>sG(e.provider,e.id)),pins:t.pins,ref:e}))&&t&&Y(c("models.listWritten"))},[ev,O,c]),ew=(0,i.useCallback)(async()=>{v(!0),j(null),C(!1);try{var e;let t=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),n=await t.json();if(!t.ok||n.error)return void j(n.error??`HTTP ${t.status}`);m(u),C(!0),setTimeout(()=>C(!1),2e3),et();let r=O?.defined,i=await ef(),l=r&&i?(e={patterns:r.length?O?.patterns??[]:[],before:new Set(r),after:new Set(i.defined)},sQ(e.patterns).filter(t=>{let n=s1(t);return null!==n&&void 0!==n.provider&&e.before.has(n.ref)&&!e.after.has(n.ref)})):[];l.length>0&&await ev(e=>e.patterns.filter(e=>!l.includes(e)))&&Y(c("models.removedWithDefinition",{count:l.length})),s?.()}catch(e){j(String(e))}finally{v(!1)}},[u,ef,s,et,ev,O,c]),ek=[y,Z].filter(Boolean).map(e=>String(e).split("\n")[0]).join(" \xb7 ")||null,ej=O?.visible??[],eS=new Set(ej.map(e=>sG(e.provider,e.id))),eC=new Set(D.map(e=>sG(e.provider,e.id))),eN=O?(a=new Set((o={patterns:O.patterns,visible:[...eS]}).visible),d=new Set(o.visible.map(e=>e.slice(e.indexOf("/")+1))),sQ(o.patterns).filter(e=>{let t=s1(e);return null!==t&&(t.provider?!a.has(t.ref):!d.has(t.id))})).filter(e=>!(O.ambiguous??[]).includes(e)):[],eE=new Set([...I.filter(e=>e.loggedIn).map(e=>e.id),...T.filter(e=>e.configured).map(e=>e.id)]),eI=N.provider,eM=[],eT=e=>{e&&!eM.includes(e)&&eM.push(e)};I.filter(e=>e.loggedIn).forEach(e=>eT(e.id)),T.filter(e=>e.configured).forEach(e=>eT(e.id)),Object.keys(u.providers??{}).forEach(eT),D.forEach(e=>eT(e.provider)),ej.forEach(e=>eT(e.provider)),eT(eI);let eL=eM.map(e=>{let t=I.find(t=>t.id===e),n=T.find(t=>t.id===e),r=u.providers?.[e],i=D.filter(t=>t.provider===e);return{id:e,label:r?.name??t?.name??n?.displayName??e,...t?{oauth:t}:{},...n?{apiKey:n}:{},...r?{json:r}:{},models:i,connected:eE.has(e)||i.length>0}}),e$=e=>ej.filter(t=>t.provider===e).length,eR=()=>n?O?(0,r.jsxs)(r.Fragment,{children:[O.readOnly&&(0,r.jsx)(lb,{tone:"warning",children:c("models.scopeReadOnly")}),J&&(0,r.jsx)(lb,{tone:"info",children:J}),K&&(0,r.jsx)(lb,{tone:"danger",children:K}),eN.length>0&&(0,r.jsx)(lB,{title:c("models.unavailable",{count:eN.length}),hint:c("models.unavailableHint"),entries:eN,readOnly:!!O.readOnly,onRemove:e=>void ev(t=>s2(t.patterns,e))}),(O.ambiguous?.length??0)>0&&(0,r.jsx)(lB,{title:c("models.ambiguous",{count:O.ambiguous?.length??0}),hint:c("models.ambiguousHint"),entries:O.ambiguous??[],readOnly:!!O.readOnly,onRemove:e=>void ev(t=>s2(t.patterns,e))})]}):K?(0,r.jsx)(lb,{tone:"danger",children:K}):null:(0,r.jsx)(lb,{children:c("models.scopeNoCwd")}),eW=e=>{let t=e.json,i=!!(e.oauth||e.apiKey),s=e.apiKey&&(!e.oauth||e.apiKey.configured||!e.oauth.loggedIn),l=t?.models??[],o=!!(t&&(t.name&&""!==t.name.trim()||t.api||t.baseUrl&&""!==t.baseUrl.trim()||t.apiKey&&""!==t.apiKey.trim()||t.headers&&Object.keys(t.headers).length>0)),a=G[e.id]??o,d=[...e.models.map(e=>{let t=l.findIndex(t=>t.id===e.id);return{id:e.id,name:e.name,ref:t>=0?{kind:"definition",index:t}:{kind:"runtime",id:e.id},usable:!0,definition:t>=0}}),...l.map((e,t)=>({model:e,index:t})).filter(({model:t})=>!eC.has(`${e.id}/${t.id}`)).map(({model:e,index:t})=>({id:e.id,name:e.name,ref:{kind:"definition",index:t},usable:!1,definition:!0}))],u=t&&(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(lv,{title:i?c("models.sectionEndpointOverride"):c("models.sectionEndpoint"),hint:i?c("models.sectionOverrideHint"):void 0,actions:i?(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>Q(t=>({...t,[e.id]:!a})),children:a?c("i18n.collapse"):c("i18n.expand")}):void 0}),(!i||a)&&(0,r.jsx)(lW,{providerId:e.id,provider:t,builtIn:i,namePlaceholder:e.oauth?.name??e.apiKey?.displayName??e.id,onChange:t=>eo(e.id,t)},e.id)]}),h=e.oauth?.loggedIn?c("models.kindOAuth"):e.apiKey?.configured?c("models.kindApiKey"):null;return(0,r.jsxs)("div",{className:"models-form",children:[(0,r.jsxs)("header",{className:"settings-detail-header",children:[(0,r.jsxs)("h2",{className:"settings-detail-title models-provider-label",children:[(0,r.jsx)(lh,{id:e.id,size:16}),e.label]}),(0,r.jsxs)("div",{className:"settings-detail-meta",children:[h&&(0,r.jsx)("span",{className:"config-scope-tag",children:h}),e.oauth&&!e.apiKey&&!e.oauth.loggedIn&&(0,r.jsx)("span",{className:"config-scope-tag",children:c("models.kindOAuth")}),t&&(0,r.jsx)("span",{className:"config-scope-tag",children:i?c("models.kindOverridden"):c("models.kindCustom")})]})]}),(e.oauth||s)&&(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(lv,{title:c("models.sectionConnection")}),e.oauth&&(0,r.jsx)(lN,{provider:e.oauth,onRefresh:er,cwd:n},e.oauth.id),s&&e.apiKey&&(0,r.jsx)(lE,{provider:e.apiKey,onRefresh:er,cwd:n},`${e.apiKey.id}-key`)]}),!i&&u,(0,r.jsxs)("section",{className:"models-section",children:[(0,r.jsx)(lv,{title:(0,r.jsx)(lr,{label:c("models.sectionModelsTitle"),count:d.length}),hint:n&&O?c("models.chatSwitchHint"):void 0,actions:t&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(la,{size:"small",disabled:!t.baseUrl?.trim(),title:t.baseUrl?.trim()?void 0:c("models.discoveryNeedsBaseUrl"),onClick:()=>z(e.id),children:c("models.discoveryFetch")}),(0,r.jsx)(la,{size:"small",onClick:()=>ed(e.id),children:c("models.newModel")})]})}),t&&W===e.id&&(0,r.jsx)(lz,{providerId:e.id,provider:t,onAddModels:t=>ec(e.id,t),onClose:()=>z(null)}),0===d.length?(0,r.jsx)("p",{className:"models-empty",children:t?c("models.noDefinitions"):c("models.connectToSeeModels")}):(0,r.jsx)("div",{className:"models-list",children:d.map(t=>{let s,l,o,a,d=sG(e.id,t.id);return(0,r.jsxs)("div",{className:"models-row",children:[(s=t.name&&t.name!==t.id?t.name:t.id||c("models.untitledModel"),l=t.name&&t.name!==t.id?t.id:void 0,o=(0,r.jsxs)(r.Fragment,{children:[t.definition&&B.has(d)?(0,r.jsx)("span",{className:"models-tag is-warning",title:c("models.replacesBuiltInHint"),children:c("models.replacesBuiltIn")}):i&&t.definition&&(0,r.jsx)("span",{className:"models-tag",children:c("models.kindDefinition")}),!t.usable&&(0,r.jsx)("span",{className:"models-tag is-warning",children:c("models.notUsable")}),O?.pins[d]&&(0,r.jsx)("span",{className:"models-tag",children:c("models.thinkingPin",{level:O.pins[d]})})]}),a=()=>es(e.id,t.ref),(0,r.jsxs)("button",{type:"button",className:"models-row-main models-row-button",title:c("models.editParams"),onClick:a,children:[(0,r.jsxs)("span",{className:"models-row-text",children:[(0,r.jsxs)("span",{className:"models-row-title-line",children:[(0,r.jsx)("span",{className:"models-row-title",children:s}),o]}),l&&(0,r.jsx)("code",{className:"models-row-sub",children:l})]}),(0,r.jsx)("svg",{className:"models-row-chevron",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 18 6-6-6-6"})})]})),t.id&&((e,t)=>{if(!n||!O)return null;let i=eS.has(e);return(0,r.jsx)("span",{className:"models-row-switch",children:(0,r.jsx)(ld,{checked:i,disabled:O.readOnly||!t&&!i,loading:_,label:c("models.showInChat"),onChange:t=>{t?ev(t=>s0(t.patterns,e)):eb(e)}})})})(d,t.usable)]},`${t.ref.kind}:${t.id}:${"definition"===t.ref.kind?t.ref.index:""}`)})})]}),i&&u,t&&(0,r.jsx)(s7,{children:(0,r.jsx)(s9,{label:i?c("models.deleteOverride"):c("models.deleteEndpoint"),description:i?c("models.deleteOverrideDescription"):c("models.deleteEndpointDescription"),children:(0,r.jsx)(la,{size:"small",variant:"danger",onClick:()=>{ea(e.id),i&&es(e.id)},children:i?c("i18n.remove"):c("i18n.delete")})})})]})};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(s8,{embedded:t,title:c("common.models"),closeLabel:c("i18n.close"),onClose:e,children:[g?(0,r.jsx)("div",{className:"models-loading",role:"status","aria-busy":"true",children:(0,r.jsx)("span",{children:c("i18n.loading")})}):(0,r.jsx)("div",{className:"models-ready settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:(()=>{let e=eL.find(e=>e.id===eI),t=e?N.model:void 0;if(e)return(0,r.jsxs)(r.Fragment,{children:[!t&&(0,r.jsx)(lt,{label:c("common.models"),onClick:()=>es(null)}),eR(),t?((e,t)=>{let i=(0,r.jsxs)("button",{type:"button","data-settings-back":!0,className:"models-breadcrumb",onClick:()=>es(e.id),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:"m15 18-6-6 6-6"})}),(0,r.jsx)(lh,{id:e.id,size:13}),e.label]});if("runtime"===t.kind){var s;let l=D.find(n=>n.provider===e.id&&n.id===t.id);if(!l)return null;let o=u.providers?.[e.id]??{},a=o.modelOverrides?.[l.id],d=(s=lR(l),a?{...s,...a,id:s.id,cost:a.cost?{...s.cost,...a.cost}:s.cost}:{...s,id:s.id});return(0,r.jsxs)(r.Fragment,{children:[i,(0,r.jsx)(lD,{providerName:e.id,provider:o,model:d,lockId:!0,cwd:n,onChange:t=>eh(e.id,l,t)},`${e.id}-${t.id}`)]})}let l=u.providers?.[e.id],o=l?.models?.[t.index];return l&&o?(0,r.jsxs)(r.Fragment,{children:[i,(0,r.jsx)(lD,{providerName:e.id,provider:l,model:o,cwd:n,onChange:n=>eu(e.id,t.index,n),onDelete:()=>ep(e.id,t.index),shadowsBuiltIn:B.has(`${e.id}/${o.id}`)},`${e.id}-${t.index}`)]}):null})(e,t)??eW(e):eW(e)]});let i=eL.filter(e=>e.connected),s=eL.filter(e=>!e.connected),l=e=>{let t;return(0,r.jsx)(le,{label:(0,r.jsxs)("span",{className:"models-provider-label",children:[(0,r.jsx)(lh,{id:e.id,size:13}),e.label,(t=e.id,JSON.stringify(u.providers?.[t]??null)!==JSON.stringify(p.providers?.[t]??null)&&(0,r.jsx)("span",{className:"models-dirty-dot",title:c("models.unsavedProvider")}))]}),description:e.oauth?.loggedIn?c("models.kindOAuth"):e.apiKey?.configured?c("models.kindApiKey"):e.json?c("models.kindCustom"):c("models.notConnected"),muted:!e.connected,onOpen:()=>es(e.id),children:O&&e.models.length>0&&(0,r.jsx)("span",{className:"settings-row-status",title:c("models.inChatCount",{count:e$(e.id),total:e.models.length}),children:c("models.inChatShort",{count:e$(e.id),total:e.models.length})})},e.id)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"settings-toolbar",children:[(0,r.jsx)("span",{className:"settings-toolbar-summary",children:c("models.summary",{count:ej.length})}),(0,r.jsx)("span",{className:"settings-toolbar-spacer"}),(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>ey(),disabled:!n||!O||O.readOnly,children:c("models.pickChatModels")}),(0,r.jsx)(la,{size:"small",onClick:()=>R(!0),children:c("models.addProvider")})]}),eR(),0===eL.length?(0,r.jsx)(s6,{children:c("models.noProviders")}):(0,r.jsxs)(r.Fragment,{children:[i.length>0&&(0,r.jsx)(s7,{title:(0,r.jsx)(lr,{label:c("models.groupConnected"),count:i.length}),children:i.map(l)}),s.length>0&&(0,r.jsx)(s7,{title:(0,r.jsx)(lr,{label:c("models.groupNotConnected"),count:s.length}),children:s.map(l)})]})]})})()})}),(ei||x||S||k||ek)&&(0,r.jsxs)(s5,{status:k||ek?(0,r.jsx)("span",{className:"models-footer-status is-danger",title:ek??void 0,children:k||ek}):ei?(0,r.jsxs)("span",{className:"models-footer-status",children:[(0,r.jsx)("span",{className:"models-dirty-dot"}),c("models.unsavedChanges")]}):null,children:[!t&&(0,r.jsx)(la,{onClick:e,children:c("i18n.cancel")}),ei&&!x&&(0,r.jsx)(la,{onClick:()=>{h(p),j(null),!N.provider||p.providers?.[N.provider]||D.some(e=>e.provider===N.provider)?N.provider&&es(N.provider):es(null)},children:c("models.discardChanges")}),(ei||x||S)&&(0,r.jsxs)(la,{variant:"primary",onClick:ew,disabled:x||S,className:S?"is-success":void 0,children:[S&&(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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:S?c("i18n.saved"):x?c("i18n.saving"):c("models.saveModelsJson")})]})]})]}),$&&(0,r.jsx)(lT,{oauthProviders:I,apiKeyProviders:T,existingIds:new Set([...Object.keys(u.providers??{}),...I.map(e=>e.id),...T.map(e=>e.id),...D.map(e=>e.provider)]),onSelectOAuth:e=>es(e),onSelectApiKey:e=>es(e),onAddCustom:el,onClose:()=>R(!1)}),P&&(0,r.jsx)(lL,{catalog:D,listedRefs:"replace"===P?new Set:eS,mode:P,providerLabel:e=>eL.find(t=>t.id===e)?.label??e,saving:_,error:K,onClose:()=>A(null),onApply:e=>{A(null),ev(t=>"replace"===P?e:e.reduce((e,t)=>s0(e,t),t.patterns))}})]})}function lB({title:e,hint:t,entries:n,readOnly:i,onRemove:s}){let{t:l}=(0,w.s)();return(0,r.jsxs)(lb,{tone:"warning",children:[(0,r.jsx)("strong",{children:e}),(0,r.jsx)("span",{className:"models-notice-hint",children:t}),(0,r.jsx)("div",{className:"models-notice-list",children:n.map(e=>(0,r.jsxs)("div",{className:"models-notice-entry",children:[(0,r.jsx)("code",{children:s1(e)?.id??e}),!i&&(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>s(e),children:l("models.removeFromChat")})]},e))})]})}function lH(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lO(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function lU(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function l_(e){return e?e.slice(0,8):"unknown"}function lq({skill:e,cwd:t,onToggle:n,toggling:i,saveError:s,updateStatus:l,checkingUpdate:o,updating:a,updateError:d,onCheckUpdate:c,onUpdate:u,onDelete:h,deleting:p,deleteError:m}){let{t:g}=(0,w.s)(),f=lO(e),x=!e.disableModelInvocation,v=l?.state==="update-available",y=o?g("i18n.checking"):l&&!v?"up-to-date"===l.state?g("i18n.upToDate"):"unsupported"===l.state?g("i18n.automaticChecksUnavailable"):l.message||g("i18n.checkFailed"):null;return(0,r.jsxs)(li,{title:e.name,meta:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`config-scope-tag${"project"===f?" is-project":""}`,children:f}),(0,r.jsx)("span",{className:"config-detail-path",title:e.filePath,children:function(e){if("project"===f&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return lH(e)}(e.filePath)})]}),description:e.description,children:[(0,r.jsxs)(s7,{children:[(0,r.jsx)(s9,{label:g("skills.modelInvocation"),description:g(x?"skills.modelInvocationOn":"i18n.hiddenButInvocable"),children:(0,r.jsx)(ld,{checked:x,loading:i,label:g("skills.modelInvocation"),onChange:()=>n(e)})}),s&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:s}),e.install&&(0,r.jsx)(s9,{label:g("i18n.version"),description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"is-mono",children:l_(l?.currentVersion??e.install.versionHash)}),v&&(0,r.jsxs)(r.Fragment,{children:[" → ",(0,r.jsx)("span",{className:"is-mono is-accent",children:l_(l.latestVersion)})]}),y&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{className:l?.state==="error"?"is-error":void 0,children:y})]})]}),children:v?(0,r.jsx)(la,{variant:"primary",size:"small",onClick:u,disabled:a||o,children:g(a?"i18n.updating":"i18n.update")}):e.install.canCheckForUpdates&&(0,r.jsx)(la,{size:"small",onClick:c,disabled:o||a,children:g("i18n.check")})}),d&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:d}),e.install?.skillsShUrl&&(0,r.jsx)(s9,{label:g("skills.source"),children:(0,r.jsxs)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,className:"settings-link",children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),(0,r.jsxs)(s7,{children:[(0,r.jsx)(s9,{label:g("skills.deleteTitle"),description:g(e.removable?"skills.deleteDescription":"skills.notRemovable"),children:e.removable&&(0,r.jsx)(la,{variant:"danger",size:"small",onClick:h,disabled:p,children:g("i18n.delete")})}),m&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:m})]})]})}function lK({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:s}){let{t:l}=(0,w.s)(),[o,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(null),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(new Set),[k,j]=(0,i.useState)("global"),S=(0,i.useRef)(null);(0,i.useEffect)(()=>{S.current?.focus()},[]);let C=(0,i.useCallback)(async e=>{if(e.trim()){h(!0),m(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 m(n.error);c(n.results??[]),0===(n.results??[]).length&&m(l("skills.noResults"))}catch(e){m(String(e))}finally{h(!1)}}},[l]),N=(0,i.useCallback)(async t=>{f(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:k,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);b(e=>new Set(e).add(`${k}:${t}`)),s()}catch(e){v(String(e))}finally{f(null)}},[s,k,e]),E="global"===k?"~/.pi/agent/skills/":`${lH(e)}/.pi/skills/`;return(0,r.jsxs)(li,{title:l("i18n.addSkill"),description:(0,r.jsxs)(r.Fragment,{children:[l("skills.addDescription")," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",className:"settings-link",children:"skills.sh ↗"})]}),children:[(0,r.jsxs)(s7,{children:[(0,r.jsxs)("div",{className:"settings-search",children:[(0,r.jsx)("input",{ref:S,className:"settings-search-input",value:o,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&C(o)},placeholder:l("i18n.skillSearchPlaceholder"),"aria-label":l("i18n.skillSearchPlaceholder")}),(0,r.jsx)(la,{variant:"primary",onClick:()=>C(o),disabled:u||!o.trim(),children:u?l("i18n.searching"):l("i18n.search")})]}),(0,r.jsx)(s9,{label:l("skills.installTo"),description:(0,r.jsx)("span",{className:"is-mono",children:E}),children:(0,r.jsx)(ls,{label:l("skills.installTo"),value:k,onChange:j,options:[{value:"global",label:l("skills.scope.global")},{value:"project",label:l("skills.scope.project"),disabled:!n,title:n?void 0:l("trust.projectScopeUnavailable")}]})}),p&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:p}),x&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:x})]}),d.length>0&&(0,r.jsx)(s7,{title:`${l("skills.results")} \xb7 ${d.length}`,children:d.map(e=>{let n=t[k].has(e.package)||y.has(`${k}:${e.package}`),i=g===e.package,s=e.package.indexOf("@"),o=s>-1?e.package.slice(0,s):e.package,a=s>-1?e.package.slice(s+1):null;return(0,r.jsx)(s9,{label:a??o,description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"is-mono",children:o})," \xb7 ",e.installs,e.url&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",className:"settings-link",children:"skills.sh ↗"})]})]}),children:n?(0,r.jsxs)("span",{className:"settings-row-status is-success",children:["✓ ",l("i18n.installed")]}):(0,r.jsx)(la,{size:"small",onClick:()=>void N(e.package),disabled:null!==g,children:i?l("i18n.installing"):l("i18n.install")})},e.package)})})]})}function lV({cwd:e,onClose:t,embedded:n=!1}){let{t:s}=(0,w.s)(),[l,o]=(0,i.useState)([]),[a,d]=(0,i.useState)(!0),[c,u]=(0,i.useState)(null),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(new Set),[f,x]=(0,i.useState)(null),[v,y]=(0,i.useState)("list"),[b,k]=(0,i.useState)(""),[j,S]=(0,i.useState)({}),[C,N]=(0,i.useState)(new Set),[E,I]=(0,i.useState)(!1),[M,T]=(0,i.useState)(null),[L,$]=(0,i.useState)(null),[R,W]=(0,i.useState)(!0),[z,P]=(0,i.useState)(null),[A,D]=(0,i.useState)(null),F=(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 o(r),W(n.projectResourcesLoaded??!0),r}catch(e){return u(String(e)),[]}finally{d(!1)}},[e]);(0,i.useEffect)(()=>{S({}),$(null),F()},[e]);let B=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(lU).filter(e=>!!e);if(0!==n.length){$(null),N(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}`);S(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){$(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||I(!1)}}},[e,l]),H=(0,i.useCallback)(async t=>{if(!t.install)return;let n=lU(t);T(n),$(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 F();let s=i.skill?.install?.versionHash;S(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:s,latestVersion:s}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,F]),O=(0,i.useCallback)(async t=>{let n=!t.disableModelInvocation;g(e=>new Set(e).add(t.filePath)),x(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:n})}),i=await r.json();if(!r.ok||i.error)return void x(i.error??`HTTP ${r.status}`);o(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:n}:e))}catch(e){x(String(e))}finally{g(e=>{let n=new Set(e);return n.delete(t.filePath),n})}},[e]),U=(0,i.useCallback)(async t=>{let n=[s("skills.deleteConfirm",{path:lH(t.filePath)}),t.install?s("skills.deleteViaSkillsSh"):null,s("skills.deleteReloadHint")].filter(Boolean).join("\n\n");if(window.confirm(n)){P(t.filePath),D(null);try{let n=await fetch("/api/skills",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath})}),r=await n.json();if(!n.ok||!r.success)throw Error(r.error??`HTTP ${n.status}`);p(null),y("list"),await F()}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(null)}}},[e,F,s]),_=l.find(e=>e.filePath===h)??null,q=()=>{y("list"),D(null)},K=Object.values(j).filter(e=>"update-available"===e.state).length,V=b.trim().toLowerCase(),J=V?l.filter(e=>`${e.name} ${e.description}`.toLowerCase().includes(V)):l,Y=["project","global","path"].map(e=>({label:s(`skills.group.${e}`),matches:t=>lO(t)===e})).map(({label:e,matches:t})=>{var n;return{label:e,skills:[...(n=J.filter(t)).filter(e=>!e.disableModelInvocation),...n.filter(e=>e.disableModelInvocation)]}}).filter(e=>e.skills.length>0);return(0,r.jsx)(s8,{embedded:n,title:s("common.skills"),subtitle:lH(e),closeLabel:s("i18n.close"),onClose:t,children:(0,r.jsx)("div",{className:"settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:"add"===v?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lt,{label:s("common.skills"),onClick:q}),(0,r.jsx)(lK,{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:()=>{F()}})]}):"detail"===v&&_?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lt,{label:s("common.skills"),onClick:q}),(0,r.jsx)(lq,{skill:_,cwd:e,onToggle:O,toggling:m.has(_.filePath),saveError:f,updateStatus:lU(_)?j[lU(_)]:void 0,checkingUpdate:!!lU(_)&&C.has(lU(_)),updating:M===lU(_),updateError:L,onCheckUpdate:()=>void B(_),onUpdate:()=>void H(_),onDelete:()=>void U(_),deleting:z===_.filePath,deleteError:A},_.filePath)]}):(0,r.jsxs)(r.Fragment,{children:[!R&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-warning",children:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{className:"settings-toolbar",children:[(0,r.jsx)(ln,{value:b,onChange:k,placeholder:s("skills.filterPlaceholder")}),(0,r.jsx)("span",{className:"settings-toolbar-spacer"}),l.some(e=>!!e.install)&&(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>void B(),disabled:E||null!==M,children:E?s("i18n.checking"):K>0?`${s("i18n.checkUpdates")} \xb7 ${K}`:s("i18n.checkUpdates")}),(0,r.jsx)(la,{size:"small",onClick:()=>y("add"),children:s("i18n.addSkill")})]}),(f||L)&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:f||L}),a?(0,r.jsx)("p",{className:"settings-row-message",children:s("i18n.loading")}):c?(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:c}):0===Y.length?(0,r.jsx)("p",{className:"settings-row-message",children:V?s("skills.noResults"):s("i18n.noSkills")}):Y.map(e=>(0,r.jsx)(s7,{title:(0,r.jsx)(lr,{label:e.label,count:e.skills.length}),children:e.skills.map(e=>{let t=lU(e),n=!!t&&j[t]?.state==="update-available";return(0,r.jsxs)(le,{label:(0,r.jsxs)(r.Fragment,{children:[e.name,e.install?.skillsShUrl&&(0,r.jsx)("span",{className:"settings-row-tag",children:"skills.sh"})]}),description:e.description,muted:e.disableModelInvocation,title:e.filePath,onOpen:()=>{p(e.filePath),D(null),y("detail")},children:[n&&(0,r.jsx)("span",{className:"settings-row-status is-accent",children:s("i18n.updateAvailable")}),(0,r.jsx)(ld,{checked:!e.disableModelInvocation,loading:m.has(e.filePath),label:s("skills.modelInvocation"),onChange:()=>void O(e)})]},e.filePath)})},e.label))]})})})})}let lJ={builtin:0,global:1,workspace:2,project:3};function lY(e,t){let n=t.toLowerCase();return e.filter(e=>e.name.toLowerCase()===n).sort((e,t)=>lJ[t.scope]-lJ[e.scope])}let lZ=["read","bash","edit","write","grep","find","ls"],lX=["",...eM],lG={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};function lQ(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 l0(e){return"builtin"!==e}function l1(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l2(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 l1(e.filePath)}function l4({label:e,children:t}){return(0,r.jsx)(s3,{label:e,children:t})}function l8({checked:e,disabled:t,label:n,onChange:i}){return(0,r.jsxs)("label",{className:"settings-checkbox",children:[(0,r.jsx)("input",{type:"checkbox",checked:e,disabled:t,onChange:e=>i(e.target.checked)}),n]})}function l3({cwd:e,sessionId:t=null,onClose:n,onReloaded:s,embedded:l=!1}){let{t:o}=(0,w.s)(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)([]),[h,p]=(0,i.useState)(!0),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),[v,y]=(0,i.useState)("list"),[b,k]=(0,i.useState)(lG),[j,S]=(0,i.useState)("view"),[C,N]=(0,i.useState)("project"),[E,I]=(0,i.useState)(!0),[M,T]=(0,i.useState)(!1),[L,$]=(0,i.useState)(!1),[R,W]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[A,D]=(0,i.useState)(!0),[F,B]=(0,i.useState)(10),[H,O]=(0,i.useState)(!0),[U,_]=(0,i.useState)(!1),[q,K]=(0,i.useState)(null),[V,J]=(0,i.useState)(!1),[Y,Z]=(0,i.useState)(!1),X=(0,i.useMemo)(()=>f?lY(a,f):[],[a,f]),G=X[0]??null,Q=X.slice(1),ee=G?.disableStub?Q[0]??G:G,et=(0,i.useMemo)(()=>[...new Set(a.map(e=>e.name.toLowerCase()))].map(e=>{let[t,n]=lY(a,e),r=t.disableStub?n??t:t;return{name:e,top:t,label:r.displayName,description:r.description}}).sort((e,t)=>e.label.localeCompare(t.label)),[a]),en=(0,i.useMemo)(()=>c.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[c]),er=(0,i.useCallback)((e,t)=>{if(x(t),P(null),!t)return;let[n,r]=lY(e,t);if(!n)return;k(lQ(n.disableStub?r??n:n));let i=l0(n.scope)&&!n.disableStub&&!n.configurationError;S(i?"edit":"view"),i&&N(n.scope)},[]),ei=(0,i.useCallback)(async()=>{let t=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.profiles??[];return d(r),r},[e]),es=(0,i.useCallback)(async e=>{I(!0),P(null);try{let t=await ei();e&&er(t,e.toLowerCase())}catch(e){P(e instanceof Error?e.message:String(e))}finally{I(!1)}},[ei,er]);(0,i.useEffect)(()=>{es()},[es]),(0,i.useEffect)(()=>{let e=new AbortController;return O(!0),K(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);D(n.enabled),"number"==typeof n.maxConcurrent&&B(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;K(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||O(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{let t=new AbortController;return p(!0),g(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}`);u(r.modelList??[]),g(r.modelError??null)}catch(e){if(t.signal.aborted)return;g(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||p(!1)}})(),()=>t.abort()},[e]);let el=async e=>{await es(e),J(!!t)},eo=async()=>{if("create"===j&&et.some(e=>e.name===b.name.trim().toLowerCase()))return void P(o("agents.nameExists",{name:b.name.trim()}));T(!0),P(null),$(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:C,profile:b})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await el(n.profile.name),$(!0),setTimeout(()=>$(!1),2e3)}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}},ea=async()=>{if(!G||!ee||!l0(G.scope))return;let t=Q[0],n=t?o("agents.restoreConfirm",{name:ee.displayName,scope:o(`agents.scope.${t.scope}`)}):o("agents.deleteConfirm",{name:ee.displayName});if(window.confirm(n)){T(!0),P(null);try{let n=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:G.scope,name:G.name})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);await el(t?G.name:void 0),t||y("list")}catch(e){P(e instanceof Error?e.message:String(e))}finally{T(!1)}}},ed="create"===j||"customize"===j,ec="view"!==j,eu=!ec||M||R,eh=ed?C:G?.scope,ep=ed?"global"===C?`~/.pi/agent/agents/${b.name||"..."}.md`:`./.pi/agents/${b.name||"..."}.md`:G?l2(G,e)??o("agents.builtinPath"):"",em=ed?ep:G?.filePath??ep,eg=!b.model||c.some(e=>`${e.provider}/${e.id}`===b.model),ef=(()=>{if(!b.model)return null;let e=b.model.indexOf("/");return e<0?{provider:"",modelId:b.model}:{provider:b.model.slice(0,e),modelId:b.model.slice(e+1)}})(),ex=(e,t)=>{k(n=>({...n,[e]:t}))},ev=async(n,r)=>{W(!0),P(null);try{let i=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,name:n,enabled:r})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);await ei(),n===f&&ex("enabled",r),J(!!t)}catch(e){P(e instanceof Error?e.message:String(e))}finally{W(!1)}},ey=async e=>{ed?ex("enabled",e):G&&await ev(G.name,e)},eb=async e=>{_(!0),K(null);try{let n=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${n.status}`);D(r.enabled),J(!!t)}catch(e){K(e instanceof Error?e.message:String(e))}finally{_(!1)}},ew=async e=>{B(e),K(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);B(n.maxConcurrent)}catch(e){K(e instanceof Error?e.message:String(e))}},ek=async()=>{if(t){Z(!0),K(null);try{await ie(t,{type:"reload"}),J(!1),s?.()}catch(e){K(e instanceof Error?e.message:String(e))}finally{Z(!1)}}},ej="create"===j?o("agents.new"):b.displayName||b.name,eS=!ed&&G?[...G.disableStub?[o("agents.stubNote")]:[],...Q.map(t=>"builtin"===t.scope?o("agents.overridesBuiltin"):o("agents.shadows",{scope:o(`agents.scope.${t.scope}`),path:l2(t,e)??""}))]:[],eC=ed?b.enabled:!!G?.enabled,eN=!ed&&G&&l0(G.scope)&&!G.disableStub;return(0,r.jsxs)(s8,{embedded:l,title:o("common.agents"),subtitle:l1(e),closeLabel:o("agents.close"),onClose:n,children:[V&&t&&(0,r.jsxs)("div",{className:"agents-feature-setting is-notice",children:[(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:o("agents.reloadRequired")}),(0,r.jsx)(la,{size:"small",onClick:()=>void ek(),disabled:Y||U,children:Y?o("agents.reloading"):o("agents.reloadSession")})]}),(0,r.jsx)("div",{className:"settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:"list"===v?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(s7,{children:[(0,r.jsx)(s9,{label:o("agents.builtInTitle"),description:o("agents.builtInDescription"),children:(0,r.jsx)(ld,{checked:A,disabled:H||Y,loading:U,label:o("agents.builtInTitle"),onChange:e=>void eb(e)})}),(0,r.jsx)(s9,{label:o("agents.maxConcurrent"),description:o("agents.maxConcurrentDescription"),children:(0,r.jsx)("input",{"aria-label":o("agents.maxConcurrent"),className:"settings-inline-input agents-number-input",type:"number",min:1,max:32,value:F,disabled:H||U,onChange:e=>B(Number(e.target.value)),onBlur:()=>void ew(F)})}),q&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:q})]}),(0,r.jsxs)(s7,{title:(0,r.jsx)(lr,{label:o("agents.profiles"),count:et.length}),action:(0,r.jsx)(la,{size:"small",onClick:()=>{let e="custom-agent",t=2;for(;et.some(t=>t.name===e);)e=`custom-agent-${t++}`;x(null),k({...lG,name:e,displayName:e}),S("create"),N("project"),P(null),y("detail")},children:o("agents.new")}),children:[z&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:z}),E?(0,r.jsx)("p",{className:"settings-row-message",children:o("agents.loading")}):et.map(({name:e,top:t,label:n,description:i})=>(0,r.jsx)(le,{label:(0,r.jsxs)(r.Fragment,{children:[n,(0,r.jsx)("span",{className:"settings-row-tag",children:o(`agents.scope.${t.scope}`)})]}),description:i,muted:!t.enabled,title:t.filePath,onOpen:()=>{er(a,e),y("detail")},children:(0,r.jsx)(ld,{checked:t.enabled,disabled:R||!!t.configurationError,label:t.enabled?o("agents.disable"):o("agents.enable"),onChange:e=>void ev(t.name,e)})},e))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lt,{label:o("common.agents"),onClick:()=>{y("list"),P(null)}}),G||"create"===j?(0,r.jsxs)(li,{title:ej,meta:(0,r.jsxs)(r.Fragment,{children:[eh&&(0,r.jsx)("span",{className:`config-scope-tag${"project"===eh?" is-project":""}`,children:o(`agents.scope.${eh}`)}),"builtin"!==eh&&(0,r.jsx)("span",{title:em,className:"config-detail-path",children:ep})]}),description:eS.length>0&&(0,r.jsx)("span",{className:"agents-source-note",children:eS.map(e=>(0,r.jsx)("span",{children:e},e))}),children:[(0,r.jsxs)(s7,{children:[(0,r.jsx)(s9,{label:o("agents.enabled"),description:o("agents.enabledDescription"),children:(0,r.jsx)(ld,{checked:eC,disabled:M||R||!ed&&!!G?.configurationError,label:eC?o("agents.disable"):o("agents.enable"),onChange:e=>void ey(e)})}),G?.scope==="builtin"&&"view"===j&&(0,r.jsx)(s9,{label:o("agents.customize"),description:o("agents.customizeDescription"),children:(0,r.jsx)(la,{size:"small",onClick:()=>{ee&&(k(lQ(ee)),S("customize"),N("project"),P(null))},disabled:M||R,children:o("agents.customize")})}),ed&&(0,r.jsx)(s9,{label:o("agents.saveScope"),description:o("agents.saveScopeDescription"),children:(0,r.jsx)("div",{role:"radiogroup","aria-label":o("agents.saveScope"),className:"settings-segmented",children:["global","project"].map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":C===e,className:"settings-segmented-option",onClick:()=>N(e),disabled:M,children:o(`agents.scope.${e}`)},e))})})]}),(0,r.jsx)(s7,{title:o("agents.profile"),children:(0,r.jsxs)("div",{className:"settings-form",children:[(0,r.jsxs)("div",{className:"settings-form-pair",children:[(0,r.jsx)(l4,{label:o("agents.name"),children:"create"===j?(0,r.jsx)("input",{"aria-label":o("agents.name"),value:b.name,disabled:eu,onChange:e=>ex("name",e.target.value)}):(0,r.jsx)("code",{className:"settings-form-value",children:b.name})}),(0,r.jsx)(l4,{label:o("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":o("agents.displayName"),value:b.displayName,disabled:eu,onChange:e=>ex("displayName",e.target.value)})})]}),(0,r.jsx)(l4,{label:o("agents.description"),children:(0,r.jsx)("input",{"aria-label":o("agents.description"),value:b.description,disabled:eu,onChange:e=>ex("description",e.target.value)})}),(0,r.jsx)(l4,{label:o("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":o("agents.prompt"),value:b.systemPrompt,disabled:eu,onChange:e=>ex("systemPrompt",e.target.value)})})]})}),(0,r.jsx)(s7,{title:o("agents.capabilities"),children:(0,r.jsxs)("div",{className:"settings-form",children:[(0,r.jsx)(l4,{label:o("agents.tools"),children:(0,r.jsx)("div",{className:"settings-checkbox-grid",children:lZ.map(e=>(0,r.jsx)(l8,{label:e,disabled:eu,checked:b.tools.includes(e),onChange:t=>ex("tools",t?[...b.tools,e]:b.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(l4,{label:o("agents.resources"),children:(0,r.jsxs)("div",{className:"settings-checkbox-grid",children:[(0,r.jsx)(l8,{label:o("agents.loadSkills"),disabled:eu,checked:b.loadSkills,onChange:e=>ex("loadSkills",e)}),(0,r.jsx)(l8,{label:o("agents.loadExtensions"),disabled:eu,checked:b.loadExtensions,onChange:e=>ex("loadExtensions",e)})]})})]})}),(0,r.jsx)(s7,{title:o("agents.runtime"),children:(0,r.jsxs)("div",{className:"settings-form",children:[(0,r.jsxs)("div",{className:"settings-form-triple",children:[(0,r.jsxs)(l4,{label:o("agents.model"),children:[(0,r.jsx)(tc,{options:en,value:ef,onChange:(e,t)=>ex("model",`${e}/${t}`),onClear:()=>ex("model",void 0),emptyLabel:h?o("agents.modelsLoading"):o("agents.inherit"),selectedLabel:b.model&&!eg?o("agents.modelUnavailable",{model:b.model}):void 0,disabled:eu||h||0===c.length&&!b.model,ariaLabel:o("agents.model"),variant:"field",placement:"auto"}),m&&(0,r.jsx)("span",{className:"settings-row-message is-error",children:m})]}),(0,r.jsx)(l4,{label:o("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":o("agents.thinking"),value:b.thinking??"",disabled:eu,onChange:e=>ex("thinking",e.target.value||void 0),children:lX.map(e=>(0,r.jsx)("option",{value:e,children:e||o("agents.inherit")},e||"default"))})}),(0,r.jsx)(l4,{label:o("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":o("agents.maxTurns"),type:"number",min:1,value:b.maxTurns??"",disabled:eu,onChange:e=>ex("maxTurns",e.target.value?Number(e.target.value):void 0)})})]}),(0,r.jsxs)("div",{className:"settings-checkbox-grid",children:[(0,r.jsx)(l8,{label:o("agents.inheritContext"),disabled:eu,checked:b.inheritContext,onChange:e=>ex("inheritContext",e)}),(0,r.jsx)(l8,{label:o("agents.background"),disabled:eu,checked:b.runInBackground,onChange:e=>ex("runInBackground",e)})]})]})}),ee&&!ed&&(0,r.jsxs)(s7,{children:[(0,r.jsx)(s9,{label:o("agents.duplicate"),description:o("agents.duplicateDescription"),children:(0,r.jsx)(la,{size:"small",onClick:()=>{if(!ee)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,s=2;for(;n.has(i.toLowerCase());)i=`${r}-${s++}`;return i}(ee.name,a);x(null),k({...lQ(ee),name:e,displayName:o("agents.copyName",{name:ee.displayName}),enabled:!0}),S("create"),N("project"),P(null)},disabled:M||R,children:o("agents.duplicate")})}),eN&&(0,r.jsx)(s9,{label:Q[0]?o("agents.restore",{scope:o(`agents.scope.${Q[0].scope}`)}):o("agents.deleteTitle"),description:Q[0]?o("agents.restoreDescription"):o("agents.deleteDescription"),children:(0,r.jsx)(la,{variant:"danger",size:"small",onClick:()=>void ea(),disabled:M||R,children:Q[0]?o("agents.restore",{scope:o(`agents.scope.${Q[0].scope}`)}):o("agents.delete")})})]})]}):(0,r.jsx)(s6,{children:o("agents.empty")})]})})}),"detail"===v&&ec&&(0,r.jsx)(s5,{status:z&&(0,r.jsx)("span",{role:"alert",className:"settings-row-message is-error",children:z}),children:(0,r.jsxs)(la,{variant:"primary",onClick:()=>void eo(),disabled:M||L||R||!b.name.trim(),className:L?"is-success":void 0,children:[L&&(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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?o("i18n.saved"):M?o("agents.saving"):o("agents.save")})]})})]})}function l6(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l5(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function l7(e){return`${e.scope}\0${e.source}`}function l9(e){return`extension\0${e.path}`}function oe(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t(1===e.counts.extensions?"i18n.extensionShortOne":"i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t(1===e.counts.skills?"i18n.skillShortOne":"i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t(1===e.counts.prompts?"i18n.promptShortOne":"i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t(1===e.counts.themes?"i18n.themeShortOne":"i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function ot({pkg:e}){let{t}=(0,w.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)(s7,{title:t("i18n.resolvedResources"),children:(0,r.jsx)("p",{className:"settings-row-message",children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")})}):n.map(e=>(0,r.jsx)(s7,{title:`${e.label} \xb7 ${e.resources.length}`,children:e.resources.map(e=>(0,r.jsx)(s9,{title:e.path,label:e.name,description:(0,r.jsx)("span",{className:"is-mono",children:e.relativePath})},`${e.kind}:${e.path}`))},e.kind))}function on({scope:e}){return(0,r.jsx)("span",{className:`config-scope-tag${"project"===e?" is-project":""}`,children:e})}function or({cwd:e,source:t,scope:n,projectResourcesLoaded:s,busy:l,actionError:o,onSourceChange:a,onScopeChange:d,onInstall:c}){let{t:u}=(0,w.s)(),h=(0,i.useRef)(null);return(0,i.useEffect)(()=>{h.current?.focus()},[]),(0,r.jsxs)(li,{title:u("i18n.addPlugin"),description:(0,r.jsxs)(r.Fragment,{children:[u("plugins.addDescription")," ",(0,r.jsx)("a",{href:"https://pi.dev/packages",target:"_blank",rel:"noopener noreferrer",className:"settings-link",children:"pi.dev/packages ↗"})]}),children:[(0,r.jsxs)(s7,{children:[(0,r.jsxs)("div",{className:"settings-search",children:[(0,r.jsx)("input",{id:"plugin-source",ref:h,className:"settings-search-input is-mono","aria-label":u("plugins.source"),value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=l5(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(l5(e.currentTarget.value)),placeholder:"npm:@scope/package",onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!l&&c()}}),(0,r.jsx)(la,{variant:"primary",onClick:c,disabled:l||!t.trim(),children:u(l?"i18n.installing":"i18n.install")})]}),(0,r.jsx)(s9,{label:u("skills.installTo"),description:(0,r.jsx)("span",{className:"is-mono",children:"project"===n?`${l6(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"}),children:(0,r.jsx)(ls,{label:u("skills.installTo"),value:n,onChange:d,options:[{value:"global",label:u("skills.scope.global")},{value:"project",label:u("skills.scope.project"),disabled:!s,title:s?void 0:u("trust.projectScopeUnavailable")}]})}),o&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error is-pre",children:o})]}),(0,r.jsx)(s7,{title:u("plugins.examples"),children:(0,r.jsx)("div",{className:"settings-examples",children:["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"].map(e=>(0,r.jsx)("button",{type:"button",className:"settings-example",onClick:()=>a(e),children:e},e))})})]})}function oi({pkg:e,busyKey:t,actionError:n,actionMessage:i,sessionId:s,updateStatus:l,checkingUpdate:o,updateError:a,onAction:d,onCheckUpdate:c,onReloadSession:u}){let h,{t:p}=(0,w.s)(),m=l7(e),g=t?.endsWith(m)??!1,f="reload"===t,x=!e.disabled,v=e.canCheckForUpdates,y=l?.state==="update-available",b=v&&(o||l&&!y)?o?p("i18n.checking"):l?.state==="up-to-date"?p("i18n.upToDate"):l?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):l?.message||p("i18n.checkFailed"):null;return(0,r.jsxs)(li,{title:e.packageName??e.source,meta:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(on,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{className:"config-scope-tag",children:p("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{className:"config-scope-tag is-warning",children:p("i18n.filtered")}),(0,r.jsx)("span",{className:"config-detail-path",title:e.source,children:e.source})]}),children:[(0,r.jsxs)(s7,{children:[(0,r.jsx)(s9,{label:p("plugins.enabled"),description:p("plugins.enabledDescription"),children:(0,r.jsx)(ld,{checked:x,loading:g||f,onChange:()=>d(e.disabled?"enable":"disable",e),label:p(e.disabled?"i18n.enablePackage":"i18n.disablePackage")})}),(0,r.jsx)(s9,{label:p("i18n.version"),description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"is-mono",children:(h=[],e.version&&h.push(p("i18n.installedVersion",{version:e.version})),e.configuredVersion&&h.push(p("i18n.configuredVersion",{version:e.configuredVersion})),h.length?h.join(" \xb7 "):p("i18n.unknown"))}),y&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{className:"is-accent",title:l.displayName,children:p("i18n.updateAvailable")})]}),b&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{className:l?.state==="error"?"is-error":void 0,children:b})]})]}),children:(0,r.jsx)(la,{size:"small",variant:y?"primary":void 0,onClick:y||!v?()=>d("update",e):c,disabled:g||f||o,children:p(t===`update:${m}`?"i18n.updating":o?"i18n.checking":y||!v?"i18n.update":"i18n.check")})}),a&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:a}),(0,r.jsx)(s9,{label:p("i18n.reloadSession"),description:p(s?"plugins.reloadDescription":"i18n.openSessionToReload"),children:(0,r.jsx)(la,{size:"small",onClick:u,disabled:!s||f||g,children:p(f?"i18n.reloading":"plugins.reload")})}),i&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-success",children:i}),n&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:n})]}),(0,r.jsx)(s7,{title:p("settings.details"),children:(0,r.jsxs)(ll,{children:[(0,r.jsx)(lo,{label:p("i18n.status"),children:(0,r.jsx)("span",{className:`settings-status is-${e.status}`,children:e.status})}),(0,r.jsx)(lo,{label:p("i18n.resources"),children:oe(e,p)}),(0,r.jsx)(lo,{label:p("i18n.installedPath"),mono:!0,children:e.installedPath?l6(e.installedPath):(0,r.jsx)("span",{className:"is-error",children:p("i18n.notFound")})})]})}),(0,r.jsx)(ot,{pkg:e}),(0,r.jsx)(s7,{children:(0,r.jsx)(s9,{label:p("plugins.removeTitle"),description:p("plugins.removeDescription"),children:(0,r.jsx)(la,{variant:"danger",size:"small",onClick:()=>d("remove",e),disabled:g||f,children:p(t===`remove:${m}`?"i18n.removing":"i18n.remove")})})})]})}function os({extension:e}){let{t}=(0,w.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsx)(li,{title:e.name,meta:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(on,{scope:e.scope}),(0,r.jsx)("span",{className:"config-detail-path",title:e.path,children:l6(e.path)})]}),children:(0,r.jsx)(s7,{title:t("settings.details"),children:(0,r.jsxs)(ll,{children:[(0,r.jsx)(lo,{label:t("i18n.status"),children:(0,r.jsx)("span",{className:`settings-status is-${n}`,children:n})}),(0,r.jsx)(lo,{label:t("i18n.installedPath"),mono:!0,children:l6(e.path)})]})})})}function ol({cwd:e,sessionId:t,onClose:n,onReloaded:s,embedded:l=!1}){let{t:o}=(0,w.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[h,p]=(0,i.useState)(null),[m,g]=(0,i.useState)(null),[f,x]=(0,i.useState)("list"),[v,y]=(0,i.useState)(""),[b,k]=(0,i.useState)("global"),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),[E,I]=(0,i.useState)(null),[M,T]=(0,i.useState)({}),[L,$]=(0,i.useState)(new Set),[R,W]=(0,i.useState)(!1),[z,P]=(0,i.useState)(null),[A,D]=(0,i.useState)(!1),F=(0,i.useMemo)(()=>a?.packages??[],[a?.packages]),B=(0,i.useMemo)(()=>a?.standaloneExtensions??[],[a?.standaloneExtensions]),H=F.find(e=>l7(e)===m)??null,O=B.find(e=>l9(e)===m)??null,U=a?.projectResourcesLoaded??!0,_=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:F.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[F]),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)}catch(e){p(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{T({}),P(null),q()},[e]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:F.filter(e=>e.canCheckForUpdates)).map(l7);if(0!==n.length){P(null),$(e=>new Set([...e,...n])),t||W(!0);try{let n=await fetch("/api/plugins/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,source:t?.source,scope:t?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);T(e=>{let t={...e};for(let e of r.updates??[])t[l7(e)]=e;return t})}catch(e){P(e instanceof Error?e.message:String(e))}finally{$(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||W(!1)}}},[e,F]),V=(0,i.useCallback)(async()=>{D(!0),N(null),I(null),P(null);try{let n=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"update",cwd:e})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);d(r),T({}),I(o("i18n.packagesUpdated")),t&&I(`${o("i18n.packagesUpdated")} ${o("agents.reloadRequired")}`)}catch(e){N(e instanceof Error?e.message:String(e))}finally{D(!1)}},[e,t,o]),J=(0,i.useCallback)(async(t,n)=>{let r=l7(n);S(`${t}:${r}`),N(null),I(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),s=await i.json();if(!i.ok||s.error)throw Error(s.error??`HTTP ${i.status}`);d(s),"remove"===t?(g(null),x("list"),I("Package removed."),T(e=>{let t={...e};return delete t[r],t})):(I({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&T(e=>{let t={...e};return delete t[r],t}))}catch(e){N(e instanceof Error?e.message:String(e))}finally{S(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=l5(v).trim();if(!t)return;y(t);let n=`${b}\0${t}`;S(`install:${n}`),N(null),I(null);try{var r;let i,s,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:b,cwd:e})}),o=await l.json();if(!l.ok||o.error)throw Error(o.error??`HTTP ${l.status}`);d(o);let a=(r=o.packages,s=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===b&&e.source===i)??r.find(e=>e.scope===b&&e.source===`npm:${s}`)??r.find(e=>e.scope===b&&e.source.endsWith(i)));g(a?l7(a):n),x("detail"),y(""),I("Package installed.")}catch(e){N(e instanceof Error?e.message:String(e))}finally{S(null)}},[e,b,v]),Z=(0,i.useCallback)(async()=>{if(t){S("reload"),N(null),I(null);try{await ie(t,{type:"reload"}),s?.(),await q(),I("Session reloaded.")}catch(e){N(e instanceof Error?e.message:String(e))}finally{S(null)}}},[q,s,t]),X=j?.startsWith("install:")??!1,G=Object.values(M).filter(e=>"update-available"===e.state).length,Q=F.some(e=>e.canCheckForUpdates),ee=c||null!==j||L.size>0||A,et=()=>{x("list"),N(null),I(null)},en=e=>{g(e),N(null),I(null),x("detail")};return(0,r.jsx)(s8,{embedded:l,title:o("common.plugins"),subtitle:l6(e),closeLabel:o("i18n.close"),onClose:n,children:(0,r.jsx)("div",{className:"settings-scroll",children:(0,r.jsx)("div",{className:"settings-page",children:"add"===f?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lt,{label:o("common.plugins"),onClick:et}),(0,r.jsx)(or,{cwd:e,source:v,scope:b,projectResourcesLoaded:U,busy:X,actionError:C,onSourceChange:y,onScopeChange:k,onInstall:Y})]}):"detail"===f&&(O||H)?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(lt,{label:o("common.plugins"),onClick:et}),O?(0,r.jsx)(os,{extension:O}):H&&(0,r.jsx)(oi,{pkg:H,busyKey:j,actionError:C,actionMessage:E,sessionId:t,updateStatus:M[l7(H)],checkingUpdate:L.has(l7(H)),updateError:z,onAction:J,onCheckUpdate:()=>void K(H),onReloadSession:Z},l7(H))]}):(0,r.jsxs)(r.Fragment,{children:[!U&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-warning",children:o("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{className:"settings-toolbar",children:[a&&(0,r.jsx)("span",{className:"settings-toolbar-summary",children:o("plugins.summary",{count:F.length,enabled:F.filter(e=>!e.disabled).length})}),(0,r.jsx)("span",{className:"settings-toolbar-spacer"}),(0,r.jsx)(la,{size:"small",variant:"ghost",onClick:()=>void q(),disabled:ee,children:o("i18n.refresh")}),Q&&(0,r.jsx)(la,{size:"small",variant:G>0?"primary":"ghost",onClick:()=>void(G>0?V():K()),disabled:ee,title:G>0?o("i18n.updateAllPluginsHint"):void 0,children:A?o("i18n.updating"):R?o("i18n.checking"):G>0?`${o("i18n.updateAllPlugins")} \xb7 ${G}`:o("i18n.checkUpdates")}),(0,r.jsx)(la,{size:"small",onClick:()=>{N(null),x("add")},children:o("i18n.addPlugin")})]}),a?.diagnostics.length?(0,r.jsx)("p",{className:`settings-row-message ${a.diagnostics.some(e=>"error"===e.type)?"is-error":"is-warning"}`,title:a.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),children:o("plugins.diagnostics",{count:a.diagnostics.length})}):null,E&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-success",children:E}),(C||z)&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error is-pre",children:C||z}),c?(0,r.jsx)("p",{className:"settings-row-message",children:o("i18n.loading")}):h?(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:h}):0===F.length&&0===B.length?(0,r.jsx)("p",{className:"settings-row-message",children:o("plugins.empty")}):(0,r.jsxs)(r.Fragment,{children:[_.map(e=>(0,r.jsx)(s7,{title:(0,r.jsx)(lr,{label:o(`skills.group.${e.scope}`),count:e.packages.length}),children:e.packages.map(e=>{let t=l7(e),n=j?.endsWith(t)??!1;return(0,r.jsxs)(le,{label:e.packageName??e.source,description:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"is-mono",children:l6(e.source)})," \xb7 ",oe(e,o)]}),muted:e.disabled,title:e.source,onOpen:()=>en(t),children:[("installed"===e.status||"missing"===e.status)&&(0,r.jsx)(lc,{tone:"missing"===e.status?"danger":"warning",title:e.status}),M[t]?.state==="update-available"&&(0,r.jsx)("span",{className:"settings-row-status is-accent",children:o("i18n.updateAvailable")}),(0,r.jsx)(ld,{checked:!e.disabled,loading:n,disabled:"reload"===j,label:e.disabled?o("i18n.enablePackage"):o("i18n.disablePackage"),onChange:()=>void J(e.disabled?"enable":"disable",e)})]},t)})},e.scope)),B.length>0&&(0,r.jsx)(s7,{title:(0,r.jsx)(lr,{label:o("i18n.extensions"),count:B.length}),children:B.map(e=>(0,r.jsx)(le,{label:e.name,description:(0,r.jsx)("span",{className:"is-mono",children:l6(e.path)}),muted:!e.enabled,title:e.path,onOpen:()=>en(l9(e))},l9(e)))})]})]})})})})}let oo=new Set(["openai-codex","antigravity","xai"]);function oa({sessionId:e=null,onReloaded:t}){let{t:n}=(0,w.s)(),[s,l]=(0,i.useState)(null),[o,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,h]=(0,i.useState)(!1),[p,m]=(0,i.useState)(!1),[g,f]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=new AbortController;return a(!0),f(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=od(n);l(r)}catch(e){e instanceof DOMException&&"AbortError"===e.name||f(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(od(n)),m(!!e)},j=async e=>{c(!0),f(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){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},S=async()=>{if(!y||!y.label.trim())return void b(null);c(!0),f(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:y.id,label:y.label.trim()})});await k(e),b(null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},C=async()=>{if(x){c(!0),f(null);try{let e=await fetch("/api/image-generation/settings/connections",{method:"edit"===x.mode?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify("edit"===x.mode?{id:x.id,label:x.label,provider:x.provider,model:x.model}:{label:x.label,provider:x.provider,model:x.model})});await k(e),v(null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}}},N=async e=>{if(window.confirm(n("agents.deleteConfirm",{name:e.label}))){c(!0),f(null);try{let t=await fetch("/api/image-generation/settings/connections",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:e.id})});await k(t),x?.mode==="edit"&&x.id===e.id&&v(null)}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}}},E=async()=>{if(e){h(!0),f(null);try{await ie(e,{type:"reload"}),m(!1),t?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}}},I=s?.connections.filter(e=>"custom"!==e.kind)??[],M=s?.connections.filter(e=>"custom"===e.kind)??[],T=s?.providers??[],L=x?.mode==="edit"?M.find(e=>e.id===x.id):void 0,$=x&&(0,r.jsxs)("form",{className:"settings-inline-form",onSubmit:e=>{e.preventDefault(),C()},children:[(0,r.jsxs)("label",{className:"settings-field",children:[(0,r.jsx)("span",{children:n("settings.imagesLabel")}),(0,r.jsx)("input",{value:x.label,onChange:e=>v({...x,label:e.target.value}),required:!0})]}),(0,r.jsxs)("label",{className:"settings-field",children:[(0,r.jsx)("span",{children:n("settings.imagesProvider")}),(0,r.jsx)("select",{value:x.provider,onChange:e=>v({...x,provider:e.target.value}),required:!0,children:T.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name===e.id?e.id:`${e.name} (${e.id})`},e.id))})]}),(0,r.jsxs)("label",{className:"settings-field",children:[(0,r.jsx)("span",{children:n("settings.imagesModel")}),(0,r.jsx)(oh,{value:x.model,t:n,onChange:e=>{let t=eg.find(t=>t.model===e);v({...x,model:e,..."create"===x.mode&&!x.label.trim()&&t?{label:t.label}:{}})}},"edit"===x.mode?x.id:"create")]}),(0,r.jsxs)("div",{className:"settings-inline-form-actions",children:[L&&(0,r.jsx)(la,{type:"button",size:"small",variant:"ghost",className:"is-danger-text is-pushed-left",disabled:d,onClick:()=>void N(L),children:n("agents.delete")}),(0,r.jsx)(la,{type:"button",size:"small",disabled:d,onClick:()=>v(null),children:n("trust.cancel")}),(0,r.jsx)(la,{type:"submit",variant:"primary",size:"small",disabled:d||!x.label.trim()||!x.provider||!x.model.trim(),children:d?n("agents.saving"):n("agents.save")})]})]});return(0,r.jsxs)("div",{className:"settings-page",children:[(0,r.jsxs)(s7,{children:[(0,r.jsxs)(s9,{label:n("settings.imagesEnabled"),description:n("settings.imagesDescription"),children:[p&&e&&(0,r.jsx)(la,{size:"small",onClick:()=>void E(),disabled:u||d,children:u?n("agents.reloading"):n("agents.reloadSession")}),(0,r.jsx)(ld,{checked:s?.enabled===!0,disabled:o||u||!s,loading:d&&!x&&!y,label:n("settings.imagesEnabled"),onChange:e=>void j({enabled:e})})]}),s?.enabled&&s.connections.some(e=>e.enabled)&&(0,r.jsx)(s9,{label:n("settings.imagesDefault"),description:n("settings.imagesDefaultDescription"),children:(0,r.jsx)("select",{className:"settings-select",value:s.defaultConnection,disabled:o||d||u,onChange:e=>void j({default:e.target.value}),children:s.connections.filter(e=>e.enabled).map(e=>(0,r.jsxs)("option",{value:e.id,disabled:!e.signedIn,children:[e.label,e.signedIn?"":` (${n("settings.imagesSignedOut")})`]},e.id))})}),p&&(0,r.jsx)("p",{role:"status",className:"settings-row-message is-warning",children:n("agents.reloadRequired")}),g&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:g})]}),s?.enabled&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s7,{title:(0,r.jsx)(lr,{label:n("settings.imagesBuiltin"),count:I.length}),children:I.map(e=>(0,r.jsx)(oc,{connection:e,disabled:o||u||d,unsignedLabel:n("settings.imagesSignedOut"),onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),renaming:y?.id===e.id,renameValue:y?.id===e.id?y.label:e.label,onRenameChange:t=>b({id:e.id,label:t}),onRenameSubmit:()=>void S(),onRenameCancel:()=>b(null),onEdit:()=>{v(null),b({id:e.id,label:e.label})},editLabel:n("i18n.rename")},e.id))}),(0,r.jsxs)(s7,{title:(0,r.jsx)(lr,{label:n("settings.imagesCustom"),count:M.length}),action:T.length>0&&!x&&(0,r.jsx)(la,{size:"small",disabled:o||u||d,onClick:()=>{b(null),v({mode:"create",label:"",provider:T.find(e=>!oo.has(e.id))?.id??T[0]?.id??"",model:""})},children:n("settings.imagesAddConnection")}),children:[0===T.length&&(0,r.jsx)("p",{className:"settings-row-message",children:n("settings.imagesNoProviders")}),M.map(e=>(0,r.jsx)(i.Fragment,{children:x?.mode==="edit"&&x.id===e.id?$:(0,r.jsx)(oc,{connection:e,disabled:o||u||d,unsignedLabel:n("settings.imagesNotConfigured"),detail:e.model,onChange:t=>void j({connections:{[e.id]:{enabled:t}}}),onEdit:()=>{b(null),v({mode:"edit",id:e.id,label:e.label,provider:e.provider,model:e.model})},editLabel:n("image.edit")})},e.id)),x?.mode==="create"&&$]})]})]})}function od(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 oc({connection:e,disabled:t,unsignedLabel:n,detail:s,onChange:l,onEdit:o,editLabel:a,renaming:d=!1,renameValue:c,onRenameChange:u,onRenameSubmit:h,onRenameCancel:p}){let m=(0,i.useRef)(!1),g=!e.signedIn&&!e.enabled,f=d?(0,r.jsx)("input",{className:"settings-inline-input",value:c,autoFocus:!0,"aria-label":a,onChange:e=>u?.(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),m.current=!0,h?.()),"Escape"===e.key&&(e.preventDefault(),m.current=!0,p?.())},onBlur:()=>{if(m.current){m.current=!1;return}h?.()}}):(0,r.jsx)("span",{className:e.signedIn?void 0:"is-dim",children:e.label});return(0,r.jsxs)(s9,{label:f,description:e.signedIn?s:n,children:[(0,r.jsx)("span",{className:"settings-row-hover-actions",children:o&&!d?(0,r.jsx)(la,{size:"small",variant:"ghost",disabled:t,onClick:o,children:a}):null}),(0,r.jsx)(ld,{checked:e.enabled,disabled:t||g,label:e.label,onChange:l})]})}let ou="__other__";function oh({value:e,onChange:t,t:n}){let s=eg.some(t=>t.model===e),[l,o]=(0,i.useState)(!s),a=l||!s?ou:e;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("select",{value:a,onChange:e=>{let n=e.target.value;n===ou?o(!0):(o(!1),t(n))},children:[eg.map(e=>(0,r.jsxs)("option",{value:e.model,children:[e.label," \xb7 ",e.model]},e.model)),(0,r.jsx)("option",{value:ou,children:n("settings.imagesOtherModel")})]}),a===ou?(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),required:!0}):null]})}let op=null;async function om(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(op)return op;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 op=null,!1}})();return op=t,t.then(e=>{e||op!==t||(op=null)}),t}let og=["/fonts/SarasaTermSC-Regular.woff2?v=1","/fonts/SarasaTermSC-SemiBold.woff2?v=1"],of="pi-web-sarasa-enabled";async function ox(){await Promise.all(og.map(async e=>{let t=await fetch(e,{cache:"force-cache"});if(!t.ok)throw Error(`HTTP ${t.status}`)})),document.documentElement.classList.add("sarasa-term-webfont"),localStorage.setItem(of,"1"),await Promise.all([document.fonts.load('400 14px "Sarasa Term SC Web"'),document.fonts.load('600 14px "Sarasa Term SC Web"')])}function ov({preference:e}){return"light"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",className:"settings-theme-icon",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.42-1.41M17.66 6.34l1.41-1.41"})]}):"dark"===e?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-theme-icon",children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"settings-theme-icon",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}function oy({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:s}){let{locale:l,setLocale:o,supportedLocales:a,t:d}=(0,w.s)(),{preference:c,setThemePreference:u}=n8(),{width:h,setWidth:p,fontSize:m,setFontSize:g}=tr(),[f,b]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(null),[N,E]=(0,i.useState)(!1),[I,M]=(0,i.useState)(!0),[T,L]=(0,i.useState)(!1),[$,R]=(0,i.useState)(!1),[W,z]=(0,i.useState)(null),[P,A]=(0,i.useState)(!1),[D,F]=(0,i.useState)(null),[B,H]=(0,i.useState)(!1),[O,U]=(0,i.useState)(!1),[_,q]=(0,i.useState)(""),[K,V]=(0,i.useState)("available"),[J,Y]=(0,i.useState)(null);(0,i.useEffect)(()=>{E(ra()),M(sK()),L(y()),R(to())},[]),(0,i.useEffect)(()=>{fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>H(e?.enabled===!0)).catch(()=>{})},[]),(0,i.useEffect)(()=>r4(z),[]);let Z=[{id:"light",label:d("settings.themeLight")},{id:"dark",label:d("settings.themeDark")},{id:"auto",label:d("settings.themeSystem")}];(0,i.useEffect)(()=>{let e=!1;return fetch("/api/tools/settings").then(async t=>{let n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);e||b(n)}).catch(t=>{e||C(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let X=async n=>{j(!0),C(null);try{let r=await fetch("/api/tools/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);b(i),e&&(await ie(e,{type:"reload"}),t())}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(!1)}},G=async()=>{if(!P){A(!0),F(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 om(l))throw Error("unsupported or not permitted");F({kind:"ok",message:d("settings.pushRegistered")})}catch(e){F({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{A(!1)}}};(0,i.useEffect)(()=>{V("1"===localStorage.getItem(of)?"cached":"available")},[]);let Q=async()=>{V("loading"),Y(null);try{await ox(),V("cached")}catch(e){V("error"),Y(e instanceof Error?e.message:String(e))}},ee=async()=>{U(!0),q("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{q(d("auth.logoutFailed"))}finally{U(!1)}},et=(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})}),en=(e,t,n,i)=>(0,r.jsx)(s9,{label:e,description:t,children:(0,r.jsx)(ld,{checked:n,label:e,onChange:i})}),er=(e,t,n,i,s,l,o,a)=>(0,r.jsxs)("div",{className:"settings-range",children:[(0,r.jsx)("input",{id:e,type:"range",min:n,max:i,step:s,value:t,onChange:e=>a(Number(e.target.value))}),(0,r.jsxs)("output",{htmlFor:e,children:[t,"px"]}),(0,r.jsx)(la,{variant:"ghost",size:"small",className:"settings-chat-reset",title:o,"aria-label":o,disabled:t===l,onClick:()=>a(l),children:et})]});return(0,r.jsxs)("div",{className:"settings-page",children:[(0,r.jsxs)(s7,{title:d("settings.appearance"),children:[(0,r.jsx)(s9,{label:d("settings.theme"),stacked:!0,children:(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.theme"),className:"settings-segmented",children:Z.map(e=>(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":c===e.id,onClick:()=>u(e.id),className:"settings-segmented-option",children:[(0,r.jsx)(ov,{preference:e.id}),(0,r.jsx)("span",{className:"settings-segmented-label",children:e.label})]},e.id))})}),(0,r.jsx)(s9,{label:d("common.language"),stacked:!0,children:(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-segmented",children:a.map(e=>(0,r.jsx)("button",{type:"button",role:"radio","aria-checked":l===e.id,onClick:()=>o(e.id),className:"settings-segmented-option",children:(0,r.jsx)("span",{className:"settings-segmented-label",children:e.label})},e.id))})}),(0,r.jsx)(s9,{label:d("settings.typography"),description:d("settings.typographyDescription"),children:"cached"===K?(0,r.jsx)("span",{role:"status",className:"settings-row-status",children:d("settings.fontCached")}):(0,r.jsx)(la,{size:"small",disabled:"loading"===K,onClick:()=>void Q(),children:"loading"===K?d("settings.fontDownloadLoading"):d("settings.fontDownload")})}),"error"===K&&(0,r.jsxs)("p",{role:"alert",className:"settings-row-message is-error",children:[d("settings.fontDownloadFailed")," ",J]}),(0,r.jsx)(s9,{label:d("settings.chatContentWidth"),description:d("settings.chatContentWidthDescription"),htmlFor:"settings-chat-content-width",stacked:!0,children:er("settings-chat-content-width",h,820,2e3,10,820,d("settings.resetChatContentWidth"),p)}),(0,r.jsx)(s9,{label:d("settings.chatContentFontSize"),description:d("settings.chatContentFontSizeDescription"),htmlFor:"settings-chat-content-font-size",stacked:!0,children:er("settings-chat-content-font-size",m,12,24,1,14,d("settings.resetChatContentFontSize"),g)}),en(d("settings.thinkingExpandedDefault"),d("settings.thinkingExpandedDefaultDescription"),N,e=>{window.localStorage.setItem(rl,String(e)),window.dispatchEvent(new Event(ro)),E(e)})]}),(0,r.jsxs)(s7,{title:d("settings.chat"),children:[en(d("settings.shiftEnterToSend"),d("settings.shiftEnterToSendDescription"),$,e=>{window.localStorage.setItem(tl,String(e)),R(e)}),en(d("settings.autoSessionTitle"),d("settings.autoSessionTitleDescription"),I,e=>{window.localStorage.setItem(sq,String(e)),M(e)}),en(d("settings.quoteSelection"),d("settings.quoteSelectionDescription"),n,s),en(d("settings.sidebarSingleProject"),d("settings.sidebarSingleProjectDescription"),T,e=>{window.localStorage.setItem(x,String(e)),window.dispatchEvent(new Event(v)),L(e)}),f?.isWindows&&(0,r.jsx)(s9,{label:d("settings.usePowerShell"),description:d("settings.shellToolDescription"),children:(0,r.jsx)(ld,{checked:f.powerShellEnabled,loading:k,label:d("settings.usePowerShell"),onChange:e=>void X(e)})}),S&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:S})]}),(0,r.jsxs)(s7,{title:d("settings.notifications"),children:[W&&(0,r.jsx)(s9,{label:d("settings.browserNotifications"),description:d("settings.browserNotificationsDescription"),children:"granted"===W?(0,r.jsx)("span",{className:"settings-row-status",children:d("settings.browserNotificationsOn")}):"denied"===W?(0,r.jsx)("span",{className:"settings-row-status",children:d("settings.browserNotificationsBlocked")}):(0,r.jsx)(la,{size:"small",onClick:()=>void Notification.requestPermission().then(z),children:d("settings.browserNotificationsEnable")})}),(0,r.jsx)(s9,{label:d("settings.pushPermission"),description:d("settings.pushPermissionDescription"),children:(0,r.jsx)(la,{size:"small",disabled:P,onClick:()=>void G(),children:P?d("settings.pushRegisterLoading"):d("settings.pushRegister")})}),D&&(0,r.jsx)("p",{role:"status",className:`settings-row-message ${"ok"===D.kind?"is-success":"is-error"}`,children:D.message})]}),(0,r.jsxs)(s7,{title:d("settings.about"),children:[(0,r.jsx)(s9,{label:d("settings.version"),children:(0,r.jsx)(iR,{showCurrentVersion:!0})}),B&&(0,r.jsx)(s9,{label:d("auth.logOut"),description:d("settings.logOutDescription"),children:(0,r.jsx)(la,{size:"small",variant:"danger",disabled:O,onClick:()=>void ee(),children:O?d("auth.loggingOut"):d("auth.logOut")})}),_&&(0,r.jsx)("p",{role:"alert",className:"settings-row-message is-error",children:_})]})]})}function ob({cwd:e,sessionId:t,initialSection:n,onClose:s,onSessionReloaded:l,onModelsChanged:o,quoteSelectionEnabled:a,onQuoteSelectionChange:d}){let{t:c}=(0,w.s)(),[u,h]=(0,i.useState)(n),[p,m]=(0,i.useState)("nav"),[g,f]=(0,i.useState)(()=>new Set([u])),x=[{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}],v=(0,i.useRef)(!1),y=(0,i.useCallback)(e=>{v.current=e},[]),b=(0,i.useCallback)(()=>{(!v.current||window.confirm(c("models.discardConfirm")))&&s()},[s,c]);(0,i.useEffect)(()=>s_(n),[n]),(0,i.useEffect)(()=>{let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),b())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[b]),(0,i.useEffect)(()=>{e||"skills"!==u&&"agents"!==u&&"plugins"!==u||(h("general"),f(e=>new Set(e).add("general")),s_("general"))},[e,u]);let k=x.find(e=>e.id===u)?.label,j=(0,i.useRef)(null),S=(e,t)=>g.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&&b()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface","data-pane":p,children:[(0,r.jsxs)("nav",{"aria-label":c("settings.title"),className:"settings-nav",children:[(0,r.jsx)("strong",{className:"settings-nav-title",children:c("settings.title")}),(0,r.jsx)("div",{className:"settings-nav-list",children:x.map(t=>{let n=t.requiresProject&&!e;return(0,r.jsxs)("button",{type:"button",className:"settings-nav-item",disabled:n,title:n?c("settings.projectRequired"):void 0,"aria-current":u===t.id?"page":void 0,onClick:()=>{var e;return e=t.id,void(f(t=>new Set(t).add(e)),h(e),s_(e),m("section"))},children:[(0,r.jsx)("span",{className:"settings-nav-label",children:t.label}),(0,r.jsx)("svg",{className:"settings-nav-chevron",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]},t.id)})})]}),(0,r.jsxs)("div",{className:"settings-dialog-content",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("button",{type:"button",className:"settings-nav-back",onClick:()=>{let e=j.current?.querySelector(".settings-section-host:not([hidden]) [data-settings-back]");e?e.click():m("nav")},"aria-label":c("i18n.back"),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:"m15 18-6-6 6-6"})})}),(0,r.jsx)("strong",{className:"settings-dialog-title",children:k})]}),(0,r.jsxs)("main",{ref:j,className:"settings-dialog-main",children:[S("general",(0,r.jsx)(oy,{sessionId:t,onSessionReloaded:l,quoteSelectionEnabled:a,onQuoteSelectionChange:d})),S("models",(0,r.jsx)(lF,{embedded:!0,onClose:b,cwd:e,onModelsChanged:o,onDirtyChange:y})),e&&S("agents",(0,r.jsx)(l3,{embedded:!0,cwd:e,sessionId:t,onClose:s,onReloaded:l},e)),S("images",(0,r.jsx)(oa,{sessionId:t,onReloaded:l})),e&&S("skills",(0,r.jsx)(lV,{embedded:!0,cwd:e,onClose:s},e)),e&&S("plugins",(0,r.jsx)(ol,{embedded:!0,cwd:e,sessionId:t,onClose:s,onReloaded:l},e))]})]}),(0,r.jsx)("button",{type:"button",onClick:b,title:c("i18n.close"),"aria-label":c("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]})})}function ow({cwd:e,busy:t,error:n,onCancel:s,onConfirm:l}){let{t:o}=(0,w.s)(),a=(0,i.useRef)(null),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=document.activeElement;return d.current?.focus(),()=>{e?.isConnected?e.focus():document.querySelector('[data-dialog-focus-fallback="true"]')?.focus()}},[]),(0,i.useEffect)(()=>{t&&a.current?.focus()},[t]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},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(),s();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:14,fontWeight:600,color:"var(--text)"},children:o("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:o("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:s,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:o("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--primary)",borderRadius:5,background:"var(--primary)",color:"var(--primary-contrast)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontSize:12},children:o(t?"trust.trusting":"trust.trustProject")})]})]})})}function ok(e){return"message"===e.type&&"message"in e&&"system"!==e.message.role}function oj(e){let t=e,n=t.branchPreview,r=ok(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&ok(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function oS(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 oC({node:e,activePathIds:t,depth:n,isLast:i,parentLines:s,onSelect:l}){let{node:o,skipped:a,branchPreview:d,labelEntry:c}=oj(e),u=t.has(o.entry.id),h=t.has(e.entry.id)||t.has(o.entry.id),p=d?.text??function(e){if("message"===e.type&&ok(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),m=d?d.role??null:ok(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(o.entry.id),children:[s.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"}}),m&&(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===m?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"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)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:p})]}),o.children.map((e,a)=>(0,r.jsx)(oC,{node:e,activePathIds:t,depth:n+1,isLast:a===o.children.length-1,parentLines:[...s,!i],onSelect:l},e.entry.id))]})}function oN({tree:e,activeLeafId:t,onLeafChange:n,inline:s,containerRef:l,open:o,onToggle:a,hasSession:d,compact:c,hideInlineButton:u,disabled:h=!1}){let{t:p}=(0,w.s)(),[m,g]=(0,i.useState)(!1),f=void 0!==o?o:m,x=(0,i.useRef)(null),[v,y]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!f||!s)return;let e=l?.current??x.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[f,s,l]);let b=(0,i.useMemo)(()=>(function(e,t){if(!t)return new Set;let n=e.map(e=>({node:e,path:[e.entry.id]}));for(;n.length>0;){let{node:e,path:r}=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return new Set(r);for(let t of e.children)n.push({node:t,path:[...r,t.entry.id]})}return new Set})(e,t),[e,t]),k=(0,i.useCallback)(e=>{n(e)},[n]),j=d?oS(e)?null:p("i18n.noBranches"):p("i18n.noActiveSession"),S=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=oj(e[0]).node;return t.children.length>1?t.children:[]}(e),C=!j&&S.length>0,N=h||!C,E=(0,r.jsxs)("svg",{width:c?13:12,height:c?13:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:X(c?13:12),strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),I=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:f?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return s?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{className:"workspace-header-action",ref:x,disabled:N,onClick:()=>{N||(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:f?"var(--bg-selected)":"none",border:"none",cursor:N?"not-allowed":"pointer",color:N?"var(--text-dim)":f?"var(--text)":"var(--text-muted)",opacity:N?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{N||(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{N||(e.currentTarget.style.color=f?"var(--text)":"var(--text-muted)",e.currentTarget.style.background=f?"var(--bg-selected)":"none")},title:N?p("i18n.noBranches",{defaultValue:"没有分支"}):p("i18n.branches"),"aria-label":p("i18n.branches"),"aria-pressed":f,children:[E,!c&&(0,r.jsx)("span",{style:{lineHeight:1},children:p("i18n.branches")})]}),f&&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)(oC,{node:e,activePathIds:b,depth:0,isLast:t===S.length-1,parentLines:[],onSelect:k},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)"},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")}),I]}),f&&(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)(oC,{node:e,activePathIds:b,depth:0,isLast:t===S.length-1,parentLines:[],onSelect:k},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)"},children:j??p("i18n.noBranches")})})]})}function oE({mobile:e,disabled:t,menuOpen:n,exporting:s=!1,error:l,labels:o,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 m=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?o.unsaved:o.menu,"aria-label":o.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)":m,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:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:n?"var(--text)":m,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":o.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:oI,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:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{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:o.full})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",title:o.exportMarkdownTitle,disabled:s,onClick:()=>{d()},style:{...oI,opacity:s?.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:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{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:o.exportMarkdown}),s&&(0,r.jsxs)("svg",{className:"animate-spin",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",style:{marginLeft:6,flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round"})]})]}),l&&(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"#dc2626",lineHeight:1.35},children:l})]})]})}let oI={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 oM({loading:e,prompt:t,translate:n}){return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":n("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:t?(0,r.jsx)("div",{className:"system-prompt-text",children:t}):(0,r.jsx)("div",{className:"system-prompt-empty",children:n(""===t?"system.empty":e?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
10
- .system-prompt-panel {
11
- display: flex;
12
- height: min(600px, 75dvh);
13
- min-height: 220px;
14
- flex-direction: column;
15
- background: var(--bg-panel);
16
- border-bottom: 1px solid var(--border);
17
- }
18
- .system-prompt-scroll {
19
- min-height: 0;
20
- flex: 1;
21
- overflow: auto;
22
- padding: 12px 16px;
23
- }
24
- .system-prompt-text {
25
- color: var(--text-muted);
26
- font-family: var(--font-mono);
27
- font-size: 12px;
28
- line-height: 1.6;
29
- overflow-wrap: anywhere;
30
- white-space: pre-wrap;
31
- }
32
- .system-prompt-empty {
33
- padding: 10px 0;
34
- color: var(--text-muted);
35
- font-size: 12px;
36
- }
37
- `})]})}function oT(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function oL({children:e}){return(0,r.jsx)("div",{className:"tool-definitions-empty",children:e})}function o$({loading:e,tools:t,translate:n}){let s=(0,i.useMemo)(()=>t?.filter(e=>e.active)??null,[t]),[l,o]=(0,i.useState)(null);(0,i.useEffect)(()=>{o(e=>s?.some(t=>t.name===e)?e:s?.[0]?.name??null)},[s]);let a=s?.find(e=>e.name===l)??s?.[0]??null,d=a?function(e){if(!e||!e.properties||"object"!=typeof e.properties)return[];let t=e.properties,n=new Set(Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[]);return Object.entries(t).map(([e,t])=>{let r=t&&"object"==typeof t?t:{};return{name:e,type:function e(t){let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(n)return n.map(t=>t&&"object"==typeof t?e(t):"unknown").filter((e,t,n)=>n.indexOf(e)===t).join(" | ");if(void 0!==t.const)return oT(t.const);if(Array.isArray(t.enum)&&t.enum.length>0&&void 0===t.type)return[...new Set(t.enum.map(e=>null===e?"null":typeof e))].join(" | ");let r=t.type,i=Array.isArray(r)?r.filter(e=>"string"==typeof e).join(" | "):"string"==typeof r?r:"string"==typeof t.$ref?t.$ref.split("/").pop()??"object":"unknown";if("array"===i){let n=t.items,r=n&&"object"==typeof n?e(n):"unknown";return`${r}[]`}return i}(r),description:"string"==typeof r.description?r.description:void 0,required:n.has(e),allowedValues:Array.isArray(r.enum)?r.enum.map(oT).join(", "):void 0,defaultValue:void 0===r.default?void 0:oT(r.default)}})}(a.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":n("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:s&&s.length>0?s.map(e=>{let t=e.name===a?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>o(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):s?(0,r.jsx)(oL,{children:n("tools.noTools")}):(0,r.jsx)(oL,{children:e?n("tools.loading"):n("tools.load")})})}),(0,r.jsx)("section",{className:"tool-definition-detail","aria-label":n("tools.details"),children:a?(0,r.jsxs)("div",{className:"tool-definition-scroll",children:[a.description&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:n("tools.description")}),(0,r.jsx)("div",{className:"tool-definition-description",children:a.description})]}),(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsxs)("div",{className:"tool-definition-section-label",children:[(0,r.jsx)("span",{children:n("tools.parameters")}),(0,r.jsx)("span",{children:n("tools.parameterCount",{count:d.length})})]}),d.length>0?(0,r.jsx)("div",{className:"tool-definition-fields",children:d.map(e=>(0,r.jsxs)("div",{className:"tool-definition-field",children:[(0,r.jsxs)("div",{className:"tool-definition-field-name",children:[(0,r.jsx)("code",{children:e.name}),(0,r.jsx)("span",{className:e.required?"required":void 0,children:n(e.required?"tools.required":"tools.optional")})]}),(0,r.jsxs)("div",{className:"tool-definition-field-value",children:[(0,r.jsx)("code",{className:"tool-definition-type",children:e.type}),e.description&&(0,r.jsx)("div",{children:e.description}),e.allowedValues&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[n("tools.allowedValues"),": ",(0,r.jsx)("code",{children:e.allowedValues})]}),void 0!==e.defaultValue&&(0,r.jsxs)("div",{className:"tool-definition-meta",children:[n("tools.defaultValue"),": ",(0,r.jsx)("code",{children:e.defaultValue})]})]})]},e.name))}):(0,r.jsx)("div",{className:"tool-definition-no-parameters",children:n("tools.noParameters")})]}),a.promptGuidelines&&a.promptGuidelines.length>0&&(0,r.jsxs)("section",{className:"tool-definition-section",children:[(0,r.jsx)("div",{className:"tool-definition-section-label",children:n("tools.guidelines")}),(0,r.jsx)("ul",{className:"tool-definition-guidelines",children:a.promptGuidelines.map((e,t)=>(0,r.jsx)("li",{children:e},`${a.name}:${t}`))})]})]}):(0,r.jsx)(oL,{children:s?n("tools.noTools"):e?n("tools.loading"):n("tools.load")})}),(0,r.jsx)("style",{children:`
38
- .tool-definitions-panel {
39
- display: grid;
40
- grid-template-columns: clamp(112px, 26%, 220px) minmax(0, 1fr);
41
- height: min(600px, 75dvh);
42
- min-height: 240px;
43
- overflow: hidden;
44
- background: var(--bg-panel);
45
- border-bottom: 1px solid var(--border);
46
- }
47
- .tool-definitions-sidebar,
48
- .tool-definition-detail {
49
- display: flex;
50
- min-width: 0;
51
- min-height: 0;
52
- flex-direction: column;
53
- }
54
- .tool-definitions-sidebar {
55
- border-right: 1px solid var(--border);
56
- background: color-mix(in srgb, var(--bg-panel) 94%, var(--bg));
57
- }
58
- .tool-definitions-list,
59
- .tool-definition-scroll {
60
- min-height: 0;
61
- flex: 1;
62
- overflow: auto;
63
- }
64
- .tool-definitions-item {
65
- display: flex;
66
- width: 100%;
67
- min-height: 38px;
68
- align-items: center;
69
- padding: 8px 12px;
70
- border: none;
71
- border-bottom: 1px solid var(--border);
72
- background: transparent;
73
- color: var(--text-muted);
74
- cursor: pointer;
75
- text-align: left;
76
- }
77
- .tool-definitions-item:hover {
78
- background: var(--bg-hover);
79
- color: var(--text);
80
- }
81
- .tool-definitions-item.selected {
82
- background: var(--bg-selected);
83
- box-shadow: inset 2px 0 0 var(--accent);
84
- color: var(--text);
85
- }
86
- .tool-definitions-item code {
87
- max-width: 100%;
88
- color: inherit;
89
- font-size: 11px;
90
- font-weight: 600;
91
- overflow-wrap: anywhere;
92
- }
93
- .tool-definition-scroll {
94
- padding: 14px 16px 20px;
95
- }
96
- .tool-definition-section + .tool-definition-section {
97
- margin-top: 18px;
98
- }
99
- .tool-definition-section-label {
100
- display: flex;
101
- align-items: center;
102
- justify-content: space-between;
103
- gap: 8px;
104
- margin-bottom: 7px;
105
- color: var(--text-dim);
106
- font-size: 11px;
107
- font-weight: 600;
108
- }
109
- .tool-definition-section-label > span:last-child {
110
- font-weight: 400;
111
- white-space: nowrap;
112
- }
113
- .tool-definition-description {
114
- color: var(--text-muted);
115
- font-size: 12px;
116
- line-height: 1.55;
117
- overflow-wrap: anywhere;
118
- white-space: pre-wrap;
119
- }
120
- .tool-definition-fields {
121
- border-top: 1px solid var(--border);
122
- }
123
- .tool-definition-field {
124
- display: grid;
125
- grid-template-columns: minmax(88px, 0.75fr) minmax(0, 1.5fr);
126
- gap: 12px;
127
- padding: 9px 0;
128
- border-bottom: 1px solid var(--border);
129
- font-size: 11px;
130
- line-height: 1.45;
131
- }
132
- .tool-definition-field-name {
133
- display: flex;
134
- min-width: 0;
135
- flex-direction: column;
136
- gap: 3px;
137
- color: var(--text);
138
- }
139
- .tool-definition-field-name code {
140
- overflow-wrap: anywhere;
141
- }
142
- .tool-definition-field-name span {
143
- color: var(--text-dim);
144
- font-size: 10px;
145
- }
146
- .tool-definition-field-name span.required {
147
- color: var(--accent);
148
- }
149
- .tool-definition-field-value {
150
- min-width: 0;
151
- color: var(--text-muted);
152
- overflow-wrap: anywhere;
153
- }
154
- .tool-definition-type {
155
- display: block;
156
- margin-bottom: 3px;
157
- color: var(--text);
158
- }
159
- .tool-definition-meta {
160
- margin-top: 4px;
161
- color: var(--text-dim);
162
- }
163
- .tool-definition-meta code {
164
- color: var(--text-muted);
165
- }
166
- .tool-definition-no-parameters {
167
- padding: 2px 0 10px;
168
- color: var(--text-dim);
169
- font-size: 11px;
170
- }
171
- .tool-definition-guidelines {
172
- margin: 0;
173
- padding-left: 18px;
174
- color: var(--text-muted);
175
- font-size: 11px;
176
- line-height: 1.5;
177
- }
178
- .tool-definitions-empty {
179
- padding: 14px 12px;
180
- color: var(--text-muted);
181
- font-size: 12px;
182
- overflow-wrap: anywhere;
183
- }
184
- @media (max-width: 640px) {
185
- .tool-definitions-panel {
186
- grid-template-columns: 112px minmax(0, 1fr);
187
- }
188
- .tool-definitions-item {
189
- padding: 8px 10px;
190
- }
191
- .tool-definition-scroll {
192
- padding: 12px;
193
- }
194
- .tool-definition-field {
195
- grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
196
- gap: 9px;
197
- }
198
- }
199
- `})]})}function oR(e){return e.name||e.firstMessage||e.id.slice(0,12)}function oW(e,t){return t?"running":e.relation?.kind==="subagent"?e.relation.status:"completed"}function oz(e){return"running"===e||"starting"===e?0:"queued"===e?1:2}function oP({status:e}){return"running"===e||"starting"===e?(0,r.jsx)(Z,{size:13}):"failed"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m9 9 6 6M15 9l-6 6"})]}):"queued"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}):"aborted"===e||"interrupted"===e?(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M9 9h6v6H9z"})]}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"m8 12 3 3 5-6"})]})}function oA({session:e,main:t,selected:n,running:i,onSelect:s,onOpenInNewTab:l}){let{locale:o,t:a}=(0,w.s)(),d=e.relation?.kind==="subagent"?e.relation:null,c=oW(e,i),u=t?a("agentSwitcher.main"):d?.description||oR(e),h=t?oR(e):`${d?.profile??a("agentSwitcher.subagent")} \xb7 ${function(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let s=Math.round(r/60);if(60>Math.abs(s))return i.format(s,"minute");let l=Math.round(s/60);return 24>Math.abs(l)?i.format(l,"hour"):i.format(Math.round(l/24),"day")}(e.modified,o)}`;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,onClick:s,onAuxClick:e=>{1===e.button&&l&&(e.preventDefault(),l())},style:{width:"100%",minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",borderBottom:"1px solid var(--border)",borderLeft:n?"2px solid var(--accent)":"2px solid transparent",background:n?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="transparent")},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:t?"var(--text-muted)":"var(--accent)"},children:t?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"M3 9h18"})]}):(0,r.jsx)(G,{size:16})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12},title:u,children:u}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:h,children:h})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:t&&!i?"var(--text-dim)":"running"===c||"starting"===c?"var(--accent)":"completed"===c?"#16a34a":"failed"===c?"#dc2626":"aborted"===c?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:t&&!i?n?a("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oP,{status:c}),(0,r.jsx)("span",{children:a(`agentSwitcher.status.${c}`)})]})})]})}function oD({rootSession:e,subagents:t,selectedSessionId:n,runningSessionIds:s,onSelectSession:l,onOpenInNewTab:o}){let{t:a}=(0,w.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useMemo)(()=>[...t].sort((e,t)=>{let n=oz(oW(e,s.has(e.id)))-oz(oW(t,s.has(t.id)));return 0!==n?n:t.modified.localeCompare(e.modified)}),[s,t]),h=d.trim().toLowerCase(),p=h?u.filter(e=>{let t=e.relation?.kind==="subagent"?e.relation:null;return[t?.description,t?.profile,e.name,e.firstMessage].some(e=>e?.toLowerCase().includes(h))}):u,m=t.filter(e=>s.has(e.id)).length;return(0,r.jsx)("div",{role:"listbox","aria-label":a("agentSwitcher.title"),style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 10px 30px rgba(0, 0, 0, 0.14)",overflow:"hidden"},children:(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{minHeight:44,display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("strong",{style:{fontSize:12,fontWeight:600},children:a("agentSwitcher.title")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:a("agentSwitcher.count",{count:t.length})}),m>0&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--accent)",fontSize:11},children:a("agentSwitcher.runningCount",{count:m})})]}),t.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",className:"agent-switcher-search-input",value:d,onChange:e=>c(e.target.value),placeholder:a("agentSwitcher.search"),"aria-label":a("agentSwitcher.search"),style:{width:"100%",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(58dvh, 480px)",overflowY:"auto"},children:[(0,r.jsx)(oA,{session:e,main:!0,selected:e.id===n,running:s.has(e.id),onSelect:()=>l(e),onOpenInNewTab:o?()=>o(e):void 0}),p.map(e=>(0,r.jsx)(oA,{session:e,selected:e.id===n,running:s.has(e.id),onSelect:()=>l(e),onOpenInNewTab:o?()=>o(e):void 0},e.id)),0===p.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:a("agentSwitcher.noMatches")})]})]})})}var oF=n(63606),oB=n(8422);async function oH(e,t){let n=await fetch(e,{...t,signal:AbortSignal.timeout(15e3)}),r=await n.json().catch(()=>{throw Error(`Terminal request failed (HTTP ${n.status}): server returned an empty or invalid JSON response. Check the pi-web server log.`)});if(!r||"object"!=typeof r)throw Error(`Terminal request failed (HTTP ${n.status}): invalid JSON response. Check the pi-web server log.`);if(!n.ok)throw Error(r.error??`HTTP ${n.status}`);return r}function oO({tab:e,active:t,onRestart:n,onClosed:s,onCloseError:l}){let{t:o}=(0,w.s)(),{id:a,cwd:d,restored:c}=e,u=(0,i.useRef)(null),h=(0,i.useRef)(null),p=(0,i.useRef)(Promise.resolve()),m=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:s,onCloseError:l});g.current={onClosed:s,onCloseError:l};let[f,x]=(0,i.useState)("connecting"),[v,y]=(0,i.useState)(null),[b,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(0);return(0,i.useEffect)(()=>{var e;let t,n,r,i,s,l=u.current;if(!l)return;let o=!1,g=null,f=!1,v=!1,b=!1;x("connecting"),y(null),k(null);let w=new oB.B({cursorBlink:!0,fontFamily:getComputedStyle(l).getPropertyValue("--font-mono").trim()||"monospace",fontSize:13,lineHeight:1.25,scrollback:8e3,screenReaderMode:!0,disableStdin:!0,theme:{background:"#111318",foreground:"#d7dce5",cursor:"#60a5fa",selectionBackground:"#365b8a",black:"#1d222b",red:"#f87171",green:"#4ade80",yellow:"#facc15",blue:"#60a5fa",magenta:"#c084fc",cyan:"#22d3ee",white:"#e5e7eb",brightBlack:"#6b7280",brightRed:"#fca5a5",brightGreen:"#86efac",brightYellow:"#fde047",brightBlue:"#93c5fd",brightMagenta:"#d8b4fe",brightCyan:"#67e8f9",brightWhite:"#ffffff"}});h.current=w;let S=new oF.Y;w.loadAddon(S),w.open(l),w.attachCustomKeyEventHandler(e=>{if("keydown"!==e.type)return!0;let t=e.key.toLowerCase();return!((e.ctrlKey||e.metaKey)&&"v"===t||(e.ctrlKey||e.metaKey)&&"c"===t&&w.hasSelection())});let C=(e=e=>{o||(b=!0,w.options.disableStdin=!0,y(e.message),x("error"))},n=Promise.resolve(),r=!1,i=null,s=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await oH(`/api/terminal/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:s(i={type:"input",data:t})},resize(e,t){i=null,s({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});m.current=C;let N=w.onData(e=>{!f||v||b||C.write(e)}),E=()=>{l.offsetWidth&&l.offsetHeight&&S.fit()},I=w.onResize(({cols:e,rows:t})=>{!f||v||b||C.resize(e,t)}),M=new ResizeObserver(E);M.observe(l);let T=()=>{o||v||!navigator.onLine||(g?.close(),(g=new EventSource(`/api/terminal/${encodeURIComponent(a)}/events${void 0===t?"":`?after=${t}`}`)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)w.reset();else if(void 0!==t&&n.offset<=t)return;w.write(n.data),t=n.offset}else v=!0,f=!1,w.options.disableStdin=!0,g?.close(),k("exit"===n.type?n.exitCode:null),x("exited")},g.onopen=()=>{f=!0,!b&&(w.options.disableStdin=!1,x("ready"),E(),C.resize(w.cols,w.rows),l.offsetWidth&&l.offsetHeight&&w.focus())},g.onerror=()=>{o||v||(f=!1,w.options.disableStdin=!0,x(g?.readyState===EventSource.CLOSED?"error":"connecting"))})};p.current=(async()=>{E(),c||j>0?await oH(`/api/terminal/${encodeURIComponent(a)}`):await oH("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:a,cwd:d,cols:w.cols,rows:w.rows})}),T()})().catch(e=>{o||(y(e.message),x("error"))});let L=()=>{f=!1,w.options.disableStdin=!0,g?.close(),v||b||x("connecting")},$=e=>{e.persisted&&T()};return window.addEventListener("pagehide",L),window.addEventListener("pageshow",$),window.addEventListener("offline",L),window.addEventListener("online",T),()=>{o=!0,g?.close(),C.stop(),M.disconnect(),N.dispose(),I.dispose(),window.removeEventListener("pagehide",L),window.removeEventListener("pageshow",$),window.removeEventListener("offline",L),window.removeEventListener("online",T),w.dispose(),h.current=null}},[a,d,c,j]),(0,i.useEffect)(()=>{t&&h.current?.focus()},[t]),(0,i.useEffect)(()=>{if(!e.closing)return;let t=!1;return h.current&&(h.current.options.disableStdin=!0),(async()=>{await p.current,await m.current?.stop(),await oH(`/api/terminal/${encodeURIComponent(a)}`,{method:"DELETE",keepalive:!0}),t||g.current.onClosed()})().catch(e=>{t||(y(e.message),x("error"),g.current.onCloseError())}),()=>{t=!0}},[a,e.closing]),(0,r.jsxs)("section",{className:"terminal-panel","aria-label":o("terminal.title"),children:[(0,r.jsxs)("header",{className:"terminal-panel-header",children:[(0,r.jsxs)("div",{className:"terminal-panel-path",children:[(0,r.jsx)("span",{className:`terminal-status-dot is-${f}`,title:o(`terminal.${f}`)}),(0,r.jsx)("span",{title:d,children:d})]}),"error"===f&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>e+1),disabled:!!e.closing,title:o("terminal.reconnect"),"aria-label":o("terminal.reconnect"),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:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,r.jsx)("button",{type:"button",onClick:n,disabled:!!e.closing,title:o("terminal.restart"),"aria-label":o("terminal.restart"),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:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]}),(0,r.jsxs)("div",{children:[v&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:v}),"exited"===f&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===b?o("terminal.exited"):o("terminal.exitCode",{code:b})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:u,className:"terminal-xterm-host"})})]})}let oU="pi-web:terminal-tabs";function o_(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function oq(e,t,n){let r=Number.isFinite(e)?e:t,i=Math.max(t,n);return Math.round(Math.max(t,Math.min(i,r)))}function oK(e){return{min:Math.max(.2,280/e),max:Math.min(.8,(e-12-280)/e)}}function oV(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function oJ(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:s,getMaxWidth:l,growthDirection:o,maxWidth:a,minWidth:d,storageKey:c,widthRef:u}=e,h=(0,i.useRef)(null),p=(0,i.useRef)(null),m=(0,i.useRef)(!1),[g,f]=(0,i.useState)(r),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1);(0,i.useEffect)(()=>{b(!0)},[]);let w=(0,i.useCallback)(()=>Math.min(a,Math.max(d,l())),[l,a,d]),k=(0,i.useCallback)(e=>oq(e,d,w()),[w,d]),j=(0,i.useCallback)(e=>{u.current=e,h.current?.style.setProperty(n,`${e}px`)},[n,u]),S=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=k(e),s=i!==u.current;return j(i),f(i),r&&(s||n)&&oV(c,i),i},[j,k,c,u]),C=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),N=(0,i.useCallback)(e=>{let t=p.current;if(t&&t.pointerId===e){p.current=null,C(t),v(!1),S(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[S,C,u]),E=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=p.current;t&&N(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),p.current={pointerId:e.pointerId,startX:e.clientX,startWidth:u.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",v(!0)},[N,u]),I=(0,i.useCallback)(e=>{let t=p.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void N(e.pointerId);e.preventDefault();let n="right"===o?1:-1,r=k(t.startWidth+(e.clientX-t.startX)*n);j(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[j,k,N,o]),M=(0,i.useCallback)(e=>{N(e.pointerId)},[N]),T=(0,i.useCallback)(e=>{N(e.pointerId)},[N]),L=(0,i.useCallback)(e=>{N(e.pointerId)},[N]),$=(0,i.useCallback)(()=>{S(s?.()??r,{forcePersist:!0})},[S,r,s]),R=(0,i.useCallback)(()=>{S(u.current)},[S,u]),W=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===o?"ArrowRight":"ArrowLeft",r="right"===o?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),S(u.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),S(u.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),S(d,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),S(w(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),$())},[S,w,o,d,$,u]);return(0,i.useLayoutEffect)(()=>{if(m.current)return;m.current=!0;let e=h.current,t=e?.style.transition??"";e&&(e.style.transition="none");let n=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(c),i=S(n??s?.()??r,{persist:!1});null!==n&&n!==i&&oV(c,i),e&&(e.offsetWidth,e.style.transition=t)},[S,r,s,c]),(0,i.useEffect)(()=>{if(!m.current)return;S(u.current);let e=()=>{S(u.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[S,u]),(0,i.useEffect)(()=>{if(!x)return;let e=()=>{let e=p.current;e&&N(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[N,x]),(0,i.useEffect)(()=>()=>{let e=p.current;e&&(p.current=null,C(e))},[C]),{isResizing:x,panelRef:h,reclampWidth:R,resetWidth:$,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":y?w():a,"aria-valuemin":d,"aria-valuenow":g,"aria-valuetext":`${g} px`,onDoubleClick:$,onKeyDown:W,onLostPointerCapture:L,onPointerCancel:T,onPointerDown:E,onPointerMove:I,onPointerUp:M,role:"separator",tabIndex:0},width:g}}let oY="pi-web:pinned-cwds";function oZ(){try{return window.localStorage}catch{return null}}function oX(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if("string"!=typeof n)continue;let e=n.trim();!e||t.includes(e)||t.push(e)}return t}function oG(e,t,n){return t&&n?k(t).replace(/\/$/,"")===k(n).replace(/\/$/,"")||e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?e:E(t,e):e}let oQ="pi-chat-draft-tabs";function o0(e){return`parked-new:${e}`}function o1(){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function o2(){let e,t,n,o,a,d,c,u,h,f,x,v,y,b,k,j,C=(0,s.useRouter)(),N=(0,s.useSearchParams)(),[E]=(0,i.useState)(()=>{let e;return{requestedCwd:e=N.get("cwd")?.trim()||null,sessionId:e?null:N.get("session")}}),{locale:I,t:M}=(0,w.s)(),T=eG();(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,s=.01>Math.abs(e.scale-1);i&&s&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]),n8(),(0,i.useEffect)(()=>r4(e=>{"granted"===e&&om(I)}),[I]);let{soundEnabled:L,onSoundToggle:$,playDoneSound:R,unlockAudio:W,soundEnabledRef:z}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),s=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),l=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=s();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[s]);return{soundEnabled:e,onSoundToggle:(0,i.useCallback)(()=>{let e=!n.current;e&&l(!0),n.current=e,localStorage.setItem("pi-sound-enabled",String(e)),t(e)},[l]),playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=s();if(!e)return;let t=()=>{try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),s=e.createGain();i.connect(s),s.connect(e.destination),i.type="sine",i.frequency.value=n;let l=t+.18*r;s.gain.setValueAtTime(0,l),s.gain.linearRampToValueAtTime(.18,l+.02),s.gain.exponentialRampToValueAtTime(.001,l+.45),i.start(l),i.stop(l+.45)})}catch{}};"suspended"===e.state?e.resume().then(t).catch(()=>{}):t()},[s]),unlockAudio:l,soundEnabledRef:n}}(),[P,A]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{A("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let D=(0,i.useCallback)(e=>{A(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),F=(0,i.useRef)(new Set),B=(0,i.useCallback)(e=>{if(!z.current)return;let t=new Set(eM.current.filter(e=>"session"===e.kind&&e.session).map(e=>e.session.id));(!e||!(e.length>0)||e.some(e=>!t.has(e)))&&R()},[R,z]),[H,O]=(0,i.useState)(null),[U,_]=(0,i.useState)([]),q=(0,i.useCallback)(e=>{_(e)},[]),K=(0,i.useMemo)(()=>g(U).map(e=>e.root),[U]),[V,J]=(0,i.useState)(()=>(function(e=oZ()){if(!e)return[];try{let t=e.getItem(oY);if(!t)return[];return oX(JSON.parse(t))}catch{return[]}})()),Y=(0,i.useCallback)(e=>{J(t=>{let n,r=(n=e.trim())?t.includes(n)?t.filter(e=>e!==n):[...t,n]:oX(t);return!function(e,t=oZ()){if(t)try{t.setItem(oY,JSON.stringify(oX(e)))}catch{}}(r),r})},[]),[Z,X]=(0,i.useState)(""),[Q,ee]=(0,i.useState)(null),et=(0,i.useMemo)(()=>H?[...U.filter(e=>e.id!==H.id),H]:U,[H,U]),en=(0,i.useMemo)(()=>{var e;return(e=H?.id)?l(et).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[H?.id,et]),er=!!en?.subagents.length,[ei,es]=(0,i.useState)(()=>new Set),el=(0,i.useCallback)(e=>{es(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[eo,ea]=(0,i.useState)(null),[ec,eu]=(0,i.useState)("initial"),eh=(0,i.useRef)(null),[ep,em]=(0,i.useState)(()=>E.requestedCwd?"validating":"idle"),[eg,ef]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(0),[ey,eb]=(0,i.useState)(0),ew=(0,i.useRef)(new Map),ek=(0,i.useCallback)((e,t)=>{ew.current.set(e,t)},[]),[ej,eS]=(0,i.useState)([]),[eC,eN]=(0,i.useState)(!1),[eE,eI]=(0,i.useState)(!1),eM=(0,i.useRef)([]);eM.current=ej;let[eT,eL]=(0,i.useState)(null),e$=(0,i.useRef)(null);e$.current=eT;let[eR,eW]=(0,i.useState)(null),ez=(0,i.useRef)(null);ez.current=eR;let[eA,eF]=(0,i.useState)("primary"),eB=(0,i.useRef)("primary");eB.current=eA;let eH=(0,i.useRef)(!1),[eU,e_]=(0,i.useState)(.5),eq=(0,i.useRef)(null),eV=(0,i.useRef)(!1),[eJ,eY]=(0,i.useState)(600);e=(0,i.useMemo)(()=>0===ej.length?H?.id?[H.id]:[]:ej.flatMap(e=>"session"===e.kind&&e.session?[e.session.id]:[]),[ej,H?.id]).join(","),(0,i.useEffect)(()=>{if(!e)return;let t=e.split(","),n=!1,r=()=>{if(!n)for(let e of t)fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store"}).catch(()=>{})};r();let i=setInterval(r,3e4),s=()=>{"visible"===document.visibilityState&&r()};return document.addEventListener("visibilitychange",s),()=>{n=!0,clearInterval(i),document.removeEventListener("visibilitychange",s)}},[e]);let eZ=(0,i.useCallback)((e,t,n)=>{let r=!!(t.trim()||n>0),i=iG(t,M("i18n.newSession"));eS(t=>{let n=!1,s=t.map(t=>"draft"!==t.kind||t.newSessionDraftKey!==e||t.dirty===r&&t.title===i?t:(n=!0,{...t,dirty:r,title:i}));return n?s:t})},[M]);(0,i.useEffect)(()=>{try{let e=window.sessionStorage.getItem(oQ),t=(e?JSON.parse(e):[]).flatMap(e=>{if("string"!=typeof e?.draftKey||"string"!=typeof e?.title)return[];let t=eP(e.draftKey);return t?[{id:`draft:${e.draftKey}`,kind:"draft",title:iG(t.value,e.title),session:null,newSessionCwd:"string"==typeof e.cwd?e.cwd:null,newSessionDraftKey:e.draftKey,projectKey:"string"==typeof e.cwd?e.cwd:null,dirty:!0}]:[]});if(t.length>0&&(eS(e=>[...e,...t.filter(t=>!e.some(e=>e.id===t.id))]),!E.sessionId&&!E.requestedCwd)){let e=t[0];eL(t=>t??e.id),O(null),ea(e.newSessionCwd),eh.current=e.newSessionDraftKey}}catch{}eN(!0)},[E.requestedCwd,E.sessionId]),(0,i.useEffect)(()=>{if(!eC)return;let e=ej.flatMap(e=>"draft"===e.kind&&e.dirty&&e.newSessionDraftKey?[{draftKey:e.newSessionDraftKey,cwd:e.newSessionCwd,title:e.title}]:[]);if(0===e.length){try{window.sessionStorage.removeItem(oQ)}catch{}eI(!1);return}try{window.sessionStorage.setItem(oQ,JSON.stringify(e)),eI(!1)}catch{eI(!0)}},[ej,eC]);let[eX,eQ]=(0,i.useState)(null),e0=(0,i.useCallback)(e=>{eQ(t=>t===e?null:t)},[]),[e1,e2]=(0,i.useState)(0),[e4,e8]=(0,i.useState)(null),[e3,e6]=(0,i.useState)(0),[e5,e7]=(0,i.useState)(null),[e9,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(!1),[tr,ti]=(0,i.useState)(null),[tl,to]=(0,i.useState)(!0),[ta,td]=(0,i.useState)(!1),[tc,tu]=(0,i.useState)(!1),[th,tp]=(0,i.useState)(!1),tm=(0,i.useRef)(260),tg=(0,i.useRef)(560),tf=(0,i.useCallback)(()=>oq(.42*window.innerWidth,360,640),[]),tx=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let i=t<960;return Math.min(480,t-(i?320:420)-(!i&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:ta,rightPanelWidth:tg.current}),[ta]),tv=(0,i.useCallback)(()=>(function(e){let{viewportWidth:t,sidebarOpen:n,sidebarWidth:r}=e;return t<960?1200:Math.min(1200,t-420-(n?r:0))})({viewportWidth:window.innerWidth,sidebarOpen:tl,sidebarWidth:tm.current}),[tl]),ty=oJ({ariaLabel:M("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tx,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:tm}),tb=oJ({ariaLabel:M("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:tf,getMaxWidth:tv,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:tg}),tw=ty.reclampWidth,tk=tb.reclampWidth;(0,i.useEffect)(()=>{T&&to(!1)},[T]),(0,i.useEffect)(()=>{tp(!0)},[]),(0,i.useEffect)(()=>{ta&&(tw(),tk())},[tk,tw,ta]),(0,i.useEffect)(()=>{if(!ta)return void tu(!1);let e=tb.panelRef.current,t=!1,n=()=>{t||(t=!0,tu(!0))};if(window.matchMedia("(prefers-reduced-motion: reduce)").matches)return void n();let r=t=>{t.target===e&&("width"===t.propertyName||"min-width"===t.propertyName||"transform"===t.propertyName)&&n()};e?.addEventListener("transitionend",r);let i=window.setTimeout(n,280);return()=>{e?.removeEventListener("transitionend",r),window.clearTimeout(i)}},[ta,tb.panelRef]);let tj=(0,i.useRef)(null),[tS,tC]=(0,i.useState)(null),tN=(0,i.useCallback)(e=>{tC(t=>t?.sessionId===e?null:t)},[]),tE=(0,i.useRef)(null),[tI,tM]=(0,i.useState)([]),[tT,tL]=(0,i.useState)(null),[t$,tR]=(0,i.useState)(!1),[tW,tz]=(0,i.useState)(!1),[tP,tA]=(0,i.useState)(null),tD=(0,i.useRef)(null),tF=oS(tI),tB=(0,i.useRef)(new Map),tH=(0,i.useRef)(new Map),tO=(0,i.useRef)(new Map),tU=(0,i.useCallback)((e,t,n)=>{ne.current&&tO.current.set(ne.current,{tree:e,activeLeafId:t}),tM(e),tL(t),tD.current=n},[]),t_=(0,i.useCallback)(e=>{tD.current?.(e)},[]),[tq,tK]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(null),[tY,tZ]=(0,i.useState)(!1),tX=(0,i.useRef)(null),tG=(0,i.useRef)(0),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(null),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),t8=(0,i.useRef)(null),t3=(0,i.useCallback)(e=>{tK(e),tZ(!1)},[]),t6=(0,i.useCallback)(e=>{tJ(e)},[]),t5=(0,i.useCallback)(e=>{tG.current+=1,tX.current=e,tZ(!1)},[]),[t7,t9]=(0,i.useState)(null),ne=(0,i.useRef)(H?.id??null);ne.current=H?.id??null;let nt=(0,i.useCallback)(e=>{null!==e&&(e.sessionId&&tB.current.set(e.sessionId,e),t9(e))},[]),[nn,nr]=(0,i.useState)(null),ni=(0,i.useRef)(null),ns=(0,i.useCallback)((e,t)=>{n3(t).then(()=>{ni.current&&clearTimeout(ni.current),nr(e),ni.current=setTimeout(()=>nr(null),1400)})},[]);(0,i.useEffect)(()=>()=>{ni.current&&clearTimeout(ni.current)},[]);let[nl,no]=(0,i.useState)(null),na=(0,i.useCallback)(e=>{null!==e&&(ne.current&&tH.current.set(ne.current,e),no(e))},[]),nd=(0,i.useCallback)(e=>{t9(tB.current.get(e)??null),no(tH.current.get(e)??null);let t=tO.current.get(e);tM(t?.tree??[]),tL(t?.activeLeafId??null)},[]);(0,i.useEffect)(()=>{if(!H){t9(null),no(null);return}nd(H.id)},[H,nd]);let[nc,nu]=(0,i.useState)(null),[nh,np]=(0,i.useState)(null),nm=(0,i.useCallback)((e=!1)=>{nu(null),e&&nc&&requestAnimationFrame(()=>{let e=document.querySelector(`[data-top-panel-trigger="${nc}"]`)??t0.current;e?.focus()})},[nc]);(0,i.useEffect)(()=>{tF||nu(e=>"branches"===e?null:e)},[tF]),(0,i.useEffect)(()=>{er||nu(e=>"agents"===e?null:e)},[er]);let ng=(0,i.useCallback)(e=>{T&&to(!1),nu(t=>t===e?null:e)},[T]),nf=(0,i.useCallback)(e=>{let t=nc!==e;if(ng(e),!t||tY)return;let n=tX.current;if(!n)return;let r=++tG.current;tZ(!0),n().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tG.current===r&&tZ(!1)})},[nc,tY,ng]),nx=(0,i.useCallback)(()=>{T&&to(!1),nu(e=>"session"===e?null:"session")},[T]),nv=(0,i.useCallback)(()=>{T&&nu(null),to(e=>!e)},[T]),ny=(0,i.useCallback)(()=>{to(!1),requestAnimationFrame(()=>t0.current?.focus())},[]);(0,i.useEffect)(()=>{if(!T||!tl||!th)return;let e=requestAnimationFrame(()=>{let e=ty.panelRef.current;e?.querySelector('[aria-current="page"], button:not(:disabled)')?.focus()}),t=e=>{"Escape"===e.key&&(e.preventDefault(),ny())};return document.addEventListener("keydown",t),()=>{cancelAnimationFrame(e),document.removeEventListener("keydown",t)}},[ny,T,th,tl,ty.panelRef]);let nb=(0,i.useCallback)(()=>{T&&(to(!1),nu(null)),td(e=>!e)},[T]),nw=(0,i.useCallback)((e=!1)=>{td(!1),e&&requestAnimationFrame(()=>t1.current?.focus())},[]);(0,i.useEffect)(()=>{if(!ta)return;let e=requestAnimationFrame(()=>{(T||!(window.innerWidth>=960))&&tb.panelRef.current?.querySelector('[role="tab"][aria-selected="true"]')?.focus()}),t=e=>{"Escape"===e.key&&(T||!(window.innerWidth>=960))&&(e.preventDefault(),e.stopPropagation(),nw(!0))};return document.addEventListener("keydown",t,!0),()=>{cancelAnimationFrame(e),document.removeEventListener("keydown",t,!0)}},[nw,T,ta,tb.panelRef]),(0,i.useEffect)(()=>{tR(!1),tA(null)},[T,H?.id,ec]),(0,i.useEffect)(()=>{nc&&tR(!1)},[nc]),(0,i.useEffect)(()=>{if(!nc||!tE.current)return;let e=()=>{let e=tE.current.getBoundingClientRect();if("agents"===nc){let t=t4.current??t2.current,n=Math.min(420,window.innerWidth-16);if(t){let e=t.getBoundingClientRect(),r=Math.max(8,Math.min(e.right-n,window.innerWidth-n-8));np({top:e.bottom+4,left:r,width:n});return}let r=Math.max(8,Math.min(e.right-n-8,window.innerWidth-n-8));np({top:e.bottom+4,left:r,width:n});return}np({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tE.current),window.addEventListener("resize",e),()=>{t.disconnect(),window.removeEventListener("resize",e)}},[nc,T]),(0,i.useEffect)(()=>{if(!nc||"branches"===nc||"language"===nc)return;let e=e=>{let t=e.target;!t||t8.current?.contains(t)||t instanceof Element&&t.closest(`[data-top-panel-trigger="${nc}"]`)||nm()},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),nm(!0))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[nc,nm]);let[nk,nj]=(0,i.useState)([]),[nS,nC]=(0,i.useState)(null),[nN,nE]=(0,i.useState)([]),[nI,nM]=(0,i.useState)(!1),nT=(0,i.useMemo)(()=>[...nk,...nN.map(e=>({id:e.id,label:S(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing}))],[nk,nN]);(0,i.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(oU));nE(e.tabs),e.activeId&&(nC(e.activeId),td(e.open))}catch{}nM(!0)},[]),(0,i.useEffect)(()=>{if(nI)try{window.sessionStorage.setItem(oU,JSON.stringify({tabs:nN.map(({id:e,cwd:t})=>({id:e,cwd:t})),activeId:nS,open:ta}))}catch{}},[nN,nS,ta,nI]);let nL=(0,i.useCallback)((e,t,n)=>{nj(r=>(function(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let s=[...e];return s[i]={...s[i],viewerState:r},s})(r,e,t,n))},[]),[n$,nR]=(0,i.useState)(null),nW=(0,i.useCallback)(()=>{let e=eH.current&&"secondary"===eB.current?ez.current:e$.current,t=eM.current.find(t=>t.id===e);return t?.kind==="session"?t.session?.cwd??null:t?.kind==="draft"?t.newSessionCwd:H?.cwd??eo??n$},[n$,eo,H?.cwd]),nz=(0,i.useCallback)((e,t,n)=>{let r=oG(e,n,nW());tj.current?.insertText(eK(r,t)),T&&(td(!1),to(!1))},[nW,T]),nP=(0,i.useCallback)((e,t)=>{let n=nW(),r=e.map(e=>oG(e,t,n)).map(e=>eK(e,!1)).join("");r&&tj.current?.insertText(r),T&&(td(!1),to(!1))},[nW,T]),nA=(0,i.useCallback)((e,t,n,r)=>{let i,s,l,o,a,d,c,u=oG(e,r,nW());tj.current?.insertText((s=(i=e=>Number.isFinite(e)&&Number.isInteger(e)&&e>=1?e:1)(t),o=Math.min(s,l=i(n)),a=Math.max(s,l),d=u.includes(" ")?`@"${u}"`:`@${u}`,c=o===a?`:${o}`:`:${o}-${a}`,`${d}${c} `)),T&&(td(!1),to(!1))},[nW,T]),nD=E.sessionId,nF=(0,i.useRef)(null),nB=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=E.requestedCwd;if(!e)return;let t=new AbortController;return em("validating"),ef(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);nB.current=!0;let r=`initial:${e}`;eu(r),eh.current=`new:${r}:${n.cwd}`,ea(n.cwd),em("ready")}).catch(e=>{t.signal.aborted||(ef(e instanceof Error?e.message:String(e)),em("error"))}),()=>t.abort()},[E]);let nH=(0,i.useCallback)((e,t,n)=>{let r=eo??n$;if(nR(e),!e)return;let i=n??t??e,s=nF.current??(H?m(H):null);if(nF.current=i,nB.current){nB.current=!1;return}if(r===e&&s!==i||void 0!==eM&&eM.current?.length>0||s===i&&(null!==H||r===e))return;let l=eh.current;l&&r&&eO(l,o0(r));let o="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${o}:${e}`;eO(o0(e),a),eu(o),eh.current=a,O(null),ea(t=>t&&t!==e?null:t),eb(e=>e+1),tM([]),tL(null),tK(null),tJ(null),tZ(!1),nu(null),s!==i&&(nj([]),(!nS||nS.startsWith("file:"))&&(nC(null),td(!1))),C.replace(window.location.pathname,{scroll:!1})},[n$,nS,eo,C,H]),nO=(0,i.useCallback)((e,t=!1,n,r,i=!1,s=!1)=>{var l,o;let a,d;eQ(n?{sessionId:e.id,entryId:n,blockIndex:r}:null);let c=eh.current,u=eo??(null===H?n$:null);if(c&&u&&!eM.current.some(e=>e.id===`draft:${c}`)&&eO(c,o0(u)),eh.current=null,e.projectKey&&(nF.current=e.projectKey),!t&&H){let t=m(H)===m(e);if(H.id===e.id&&t){i&&eS(t=>i2(t,e.id)),T&&to(!1);return}}ea(null),"function"==typeof nd&&nd(e.id),O(e);let h=eH.current?eB.current:"primary",g=(l=eM.current,o=e.id,"secondary"===(d=(a=l.find(e=>e.id===o))?iQ(a):h)?{splitChatTabId:o,pane:d}:{activeChatTabId:o,pane:d});eS(n=>!s||t||i?(t||i?i8(n,e,h):i1(n,e,h)).tabs:function(e,t,n,r="primary"){let i=e.findIndex(e=>e.id===n.id),s=p(n);if(i>=0){let t=[...e];return t[i]={...t[i],session:n,title:s,projectKey:n.projectKey??n.cwd},{tabs:t,tabId:n.id}}let l=t?e.findIndex(e=>e.id===t):-1,o=l>=0?e[l]:void 0;if(!o||"session"!==o.kind)return i1(e,n,r);let a=[...e];return a[l]={...o,id:n.id,title:s,session:n,newSessionCwd:null,newSessionDraftKey:null,projectKey:n.projectKey??n.cwd,mountKey:void 0},{tabs:a,tabId:n.id}}(n,"secondary"===h?ez.current:e$.current,e,h).tabs),void 0!==g.activeChatTabId&&eL(g.activeChatTabId),void 0!==g.splitChatTabId&&eW(g.splitChatTabId),eF(g.pane),eb(e=>e+1),tM([]),tL(null),tD.current=null,tK(null),tJ(null),tZ(!1),T&&!t&&to(!1),t&&(nB.current=!0),t||C.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[n$,C,T,eo,H,nd]),nU=(0,i.useCallback)((e,t)=>{let n=`new:${e}:${t}`;eO(o0(t),n),eh.current=n,eu(e),O(null),ea(t);{let e=eH.current&&"secondary"===eB.current,r=`draft:${n}`;eS(r=>i3(r,t,n,M("i18n.newSession"),e?"secondary":"primary").tabs),e?eW(r):eL(r)}eb(e=>e+1),tM([]),tL(null),tK(null),tJ(null),tZ(!1),nu(null),T&&to(!1),C.replace(window.location.pathname,{scroll:!1})},[C,T,M]),n_=(0,i.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&(O(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t),eS(t=>t.map(t=>t.id===e&&"session"===t.kind?{...t,title:p(n),session:{...t.session,...n}}:t)))}).catch(()=>{})},[]),nq=(0,i.useCallback)(e=>{nO(e,!1,void 0,void 0,!0)},[nO]),nK=(0,i.useCallback)(e=>{nO(e,!1,void 0,void 0,!1,!0)},[nO]),nV=(0,i.useCallback)(async e=>{try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`,{cache:"no-store"}),n=await t.json();if(!t.ok||!n.info)throw Error(n.error??`HTTP ${t.status}`);nq(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[nq]),nJ=(0,i.useCallback)((e,t)=>{ev(e=>e+1),eS(n=>{var r;let i,{tabs:s,newTabId:l}=(r=`draft:${t}`,i=p(e),{tabs:n.map(t=>t.id===r?{...t,id:e.id,kind:"session",title:i,session:e,newSessionCwd:null,newSessionDraftKey:null,projectKey:e.projectKey??e.cwd,mountKey:t.mountKey??t.id}:t),newTabId:e.id});return eL(e=>e===`draft:${t}`?l:e),eW(e=>e===`draft:${t}`?l:e),s}),eh.current===t&&(eh.current=null,ea(null),O(e),n_(e.id),C.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[C,n_]),nY=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&r3({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&nq(e)}})},[nq]),nZ=(0,i.useCallback)((e,t)=>{ev(e=>e+1),O(n=>n?.id===e?{...n,name:t}:n),eS(n=>n.map(n=>n.id===e&&"session"===n.kind?{...n,title:t,session:n.session?{...n.session,name:t}:n.session}:n)),t9(n=>n?.sessionId===e?{...n,sessionName:t}:n)},[]),nX=(0,i.useRef)(void 0),nG=(0,i.useRef)(new Set),nQ=(0,i.useCallback)(e=>{ev(e=>e+1),e2(e=>e+1),H&&n_(H.id);let t=e??H;if(sK()&&t&&t.id&&!t.name&&t.relation?.kind!=="subagent"&&!nG.current.has(t.id)){let e=t.id;setTimeout(()=>{nX.current?.({sessionId:e})},350)}t?.relation?.kind==="subagent"||r2()&&nY({targetSession:t,title:t?.name??M("i18n.sessionComplete"),body:M("i18n.taskFinished"),tag:t?`pi-session-complete:${t.id}`:"pi-session-complete"})},[nY,n_,H,M]),n0=(0,i.useCallback)((e,t)=>{var n;t?.relation?.kind!=="subagent"&&r2()&&(n=F.current,!(!r8(e)||n.has(e.id))&&(n.add(e.id),1)&&nY({targetSession:t,title:M("i18n.attentionNeeded"),body:"custom"===e.method?M("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nY,M]);nX.current=(0,i.useCallback)(async e=>{let t=e?.sessionId;if(t&&!nG.current.has(t)){nG.current.add(t);try{let e=await fetch(`/api/sessions/${encodeURIComponent(t)}/auto-name`,{method:"POST"}),n=await e.json().catch(()=>({}));if(!e.ok||!n.title)throw Error(n.error||`HTTP ${e.status}`);nZ(t,n.title.trim())}catch(e){console.warn("[pi-web] silent auto-name failed:",e instanceof Error?e.message:e)}finally{nG.current.delete(t)}}},[nZ]);let n1=(0,i.useCallback)(()=>{e2(e=>e+1)},[]),n2=(0,i.useCallback)((e,t)=>{let n=eM.current.find(e=>e.id===(t??H?.id)),r=t?n?.session:H,i=eH.current&&n?iQ(n):"primary",s={...r??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1},l=!t||ne.current===t;ev(e=>e+1),eS(e=>i8(e,s,i).tabs),n_(e),l&&(eh.current=null,eb(e=>e+1),ea(null),O(s),"secondary"===i?eW(e):eL(e),eF(i),C.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1}))},[n_,C,H]),n4=(0,i.useCallback)(async(e,t,n)=>{eS(e=>i2(e,t));let r=await ie(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(M("chat.quoteForkFailed"));tC({sessionId:r.newSessionId,text:e}),n2(r.newSessionId,t)},[n2,M]),n6=(0,i.useCallback)(e=>{ev(e=>e+1),eS(t=>{if(!t.some(t=>t.id===e))return t;let{tabs:n,nextActiveTabId:r,nextSplitTabId:i}=i6(t,e,e$.current??"",ez.current);if(0===n.length){let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,t=n$?`new:${e}:${n$}`:`draft:${e}`,n=i3([],n$??null,t,M("i18n.newSession"));return eL(n.tabId),eW(null),eF("primary"),O(null),ea(n$??null),C.replace(window.location.pathname,{scroll:!1}),n.tabs}eL(r),eW(i),i||"secondary"!==eB.current||eF("primary");let s="secondary"===eB.current&&i?i:r,l=n.find(e=>e.id===s);return l?.kind==="session"&&l.session?(O(l.session),ea(null),C.replace(`?session=${encodeURIComponent(l.session.id)}`,{scroll:!1})):l?.kind==="draft"&&(O(null),ea(l.newSessionCwd),C.replace(window.location.pathname,{scroll:!1})),n}),ne.current===e&&(tM([]),tL(null),tK(null),tJ(null),tZ(!1),nu(null))},[n$,C,M]),n5=(0,i.useCallback)(e=>{let t=eq.current;if(!t)return;let n=t.getBoundingClientRect();if(n.width<=0)return;let r=oK(n.width);e_(Math.max(r.min,Math.min(r.max,(e-n.left)/n.width)))},[]),n7=(0,i.useCallback)(e=>{e.preventDefault(),eV.current=!0,e.currentTarget.setPointerCapture(e.pointerId),n5(e.clientX)},[n5]),n9=(0,i.useCallback)(e=>{eV.current&&n5(e.clientX)},[n5]),re=(0,i.useCallback)(()=>{eV.current=!1},[]),rt=(0,i.useCallback)(e=>{let t=oK(eJ);if("ArrowLeft"===e.key||"ArrowRight"===e.key){e.preventDefault();let n="ArrowLeft"===e.key?-1:1;e_(e=>Math.max(t.min,Math.min(t.max,e+.05*n)))}else("Home"===e.key||"End"===e.key)&&(e.preventDefault(),e_("Home"===e.key?t.min:t.max))},[eJ]),rn=(0,i.useMemo)(()=>i0(ej,"primary"),[ej]),rr=(0,i.useMemo)(()=>i0(ej,"secondary"),[ej]),ri=(0,i.useMemo)(()=>rn.find(e=>e.id===eT)??rn[0]??null,[rn,eT]),rs=(0,i.useMemo)(()=>eR?ej.find(e=>e.id===eR)??null:null,[ej,eR]),rl=!T&&eJ>=600,ro=!!(rl&&eR&&rs&&eT!==eR);eH.current=ro;let ra=!ro||"primary"===eA,rd=(0,i.useCallback)((e,t)=>{if(eF(t),"session"===e.kind&&e.session){eh.current=null,ne.current!==e.session.id&&(tD.current=null,nd(e.session.id),tK(null),tJ(null),tZ(!1),nu(null)),O(e.session),ea(null),C.replace(`?session=${encodeURIComponent(e.session.id)}`,{scroll:!1});return}eh.current=e.newSessionDraftKey,O(null),ea(e.newSessionCwd),t9(null),no(null),tM([]),tL(null),tD.current=null,tK(null),tJ(null),tZ(!1),nu(null),C.replace(window.location.pathname,{scroll:!1})},[C,nd]),rc=(0,i.useCallback)(e=>{let t="secondary"===e?rs:ri;t&&rd(t,e)},[rd,ri,rs]);(0,i.useLayoutEffect)(()=>{let e=eq.current;if(!e)return;let t=e=>{if(eY(e),e<600)return;let t=oK(e);e_(e=>Math.max(t.min,Math.min(t.max,e)))};t(e.getBoundingClientRect().width);let n=new ResizeObserver(([e])=>t(e.contentRect.width));return n.observe(e),()=>n.disconnect()},[]),(0,i.useEffect)(()=>{if(!eR||rl)return;let e="secondary"===eA?rs:ri;(eS(t=>i4(t,e?.id??null)),eW(null),e)?(eL(e.id),rd(e,"primary")):eF("primary")},[eA,rl,rd,ri,rs,eR]);let ru=(0,i.useCallback)(e=>{let t=ej.find(t=>t.id===e);t&&(eL(e),rd(t,"primary"))},[ej,rd]),rh=(0,i.useCallback)(e=>{let t=ej.find(t=>t.id===e);t&&(eW(e),rd(t,"secondary"))},[ej,rd]),rp=(0,i.useCallback)(e=>{let t=ej.find(t=>t.id===e);if(!t)return;let n=ro?iQ(t):"primary";"secondary"===n?eW(e):eL(e),rd(t,n)},[ej,rd,ro]),rm=(0,i.useCallback)(e=>{let t=eM.current.find(t=>t.id===e);if(t?.kind==="draft"&&t.newSessionDraftKey){let e=eP(t.newSessionDraftKey);if((t.dirty||e&&(e.value.trim()||e.images.length>0))&&!window.confirm(M("chatTabs.discardDraft")))return!1;eD(t.newSessionDraftKey)}return eS(t=>{let{tabs:n,nextActiveTabId:r,nextSplitTabId:i}=i6(t,e,eT??"",eR);if(0===n.length){let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,t=`new:${e}:${n$??""}`;eO(o0(n$??""),t),eh.current=t,eu(e);let n=i3([],n$,t,M("i18n.newSession"));return eL(n.tabId),eW(null),eF("primary"),O(null),ea(n$),C.replace(window.location.pathname,{scroll:!1}),n.tabs}eL(r),eW(i),i||"secondary"!==eA||eF("primary");let s="secondary"===eA&&i?i:r,l=n.find(e=>e.id===s)??n.find(e=>e.id===r);return l?.kind==="session"&&l.session?(O(l.session),ea(null),C.replace(`?session=${encodeURIComponent(l.session.id)}`,{scroll:!1})):l?.kind==="draft"&&(O(null),ea(l.newSessionCwd),C.replace(window.location.pathname,{scroll:!1})),n}),!0},[eA,eT,n$,C,eR,M]),rg=(0,i.useCallback)(e=>{var t;let n=ro&&("secondary"===e||"primary"!==e&&"secondary"===eA),r=((t=n?rs:ri)?"session"===t.kind?t.session?.cwd??null:t.newSessionCwd:null)??n$,i="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,s=`new:${i}:${r??""}`;eO(o0(r??""),s),eh.current=s,eu(i);let{tabs:l,tabId:o}=i3(ej,r,s,M("i18n.newSession"),n?"secondary":"primary");eS(l),n?(eW(o),eF("secondary")):(eL(o),eF("primary")),O(null),ea(r),C.replace(window.location.pathname,{scroll:!1})},[eA,n$,ej,ro,ri,C,rs,M]),rf=(0,i.useCallback)(async(e,t)=>{let n=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),r=await n.json();if(!n.ok||!r.cwd)throw Error(r.error??`HTTP ${n.status}`);let i=r.cwd;e&&eS(t=>t.map(t=>"draft"===t.kind&&t.newSessionDraftKey===e?{...t,newSessionCwd:i,projectKey:i}:t)),e&&eh.current!==e||ea(i),nR(i)},[]),rx=(0,i.useCallback)(()=>{if(eR){let e="secondary"===eA?rs:ri;eS(t=>i4(t,e?.id??null)),eW(null),eF("primary"),e&&(eL(e.id),rd(e,"primary"))}else if(rl){let e=ej.findIndex(e=>e.id===eT),t=ej[e+1]??ej[e-1];if(t)eS(e=>e.map(e=>e.id===t.id?{...e,pane:"secondary"}:e)),eW(t.id),eF("secondary"),"session"===t.kind&&t.session?(O(t.session),ea(null),C.replace(`?session=${encodeURIComponent(t.session.id)}`,{scroll:!1})):"draft"===t.kind&&(O(null),ea(t.newSessionCwd),C.replace(window.location.pathname,{scroll:!1}));else{let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,t=`new:${e}:${n$??""}`;eO(o0(n$??""),t),eh.current=t,eu(e);let{tabs:n,tabId:r}=i3(ej,n$,t,M("i18n.newSession"),"secondary");eS(n),eW(r),eF("secondary"),O(null),ea(n$),C.replace(window.location.pathname,{scroll:!1})}}},[eA,eT,n$,rl,ej,rd,ri,C,rs,eR,M]),rv=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,s=`file:${e}`;nj(l=>(function(e,t){let n=e.find(e=>e.id===t.tabId);if(!n)return[...e,{id:t.tabId,label:t.fileName,filePath:t.filePath,cwd:t.cwd,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,...void 0!==t.page?{pdfPage:t.page}:{},viewerState:t.modeHint?{displayMode:t.modeHint,wrapLines:!1,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=!!(t.cwd&&n.cwd!==t.cwd),s=(t.page??void 0)!==n.pdfPage;return r||i||t.modeHint||s?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e};return r&&(n.sourceSessionId=t.sourceSessionId),i&&(n.cwd=t.cwd),s&&(n.pdfPage=t.page,n.viewerRevision=(e.viewerRevision??0)+1),t.modeHint?(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines??!1,scrollTop:0,scrollLeft:0,loadedBytes:e.viewerState?.loadedBytes,scrollByMode:{...e.viewerState?.scrollByMode,diff:{scrollTop:0,scrollLeft:0}}},n.viewerRevision=(e.viewerRevision??0)+1):(r||i)&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(l,{fileName:t,filePath:e,cwd:n?.cwd??n$??void 0,modeHint:i,sourceSessionId:r,...n?.page!==void 0?{page:n.page}:{},tabId:s})),nC(s),td(!0),T&&to(!1)},[n$,T]),ry=(0,i.useCallback)((e,t,n)=>{let r=t?eM.current.find(e=>e.id===t)?.session?.cwd:void 0;rv(e,S(e),{sourceSessionId:t,cwd:r,...void 0!==n?{page:n}:{}})},[rv]),rb=(0,i.useCallback)(e=>{let t=nN.find(t=>t.cwd===e),n=t??o_(e);t||nE(e=>[...e,n]),nC(n.id),td(!0),T&&to(!1)},[nN,T]),rw=(0,i.useCallback)(e=>{if(nN.some(t=>t.id===e))return void nE(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"}));let t=sD(nT,e);nj(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nN.length&&td(!1),n}),nC(n=>n!==e?n:t)},[nT,nN]),rk=(0,i.useCallback)(()=>{H&&window.open(`/api/sessions/${encodeURIComponent(H.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[H]);(0,i.useEffect)(()=>{if(H)eS(e=>e.some(e=>e.id===H.id)?e:i8(e,H).tabs),eL(e=>e??H.id);else if(eo){let e=eh.current??ec;eS(t=>{let n=`draft:${e}`;return t.some(e=>e.id===n)?t:i3(t,eo,e,M("i18n.newSession")).tabs}),eL(e=>e??`draft:${eh.current??ec}`)}},[eo,ec,H,M]);let rj=(0,i.useCallback)(e=>{eS(t=>i2(t,e))},[]),rS=(e,t,n,i,s,l)=>{let o=e?ei.has(e.id):!!(H&&ei.has(H.id));return(0,r.jsx)(iK,{session:e,searchTarget:i&&eX?.sessionId===e?.id?eX:null,onSearchTargetHandled:e0,initialScrollPosition:e?ew.current.get(e.id)??null:null,onScrollPositionChange:ek,sessionRunning:o,newSessionCwd:t,newSessionDraftKey:n,onDraftChange:eZ,onKeepTabOpen:rj,onNewSessionCwdChange:!e&&t?e=>rf(n,e):void 0,recentProjectPaths:K,pinnedCwds:V,onTogglePinnedCwd:Y,homeDir:Z,worktreeInfo:Q,draftPersistenceWarning:eE,onAgentEnd:nQ,onAttentionNeeded:n0,onSessionCreated:nJ,onSessionForked:n2,modelsRefreshKey:e3,chatInputRef:i?tj:void 0,isFocusedPane:i,isVisiblePane:l,onBranchDataChange:i?tU:void 0,onSystemPromptChange:i?t3:void 0,onSystemToolsChange:i?t6:void 0,onSystemInfoLoaderChange:i?t5:void 0,onSessionStatsChange:i?nt:void 0,onSessionStatsPanelOpen:nx,onContextUsageChange:i?na:void 0,onOpenFile:ry,onOpenSession:nV,onAskInNewChat:n4,quoteSelectionEnabled:P,initialPrompt:tS?.sessionId===e?.id?tS?.text:void 0,onInitialPromptConsumed:tN,soundEnabled:L,onSoundToggle:$,playDoneSound:R,unlockAudio:W},s??ey)},rC=(0,i.useCallback)(e=>{e&&nu(null),tR(e),e||tA(null)},[]),rN=(0,i.useCallback)(async()=>{if(H){tA(null),tz(!0);try{let e=new URLSearchParams({format:"md"});tT&&e.set("leafId",tT),e.set("tz",String(-new Date().getTimezoneOffset()));let t=await fetch(`/api/sessions/${encodeURIComponent(H.id)}/export?${e}`);if(!t.ok){let e=await t.json().catch(()=>null);tA(e?.error==="empty"?M("history.exportEmpty"):M("history.exportFailed"));return}let n=await t.blob(),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=function(e){if(!e)return null;let t=/filename\*=UTF-8''([^;]+)/i.exec(e);if(t?.[1])try{return decodeURIComponent(t[1])}catch{return t[1]}return/filename="([^"]+)"/i.exec(e)?.[1]??null}(t.headers.get("Content-Disposition"))??"session.md",document.body.appendChild(i),i.click(),i.remove(),URL.revokeObjectURL(r),tR(!1)}catch{tA(M("history.exportFailed"))}finally{tz(!1)}}},[tT,H,M]),rE=eo??(null===H&&n$?n$:null),rI=null===H&&rE?`new:${ec}:${rE}`:null,rM=ro&&"secondary"===eA?rs:ri,rT=rM?.kind==="draft"?rM.newSessionDraftKey:0===ej.length?rI:null;(0,i.useLayoutEffect)(()=>{eh.current=rT},[rT]);let rL=null!==H||null!==rE,r$=!!(H&&t7?.sessionId===H.id),rR=H?.cwd??rE;(0,i.useEffect)(()=>{if(e7(null),te(!1),ti(null),!rR)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rR)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e7(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rR]);let rW=(0,i.useCallback)(async()=>{if(rR&&!tt){tn(!0),ti(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rR})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e7(t),te(!1),e6(e=>e+1),eb(e=>e+1)}catch(e){ti(e instanceof Error?e.message:String(e))}finally{tn(!1)}}},[tt,rR]),rz=nk.find(e=>e.id===nS)??null,rP=n$?S(n$)||n$:null,rA=rP?`${rP} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rA&&(document.title=rA)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rA]);let rD=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ed,{selectedSessionId:H?.id??null,onPinSession:nq,onSelectSession:nO,onOpenSessionInNewTab:nq,onNewSession:nU,initialSessionId:nD,skipInitialProjectSelection:null!==E.requestedCwd,refreshKey:ex,onSessionDeleted:n6,selectedCwd:n$??H?.cwd??eo??null,onCwdChange:nH,onOpenFile:rv,onOpenTerminal:rb,explorerRefreshKey:e1,onExplorerRefresh:n1,onAtMention:nz,onAtMentions:nP,onBackgroundTaskDone:B,onRunningSessionIdsChange:el,onSessionsChange:q,pinnedCwds:V,onTogglePinnedCwd:Y,onHomeDirChange:X,onWorktreeInfoChange:ee}),(0,r.jsx)("div",{className:"sidebar-footer",children:(0,r.jsxs)("button",{type:"button",onClick:()=>e8(function(e,t=sO()){if(!t)return"general";try{let n=sU(t).section;if(!("string"==typeof n&&sF.includes(n)))return"general";return sH.has(n)&&!e?"general":n}catch{return"general"}}(rR)),title:M("common.settings"),"aria-label":M("common.settings"),className:"sidebar-footer-item",children:[(0,r.jsx)("span",{className:"sidebar-section-gutter",children:(0,r.jsx)(o1,{})}),(0,r.jsx)("span",{children:M("common.settings")})]})})]}),rF=e=>rL&&e5?.requiresTrust&&!e5.trusted?(0,r.jsxs)("button",{type:"button",onClick:()=>{ti(null),te(!0)},title:M("trust.resourcesNotLoaded"),"aria-label":M("trust.resourcesNotLoaded"),style:{display:"flex",alignItems:"center",justifyContent:e?"flex-start":"center",gap:6,width:e?"100%":void 0,minHeight:e?32:void 0,height:e?void 0:"100%",padding:e?"6px 12px":"0 12px",background:e?"color-mix(in srgb, #d97706 8%, var(--bg-panel))":"none",border:"none",borderRight:e?"none":"1px solid var(--border)",borderBottom:e?"1px solid var(--border)":"none",color:"#d97706",cursor:"pointer",flexShrink:0,fontSize:11,lineHeight:e?1.35:void 0,textAlign:"left"},className:e?void 0:"workspace-header-action","data-mobile-trust-banner":e?"true":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:M("trust.resourcesNotLoaded")})]}):null,rB=(e,t)=>{let n=t?.sessionTools??!0;return(e||rL)&&(e||n||er)?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[er&&H?.relation?.kind==="subagent"&&(0,r.jsx)("button",{type:"button",onClick:()=>nK(en.root),title:M("agentSwitcher.backToMain"),"aria-label":M("agentSwitcher.backToMain"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M19 12H5"}),(0,r.jsx)("path",{d:"m12 19-7-7 7-7"})]})}),er&&(0,r.jsxs)("button",{ref:e?void 0:t2,type:"button",onClick:e=>{t4.current=e.currentTarget,ng("agents")},title:M("agentSwitcher.title"),"aria-label":M("agentSwitcher.title"),"aria-pressed":"agents"===nc,"aria-expanded":"agents"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"agents",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"agents"===nc?"var(--bg-selected)":"none",border:"none",color:"agents"===nc?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.1s, background 0.1s"},className:"workspace-header-action","data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsx)(G,{size:13}),(0,r.jsx)("span",{"aria-hidden":"true",style:{position:"absolute",top:2,right:2,minWidth:13,height:13,padding:"0 3px",display:"grid",placeItems:"center",borderRadius:4,background:"var(--bg-selected)",color:"var(--accent)",fontSize:10,lineHeight:1,fontVariantNumeric:"tabular-nums"},children:en.subagents.length})]}),n&&(e?tF&&(0,r.jsx)("button",{type:"button",onClick:()=>ng("branches"),title:M("i18n.branches"),"aria-label":M("i18n.branches"),"aria-pressed":"branches"===nc,style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"branches"===nc?"var(--bg-selected)":"none",border:"none",color:"branches"===nc?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action","data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:"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:"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)(oN,{tree:tI,activeLeafId:tT,onLeafChange:t_,inline:!0,compact:!0,containerRef:tE,open:"branches"===nc,onToggle:()=>ng("branches"),disabled:!tF,hasSession:!0})),n&&(0,r.jsx)(oE,{mobile:e,disabled:!H,menuOpen:t$,exporting:tW,error:tP,labels:{full:M("history.full"),unsaved:M("history.unsaved"),menu:M("history.menu"),exportMarkdown:M("history.exportMarkdown"),exportMarkdownTitle:M("history.exportMarkdownTitle")},onMenuOpenChange:e=>{rC(e)},onViewFullHistory:()=>{rk()},onExportMarkdown:()=>{rN()}}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:tQ,type:"button",onClick:()=>nf("system"),disabled:e&&!rL,title:M("system.prompt"),"aria-label":M("system.prompt"),"aria-pressed":"system"===nc,"aria-expanded":"system"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"system",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"system"===nc?"var(--bg-selected)":"none",border:"none",cursor:e&&!rL?"not-allowed":"pointer",color:"system"===nc?"var(--text)":"var(--text-muted)",opacity:e&&!rL?.45:1,transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rL)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===nc?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":e?"system":void 0,children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,r.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,r.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>nf("tools"),disabled:e&&!rL,title:M("tools.title"),"aria-label":M("tools.title"),"aria-pressed":"tools"===nc,"aria-expanded":"tools"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"tools",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"tools"===nc?"var(--bg-selected)":"none",border:"none",cursor:e&&!rL?"not-allowed":"pointer",color:"tools"===nc?"var(--text)":"var(--text-muted)",opacity:e&&!rL?.45:1,transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||rL)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===nc?"var(--text)":"var(--text-muted)"},className:"workspace-header-action","data-mobile-toolbar-action":e?"tools":void 0,children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,display:"block"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"})})}),n&&e&&(0,r.jsx)("button",{type:"button",onClick:()=>window.dispatchEvent(new CustomEvent("pi-toggle-outline")),title:M("chatMinimap.userOutline")||"Outline","aria-label":M("chatMinimap.userOutline")||"Outline",style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},className:"workspace-header-action","data-mobile-toolbar-action":"outline",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),(0,r.jsx)("line",{x1:"4",y1:"12",x2:"14",y2:"12"}),(0,r.jsx)("line",{x1:"4",y1:"18",x2:"17",y2:"18"})]})})]})]}):null},rH=H?p(H):M("i18n.newSession"),rO=e=>{if(!e&&(!rL||!r$))return null;let t=nl??t7?.contextUsage;if(!t7&&(!e||!t))return null;let n=t7?.tokens,i=t7?.cost??0,s=i>=.01?`$${i.toFixed(2)}`:i>0?"<$0.01":"$0.00",l=(n?.cacheRead??0)+(n?.cacheWrite??0)+(n?.input??0),o=l>0?(n?.cacheRead??0)/l*100:null,a=[];if(n&&(a.push(`in: ${n.input.toLocaleString(I)}`),a.push(`out: ${n.output.toLocaleString(I)}`),a.push(`cache read: ${n.cacheRead.toLocaleString(I)}`),a.push(`cache write: ${n.cacheWrite.toLocaleString(I)}`),null!==o&&a.push(`${M("session.cacheHitRate")}: ${o.toFixed(1)}%`),i>0&&a.push(`cost: $${i.toFixed(4)}`)),t?.contextWindow){let e=t.percent;a.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${t.contextWindow.toLocaleString()} tokens`)}let d=a.join(" | ");return(0,r.jsx)("button",{type:"button",onClick:()=>ng("session"),disabled:!rL,title:d||M("session.title"),"aria-label":d||M("session.title"),"aria-pressed":"session"===nc,"aria-expanded":"session"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"session",className:"workspace-header-action","data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:"auto",display:"flex",alignItems:"center",justifyContent:"flex-end",minWidth:0,gap:e?8:10,paddingLeft:e?6:8,paddingRight:e?6:8,height:"100%",overflow:"hidden",background:"session"===nc?"var(--bg-selected)":"none",border:"none",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:rL?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{rL&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===nc?"var(--text)":"var(--text-muted)"},children:s&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text-muted)",fontWeight:400,flexShrink:0,lineHeight:1},children:s})})},rU=e=>(0,r.jsx)("button",{ref:t1,type:"button",onClick:nb,"aria-controls":"file-panel","aria-expanded":ta,title:ta?M("files.hidePanel"):M("files.showPanel"),"aria-label":ta?M("files.hidePanel"):M("files.showPanel"),className:"workspace-header-action","data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:t7||nl?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:ta?(0,r.jsxs)("svg",{width:"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:"15",y1:"3",x2:"15",y2:"21"})]}):(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)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
200
- @keyframes session-info-pop {
201
- 0% {
202
- opacity: 0;
203
- transform: translateY(-8px);
204
- }
205
- 100% {
206
- opacity: 1;
207
- transform: translateY(0);
208
- }
209
- }
210
- .session-info-popover {
211
- position: relative;
212
- overflow: hidden;
213
- animation: session-info-pop 180ms cubic-bezier(0.16, 1, 0.3, 1) both;
214
- }
215
- @media (prefers-reduced-motion: reduce) {
216
- .session-info-popover {
217
- animation: none;
218
- }
219
- }
220
- @media (max-width: 640px) {
221
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
222
- opacity: 0 !important;
223
- pointer-events: none !important;
224
- }
225
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
226
- transform: translateX(calc(-100% - env(safe-area-inset-left)));
227
- box-shadow: none;
228
- }
229
- }
230
- `}),(0,r.jsxs)("div",{style:{display:"flex",width:"100%",height:"var(--app-viewport-height, 100dvh)",paddingLeft:"env(safe-area-inset-left)",paddingRight:"env(safe-area-inset-right)",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{className:`sidebar-overlay-backdrop${th?"":" sidebar-mobile-pending"}`,"aria-hidden":"true",onClick:ny,style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!tl,pointerEvents:tl?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:ty.panelRef,id:"session-sidebar",role:"navigation","aria-label":"Pi Web","aria-hidden":!!T&&!tl||void 0,inert:!!T&&!tl||void 0,className:`sidebar-container${tl?" sidebar-open":" sidebar-closed"}${th?"":" sidebar-mobile-pending"}${ty.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${ty.width}px`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)",zIndex:200},children:rD}),tl&&(0,r.jsx)("div",{...ty.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${ty.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${M("layout.resizeSidebar")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tE,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{position:"relative"},children:[(0,r.jsx)("button",{ref:t0,"data-dialog-focus-fallback":"true",className:"workspace-header-action",onClick:nv,title:tl?M("sidebar.hide"):M("sidebar.show"),"aria-label":tl?M("sidebar.hide"):M("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:tl?(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:"9",y1:"3",x2:"9",y2:"21"})]}):(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)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),T&&(0,r.jsxs)("div",{"data-mobile-toolbar":"true",style:{display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[rB(!0),rO(!0),rU(!0)]}),!T&&(0,r.jsxs)(r.Fragment,{children:[!ro&&rL&&ej.length>0&&(0,r.jsx)("div",{style:{flex:"0 1 auto",minWidth:0,height:"100%",overflow:"hidden",display:"flex",alignItems:"stretch"},children:(0,r.jsx)(iX,{tabs:ej,activeTabId:eT??"",activePane:"primary",runningSessionIds:ei,onSelectTab:rp,onCloseTab:rm,onPinTab:rj,onNewTab:rg,onToggleSplit:rx,canSplit:rl,unifiedHeader:!0})}),tl||!rL||ej.length>0?null:(0,r.jsx)("button",{type:"button",onClick:()=>ng("session"),title:rH,"aria-label":rH,"aria-pressed":"session"===nc,"aria-expanded":"session"===nc,"aria-controls":"workspace-top-panel","data-top-panel-trigger":"session",className:"workspace-header-action","data-collapsed-session-title":"true",style:{display:"flex",alignItems:"center",minWidth:0,flex:1,height:"100%",padding:"0 12px",border:"none",borderRight:"1px solid var(--border)",background:"session"===nc?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:rH})}),(0,r.jsxs)("div",{"data-desktop-header-actions":"true",style:{marginLeft:"auto",display:"flex",alignItems:"stretch",height:"100%",flexShrink:0},children:[rF(!1),rO(!1),rB(!1,{sessionTools:r$})]})]}),!T&&rU(!1),T&&tF&&(0,r.jsx)(oN,{tree:tI,activeLeafId:tT,onLeafChange:t_,inline:!0,compact:!0,containerRef:tE,open:"branches"===nc,onToggle:()=>ng("branches"),hasSession:rL,hideInlineButton:!0}),nc&&nh&&(0,r.jsxs)("div",{ref:t8,id:"workspace-top-panel",role:"region","aria-label":"agents"===nc?M("agentSwitcher.title"):"system"===nc?M("system.prompt"):"tools"===nc?M("tools.title"):M("session.title"),style:{position:"fixed",top:nh.top,left:nh.left,width:nh.width,maxHeight:`calc(100dvh - ${nh.top}px - 16px)`,overflowY:"agents"===nc?"visible":"auto",zIndex:520},children:["agents"===nc&&en&&H&&(0,r.jsx)(oD,{rootSession:en.root,subagents:en.subagents,selectedSessionId:H.id,runningSessionIds:ei,onSelectSession:nK,onOpenInNewTab:nq}),"system"===nc&&(0,r.jsx)(oM,{loading:tY,prompt:tq,translate:M}),"tools"===nc&&(0,r.jsx)(o$,{loading:tY,tools:tV,translate:M}),"session"===nc&&(0,r.jsxs)("div",{className:"session-info-popover",style:{position:"relative",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 8px 24px rgba(0,0,0,0.08)",padding:T?"12px 14px":"14px 20px"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:10,right:12,zIndex:2},children:(0,r.jsx)("button",{type:"button",onClick:()=>nm(!0),title:M("i18n.close"),"aria-label":M("i18n.close"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:"transparent",border:"none",borderRadius:4,color:"var(--text-muted)",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-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"})]})})}),t7?(t=t7.totalActiveMs??0,n={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},o=(e,t)=>{let i=nn===e;return(0,r.jsx)("button",{type:"button",title:i?M("session.copied"):M(n[e]),onClick:()=>ns(e,t),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:20,height:20,color:i?"var(--accent)":"var(--text-muted)",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-muted)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:i?(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:"2.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=nl??t7.contextUsage,c=null!==(d=a?.percent??(a?.tokens!==null&&a?.contextWindow?a.tokens/a.contextWindow*100:null))?Math.min(100,Math.max(0,d)):0,u=null!==d&&d>=85,h=null!==d&&d>=70&&d<85,f=a?.tokens!==null&&a?.contextWindow?Math.max(0,a.contextWindow-a.tokens):null,x=a?.contextWindow?(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text)",marginBottom:6,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)("span",{children:M("session.activeContext")}),null!==d&&(0,r.jsxs)("span",{style:{fontSize:11,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},children:[null!==a.tokens&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.contextUsed")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:ts(a.tokens,I)})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.contextWindow")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:ts(a.contextWindow,I)}),null!==f&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.contextRemaining")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:ts(f,I)})]})]}),u&&(0,r.jsxs)("div",{style:{marginTop:6,fontSize:11,color:"#ef4444",display:"flex",alignItems:"center",gap:4},children:[(0,r.jsx)("span",{children:"⚠️"}),(0,r.jsx)("span",{children:M("chat.contextHighWarning")})]})]}):null,y=(v=t7.tokens.cacheRead+t7.tokens.cacheWrite)+t7.tokens.input>0?`${(t7.tokens.cacheRead/(v+t7.tokens.input)*100).toFixed(1)}%`:null,b=(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text)",marginBottom:6,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)("span",{children:M("session.cumulativeTokens")}),t7.cost>0&&(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text)"},children:["$",t7.cost.toFixed(4)]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"max-content max-content",columnGap:14,rowGap:4,justifyContent:"start",fontSize:11},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.total")}),(0,r.jsx)("div",{style:{color:"var(--text)",textAlign:"right",whiteSpace:"nowrap"},children:ts(t7.tokens.total,I)}),(0,r.jsxs)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:[M("session.input")," / ",M("session.output")]}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:[ts(t7.tokens.input,I)," / ",ts(t7.tokens.output,I)]}),t7.tokens.cacheRead>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.cacheRead")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:ts(t7.tokens.cacheRead,I)})]}),y&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:M("session.cacheHitRate")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",textAlign:"right",whiteSpace:"nowrap"},children:y})]})]})]}),j=(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:"column"},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text)",marginBottom:6},children:M("session.infoSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5,fontSize:11},children:[t7.sessionName&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.name"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t7.sessionName})]}),H&&(k=Z&&H.cwd.startsWith(Z)?`~${H.cwd.slice(Z.length)}`:H.cwd,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.directory"),":"]}),(0,r.jsx)("span",{title:H.cwd,style:{color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:k})}),H.branch&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:["\xb7 ",H.branch]}),o(H.isWorktree?"gitWorktree":"projectDir",H.cwd)]})),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.messages"),":"]}),(0,r.jsxs)("span",{style:{color:"var(--text-muted)",whiteSpace:"nowrap"},children:[t7.userMessages," ",M("session.user").toLowerCase()," \xb7 ",t7.assistantMessages," ",M("session.assistant").toLowerCase()," \xb7 ",t7.toolCalls," ",M("session.toolCalls").toLowerCase(),t>0?` (${(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`})(t)})`:""]})]}),t7.sessionFile&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.file"),":"]}),(0,r.jsx)("span",{title:t7.sessionFile,style:{color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left"},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:t7.sessionFile})}),o("file",t7.sessionFile)]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("span",{style:{color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:[M("session.id"),":"]}),(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:t7.sessionId?`${t7.sessionId.slice(0,8)}...${t7.sessionId.slice(-6)}`:"?"}),t7.sessionId&&o("id",t7.sessionId)]})]})]}),(0,r.jsxs)("div",{className:"session-stats-grid",style:{fontFamily:"var(--font-mono)",lineHeight:1.45},children:[x,b,j]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:M("session.load")})]})]})]}),T&&rL&&ej.length>1&&(0,r.jsx)("div",{"data-mobile-chat-tabs":"true",style:{borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",height:"var(--workspace-header-height, 30px)",minHeight:"var(--workspace-header-height, 30px)",width:"100%",maxWidth:"100%",minWidth:0,overflow:"hidden",display:"flex",alignItems:"stretch"},children:(0,r.jsx)(iX,{tabs:ej,activeTabId:eT??"",activePane:"primary",runningSessionIds:ei,onSelectTab:rp,onCloseTab:rm,onPinTab:rj,onNewTab:rg,canSplit:!1,isMobile:!0})}),T&&rF(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative",display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{ref:eq,style:{flex:1,overflow:"hidden",position:"relative",display:"grid",minHeight:0,gridTemplateColumns:ro?`${100*eU}% 0 minmax(0, 1fr)`:"minmax(0, 1fr)",gridTemplateRows:ro?"auto minmax(0, 1fr)":"minmax(0, 1fr)"},children:rL?(0,r.jsxs)(r.Fragment,{children:[ro&&(0,r.jsx)("div",{style:{gridColumn:1,gridRow:1,minWidth:0,overflow:"hidden"},onPointerDownCapture:()=>rc("primary"),children:(0,r.jsx)(iX,{tabs:rn,activeTabId:eT??"",activePane:"primary"===eA?"primary":"secondary",runningSessionIds:ei,onSelectTab:ru,onCloseTab:rm,onPinTab:rj,onNewTab:()=>rg("primary"),onToggleSplit:rx,canSplit:!1})}),ej.length>0?ej.map(e=>{let t=ro?iQ(e):"primary",n=e.id===("secondary"===t?eR:eT),i="secondary"===t?"secondary"===eA:ra,s=e.mountKey??e.id;return(0,r.jsx)("div",{"data-chat-pane":t,onPointerDownCapture:()=>{n&&ro&&rc(t)},style:{gridColumn:"secondary"===t?3:1,gridRow:ro?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,s,n)},s)}):(0,r.jsx)("div",{style:{gridColumn:1,gridRow:ro?2:1,minHeight:0,display:"flex",flexDirection:"column"},children:rS(H,rE,rI,ra,void 0,!0)}),ro&&(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*oK(eJ).min),"aria-valuemax":Math.round(100*oK(eJ).max),"aria-valuenow":Math.round(100*eU),tabIndex:0,title:M("chatTabs.splitView",{defaultValue:"调整分屏大小"}),onPointerDown:n7,onPointerMove:n9,onPointerUp:re,onPointerCancel:re,onKeyDown:rt,onDoubleClick:()=>e_(.5)}),ro&&rs&&(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)(iX,{tabs:rr,activeTabId:eR??"",activePane:"secondary"===eA?"primary":"secondary",runningSessionIds:ei,onSelectTab:rh,onCloseTab:rm,onPinTab:rj,onNewTab:()=>rg("secondary"),onClosePane:rx,isSecondaryPane:!0})})]}):"validating"===ep?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:M("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children: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:M("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${ta?" is-open":""}`,onClick:()=>nw(!0)}),ta&&(0,r.jsx)("div",{...tb.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tb.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${M("layout.resizeFilePanel")}: ${M("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tb.panelRef,id:"file-panel","aria-hidden":!ta,inert:!ta||void 0,className:`right-panel-container${ta?" right-panel-open":" right-panel-closed"}${tb.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tb.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{className:"workspace-header",style:{background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,height:"100%",overflow:"hidden"},children:(0,r.jsx)(sA,{tabs:nT,activeTabId:nS??"",onSelectTab:nC,onCloseTab:rw})}),(0,r.jsx)("button",{type:"button",onClick:()=>nw(!0),className:"workspace-header-action right-panel-header-close","aria-controls":"file-panel",title:M("files.hidePanel"),"aria-label":M("files.hidePanel"),style:{alignItems:"center",justifyContent:"center",width:30,height:"100%",padding:0,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"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:"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)(s$,{filePath:rz.filePath,cwd:rz.cwd??n$??void 0,sourceSessionId:rz.sourceSessionId,gitRefreshKey:e1,initialDisplayMode:rz.initialDisplayMode,initialState:rz.viewerState,watchEnabled:tc,pdfPage:rz.pdfPage,onStateChange:e=>nL(rz.id,rz.viewerRevision??0,e),onMentionLines:ta?nA:void 0,onAtMention:nz,onOpenFile:(e,t)=>rv(e,S(e),{sourceSessionId:rz.sourceSessionId,cwd:rz.cwd,page:t})},`${rz.id}:${rz.viewerRevision??0}`):nN.some(e=>e.id===nS)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:M("files.noneOpen")}),nN.map(e=>(0,r.jsx)("div",{hidden:e.id!==nS,style:{width:"100%",height:"100%"},children:(0,r.jsx)(oO,{tab:e,active:ta&&e.id===nS,onRestart:()=>nE(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n,r;return t="restart"===e.closing?o_(e.cwd):null,n=nN.filter(t=>t.id!==e.id),r=sD(nT,e.id),void(nE(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nC(n=>n!==e.id?n:t?.id??r),!t&&!n.length&&!nk.length&&td(!1))},onCloseError:()=>nE(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),e4&&(0,r.jsx)(ob,{cwd:rR,sessionId:H?.id??null,initialSection:e4,quoteSelectionEnabled:P,onQuoteSelectionChange:D,onClose:()=>{e8(null),e6(e=>e+1)},onSessionReloaded:()=>eb(e=>e+1),onModelsChanged:()=>e6(e=>e+1)}),e9&&rR&&(0,r.jsx)(ow,{cwd:rR,busy:tt,error:tr,onCancel:()=>{tt||te(!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=9669)),_N_E=e.O()}]);