@pricening/pi-web 0.9.8 → 0.9.9

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 (66) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +11 -11
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +4 -4
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/_not-found.html +1 -1
  15. package/.next/server/app/_not-found.rsc +3 -3
  16. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  17. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  19. package/.next/server/app/api/agent/[id]/events/route.js +2 -2
  20. package/.next/server/app/api/app-update/route.js +1 -1
  21. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  22. package/.next/server/app/api/models/route.js +1 -1
  23. package/.next/server/app/api/sessions/[id]/auto-name/route.js +4 -3
  24. package/.next/server/app/api/sessions/[id]/auto-name/route.js.nft.json +1 -1
  25. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  26. package/.next/server/app/index.html +1 -1
  27. package/.next/server/app/index.rsc +5 -5
  28. package/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
  29. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  30. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  31. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  32. package/.next/server/app/login.html +1 -1
  33. package/.next/server/app/login.rsc +4 -4
  34. package/.next/server/app/login.segments/_full.segment.rsc +4 -4
  35. package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
  36. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +4 -4
  37. package/.next/server/app/page.js +20 -20
  38. package/.next/server/app/page_client-reference-manifest.js +1 -1
  39. package/.next/server/app-paths-manifest.json +11 -11
  40. package/.next/server/chunks/2243.js +1 -1
  41. package/.next/server/chunks/3573.js +1 -1
  42. package/.next/server/chunks/4353.js +1 -0
  43. package/.next/server/chunks/5582.js +2 -2
  44. package/.next/server/chunks/6429.js +1 -1
  45. package/.next/server/instrumentation.js +1 -1
  46. package/.next/server/instrumentation.js.nft.json +1 -1
  47. package/.next/server/middleware-build-manifest.js +1 -1
  48. package/.next/server/pages/404.html +1 -1
  49. package/.next/server/pages/500.html +1 -1
  50. package/.next/server/server-reference-manifest.json +1 -1
  51. package/.next/static/chunks/1278-c20177e2f0547fb0.js +1 -0
  52. package/.next/static/chunks/app/{layout-defc84c8112fb814.js → layout-d336308f5f5c4e97.js} +1 -1
  53. package/.next/static/chunks/app/page-ebd11e43d32c7c7f.js +283 -0
  54. package/.next/static/css/{f4a799a04a7a8a76.css → ca4e6d06382119bd.css} +1 -1
  55. package/.next/trace +40 -39
  56. package/.next/trace-build +1 -1
  57. package/README.ja.md +7 -130
  58. package/README.md +51 -123
  59. package/README.ru.md +7 -130
  60. package/README.zh-CN.md +51 -77
  61. package/package.json +2 -2
  62. package/.next/server/chunks/2349.js +0 -1
  63. package/.next/static/chunks/1278-4e101e127edaae15.js +0 -1
  64. package/.next/static/chunks/app/page-89f22c7c0fc4ff07.js +0 -283
  65. /package/.next/static/{v2ujhGjLkjIUa9TUL8cVR → qDrZc4StIk3gX1M8cE65k}/_buildManifest.js +0 -0
  66. /package/.next/static/{v2ujhGjLkjIUa9TUL8cVR → qDrZc4StIk3gX1M8cE65k}/_ssgManifest.js +0 -0
@@ -1,283 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14755:(e,t,n)=>{"use strict";n.d(t,{YO:()=>u,getPresetFromTools:()=>c,sn:()=>d,xG:()=>p});let r=["none","read-only","default","full"],i=[],o=["read","grep","find","ls"],l=["read","bash","edit","write"],s=["bash","read","edit","write","grep","find","ls"],a=new Set([...s,"powershell"]);function d(e){return"string"==typeof e&&r.includes(e)}function c(e){return u(e.filter(e=>e.active).map(e=>e.name))}function u(e){if(0===e.length)return"none";let t=e.map(e=>"powershell"===e?"bash":e).filter(e=>a.has(e)).sort().join(",");return t===[...o].sort().join(",")?"read-only":t===[...l].sort().join(",")?"default":t===[...s].sort().join(",")?"full":"default"}function p(e){return"none"===e?[...i]:"read-only"===e?[...o]:"full"===e?[...s]:[...l]}},42927:(e,t,n)=>{Promise.resolve().then(n.bind(n,86810)),Promise.resolve().then(n.bind(n,21278))},86810:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>lb});var r=n(95155),i=n(12115),o=n(73321);let l=null;function s(){return{sessions:new Set,projects:new Set}}function a(e){return{sessions:new Set(e.sessions),projects:new Set(e.projects)}}function d(e){return e&&"object"==typeof e?{sessions:c(e.sessions),projects:c(e.projects)}:{sessions:[],projects:[]}}function c(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){if("string"!=typeof n)continue;let e=n.trim();e&&t.add(e)}return[...t].sort()}function u(e,t){return!p(e.sessions,t.sessions)||!p(e.projects,t.projects)}function p(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function h(e,t){let n=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,o=r.id,l=null;for(;;){if(n.has(o)){l=n.get(o)??null;break}if(i.has(o))break;i.add(o),e.push(o);let r=t.get(o);if(!r)break;if(r.relation?.kind!=="subagent"){l=r.id;break}o=r.relation.parentSessionId}for(let t of e)n.set(t,l)}return n}(e),r=new Map;for(let t of e)t.relation?.kind!=="subagent"&&r.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let t of e){if(t.relation?.kind!=="subagent")continue;let e=n.get(t.id),i=e?r.get(e):void 0;i&&(i.subagents.push(t),t.modified>i.latestModified&&(i.latestModified=t.modified))}return[...r.values()].sort((e,n)=>{var r;return r=!!t?.has(e.root.id),(!!t?.has(n.root.id)===r?0:r?-1:1)||n.latestModified.localeCompare(e.latestModified)})}let g="pi-web:file-explorer:open";function f(){try{return window.localStorage}catch{return null}}let x=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function m(e){let t=e.match(x);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let v="pi-web:last-open-by-workspace";function y(){try{return window.localStorage}catch{return null}}function b(e){let t=e.getItem(v);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function j(e,t=y()){if(t)try{let n=b(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(v):t.setItem(v,JSON.stringify(n))}catch{}}function w(e){return e.projectKey??e.projectRoot??e.cwd}function k(e,t,n){let r=new Map;for(let t of e){let e=t.projectRoot??t.cwd;if(!e)continue;let i=w(t);if(n?.has(i))continue;let o=r.get(i);(!o||t.modified>o.modified)&&r.set(i,{root:e,modified:t.modified})}return[...r.entries()].sort((e,n)=>{var r;return r=!!t?.has(e[0]),(!!t?.has(n[0])===r?0:r?-1:1)||n[1].modified.localeCompare(e[1].modified)}).map(([e,{root:t}])=>({key:e,root:t}))}function S(e,t){return e.filter(e=>w(e)===t)}var C=n(2730),T=n(21278),M=n(47650);async function E(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function I(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function R(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function L({onCancel:e,onSelect:t,initialPath:n,busy:o=!1,error:l}){let{t:s}=(0,T.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[p,h]=(0,i.useState)(null),[g,f]=(0,i.useState)(n??""),[x,m]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(null),[w,k]=(0,i.useState)(!0),S=(0,i.useCallback)(async e=>{k(!0),j(null);try{let t=await E(e),n=t.path??e??"/";u(n),h(t.parentPath??null),f(n),m(t.directories??[]),y(t.drives??null)}catch(e){j(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),S(n||void 0)},[n,S]);let C=g.trim()!==c,$=!!c&&!C&&!o,N=!!p||/^[a-zA-Z]:[\\/]?$/.test(c);return a?(0,M.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||o||e()},onKeyDown:t=>{"Escape"!==t.key||o||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:o,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:o?"default":"pointer",opacity:o?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&S(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 S(p??void 0),disabled:w||!N,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:N?"pointer":"default",opacity:N?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:g,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{f(e.target.value),j(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:w||!g.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:w||!g.trim()?"default":"pointer",opacity:w||!g.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[w?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==v?(0,r.jsx)(r.Fragment,{children:v.length>0?v.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void S(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)(R,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void S(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(I,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(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:o,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:o?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(c),disabled:!$,title:s(C?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--accent)",color:"var(--accent-contrast)",fontSize:13,fontWeight:600,opacity:$?1:.6,cursor:$?"pointer":"default"},children:s(o?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),a):null}let $="/icons/catppuccin";function N({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${$}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${$}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function z({size:e=14,open:t=!1}){return(0,r.jsx)(N,{name:t?"_folder_open":"_folder",size:e})}function W({size:e=14}){return(0,r.jsx)(N,{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)(N,{name:i,size:t});let o=P[n.split(".").pop()??""];return o?(0,r.jsx)(N,{name:o,size:t}):(0,r.jsx)(W,{size:t})}function F(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function B(e){let t=F(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function D(e){let t=F(e).replace(/\/+$/,"");return t.split("/").pop()??t}function H(e){let t=F(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 O(e,t){if(!t)return e;let n=F(e),r=F(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function U(e,t){return`${F(e).replace(/\/$/,"")}/${t}`}async function _(e){let t=B(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:U(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function q(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 K={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},V={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function J({status:e,t}){return(0,r.jsx)("span",{title:t(K[e.status]),"aria-label":t(K[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:V[e.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:e.code})}function Y({size:e=11}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function Z({onClick:e,title:t}){return(0,r.jsx)("button",{type:"button",onClick:e,title:t,"aria-label":t,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}function G({node:e,depth:t,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:p,t:h}){let g=s.has(e.fullPath),f=c.has(e.fullPath),x=F(e.fullPath),m=u.get(x),v=e.isDir&&(void 0!==m||p.has(x)),[y,b]=(0,i.useState)(e.children??[]),[j,w]=(0,i.useState)(e.loaded??!1),[k,S]=(0,i.useState)(!1),[C,T]=(0,i.useState)(!1),M=(0,i.useCallback)(async(t=!1)=>{if(!j||t){S(!0);try{let t=await _(e.fullPath);b(t),w(!0)}catch{}finally{S(!1)}}},[j,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&g&&j&&M(!0)},[d]);let E=(0,i.useCallback)(()=>{if(e.isDir){let t=!g;a(e.fullPath,t),t&&!j&&M()}else o(e.fullPath,e.name)},[e.isDir,e.fullPath,e.name,j,g,M,o,a]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:E,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*t,paddingRight:8,height:24,cursor:"pointer",background:C?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[e.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:g?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!e.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(z,{size:14,open:g}):A(e.name,14)}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),f&&(0,r.jsx)("span",{title:h("files.newlyUploaded"),"aria-label":h("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"}})}),!C&&!e.isDir&&m&&(0,r.jsx)(J,{status:m,t:h}),!C&&v&&(0,r.jsx)("span",{title:h("files.containsChangedFiles"),"aria-label":h("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"}})}),k&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),l&&C&&(0,r.jsxs)("button",{onClick:t=>{t.stopPropagation(),l(O(e.fullPath,n),e.isDir)},title:h("files.insertPath"),style:{position:"absolute",right:e.isDir?4:28,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 8px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(Y,{}),h("files.mention")]}),C&&!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${B(e.fullPath)}?type=download`,download:!0,onClick:e=>e.stopPropagation(),title:h("files.download"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",gap:4,padding:"0 5px",height:20,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap",textDecoration:"none"},children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})]}),e.isDir&&g&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(G,{node:e,depth:t+1,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:p,t:h},e.fullPath)),0===y.length&&j&&(0,r.jsx)("div",{style:{paddingLeft:8+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:"empty"})]})]})}function X({status:e,cwd:t,onOpenFile:n,t:o}){let[l,s]=(0,i.useState)(!1),a=D(e.filePath),d=O(e.filePath,t);return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,a,{modeHint:"diff"}),onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:24,cursor:"pointer",background:l?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[(0,r.jsx)(J,{status:e,t:o}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:A(a,13)}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:d})]})}let Q=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:o,onAtMentions:l,onUploadBusyChange:s,changesCollapsed:a,onChangesCountChange:d,fileSearchOpen:c=!1,onFileSearchOpenChange:u},p){let{t:h}=(0,T.s)(),[g,f]=(0,i.useState)([]),[x,m]=(0,i.useState)(!0),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(new Set),[w,k]=(0,i.useState)(0),[S,C]=(0,i.useState)(new Set),[M,E]=(0,i.useState)([]),[I,R]=(0,i.useState)({additions:0,deletions:0}),[L,$]=(0,i.useState)("idle"),[N,z]=(0,i.useState)(0),[W,P]=(0,i.useState)(null),[A,D]=(0,i.useState)(null),[K,J]=(0,i.useState)(null),[Q,ee]=(0,i.useState)(""),[et,en]=(0,i.useState)([]),[er,ei]=(0,i.useState)(!1),[eo,el]=(0,i.useState)(!1),[es,ea]=(0,i.useState)(new Set),ed=(0,i.useRef)(null),ec=(0,i.useRef)(null),eu=(0,i.useRef)(null),ep=`${n??0}:${w}`,eh="idle"!==L,eg=Q.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=Q.trim();if(!t){en([]),ei(!1),el(!1);return}let n=new AbortController;ei(!0),el(!1);let r=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(e)}&q=${encodeURIComponent(t)}`,{signal:n.signal}).then(e=>e.ok?e.json():Promise.reject(Error("Search failed"))).then(e=>en((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{n.signal.aborted||(en([]),el(!0))}).finally(()=>{n.signal.aborted||ei(!1)})},150);return()=>{clearTimeout(r),n.abort()}},[e,c,Q]),(0,i.useEffect)(()=>{c&&ed.current?.focus()},[c]),(0,i.useEffect)(()=>{if(0===et.length)return;let t=new Set;for(let n of et){let r=n.split("/"),i="";for(let n=0;n<r.length-1;n++)i=i?`${i}/${r[n]}`:r[n],t.add(U(e,i))}ea(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,et]);let ef=(0,i.useMemo)(()=>{let t=n=>({name:n.name,fullPath:U(e,n.path),isDir:n.isDir,size:0,children:n.children.map(t),loaded:!0});return(function(e){let t=[],n=new Map;for(let r of e){let e=r.split("/"),i=t,o="";for(let t=0;t<e.length;t++){o=o?`${o}/${e[t]}`:e[t];let r=n.get(o);r||(r={name:e[t],path:o,isDir:t<e.length-1,children:[]},n.set(o,r),i.push(r)),i=r.children}}let r=e=>{e.sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name)),e.forEach(e=>r(e.children))};return r(t),t})(et).map(t)},[e,et]),ex=(0,i.useMemo)(()=>new Map(M.map(e=>[F(e.filePath),e])),[M]),em=(0,i.useMemo)(()=>{let t=new Set,n=F(e).replace(/\/$/,"");for(let e of M){let r=H(F(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=H(r);if(e===r)break;r=e}}return t},[e,M]),ev=(0,i.useCallback)((e,t)=>{j(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ey=(0,i.useCallback)(t=>{let n=t.uploaded??[];D({uploaded:n,skipped:t.skipped??[],errors:t.errors??[]}),n.length>0&&(C(new Set(n.map(t=>U(e,t)))),k(e=>e+1))},[e]),eb=(0,i.useCallback)(async(t,n)=>{J(null),P(null),z(0),$("uploading");try{let{status:r,data:i}=await new Promise((r,i)=>{let o=new FormData;t.forEach(e=>o.append("files",e,e.name));let l=new XMLHttpRequest;l.open("POST",`/api/files/${B(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&z(Math.round(e.loaded/e.total*100))},l.onerror=()=>i(Error("Network error while uploading files")),l.onabort=()=>i(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}r({status:l.status,data:e})},l.send(o)});if(409===r&&i.conflicts?.length)return void J({files:t,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);z(100),ey(i)}catch(e){P(e instanceof Error?e.message:String(e))}finally{$("idle")}},[ey,e]),ej=(0,i.useCallback)(async t=>{if(0!==t.length&&!eh){D(null),C(new Set),J(null),P(null),z(0),$("checking");try{let n=await fetch(`/api/files/${B(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 J({files:t,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await eb(t,"error")}catch(e){P(e instanceof Error?e.message:String(e))}finally{$("idle")}}},[e,eb,eh]),ew=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ej(t)},[ej]);(0,i.useImperativeHandle)(p,()=>({openUploadPicker(){eh||eu.current?.click()}}),[eh]),(0,i.useEffect)(()=>{s?.(eh)},[s,eh]),(0,i.useEffect)(()=>()=>s?.(!1),[s]),(0,i.useEffect)(()=>{let t=ec.current!==e;ec.current=e,t&&(j(new Set),C(new Set),D(null),J(null),P(null)),m(t),y(null);let n=!1;return _(e).then(e=>{n||f(e)}).catch(e=>{n||y(e instanceof Error?e.message:String(e))}).finally(()=>{n||m(!1)}),()=>{n=!0}},[e,n,w]),(0,i.useEffect)(()=>{let t=!1;return q(e).then(e=>{t||(E(e.isGitRepository?e.files:[]),R(e.isGitRepository?{additions:e.additions,deletions:e.deletions}:{additions:0,deletions:0}))}).catch(()=>{t||(E([]),R({additions:0,deletions:0}))}),()=>{t=!0}},[e,n,w]),(0,i.useEffect)(()=>{d?.(M.length)},[M,d]);let ek=eh||null!==K||null!==W||null!==A,eS=(0,i.useCallback)(()=>{A&&0!==A.uploaded.length&&l?.(A.uploaded.map(t=>O(U(e,t),e)))},[e,l,A]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:eu,type:"file",multiple:!0,hidden:!0,onChange:ew}),ek&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[eh&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===L?h("files.checking"):h("files.uploading",{progress:N}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===L?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===L&&(0,r.jsxs)("span",{style:{fontSize:10},children:[N,"%"]})]}),"uploading"===L&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${N}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),K&&(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:h("files.conflictSummary",{count:K.conflicts.length,countSuffix:1===K.conflicts.length?"":"s",files:K.conflicts.join(", ")})}),K.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:h("files.cannotReplace",{files:K.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void eb(K.files,"overwrite"),style:{height:22,padding:"0 7px",border:"1px solid #ef4444",borderRadius:4,background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:10},children:h("files.replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void eb(K.files,"skip"),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:h("files.skipExisting")}),(0,r.jsx)("button",{type:"button",onClick:()=>J(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:h("files.cancel")})]})]}),W&&(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:W}),(0,r.jsx)(Z,{onClick:()=>P(null),title:h("files.dismissError")})]}),A&&(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:[A.uploaded.length>0&&(0,r.jsxs)("span",{title:`${A.uploaded.length} uploaded`,"aria-label":`${A.uploaded.length} uploaded`,style:{display:"flex",alignItems:"center",gap:3,color:"#22c55e"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:A.uploaded.length})]}),A.skipped.length>0&&(0,r.jsxs)("span",{title:`${A.skipped.length} skipped`,"aria-label":`${A.skipped.length} skipped`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:A.skipped.length})]}),A.errors.length>0&&(0,r.jsxs)("span",{title:`${A.errors.length} failed`,"aria-label":`${A.errors.length} failed`,style:{display:"flex",alignItems:"center",gap:3,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:A.errors.length})]})]}),A.uploaded.length>0&&l&&(0,r.jsxs)("button",{type:"button",onClick:eS,title:1===A.uploaded.length?h("files.addUploadedFile"):h("files.addAllUploadedFiles"),"aria-label":1===A.uploaded.length?h("files.addUploadedFile"):h("files.addAllUploadedFiles"),style:{height:22,padding:"0 7px",display:"flex",alignItems:"center",justifyContent:"center",gap:4,flexShrink:0,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsx)(Y,{}),h("files.mention")]}),(0,r.jsx)(Z,{onClick:()=>D(null),title:h("files.dismissUploadResults")})]}),A.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"#f87171"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),c&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{position:"absolute",left:8,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{ref:ed,value:Q,onChange:e=>ee(e.target.value),onKeyDown:e=>{"Escape"===e.key&&u?.(!1)},placeholder:h("sidebar.searchFilesPlaceholder"),"aria-label":h("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:"var(--font-mono)",fontSize:11}}),Q&&(0,r.jsx)("button",{type:"button",onClick:()=>ee(""),title:h("sidebar.clearSearch"),"aria-label":h("sidebar.clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,padding:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),eg&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[er&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:h("sidebar.searchingFiles")}),!er&&eo&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:h("i18n.networkError")}),!er&&!eo&&0===et.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:h("sidebar.noMatchingFiles")}),!er&&!eo&&et.length>0&&(0,r.jsx)("div",{children:ef.map(n=>(0,r.jsx)(G,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:es,onToggleExpanded:(e,t)=>{ea(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:S,gitStatusByPath:ex,changedDirectoryPaths:em,t:h},`${Q}:${n.fullPath}`))})]})]}),!a&&M.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":h("files.changeStats",{count:M.length,additions:I.additions,deletions:I.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:h("files.changedCount",{count:M.length})}),(0,r.jsxs)("span",{style:{color:V.added,fontFamily:"var(--font-mono)"},children:["+",I.additions]}),(0,r.jsxs)("span",{style:{color:V.deleted,fontFamily:"var(--font-mono)"},children:["-",I.deletions]})]}),M.map(n=>(0,r.jsx)(X,{status:n,cwd:e,onOpenFile:t,t:h},n.filePath))]}),(a||0===M.length)&&(!c||!eg)&&(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[x?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:"Loading files..."}):v?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:v}):g.map(n=>(0,r.jsx)(G,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:b,onToggleExpanded:ev,refreshToken:ep,highlightedPaths:S,gitStatusByPath:ex,changedDirectoryPaths:em,t:h},n.fullPath)),!x&&!v&&0===g.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:h("files.noFiles")})]})]})});function ee({open:e,query:t,refreshKey:n,children:o,selectedSessionId:l,onSelectSession:s}){let{t:a,locale:d}=(0,T.s)(),[c,u]=(0,i.useState)({query:""}),p=t.trim(),h=c.query===p?c.response:void 0,g=c.query===p&&c.failed;return(0,i.useEffect)(()=>{if(!e||!p)return;let t=new AbortController;u({query:p});let n=setTimeout(async()=>{try{let e=await fetch(`/api/sessions/search?${new URLSearchParams({q:p})}`,{signal:t.signal});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await e.json();t.signal.aborted||u({query:p,response:n})}catch{t.signal.aborted||u({query:p,failed:!0})}},300);return()=>{clearTimeout(n),t.abort()}},[e,p,n]),e&&p?(0,r.jsxs)("div",{className:"min-h-20 flex-1 overflow-y-auto","aria-busy":!h&&!g,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:g?a("sidebar.sessionSearchFailed"):h?0===h.results.length?a("sidebar.sessionSearchEmpty"):a("sidebar.sessionSearchCount",{count:h.results.length}):a("sidebar.sessionSearching")}),h?.truncated&&(0,r.jsx)("div",{role:"status",className:"px-3 pb-2 text-xs text-text-muted",children:a("sidebar.sessionSearchPartial")}),h?.results.map(({session:e,entryId:t,blockIndex:n,before:i,match:o,after:a})=>(0,r.jsxs)("button",{type:"button",onClick:()=>s(e,t,n),"aria-current":e.id===l?"true":void 0,className:`block w-full cursor-pointer border-b border-border px-3 py-2 text-left hover:bg-bg-hover focus-visible:outline-2 focus-visible:outline-accent ${e.id===l?"bg-bg-selected":""}`,children:[(0,r.jsx)("span",{className:"block truncate text-xs font-medium text-text",children:e.name||e.firstMessage}),(0,r.jsxs)("span",{className:"mt-1 flex min-w-0 gap-2 text-[10px] text-text-dim",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",title:e.cwd,children:e.cwd}),(0,r.jsx)("span",{className:"shrink-0",children:(0,C.fw)(e.modified,d)})]}),(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[i,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:o}),a]})]},e.id))]}):o}let et="(max-width: 640px)",en="(max-width: 480px)";function er(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function ei(e){return!!window.matchMedia&&window.matchMedia(e).matches}let eo=e=>er(et,e),el=()=>ei(et),es=e=>er(en,e),ea=()=>ei(en);function ed(){return!1}function ec(){return(0,i.useSyncExternalStore)(eo,el,ed)}let eu={en:{pinSession:"Pin session",unpinSession:"Unpin session",pinProject:"Pin project",unpinProject:"Unpin project",pinFailed:"Could not save the pin"},"zh-CN":{pinSession:"置顶会话",unpinSession:"取消置顶会话",pinProject:"置顶项目",unpinProject:"取消置顶项目",pinFailed:"置顶保存失败"},"zh-TW":{pinSession:"釘選工作階段",unpinSession:"取消釘選工作階段",pinProject:"釘選專案",unpinProject:"取消釘選專案",pinFailed:"釘選儲存失敗"}},ep={display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,flexShrink:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s, border-color 0.12s"},eh={display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transition:"color 0.12s"};function eg({filled:e}){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:e?"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"})]})}function ef({kind:e,id:t,pinned:n,onToggle:o,variant:l="action",as:s="button",hovered:a=!1}){let{locale:d}=(0,T.s)(),c=ec(),[u,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(!1),m=(0,i.useRef)(!0);(0,i.useEffect)(()=>(m.current=!0,()=>{m.current=!1}),[]),(0,i.useEffect)(()=>{if(!u)return;let e=setTimeout(()=>p(!1),1600);return()=>clearTimeout(e)},[u]);let v=(0,i.useCallback)(r=>{r.stopPropagation(),r.preventDefault(),h||(g(!0),(async()=>{let r=await o(e,t,!n);m.current&&(g(!1),!1===r&&p(!0))})())},[h,t,e,o,n]),y=(0,i.useCallback)(e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),v(e))},[v]);if("action"===l&&!(c||a||n))return null;let b=eu[d]??eu.en,j=n?"session"===e?b.unpinSession:b.unpinProject:"session"===e?b.pinSession:b.pinProject,w="action"===l?ep:eh,k="action"===l?{...w,background:f?"var(--bg-selected)":"var(--bg-hover)",color:u?"#ef4444":n||f?"var(--accent)":"var(--text-muted)",borderColor:u||n||f?"rgba(37,99,235,0.35)":"var(--border)"}:{...w,color:u?"#ef4444":n?"var(--accent)":"var(--text-dim)",opacity:n||c?1:.7};return(0,r.jsx)("span"===s?"span":"button",{onClick:v,onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),..."span"===s?{role:"button",tabIndex:0,onKeyDown:y}:{},"aria-pressed":n,title:u?b.pinFailed:j,"aria-label":j,style:k,children:(0,r.jsx)(eg,{filled:n})})}let ex={en:{archiveProject:"Archive project",unarchiveProject:"Unarchive project",archiveFailed:"Could not save the archive"},"zh-CN":{archiveProject:"归档项目",unarchiveProject:"取消归档",archiveFailed:"归档保存失败"},"zh-TW":{archiveProject:"封存專案",unarchiveProject:"取消封存",archiveFailed:"封存儲存失敗"}},em={display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transition:"color 0.12s"};function ev({filled:e}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}function ey({id:e,archived:t,onToggle:n,as:o="button"}){let{locale:l}=(0,T.s)(),s=ec(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),p=(0,i.useRef)(!0);(0,i.useEffect)(()=>(p.current=!0,()=>{p.current=!1}),[]),(0,i.useEffect)(()=>{if(!a)return;let e=setTimeout(()=>d(!1),1600);return()=>clearTimeout(e)},[a]);let h=(0,i.useCallback)(r=>{r.stopPropagation(),r.preventDefault(),c||(u(!0),(async()=>{let r=await n(e,!t);p.current&&(u(!1),!1===r&&d(!0))})())},[t,c,e,n]),g=(0,i.useCallback)(e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),h(e))},[h]),f=ex[l]??ex.en,x=t?f.unarchiveProject:f.archiveProject,m={...em,color:a?"#ef4444":t?"var(--accent)":"var(--text-dim)",opacity:t||s?1:.7};return(0,r.jsx)("span"===o?"span":"button",{onClick:h,..."span"===o?{role:"button",tabIndex:0,onKeyDown:g}:{},"aria-pressed":t,title:a?f.archiveFailed:x,"aria-label":x,style:m,children:(0,r.jsx)(ev,{filled:t})})}function eb(e){return new Set(e.projects)}function ej(e){return e&&"object"==typeof e?{projects:function(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){if("string"!=typeof n)continue;let e=n.trim();e&&t.add(e)}return[...t].sort()}(e.projects??e.archives)}:{projects:[]}}function ew(e,t){if(e.size!==t.size)return!0;for(let n of e)if(!t.has(n))return!0;return!1}function ek({onClick:e,title:t,disabled:n,skipHover:i,color:o,background:l="none",marginRight:s,ariaPressed:a,children:d}){return(0,r.jsx)("button",{onClick:e,disabled:n,title:t,"aria-label":t,"aria-pressed":a,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,marginRight:s,background:l,border:"none",color:o,cursor:n?"default":"pointer",borderRadius:5,flexShrink:0,opacity:n?.6:1,transition:"color 0.3s, background 0.3s"},onMouseEnter:e=>{n||i||(e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||i||(e.currentTarget.style.color=o,e.currentTarget.style.background=l)},children:d})}let eS="pi-web:unread-session-ids",eC="pi-web:last-custom-cwd";function eT(){try{return window.localStorage.getItem(eC)??""}catch{return""}}function eM(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eE({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 eI({open:e,children:t,style:n}){let[o,l]=(0,i.useState)(e),[s,a]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(l(!0),a(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>a(!0))})):(a(!1),n=setTimeout(()=>l(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),o)?(0,r.jsx)("div",{style:{...n,opacity:+!!s,transform:s?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let eR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function eL(){let[e,t]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),s=function(e,t){let[n,r]=(0,i.useState)(e),o=(0,i.useRef)(null),l=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);l.current=0;let n=4*e.length,i=()=>{l.current+=1;let t=Math.floor(l.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:eR[Math.floor(Math.random()*eR.length)]).join("")),l.current<n?o.current=requestAnimationFrame(i):r(e)};return o.current=requestAnimationFrame(i),()=>{o.current&&cancelAnimationFrame(o.current)}},[e,t]),n}(e?"0.9.8p0.85.1":"Pi Web",n),a=(0,i.useCallback)(e=>{t(e),o(!0),setTimeout(()=>o(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{l.current&&clearTimeout(l.current);let t=!e;a(t),t&&(l.current=setTimeout(()=>a(!1),3e3))},[e,a]);return(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,r.jsx)("button",{onClick:d,style:{background:"none",border:"none",padding:0,cursor:"default",fontWeight:700,fontSize:15,letterSpacing:"-0.01em",color:e?"var(--accent)":"var(--text)",fontFamily:"var(--font-mono)",minWidth:"6ch"},children:s})}function e$({selectedSessionId:e,onSelectSession:t,onNewSession:n,initialSessionId:o,skipInitialProjectSelection:l,onInitialRestoreDone:c,refreshKey:p,onSessionDeleted:x,selectedCwd:m,onCwdChange:v,onOpenFile:y,onOpenTerminal:b,explorerRefreshKey:j,onExplorerRefresh:C,onAtMention:M,onAtMentions:E,onBackgroundTaskDone:I,onRunningSessionIdsChange:R,onSessionsChange:$}){let{t:N}=(0,T.s)(),{sets:z,applyPayload:W,toggle:P}=function(){let[e,t]=(0,i.useState)(s),n=(0,i.useRef)(0),r=(0,i.useCallback)(e=>{let r=a(d(e));n.current+=1,t(e=>u(r,e)?r:e)},[]),o=(0,i.useCallback)(async()=>{let e=n.current;try{let r=await fetch("/api/pins",{cache:"no-store"});if(!r.ok)return;let i=d(await r.json());if(e!==n.current)return;t(e=>{let t=a(i);return u(t,e)?t:e})}catch{}},[]),l=(0,i.useCallback)(async(e,i,l)=>{n.current+=1,t(t=>(function(e,t,n,r){let i="session"===t?e.sessions:e.projects;if(i.has(n)===r)return e;let o=new Set(i);return r?o.add(n):o.delete(n),"session"===t?{...e,sessions:o}:{...e,projects:o}})(t,e,i,l));try{let t=await fetch("/api/pins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:e,key:i,pinned:l}),cache:"no-store"});if(!t.ok)return await o(),!1;return r(await t.json()),!0}catch{return await o(),!1}},[r,o]);return(0,i.useEffect)(()=>{o()},[o]),{sets:e,applyPayload:r,toggle:l,refresh:o}}(),{set:A,applyPayload:F,toggle:B}=function(){let[e,t]=(0,i.useState)(()=>new Set),n=(0,i.useRef)(0),r=(0,i.useCallback)(e=>{let r=eb(ej(e));n.current+=1,t(e=>ew(r,e)?r:e)},[]),o=(0,i.useCallback)(async()=>{let e=n.current;try{let r=await fetch("/api/archives",{cache:"no-store"});if(!r.ok)return;let i=ej(await r.json());if(e!==n.current)return;t(e=>{let t=eb(i);return ew(t,e)?t:e})}catch{}},[]),l=(0,i.useCallback)(async(e,i)=>{n.current+=1,t(t=>{if(t.has(e)===i)return t;let n=new Set(t);return i?n.add(e):n.delete(e),n});try{let t=await fetch("/api/archives",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e,archived:i}),cache:"no-store"});if(!t.ok)return await o(),!1;return r(await t.json()),!0}catch{return await o(),!1}},[r,o]);return(0,i.useEffect)(()=>{o()},[o]),{set:e,applyPayload:r,toggle:l,refresh:o}}(),[D,H]=(0,i.useState)([]),[O,U]=(0,i.useState)(null),_=(0,i.useRef)(null),q=(0,i.useRef)(0),[K,V]=(0,i.useState)(!0),[J,Y]=(0,i.useState)(null),[Z,G]=(0,i.useState)(null),[X,et]=(0,i.useState)(""),[en,er]=(0,i.useState)(!1),[ei,eo]=(0,i.useState)(""),[el,es]=(0,i.useState)(""),[ea,ed]=(0,i.useState)(!1),[ec,eu]=(0,i.useState)(eT),[ep,eh]=(0,i.useState)(null),[eg,ex]=(0,i.useState)(!1),[em,ev]=(0,i.useState)(null),eR=(0,i.useRef)(null),[eN,ez]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(!1),[eF,eB]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(""),[eO,eU]=(0,i.useState)(null),[e_,eq]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(null),[eJ,eY]=(0,i.useState)(null),eZ=(0,i.useRef)(null),eG=(0,i.useRef)(null),[eX,eQ]=(0,i.useState)(!0),[e0,e1]=(0,i.useState)(0),[e2,e4]=(0,i.useState)(!1),[e8,e5]=(0,i.useState)(!1),[e6,e3]=(0,i.useState)(!1),[e9,e7]=(0,i.useState)(""),te=e6&&!!e9.trim(),[tt,tn]=(0,i.useState)(0),[tr,ti]=(0,i.useState)(!0),[to,tl]=(0,i.useState)(!1),[ts,ta]=(0,i.useState)(()=>new Set),[td,tc]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(eS);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}})()),tu=(0,i.useRef)(new Set),tp=(0,i.useRef)(new Set),th=(0,i.useRef)(new Set),tg=(0,i.useRef)(!1),tf=(0,i.useRef)(null),tx=(0,i.useRef)(null),tm=(0,i.useRef)(null),[tv,ty]=(0,i.useState)(0),[tb,tj]=(0,i.useState)(0),[tw,tk]=(0,i.useState)(null),tS=(0,i.useRef)(null),tC=(0,i.useCallback)(e=>{let t=e.currentTarget.scrollTop;null==tS.current&&(tS.current=requestAnimationFrame(()=>{tS.current=null,tj(t)}))},[]);(0,i.useLayoutEffect)(()=>{let e=tm.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)ty(t.contentRect.height)});return t.observe(e),ty(e.clientHeight),tj(e.scrollTop),()=>t.disconnect()},[te]);let tT=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++q.current;try{e&&V(!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!==q.current)return;_.current=i.sessionListVersion,U(i.sessionListVersion),H(i.sessions),tg.current||(tp.current=new Set(i.completionNotificationSuppressedSessionIds??[]),ta(new Set(i.runningSessionIds??[])));let o=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));tc(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),Y(null)}catch(e){n===q.current&&Y(String(e))}finally{n===q.current&&V(!1)}},[]),tM=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tM.current;tM.current=!0,tT(e,!e)},[tT,p]),(0,i.useEffect)(()=>{eQ(function(e=f()){if(!e)return!0;try{return"false"!==e.getItem(g)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===td.size?window.localStorage.removeItem(eS):window.localStorage.setItem(eS,JSON.stringify([...td]))}catch{}},[td]),(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let o=new AbortController;n?.abort(),n=o;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:o.signal});if(!t.ok)return;let r=await t.json();if(e||n!==o)return;tg.current=!0,W(r.pins),F(r.archives),tp.current=new Set(r.completionNotificationSuppressedSessionIds??[]),ta(new Set(r.runningSessionIds??[])),r.sessionListVersion!==_.current&&await tT()}catch{}finally{n===o&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},o=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",o),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",o)}},[F,W,tT]),(0,i.useEffect)(()=>{R?.(ts)},[R,ts]),(0,i.useEffect)(()=>{$?.(D)},[D,$]),(0,i.useEffect)(()=>{let t=tu.current,n=[...t].filter(t=>!ts.has(t)&&t!==e),r=new Set(D.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!th.current.has(e)&&!r.has(e)),o=[...ts].filter(e=>!t.has(e));(i.length>0||o.length>0)&&tc(e=>{let t=new Set(e);return ts.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let l=o.some(e=>!D.some(t=>t.id===e));(n.length>0||l)&&tT(!1,!0),i.length>0&&I?.(),tu.current=ts,th.current=new Set([...ts].filter(e=>tp.current.has(e)||r.has(e)))},[ts,e,D,tT,I]),(0,i.useEffect)(()=>{e&&tc(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==j&&e1(e=>e+1)},[j]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&et(e.home)}).catch(()=>{})},[]);let tE=(0,i.useRef)(!1),tI=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),tR=(0,i.useCallback)(e=>{if(!e)return null;if(em?.cwd===e)return tI(em.root,em.key);if(eN&&eN.forCwd===e||eN?.worktrees.some(t=>t.path===e))return tI(eN.projectRoot,eN.projectKey);let t=D.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?tI(t.projectRoot??t.cwd,w(t)):tI(e,e)},[em,eN,D,tI]),tL=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tR(Z),t=tL.current;(t?.cwd!==Z||t.key!==(e?.key??null))&&(tL.current={cwd:Z,key:e?.key??null},v?.(Z,e?.root??null,e?.key??null))},[Z,v,tR]);let t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{m&&m!==t$.current&&(t$.current=m,G(m))},[m]);let[tN,tz]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!Z){ez(null),eY(null);return}let e=!1;return eY(Z),fetch(`/api/worktrees?cwd=${encodeURIComponent(Z)}`).then(e=>e.json()).then(t=>{if(!e){if(eY(null),t.error||!t.projectRoot)return void ez(null);ez({forCwd:Z,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||(eY(null),ez(null))}),()=>{e=!0}},[Z,tN,p]),(0,i.useEffect)(()=>{if(0!==D.length&&!l&&null===Z){if(o&&!tE.current){tE.current=!0;let e=D.find(e=>e.id===o);if(e){G(e.cwd),t(e,!0);return}c?.()}let e=k(D,void 0,A);e.length>0&&G(e[0].root)}},[D,A,Z,o,l,t,c]);let tW=eN?eN.worktrees.find(e=>e.path===Z)??(eN.forCwd===Z&&eN.currentWorktreePath?eN.worktrees.find(e=>e.path===eN.currentWorktreePath):void 0)??eN.worktrees.find(e=>e.isMain):void 0,tP=tW?.path??null,tA=(0,i.useCallback)(async e=>{let t=(e??ec).trim();if(t&&!eg){ex(!0),eh(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 eh(r.error??`HTTP ${e.status}`);ev({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(eC,n)}catch{}eu(r.cwd),G(r.cwd),ed(!1),er(!1)}catch(e){eh(e instanceof Error?e.message:String(e))}finally{ex(!1)}}},[ec,eg]),tF=(0,i.useCallback)(()=>{ed(!0),eh(null),er(!1)},[]),tB=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(G(t.cwd),ed(!1),eh(null),er(!1))}catch{}},[]),tD=(0,i.useCallback)(async()=>{let e=eD.trim();if(e&&!e_&&eN){eq(!0),eU(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eN.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eU(n.error??`HTTP ${t.status}`);eB(!1),eH(""),eA(!1),ez(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),G(n.path),tz(e=>e+1)}catch(e){eU(e instanceof Error?e.message:String(e))}finally{eq(!1)}}},[eD,e_,eN]),tH=(0,i.useCallback)(async(e,t)=>{if(eN&&!e_){eq(!0),eU(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eN.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void eV(e);eU(r.error??`HTTP ${n.status}`);return}eV(null),tP===e&&G(eN.projectRoot),tz(e=>e+1)}catch(e){eU(e instanceof Error?e.message:String(e))}finally{eq(!1)}}},[eN,e_,tP]);(0,i.useEffect)(()=>{let e=e=>{eR.current&&!eR.current.contains(e.target)&&(er(!1),eo("")),eZ.current&&!eZ.current.contains(e.target)&&(eA(!1),eB(!1),eH(""),eU(null),eV(null),es(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tO=(0,i.useCallback)((e,n,r)=>{H(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&G(e.cwd);let i=w(e);i&&A.has(i)&&B(i,!1),t(e,!1,n,r)},[A,t,B]),tU=(0,i.useCallback)(()=>{if(!Z)return;let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;n?.(e,Z)},[n,Z]),t_=k(D,z.projects,A),tq=tR(Z),tK=(0,i.useCallback)(e=>{e&&A.has(e)&&B(e,!1)},[A,B]);(0,i.useEffect)(()=>{tK(em?.key)},[tK,em?.key]);let tV=(0,i.useCallback)(()=>{tK(tq?.key),tU()},[tU,tq,tK]),tJ=t_[0]?.root??null;(0,i.useEffect)(()=>{!tq||A.has(tq.key)&&G(tJ)},[A,tJ,tq]);let tY=t_.length>8,tZ=ei.trim()?t_.filter(e=>e.root.toLowerCase().includes(ei.trim().toLowerCase())):t_,tG=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=w(i);if(!e)continue;let o=r.get(e);o||(o={running:0,unread:0},r.set(e,o)),t.has(i.id)&&o.running++,n.has(i.id)&&o.unread++}return r})(D,ts,td),[D,ts,td]),tX=(0,i.useMemo)(()=>[...tG.entries()].some(([e,{running:t,unread:n}])=>e!==tq?.key&&!A.has(e)&&(t>0||n>0)),[A,tG,tq]),tQ=tq?S(D,tq.key):D,t0=!!(eN?.isGit&&eN.isTopLevel&&Z&&tq?.key===eN.projectKey),t1=Z&&eN&&tq?.key===eN.projectKey&&!t0?eN.isGit?{label:N("sidebar.openRepoRoot"),title:N("sidebar.openRepoRootTitle")}:{label:N("sidebar.gitRepoRootOnly"),title:N("sidebar.gitRepoRootOnlyTitle")}:null,t2=!!(Z&&eJ===Z),t4=t1??(t2&&!t0?{label:N("sidebar.worktrees"),title:N("sidebar.checkingWorktrees")}:null),t8=h(tQ,z.sessions),t5=function(e,t,n,r=-1){let i=Math.ceil((n||600)/54)+16,o=Math.max(0,Math.min(Math.floor(t/54)-8,e-i)),l=Math.min(e,o+i),s=Array.from({length:l-o},(e,t)=>o+t);return r>=0&&r<o&&s.unshift(r),r>=l&&r<e&&s.push(r),s}(t8.length,tb,tv,t8.findIndex(e=>e.root.id===tw));return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[ea&&(0,r.jsx)(L,{initialPath:ec,busy:eg,error:ep,onCancel:()=>{ed(!1),eh(null)},onSelect:e=>void tA(e)}),(0,r.jsxs)("div",{style:{padding:"12px 10px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[(0,r.jsx)(eL,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsxs)("button",{onClick:tV,disabled:!Z,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,background:"var(--bg-hover)",border:"1px solid var(--border)",color:Z?"var(--text-muted)":"var(--text-dim)",cursor:Z?"pointer":"not-allowed",height:32,paddingLeft:10,paddingRight:12,borderRadius:7,fontSize:12,fontWeight:500,letterSpacing:"-0.01em",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:Z?N("sidebar.newSessionTitle",{path:Z}):N("sidebar.selectProject"),onMouseEnter:e=>{Z&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=Z?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]}),N("sidebar.new")]}),(0,r.jsx)("button",{type:"button",onClick:()=>{e3(e=>!e),eA(!1)},title:N("sidebar.toggleSessionSearch"),"aria-label":N("sidebar.toggleSessionSearch"),"aria-expanded":e6,"aria-controls":"session-search-input",className:`flex h-[32px] w-[32px] shrink-0 cursor-pointer items-center justify-center rounded-[7px] border border-border hover:bg-bg-selected focus-visible:outline-2 focus-visible:outline-accent ${e6?"bg-bg-selected text-accent":"bg-bg-hover text-text-muted"}`,children:(0,r.jsxs)("svg",{width:"18",height:"18",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)("div",{ref:eR,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>er(e=>!e),title:tq?.root??Z??"",style:{width:"100%",display:"flex",alignItems:"center",padding:"6px 10px",background:Z?"var(--bg-hover)":"rgba(37,99,235,0.06)",border:Z?"1px solid var(--border)":"1px solid rgba(37,99,235,0.4)",borderRadius:7,cursor:"pointer",fontSize:12,color:"var(--text)",textAlign:"left",transition:"border-color 0.15s, background 0.15s"},children:[Z?(0,r.jsx)(eE,{text:eM(tq?.root??Z,X),style:{flex:1,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text)"}}):(0,r.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:o&&!tE.current?"":N("sidebar.selectProject")}),tX&&(0,r.jsx)("span",{title:N("sidebar.newActivity"),"aria-label":N("sidebar.newActivity"),style:{width:8,height:8,borderRadius:"50%",flexShrink:0,marginLeft:6,background:"var(--accent)"}})]}),(0,r.jsxs)(eI,{open:en,style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[tY&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:ei,onChange:e=>eo(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eo(""),er(!1))},placeholder:N("sidebar.filterProjects"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(50vh, 380px)",overflowY:"auto"},children:[tZ.map(e=>{var t,n;return(0,r.jsxs)("button",{onClick:()=>{G(e.root),eo(""),ed(!1),eh(null),er(!1)},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"var(--bg)",border:"none",borderBottom:"1px solid var(--border)",color:e.key===tq?.key?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.root,children:[e.key===tq?.key&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}),e.key!==tq?.key&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(eE,{text:eM(e.root,X),style:{flex:1}}),(t=tG.get(e.key),n=N,t&&(0!==t.running||0!==t.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[t.running>0&&(0,r.jsxs)("span",{title:n("sidebar.agentRunning"),"aria-label":`${n("sidebar.agentRunning")} (${t.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsxs)("g",{children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"}),(0,r.jsx)("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.9s",repeatCount:"indefinite"})]})}),t.running]}),t.unread>0&&(0,r.jsxs)("span",{title:n("sidebar.newSessionActivity"),"aria-label":`${n("sidebar.newSessionActivity")} (${t.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"#0891b2",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),t.unread]})]}):null),(0,r.jsx)(ef,{as:"span",variant:"inline",kind:"project",id:e.key,pinned:z.projects.has(e.key),onToggle:P}),(0,r.jsx)(ey,{as:"span",id:e.key,archived:!1,onToggle:B})]},e.key)}),0===tZ.length&&ei.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:N("sidebar.noMatchingProjects")})]}),!ea&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),tB()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderTop:tZ.length>0?"1px solid var(--border)":"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round",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:N("sidebar.useDefaultDirectory")})]}),(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),tF()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:N("sidebar.customPath")})]})]})]}),e6&&(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:e9,maxLength:200,"aria-label":N("sidebar.searchSessions"),placeholder:N("sidebar.searchSessions"),onChange:e=>e7(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),e7(""))},className:"mt-[6px] block h-[29px] w-full min-w-0 rounded-[7px] border border-border bg-bg px-[10px] text-xs text-text focus:outline-2 focus:outline-accent"}),!e6&&t0&&(()=>{if(!eN)return null;let e=eN.worktrees.length>=8,t=e&&el.trim()?eN.worktrees.filter(e=>(e.branch??eM(e.path,X)).toLowerCase().includes(el.trim().toLowerCase())):eN.worktrees;return(0,r.jsxs)("div",{ref:eZ,style:{position:"relative",marginTop:6},children:[(0,r.jsxs)("button",{onClick:()=>eA(e=>!e),title:tW?N("sidebar.switchWorktreeTitle",{path:tW.path}):N("sidebar.switchWorktree"),style:{width:"100%",height:29,boxSizing:"border-box",display:"flex",alignItems:"center",gap:6,padding:"0 10px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",fontSize:11,lineHeight:1.35,color:"var(--text-muted)",textAlign:"left"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,color:tW&&!tW.isMain?"var(--accent)":"var(--text-dim)"},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)(eE,{text:tW?tW.branch??eM(tW.path,X):"…",style:{flex:1,fontFamily:"var(--font-mono)",color:"var(--text)"}}),tW?.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:N("sidebar.main")}),eN.worktrees.length>1&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:eN.worktrees.length}),(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),(0,r.jsxs)(eI,{open:eP,style:{position:"absolute",top:"calc(100% + 4px)",left:0,right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden"},children:[e&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:el,onChange:e=>es(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(es(""),eA(!1))},placeholder:N("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[t.map(e=>{let t=e.path===tP;return eK===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:N("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tH(e.path,!0),disabled:e_,style:{padding:"3px 9px",background:"#ef4444",border:"none",borderRadius:5,color:"#fff",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:N("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>eV(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:N("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:()=>{G(e.path),eA(!1),eU(null),es("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(eE,{text:e.branch??eM(e.path,X),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:N("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tH(e.path,!1),disabled:e_,title:N("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),e&&0===t.length&&el.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:N("sidebar.noMatchingWorktrees")})]}),eF?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:eG,value:eD,onChange:e=>{eH(e.target.value),eU(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tD()),"Escape"===e.key&&(eB(!1),eH(""),eU(null))},placeholder:N("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,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 tD(),disabled:e_||!eD.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--accent-contrast)",fontSize:11,fontWeight:600,cursor:e_||!eD.trim()?"not-allowed":"pointer",opacity:e_||!eD.trim()?.65:1},children:e_?N("sidebar.creating"):N("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eB(!1),eH(""),eU(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:N("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eB(!0),eU(null),setTimeout(()=>eG.current?.focus(),0)},title:N("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:N("sidebar.newWorktree")})]}),eO&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eO})]})]})})(),!e6&&t4&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:t4.title,style:{width:"100%",height:29,boxSizing:"border-box",marginTop:6,display:"flex",alignItems:"center",gap:6,padding:"0 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-hover)",color:"var(--text-dim)",fontSize:11,lineHeight:1.35,whiteSpace:"nowrap",textAlign:"left",cursor:"default",opacity:.82},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("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"},children:t4.label})]})]}),(0,r.jsx)(ee,{open:e6,query:e9,refreshKey:O,selectedSessionId:e,onSelectSession:tO,children:(0,r.jsxs)("div",{ref:tm,onScroll:tC,style:{flex:eX&&(m||Z)?"1 1 0":"1 1 auto",overflowY:"auto",padding:"0",minHeight:80},children:[K&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:N("sidebar.loading")}),J&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:J}),!K&&!J&&0===t8.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:N("sidebar.noSessions")}),t8.length>0&&(0,r.jsx)("div",{style:{position:"relative",height:54*t8.length},children:t5.map(t=>{let n=t8[t],i=[n.root,...n.subagents],o=n.latestModified===n.root.modified?n.root:{...n.root,modified:n.latestModified};return(0,r.jsx)("div",{onFocus:()=>tk(n.root.id),onBlur:()=>tk(null),style:{position:"absolute",top:54*t,left:0,right:0},children:(0,r.jsx)(eW,{session:o,isSelected:i.some(t=>t.id===e),isRunning:i.some(e=>ts.has(e.id)),isUnread:i.some(e=>td.has(e.id)),onClick:()=>tO(n.root),onRenamed:tT,onDeleted:e=>{x?.(e),tT()},pinned:z.sessions.has(n.root.id),onTogglePin:P})},n.root.id)})})]})}),(m||Z)&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:eX?"1 1 0":"0 0 auto",minHeight:0,overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0},children:[(0,r.jsxs)("button",{onClick:()=>eQ(e=>{let t=!e;return!function(e,t=f()){if(t)try{t.setItem(g,String(e))}catch{}}(t),t}),style:{display:"flex",alignItems:"center",gap:6,flex:1,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,letterSpacing:"0.05em",textTransform:"uppercase",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:eX?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),N("files.explorer")]}),b&&(0,r.jsx)(ek,{onClick:()=>b(Z??m),title:N("terminal.open"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"4 17 10 11 4 5"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),eX&&tt>0&&(0,r.jsx)(ek,{onClick:()=>ti(e=>!e),title:N("sidebar.changedFiles",{count:tt}),ariaPressed:!tr,color:tr?"var(--text-dim)":"var(--accent)",background:tr?"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"})]})}),eX&&(0,r.jsx)(ek,{onClick:()=>{e5(e=>!e)},title:N("sidebar.searchFiles"),ariaPressed:e8,color:e8?"var(--accent)":"var(--text-dim)",background:e8?"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"})]})}),eX&&(0,r.jsx)(ek,{onClick:()=>tx.current?.openUploadPicker(),disabled:e2,title:N("sidebar.uploadFilesTitle"),color:"var(--text-dim)",children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}),(0,r.jsx)(ek,{onClick:()=>{C?C():e1(e=>e+1),tl(!0),tf.current&&clearTimeout(tf.current),tf.current=setTimeout(()=>tl(!1),2e3)},title:N("sidebar.refreshExplorer"),skipHover:to,color:to?"#4ade80":"var(--text-dim)",background:to?"rgba(74,222,128,0.18)":"none",marginRight:6,children:to?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(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"})]})})]}),eX&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(Q,{ref:tx,cwd:Z??m,onOpenFile:y??(()=>{}),refreshKey:e0,onAtMention:M,onAtMentions:E,onUploadBusyChange:e4,changesCollapsed:tr,onChangesCountChange:tn,fileSearchOpen:e8,onFileSearchOpenChange:e5})})]})]})}function eN(){let{t:e}=(0,T.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsxs)("g",{children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"}),(0,r.jsx)("animateTransform",{attributeName:"transform",type:"rotate",from:"0 12 12",to:"360 12 12",dur:"0.9s",repeatCount:"indefinite"})]})})})}function ez(){let{t:e}=(0,T.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"#0891b2"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsxs)("circle",{cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4",opacity:"0.32",children:[(0,r.jsx)("animate",{attributeName:"r",values:"3;6;3",dur:"1.6s",repeatCount:"indefinite"}),(0,r.jsx)("animate",{attributeName:"opacity",values:"0.32;0;0.32",dur:"1.6s",repeatCount:"indefinite"})]})]})})}function eW({session:e,isSelected:t,isRunning:n,isUnread:o,onClick:l,onRenamed:s,onDeleted:a,depth:d=0,hasChildren:c=!1,collapsed:u=!1,onToggleCollapse:p,pinned:h=!1,onTogglePin:g}){let{locale:f,t:x}=(0,T.s)(),[v,y]=(0,i.useState)(!1),[b,j]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[S,M]=(0,i.useState)(!1),[E,I]=(0,i.useState)(!1),R=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>R.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let L=m(e.firstMessage)??e.firstMessage,$=e.name||L.slice(0,50)||e.id.slice(0,12),N=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||L.slice(0,50)||e.id.slice(0,12)),j(!0))},[e.name,e.transient,L,e.id]),z=(0,i.useCallback)(async()=>{let t=w.trim();if(j(!1),w!==$&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),s?.()}catch{}},[w,e.id,e.name,s,$]),W=(0,i.useCallback)(async()=>{if(!e.transient){M(!1),I(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),a?.(e.id)}catch{I(!1)}}},[e.id,e.transient,a]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?W():M(!0)},[W]),A=(0,i.useCallback)(e=>{e.stopPropagation(),W()},[W]),F=(0,i.useCallback)(e=>{e.stopPropagation(),M(!1)},[]),B=(0,i.useCallback)(t=>{(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:()=>{s?.()}})&&(t.preventDefault(),t.stopPropagation())},[s,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{onClick:S||b?void 0:l,onContextMenu:S||b?void 0:B,onMouseEnter:()=>y(!0),onMouseLeave:()=>{y(!1)},style:{height:54,display:"flex",alignItems:"center",paddingLeft:d>0?12*d+14:14,paddingRight:8,cursor:S||b?"default":"pointer",background:S?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":v?"var(--bg-hover)":"transparent",borderLeft:S?"2px solid #ef4444":t?"2px solid var(--accent)":"2px solid transparent",transition:"background 0.1s",opacity:E?.5:1,gap:6,overflow:"hidden"},children:S?(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:x("sidebar.deleteSession",{title:$.slice(0,22)+($.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:A,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"#ef4444",border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),x("sidebar.delete")]}),(0,r.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:x("sidebar.cancel")})]})]}):b?(0,r.jsx)("input",{ref:R,value:w,onChange:e=>k(e.target.value),onBlur:z,onKeyDown:e=>{"Enter"===e.key&&z(),"Escape"===e.key&&j(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[d>0&&(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0,fontSize:12,fontWeight:t?500:400,lineHeight:1.4,color:"var(--text)"},title:$,children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:$})}),(0,r.jsxs)("div",{style:{marginTop:2,display:"flex",alignItems:"center",gap:8,color:"var(--text-dim)",fontSize:11,minWidth:0},children:[n?(0,r.jsx)(eN,{}):o?(0,r.jsx)(ez,{}):(0,r.jsx)("span",{title:e.modified,children:(0,C.fw)(e.modified,f)}),(0,r.jsx)("span",{children:x("sidebar.messagesCount",{count:e.messageCount})}),e.isWorktree&&e.branch&&(0,r.jsxs)("span",{title:`Worktree: ${e.cwd}`,style:{display:"flex",alignItems:"center",gap:3,color:"var(--accent)",minWidth:0,overflow:"hidden"},children:[(0,r.jsxs)("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round",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"},children:e.branch})]})]})]}),c&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),p?.()},title:x(u?"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:u?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),g&&(0,r.jsx)(ef,{kind:"session",id:e.id,pinned:h,hovered:v,onToggle:g}),v&&!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:N,title:x("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="rgba(37,99,235,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsx)("svg",{width:"14",height:"14",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:P,title:x("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",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"})]})})]})]})})}var eP=n(5772);let eA=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eF=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eB=/\x1B_pi:c\x07/g;function eD(e){return e.replace(eB,"").replace(eA,"")}function eH(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eF);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 eO(e,t){let n=eH(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eU(e){return eH(e)[0]?.char}let e_={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:""},eq={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function eK(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function eV(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function eJ(e,t={}){return(e.content??[]).filter(e=>!eV(e,t))}function eY(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eZ(e,t={}){let n=eJ(e,t),r=n.findLastIndex(e=>"text"!==e.type&&"image"!==e.type);return -1===r?{answerBlocks:n,processBlocks:[]}:{answerBlocks:n.slice(r+1),processBlocks:n.slice(0,r+1)}}function eG(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function eX(e){try{return decodeURIComponent(e)}catch{return e}}function eQ(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e0(e){let t=eQ(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,o=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){o.length>0&&".."!==o[o.length-1]?o.pop():i||n||r||o.push(e);continue}o.push(e)}let l=o.join("/");return n?l:r?`//${l}`:i?`/${l}`:l}function e1(e,t,n=t){let r,i,o,l,s;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=eX(a),p=u.startsWith("\\\\"),h=eQ(u),g=h.toLowerCase();if(g.startsWith("/api/")||g.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!g.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(g.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=eX(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(a))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${eQ(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let f=e0(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=e0(f).replace(/\/+$/,""),i=e0(n).replace(/\/+$/,""),l=(o=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(l===(s=o?i.toLowerCase():i)||l.startsWith(`${s}/`)))?null:f}function e2(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 e4(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
2
-
3
- ${r}
4
-
5
- ${n}`}var e8=n(32316),e5=n(88374),e6=n(5924),e3=n(94764),e9=n(63835),e7=n(54152),te=n(84678),tt=n(98164);let tn={...e3.j,attributes:{...e3.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...e3.j.protocols,href:[...e3.j.protocols?.href??[],"file"]},strip:[...e3.j.strip||[],"iframe","object","style","form"]};function tr(e){return/^file:/i.test(e)?e:(0,e8.Lv)(e)}let ti=/(?<![\\`])`((?:[^`\n]|\\`)+?)(?<![\\`])`(?!`)/g;function to(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,o=0,l=null,s=new Map;for(let e=0;e<n.length;e++){var a,d;let t=n[e];if(l){r.push(t),RegExp(`</${l}\\s*>`,"i").test(t)&&(l=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},o=0,r.push(t);continue}if(i){r.push(t);continue}let u=t.match(/<(code|pre|script|style)\b/i);if(u){let e=u[1].toLowerCase(),n=t.slice((u.index??0)+u[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(l=e),o=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){o=0,r.push(t);continue}if(o||(t=t.replace(ti,(e,t)=>{let n=t.replace(/\\`/g,"`");if(n===t)return e;let r="`".repeat(Math.max(...n.match(/`+/g)?.map(e=>e.length)??[0])+1);return`${r}${n}${r}`})),o||t.includes("`")){o=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,o),r.push(t);continue}let p=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let h=t.match(/^([ ]{0,3})\[[ \t]*(.+?)[ \t]*\][ \t]*$/);if(h){let e=h[2].trim();if(a=e,/\\[A-Za-z]+/.test(a)&&!/\b(?:https?|file|mailto):|\b[A-Za-z]:\\|^\\\\/i.test(a)){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[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=>ts(e,g[1])),`${g[1]}$$`),e=t;continue}}let f=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \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]{0,3})\$\$(.+)$/);if(x){let t=x[1],i=x[2].trimEnd();if(i&&!i.includes("$$")){let o=tl(n,e+1,t,s);if(o){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<o.index;i++)r.push(ts(n[i],t));o.content&&r.push(`${t}${o.content}`),r.push(`${t}$$`),e=o.index;continue}}}let m=t.match(/^([ \t]{0,3})\$\$\s*$/);if(m){let t=m[1],i=tl(n,e+1,t,s);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let o=e+1;o<i.index;o++)r.push(ts(n[o],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((d=t,/^\s{0,3}\[[^\]]+\]:/.test(d)||/]\s*\(/.test(d)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(d)||/\b(?:https?|file|mailto):/i.test(d)||/\b[A-Za-z]:\\/.test(d)?d:d.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tl(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var o,l,s,a;let t=e[i];if(o=t,""===(l=n)?/^ {0,3}\$\$\s*$/.test(o):o.startsWith(l)&&/^\$\$\s*$/.test(o.slice(l.length)))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)||(a=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(a)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function ts(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 ta={singleTilde:!1},td=[[e7.A,["yaml"]],[te.A,ta],tt.A],tc=[[e7.A,["yaml"]],[te.A,ta],tt.A],tu=[e6.A,[e9.A,tn],[e5.A,{throwOnError:!1,strict:!1}]],tp=[e6.A,[e9.A,tn],[e5.A,{throwOnError:!1,strict:!1}]];var th=n(65063),tg=n(7644);let tf=[{id:"light",label:"settings.themeLight"},{id:"dark",label:"settings.themeDark"},{id:"mist",label:"settings.themeMist"},{id:"rose",label:"settings.themeRose"},{id:"pine",label:"settings.themePine"},{id:"auto",label:"settings.themeSystem"}];function tx(e){return"dark"===e||"pine"===e}let tm="pi-theme",tv={preference:"auto",theme:"light"},ty=new Set,tb=null,tj=!1;function tw(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tk(e){return"auto"===e?tw():e}function tS(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",tx(e)))}function tC(){if(tb)return tb;let e=function(){try{let e=localStorage.getItem(tm);if(tf.some(t=>t.id===e))return e}catch{}return"auto"}(),t=tk(e);return tS(t),tb={preference:e,theme:t}}function tT(e,t,n){if(tS(t),n)try{localStorage.setItem(tm,e)}catch{}tb={preference:e,theme:t},ty.forEach(e=>e())}function tM(){let e=tC();if("auto"!==e.preference)return;let t=tw();t!==e.theme&&tT("auto",t,!1)}function tE(e){return ty.add(e),tC(),tj||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tM),window.addEventListener("focus",tM),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tM()}),tj=!0),tM(),()=>{ty.delete(e)}}function tI(){return tC()}function tR(){return tv}function tL(){let e=(0,i.useSyncExternalStore)(tE,tI,tR),t=(0,i.useCallback)((e,t)=>{if(tC().preference===e)return;let n=tk(e),r=()=>{tT(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let o=t?.x??window.innerWidth/2,l=t?.y??window.innerHeight/2,s=Math.hypot(Math.max(o,window.innerWidth-o),Math.max(l,window.innerHeight-l));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${o}px ${l}px)`,`circle(${s}px at ${o}px ${l}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]);return{theme:e.theme,preference:e.preference,setThemePreference:t,isDark:tx(e.theme)}}function t$(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()}}function tN({code:e,isStreaming:t,defaultPreview:o=!1}){let{isDark:l}=tL(),{t:s}=(0,T.s)(),[a,d]=(0,i.useState)(o),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),g=(0,i.useRef)(null),f=`${l?"dark":"light"}
6
- ${e}`,x=a&&!t;(0,i.useEffect)(()=>{if(!x)return;let t=!1;return u({key:f,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(988),n.e(9425),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:l?"dark":"default"}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(i,e);t||u({key:f,status:"ready",svg:o.svg})})().catch(()=>{t||u({key:f,status:"error"})}),()=>{t=!0}},[e,f,l,x]);let m=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?s("i18n.previewAfterStreaming"):x?s("i18n.showMermaidSource"):s("i18n.previewMermaid"),className:["markdown-code-action",x?"is-active":""].filter(Boolean).join(" "),children:x?s("i18n.source"):s("i18n.preview")}),[t,x,s]);if(!x)return(0,r.jsx)(tW,{code:e,lang:"mermaid",headerAction:m,isStreaming:t});let v=c?.key===f&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==f||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.jsx)("button",{ref:g,type:"button",className:"mermaid-block mermaid-preview-button",title:s("i18n.openMermaidViewer"),"aria-label":s("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:c.svg}}),p&&(0,r.jsx)(tz,{svg:c.svg,onClose:()=>h(!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===f&&"ready"===c.status&&(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${s("i18n.downloadFile")} (SVG)`,"aria-label":`${s("i18n.downloadFile")} (SVG)`,onClick:()=>{let e,t,n,r=g.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"}),m]})]}),v]})}function tz({svg:e,onClose:t}){let{t:n}=(0,T.s)(),o=(0,i.useRef)(null),[l,s]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:o,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>s(e=>Math.max(.5,e-.25)),disabled:l<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*l),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>s(e=>Math.min(3,e+.25)),disabled:l>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>s(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*l}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tW=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:o}){let{isDark:l}=tL(),{t:s}=(0,T.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.jsx)("button",{onClick:()=>{t$(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:s(a?"i18n.copied":"i18n.copy")})]})]}),o?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(th.A,{language:t||"text",style:l?tg.xJ:tg.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:"calc(12.5px + var(--chat-font-size-offset, 0px))",lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function tP({children:e,className:t,isStreaming:n,cwd:o,onOpenFile:l}){let s=(0,i.useMemo)(()=>to(e),[e]),a=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let o=e?.replace("language-","").toLowerCase()??"",l=String(t);return e?.includes("language-")||l.includes("\n")?"mermaid"===o?(0,r.jsx)(tN,{code:l.replace(/\n$/,""),isStreaming:n,defaultPreview:!0}):(0,r.jsx)(tW,{code:l.replace(/\n$/,""),lang:o,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=l?e1(e,o):null;return i&&l?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(!eG(e))return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),l(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?e1(e,o):null,l=i?`/api/files/${B(i)}?type=read`:e;return(0,r.jsx)("img",{src:l,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[o,n,l]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(e8.oz,{remarkPlugins:td,rehypePlugins:tu,urlTransform:l?tr:void 0,components:a,children:s})})}function tA({src:e,alt:t="",children:n,className:o,style:l}){let{t:s}=(0,T.s)(),[a,d]=(0,i.useState)(!1),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(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(),p.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[a]);let h=()=>{u.current?.open&&u.current.close(),d(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:c,type:"button",className:o,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...l},onClick:()=>d(!0),"aria-label":s("chat.previewImage"),"aria-haspopup":"dialog","aria-expanded":a,title:s("chat.previewImage"),children:n}),a&&(0,r.jsxs)("dialog",{ref:u,className:"image-preview-dialog","aria-label":s("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),h()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),h())},onClick:e=>{e.target===e.currentTarget&&h()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:e,alt:t}),(0,r.jsx)("button",{ref:p,type:"button",className:"image-preview-close",onClick:h,"aria-label":s("chat.close"),title:s("chat.close"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]})}function tF({active:e,size:t=14}){return(0,r.jsxs)("svg",{width:t,height:t,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:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z",stroke:e?"#d4a017":void 0,fill:e?"rgba(250, 204, 21, 0.18)":"none",style:{filter:e?"drop-shadow(0 0 2px rgba(250, 204, 21, 0.35))":"none"}}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]})}let tB=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,tD=/(?:\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 tH(e){let t,n=[],r=null,i=0,o=0,l=0,s=0,a=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){a=[],d=[];return}let e=Math.max(a.length,d.length);for(let t=0;t<e;t++){let e=a[t]?{lineNo:a[t].lineNo,text:a[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}a=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(l>0||s>0)){if(c.startsWith("--- ")){u(),t=tO(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:tO(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),o=Number(e[3]),l=void 0===e[2]?1:Number(e[2]),s=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:o++,text:h,type:"context"}}),l>0&&l--,s>0&&s--):"-"===p?(a.push({lineNo:i++,text:h}),l>0&&l--):"+"===p?(d.push({lineNo:o++,text:h}),s>0&&s--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function tO(e){return e.split(" ")[0].trim()}let tU="pi-thinking-expanded",t_="pi-thinking-expanded-changed";function tq(){return"true"===window.localStorage.getItem(tU)}function tK({files:e,onOpenFile:t}){let{t:n}=(0,T.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=D(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:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[A(i,12),(0,r.jsx)("span",{children:i})]},e)})})}let tV=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function tJ(e){let t=0,n=0;for(let r of e)tV.test(r)?t++:n++;return t+n/4}let tY=new Map;function tZ({children:e,className:t,...n}){let{t:o}=(0,T.s)(),[l,s]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(tP,{className:t,...n,children:e});if(!l){var a;return(0,r.jsxs)("button",{onClick:()=>s(!0),style:{display:"block",width:"100%",margin:"4px 0",padding:"7px 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:["⚠ ",o("i18n.largeMessageReveal",{size:(a=e.length)>=1e6?`${(a/1e6).toFixed(1)} MB`:a>=1e3?`${Math.round(a/1e3)} KB`:`${a} B`})]})}return(0,r.jsx)("div",{className:t,style:{maxHeight:420,overflow:"auto",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)",color:"var(--text-muted)"},children:e})})}function tG(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let o=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${o} ${i}`}let tX=(0,i.memo)(function({message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:o,onOpenFile:l,onOpenSession:s,entryId:a,searchBlock:d,onFork:c,forking:u,onNavigate:p,onEditContent:h,showTimestamp:g,prevTimestamp:f,sessionId:x,writtenFiles:m}){return"user"===e.role?(0,r.jsx)(tQ,{message:e,cwd:o,onOpenFile:l,entryId:a,onFork:c,forking:u,onNavigate:p,onEditContent:h}):"assistant"===e.role?(0,r.jsx)(t0,{message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:o,onOpenFile:l,onOpenSession:s,showTimestamp:g,prevTimestamp:f,sessionId:x,entryId:a,searchBlock:d,writtenFiles:m}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(nt,{message:e}):(0,r.jsx)(ni,{message:e,cwd:o,onOpenFile:l}):"bashExecution"===e.role?(0,r.jsx)(na,{message:e,sessionId:x}):null},(e,t)=>e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.modelNames===t.modelNames&&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.onEditContent===t.onEditContent&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.writtenFiles===t.writtenFiles&&e.sessionId===t.sessionId);function tQ({message:e,cwd:t,onOpenFile:n,entryId:o,onFork:l,forking:s,onNavigate:a,onEditContent:d}){let{t:c}=(0,T.s)(),[u,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(!1),v="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),y="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),b=m(v),j=b?.search(/\s/)??-1,w=b?-1===j?b:b.slice(0,j):"",k=b&&-1!==j?b.slice(j+1):"",S=tG(e.timestamp),C=!!o&&!!l,M=b??v,E=b?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,b):e,I=y.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!v},children:y.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)(tA,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid rgba(59,130,246,0.15)"}})},t)})}),R=!!o&&!!a;return(0,r.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsx)("div",{style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid rgba(59,130,246,0.2)",borderRadius:12,padding:"8px 12px",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,color:"var(--text)",wordBreak:"break-word",maxHeight:300,overflowY:"auto"},children:b?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[I,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>x(e=>!e),title:c(f?"i18n.collapse":"i18n.expand"),"aria-expanded":f,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:f?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),k&&(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word",minWidth:0,flex:1},children:k})]}),f&&(0,r.jsx)(tP,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:v})]}):(0,r.jsxs)(r.Fragment,{children:[I,v&&(0,r.jsx)(tZ,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:v})]})})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!u,pointerEvents:u?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsxs)("button",{onClick:()=>{t$(M).then(()=>{g(!0),setTimeout(()=>g(!1),1500)})},title:c("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{h||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{h||(e.currentTarget.style.color="var(--text-dim)")},children:[h?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),c(h?"i18n.copied":"i18n.copy")]})}),(C||R)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:u||s?1:0,pointerEvents:u||s?"auto":"none",transition:"opacity 0.12s"},children:[R&&(0,r.jsxs)("button",{onClick:()=>void a(o).then(e=>{e&&d?.(E)}),title:c("i18n.editFromHereTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),c("i18n.editFromHere")]}),C&&(0,r.jsxs)("button",{onClick:()=>{l(o)},disabled:s,title:c(s?"i18n.creatingSession":"i18n.newSessionTitle"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:s?"var(--accent)":"var(--text-dim)",cursor:s?"not-allowed":"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{s||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{s||(e.currentTarget.style.color="var(--text-dim)")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),c(s?"i18n.creating":"i18n.newSession")]})]}),S&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:S})]})]})}function t0({message:e,isStreaming:t,toolResults:n,modelNames:o,cwd:l,onOpenFile:s,onOpenSession:a,showTimestamp:d,prevTimestamp:c,sessionId:u,entryId:p,searchBlock:h,writtenFiles:g}){var f,x,m;let v,y,b,j,w,k,{t:S}=(0,T.s)(),C=d?tG(e.timestamp):null,M=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!eV(e,{isStreaming:t})),[e.content,t]),E=(0,i.useMemo)(()=>M.map(({block:e})=>e),[M]),I=eY(e,{isStreaming:t}),[R,L]=(0,i.useState)(!1),[$,N]=(0,i.useState)(!1),z=(0,i.useRef)(null),[W,P]=(0,i.useState)(null),A=(0,i.useRef)(M);A.current=M;let F=(0,i.useRef)(new Map),B=(0,i.useMemo)(()=>{if(!t)return F.current=new Map,0;let e=new Map,n=0;for(let{block:t,originalIndex:r}of M){let i="text"===t.type?t.text:"thinking"===t.type?t.thinking:"toolCall"===t.type?t.rawInput??JSON.stringify(t.input??{})??"":null;if(null===i)continue;let o=function(e,t){var n,r;if(!e||!t.startsWith(e.text))return tJ(t);let i=e.tokens,o=e.text.length;return o>0&&o<t.length&&(n=e.text.charCodeAt(o-1))>=55296&&n<=56319&&(r=t.charCodeAt(o))>=56320&&r<=57343&&(i-=1/4,o--),i+tJ(t.slice(o))}(F.current.get(r),i);e.set(r,{text:i,tokens:o}),n+=o}return F.current=e,n},[M,t]),D=(0,i.useRef)(B);D.current=B;let H=(0,i.useRef)(new Map),[O,U]=(0,i.useState)(new Map),_=(0,i.useMemo)(()=>{if(!e.timestamp||!c)return;let t=Math.round((e.timestamp-c)/1e3);return t>0?t:void 0},[e.timestamp,c]),q=(0,i.useMemo)(()=>{let t=new Map;if(!n||!e.timestamp)return t;for(let[r,i]of n)if(i.timestamp&&e.timestamp){let n=Math.round((i.timestamp-e.timestamp)/1e3);n>0&&t.set(r,n)}return t},[n,e.timestamp]),K=E.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if((0,i.useEffect)(()=>{if(!t){let e=new Date().getTime();U(t=>{let n=new Map(t);for(let[t,r]of H.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),z.current=null,P(null);return}let e=setInterval(()=>{let e=A.current,t=Date.now();e.forEach(({originalIndex:e})=>{H.current.has(e)||H.current.set(e,t)}),U(n=>{let r=!1,i=new Map(n);for(let n=0;n<e.length-1;n++){let o=e[n].originalIndex,l=e[n+1].originalIndex;if(!i.has(o)&&H.current.has(o)){let e=H.current.get(o),n=H.current.get(l)??t;i.set(o,Math.round((n-e)/1e3)),r=!0}}return r?i:n});let n=D.current;if(0===n)return;null===z.current&&(z.current=t);let r=(t-z.current)/1e3;r>.5&&P(n/r)},300);return()=>clearInterval(e)},[t]),0===E.length&&!t&&!I)return null;return(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":p,style:{marginBottom:16},onMouseEnter:()=>L(!0),onMouseLeave:()=>L(!1),children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,display:"flex",alignItems:"center",gap:6},children:[e.provider&&(0,r.jsx)("span",{children:(f=e.provider,x=e.model,y=f.toLowerCase(),b=x.toLowerCase(),j=Object.entries(o??{}).flatMap(([e,t])=>{let n=e.indexOf(":");return n>0&&e.slice(0,n).toLowerCase()===y?[{id:e.slice(n+1).toLowerCase(),name:t}]:[]}),j.find(e=>e.id===b)?.name??j.find(e=>b.endsWith(`/${e.id}`))?.name??Object.entries(o??{}).find(([e])=>e.toLowerCase()===b)?.[1]??`${f}/${x}`)}),t&&(w=Math.round(B),(0,r.jsx)(r.Fragment,{children:w>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:S("i18n.estimatedTokens"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),w]}),null!==W&&(k=W>=50?"#53b3cb":W>=30?"#9bc53d":W>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:k,color:"#fff",fontSize:11,fontWeight:400},children:[W.toFixed(1)," t/s"]}))]})}))]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:M.map(({block:e,originalIndex:i})=>(0,r.jsx)(t1,{block:e,searchTarget:e===h,toolResults:n,isStreaming:t,streamingDuration:O.get(i)??("thinking"===e.type?_:void 0),toolCallDurations:q,cwd:l,onOpenFile:s,onOpenSession:a,sessionId:u,entryId:p,blockIndex:i},`${p??"stream"}-${i}`))}),I&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(E.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: ",I]}),g&&g.length>0&&(0,r.jsx)(tK,{files:g,onOpenFile:s}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:(m=e.usage,v=[],m.input&&v.push(`${m.input.toLocaleString()} in`),m.output&&v.push(`${m.output.toLocaleString()} out`),m.cacheRead&&v.push(`${m.cacheRead.toLocaleString()} cache R`),m.cacheWrite&&v.push(`${m.cacheWrite.toLocaleString()} cache W`),m.cost?.total&&v.push(`$${m.cost.total.toFixed(4)}`),v.join(" \xb7 "))}),K&&!t&&(0,r.jsxs)("button",{onClick:()=>{t$(K).then(()=>{N(!0),setTimeout(()=>N(!1),1500)})},title:S("i18n.copyMessage"),style:{display:"flex",alignItems:"center",gap:4,padding:"3px 8px",height:22,background:"none",border:"none",borderRadius:5,color:$?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",opacity:+!!R,pointerEvents:R?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{$||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{$||(e.currentTarget.style.color="var(--text-dim)")},children:[$?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),S($?"i18n.copied":"i18n.copy")]}),C&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:C})]})]})}function t1({block:e,searchTarget:t,toolResults:n,isStreaming:i,streamingDuration:o,toolCallDurations:l,cwd:s,onOpenFile:a,onOpenSession:d,sessionId:c,entryId:u,blockIndex:p}){if("text"===e.type)return(0,r.jsx)("div",{"data-message-text":!0,"data-search-target":t||void 0,children:(0,r.jsx)(t2,{block:e,isStreaming:i,cwd:s,onOpenFile:a})});if("thinking"===e.type)return(0,r.jsx)(t4,{block:e,duration:o,sessionId:c,entryId:u,blockIndex:p});if("toolCall"===e.type){let t=n?.get(e.toolCallId),i=l?.get(e.toolCallId);return(0,r.jsx)(t8,{block:e,result:t,duration:i,onOpenSession:d})}return null}function t2({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(tZ,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function t4({block:e,duration:t,sessionId:n,entryId:o,blockIndex:l}){var s;let{t:a}=(0,T.s)(),[d,c]=(0,i.useState)(tq),[u,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(null),m=(0,i.useRef)(a);m.current=a;let v=(s=e.thinking,s.trimStart().match(/^[^\r\n]{0,240}/u)?.[0].trimEnd()??"");return(0,i.useEffect)(()=>{let e=()=>c(tq());return window.addEventListener(t_,e),()=>window.removeEventListener(t_,e)},[]),(0,i.useEffect)(()=>{if(!d||!e.deferred||null!==u)return;if(!n||!o)return void x(m.current("i18n.thinkingUnavailable"));let t=!1;return g(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=tY.get(r);if(i)return tY.delete(r),tY.set(r,i),i;let o=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw tY.delete(r),e});if(tY.set(r,o),tY.size>100){let e=tY.keys().next().value;e&&tY.delete(e)}return o})(n,o,l).then(e=>{t||(p(e),g(!1))}).catch(e=>{t||(x(e instanceof Error?e.message:String(e)),g(!1))}),()=>{t=!0}},[d,e.deferred,u,n,o,l]),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:6,minWidth:0,border:"1px solid var(--border)",borderRadius:7,padding:"6px 10px",background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"calc(11px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":d,"aria-label":`${a("i18n.thinking")}${v?`: ${v}`:""}`,title:a("i18n.thinking"),onClick:()=>c(e=>!e),style:{display:"inline-flex",alignItems:"center",gap:6,width:d?14:"100%",flexShrink:+!d,minWidth:0,minHeight:"1.5em",padding:0,background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)(tF,{active:d}),!d&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v?(0,r.jsx)(e8.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:v}):"..."})]}),d&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:f?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:h?a("i18n.loadingThinking"):f??(e.deferred?u:e.thinking)}),void 0!==t&&(0,r.jsxs)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:[t,"s"]})]})}function t8({block:e,result:t,duration:n,onOpenSession:o}){var l,s;let{t:a}=(0,T.s)(),[d,c]=(0,i.useState)(!1),u=(s=e).rawInput??JSON.stringify(s.input,null,2),p=void 0!==e.rawInput,h=e2(e.toolName),g=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,f=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,x=nl(t?.content??[]),m=null!==f&&("(no output)"===f.trim()||""===f.trim()),v=t?.isError??!1,y=(l=t?.details)&&"object"==typeof l&&"pi-web-subagent"===l.kind&&"string"==typeof l.sessionId?t.details:null;return(0,r.jsxs)("div",{style:{borderRadius:7,overflow:"hidden",fontSize:12,border:v?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:v?"rgba(248,113,113,0.05)":"rgba(34,197,94,0.04)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",minWidth:0},children:[(0,r.jsxs)("button",{onClick:()=>c(e=>!e),style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:[(0,r.jsx)("span",{style:{color:v?"#f87171":"#16a34a",fontFamily:"var(--font-mono)",fontWeight:600,fontSize:11,flexShrink:0},children:e.toolName}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:p?a("chat.generatingToolInput"):function(e){let t=e.input;if(!t||"object"!=typeof t)return"";let n=Object.keys(t);return 0===n.length?"":"command"in t?String(t.command).slice(0,120):"path"in t?String(t.path).slice(0,120):"file_path"in t?String(t.file_path).slice(0,120):"pattern"in t?String(t.pattern).slice(0,120):"query"in t?String(t.query).slice(0,120):String(t[n[0]]).slice(0,120)}(e)}),void 0!==n&&(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-dim)",flexShrink:0,fontVariantNumeric:"tabular-nums"},children:[n,"s"]}),(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:d?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),y&&o&&(0,r.jsx)("button",{type:"button",onClick:()=>o(y.sessionId),title:a("subagent.open"),"aria-label":a("subagent.open"),style:{width:32,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:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M15 3h6v6"}),(0,r.jsx)("path",{d:"M10 14 21 3"}),(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})})]}),d&&(p||!h)&&(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-subtle)",borderTop:v?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:u}),d&&t&&(g?(0,r.jsx)(t5,{diff:g}):(0,r.jsx)(ne,{text:f??"",images:x,isEmpty:m,isError:v}))]})}function t5({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(t6,{text:e.text})})}function t6({text:e}){let{t}=(0,T.s)(),n=(0,i.useMemo)(()=>tH(e),[e]);if(!n)return(0,r.jsx)(t7,{text:e});let o=n.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[o&&(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)(t3,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(t3,{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)(t9,{cell:e.left,side:"left"}),(0,r.jsx)(t9,{cell:e.right,side:"right"})]},t))})]},n))})}function t3({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 t9({cell:e,side:t}){let n="added"===e.type?"rgba(34,197,94,0.12)":"removed"===e.type?"rgba(248,113,113,0.13)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"#22c55e":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:o,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function t7({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 ne({text:e,images:t,isEmpty:n,isError:i}){let{t:o}=(0,T.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:t.map((e,t)=>{let n=ns(e);return n?(0,r.jsx)(tA,{src:n,style:{maxWidth:"100%"},children:(0,r.jsx)("img",{src:n,alt:"",loading:"lazy",style:{display:"block",maxWidth:"min(100%, 720px)",maxHeight:520,borderRadius:6,objectFit:"contain",border:"1px solid var(--border)"}})},`${n}-${t}`):null})}),l&&(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:i?"#f87171":n?"var(--text-dim)":"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:n?"italic":"normal",opacity:n?.6:1},children:n?o("i18n.noOutput"):e})]})}function nt({message:e}){let{t}=(0,T.s)(),n=no(e.content),o=(0,i.useMemo)(()=>{let e,t,r,i,o;return e=[],t=[],r=n.match(tD),i=r?.[1]??"",o=r?.index===void 0?n:n.slice(0,r.index),i.replace(tB,(n,r,i)=>{let o=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...o):t.push(...o),""}),{body:o.trim(),readFiles:e,modifiedFiles:t}},[n]),l=tG(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),l&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:l})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"calc(15px + var(--chat-font-size-offset, 0px))",fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:"calc(14px + var(--chat-font-size-offset, 0px))",lineHeight:1.5},children:t("i18n.compactionDescription")}),o.body?(0,r.jsx)(tP,{className:"markdown-compaction-message",children:o.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(nn,{readFiles:o.readFiles,modifiedFiles:o.modifiedFiles})]})]})})}function nn({readFiles:e,modifiedFiles:t}){let{t:n}=(0,T.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)(nr,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(nr,{title:n("i18n.readFiles"),files:e})]})}function nr({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 ni({message:e,cwd:t,onOpenFile:n}){let o,{t:l}=(0,T.s)(),s=!1===e.display,[a,d]=(0,i.useState)(!s),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!1),g=no(e.content),f=nl(e.content),x=void 0!==e.details,m=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",v=e.customType||"extension",y=tG(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:s?"var(--bg-subtle)":"var(--bg)",opacity:s&&!a?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:v}),s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),a?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[f.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!g},children:f.map((e,t)=>{let n=ns(e);return n?(0,r.jsx)(tA,{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})}),g?(0,r.jsx)(tP,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:g}):(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:g?(o=g.replace(/\s+/g," ").trim())?o.length>140?`${o.slice(0,140)}...`:o:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[g||m?(0,r.jsx)("button",{onClick:()=>{t$(g||m).then(()=>{h(!0),setTimeout(()=>h(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:p?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(p?"i18n.copied":"i18n.copy")}):null,(x||s)&&(0,r.jsx)("button",{onClick:()=>{s?d(e=>!e):u(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(s?a?"i18n.collapse":"i18n.expand":c?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(s&&a||!s&&c)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:m})]})})}function no(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function nl(e){return"string"==typeof e?[]:e.filter(e=>"image"===e.type)}function ns(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 na({message:e,sessionId:t}){let[n,o]=(0,i.useState)(null),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===n,g=n??e.output;async function f(){if(p){s(!0),d(null);try{let e=await fetch(p),t=await e.json();t.success?o(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{s(!1)}}}let x=e.excludeFromContext?"bash (local)":"bash",m={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:x,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:m.toolCallId,toolName:x,content:g?[{type:"text",text:g}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(t8,{block:m,result:v}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,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:`${p}&download=1`,style:{marginLeft:10*!!h,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 nd(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}let nc=new Map;function nu(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function np(e){return!e.value&&0===e.images.length}function nh(e){let t=nc.get(e);return t?nu(t):null}function ng(e,t){np(t)?nc.delete(e):nc.set(e,nu(t))}function nf(e){nc.delete(e)}function nx(e,t){return e.trim()?t.trim()?`${e}
7
-
8
- ${t}`:e:t}function nm(e,t,n,r){let i=[...t??[],...r].filter(nd).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t}));return{value:nx(e,n),images:i}}function nv(e,t,n){if(e===t)return n?nu(n):nh(t);let r=nh(e),i=n&&!np(n)?nu(n):r??(n?nu(n):null),o=nh(t);if(nf(e),!i)return o;let l=o?nm(o.value,o.images,i.value,i.images):i;return ng(t,l),nu(l)}function ny(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 nb(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function nj(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 nw(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}let nk="pi-chat-content-width",nS="pi-chat-content-font-size",nC={width:820,fontSize:14},nT=null,nM=new Set;function nE(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function nI(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function nR(e){try{return window.localStorage.getItem(e)}catch{return null}}function nL({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 n$(){return nT||nL(nT={width:nE(nR(nk)),fontSize:nI(nR(nS))}),nT}function nN(e){return nM.add(e),()=>{nM.delete(e)}}function nz(e,t){let n="width"===e?nE(t):nI(t);nL(nT={...n$(),[e]:n});try{window.localStorage.setItem("width"===e?nk:nS,String(n))}catch{}nM.forEach(e=>e())}let nW=e=>nz("width",e),nP=e=>nz("fontSize",e);function nA(){return{...(0,i.useSyncExternalStore)(nN,n$,()=>nC),setWidth:nW,setFontSize:nP}}let nF=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function nB(e,t){return nF.compare(e.name||e.modelId,t.name||t.modelId)||nF.compare(e.provider,t.provider)||nF.compare(e.modelId,t.modelId)}function nD({options:e,value:t,onChange:n,onClear:o,emptyLabel:l,selectedLabel:s,disabled:a=!1,busy:d=!1,isAutoSelection:c=!1,ariaLabel:u,variant:p="toolbar",placement:h="up"}){let g,f,x,m,v,y,b,j,w,{t:k}=(0,T.s)(),S=ec(),C=(0,i.useRef)(null),M=(0,i.useRef)(null),[E,I]=(0,i.useState)(!1),[R,L]=(0,i.useState)(null),[$,N]=(0,i.useState)(""),z=a||d,W=(0,i.useMemo)(()=>[...e].sort(nB),[e]),P=(g=$.trim().toLocaleLowerCase())?W.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(g)):W,A=W.length>8,F=[];for(let e of P){let t=F.find(t=>t.provider===e.provider);t?t.options.push(e):F.push({provider:e.provider,options:[e]})}let B=s??(t?W.find(e=>e.modelId===t.modelId&&e.provider===t.provider)?.name??t.modelId:l??(W.length>0?"Select model":"No models"));(0,i.useEffect)(()=>{let e=e=>{C.current&&!C.current.contains(e.target)&&M.current&&!M.current.contains(e.target)&&(I(!1),N(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{z&&(I(!1),N(""))},[z]);let D="field"===p?{display:"flex",alignItems:"center",gap:7,width:"100%",minWidth:0,height:34,padding:"0 9px",overflow:"hidden",border:"1px solid var(--border)",borderRadius:5,background:z?"var(--bg-panel)":"var(--bg)",color:z?"var(--text-dim)":"var(--text)",cursor:z?"default":"pointer",fontSize:12,textAlign:"left"}:{display:"flex",alignItems:"center",justifyContent:S?"flex-start":void 0,gap:6,width:S?"100%":void 0,maxWidth:S?"100%":220,height:32,padding:S?"8px 10px":"8px 12px",overflow:"hidden",border:"none",borderRadius:9,background:E?"var(--bg-hover)":"none",color:"var(--text-muted)",cursor:z?"not-allowed":"pointer",fontSize:12,opacity:z?.5:1,transition:"background 0.12s, color 0.12s"};return(0,r.jsxs)("div",{ref:C,className:`model-selector is-${p}${z?" is-disabled":""}`,style:{position:"relative",width:"field"===p||S?"100%":void 0,minWidth:0,flex:"toolbar"===p&&S?"1 1 auto":void 0},onKeyDown:e=>{"Escape"===e.key&&E&&(e.preventDefault(),e.stopPropagation(),N(""),I(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":u,"aria-haspopup":"listbox","aria-expanded":E,"aria-busy":d||void 0,disabled:z,title:d?"Switching model":z?B:W.length>0||o?"Change model":"No available models",style:D,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();L({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),I(e=>(e&&N(""),!e))},onMouseEnter:e=>{z||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{if(z){e.currentTarget.style.background="field"===p?"var(--bg-panel)":"none",e.currentTarget.style.color="field"===p?"var(--text-dim)":"var(--text-muted)";return}e.currentTarget.style.background=E?"var(--bg-hover)":"field"===p?"var(--bg)":"none",e.currentTarget.style.color="field"===p?"var(--text)":"var(--text-muted)"},children:[d?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:B}),"field"===p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),E&&R&&(f=window.visualViewport?.height??window.innerHeight,x=window.visualViewport?.width??window.innerWidth,m=R.top-8,v=f-R.bottom-8,b=Math.max(120,Math.min((y="up"===h||m>v)?m:v,.6*f)),j=y?{bottom:f-R.top+6}:{top:R.bottom+6},w=S?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:R.left,width:"max-content",minWidth:R.width,maxWidth:Math.max(R.width,x-R.left-8)},(0,r.jsxs)("div",{ref:M,role:"listbox","aria-label":u,style:{position:"fixed",...j,...w,zIndex:500,display:"flex",flexDirection:"column",maxHeight:b,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:y?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)"},children:[A&&(0,r.jsx)("div",{style:{flexShrink:0,padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:$,onChange:e=>N(e.target.value),placeholder:k("chat.filterModels"),"aria-label":k("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{boxSizing:"border-box",width:"100%",minWidth:220*!S,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[o&&!$.trim()&&(0,r.jsx)(nH,{active:!t,label:l??"Default",onClick:()=>{I(!1),N(""),o()}}),0===F.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:$.trim()?k("chat.noMatchingModels"):"No available models"}):F.map((e,i)=>(0,r.jsxs)("div",{children:[F.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",borderTop:i>0||o?"1px solid var(--border)":"none",color:"var(--text-dim)",fontSize:10,fontWeight:600,letterSpacing:0,textTransform:"uppercase"},children:e.provider}),e.options.map(e=>(0,r.jsx)(nH,{active:e.modelId===t?.modelId&&e.provider===t?.provider,label:e.name,onClick:()=>{let r;return r=e.modelId===t?.modelId&&e.provider===t?.provider,void(I(!1),N(""),(!r||c)&&n(e.provider,e.modelId))}},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function nH({active:e,label:t,onClick:n}){return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":e,onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",border:"none",background:e?"var(--bg-selected)":"none",color:e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:e?600:400,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:t=>{e||(t.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:t=>{e||(t.currentTarget.style.background="none")},children:[e?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{title:t,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:t})]})}let nO=["chat-only","read-only","default","full"],nU={"chat-only":"none","read-only":"read-only",default:"default",full:"full"},n_=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function nq(e,t,n){return t<=0?0:((e+n)%t+t)%t}function nK(e,t){let n=null,r=()=>{n=null,t(function(e,t,n=8){return Math.max(0,Math.floor(e-t-n))}(e.getBoundingClientRect().bottom,function(e){let t=window.visualViewport?.offsetTop??0;for(let n=e.parentElement;n;n=n.parentElement){let e=window.getComputedStyle(n).overflowY;("auto"===e||"scroll"===e||"hidden"===e||"clip"===e)&&(t=Math.max(t,n.getBoundingClientRect().top+n.clientTop))}return t}(e)))},i=()=>{null!==n&&cancelAnimationFrame(n),n=requestAnimationFrame(r)};r();let o=e.parentElement,l=o?.parentElement,s="u">typeof ResizeObserver&&o?new ResizeObserver(i):null;o&&s?.observe(o),l&&s?.observe(l);let a=window.visualViewport;return a?.addEventListener("resize",i),a?.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{s?.disconnect(),a?.removeEventListener("resize",i),a?.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0),null!==n&&cancelAnimationFrame(n)}}let nV=["auto","off","minimal","low","medium","high","xhigh","max"],nJ={auto:"chat.thinkingUseDefault",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"};function nY(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let nZ=[{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"}];function nG(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return nZ.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let nX=["builtin","extension","prompt","skill"],nQ={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},n0={builtin:0,extension:1,prompt:2,skill:3};function n1(e,t,n){let r=e.name.toLowerCase(),i=n2(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function n2(e,t){return"builtin"===e.source?t(e.description):e.description??""}function n4(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function n8(e){let t=()=>{var t;return t=e.type,new Promise((n,r)=>{let i=new FileReader;i.onload=()=>{let e="string"==typeof i.result?i.result.split(",")[1]:void 0;e?n({data:e,mimeType:t}):r(Error("Failed to read image"))},i.onerror=r,i.readAsDataURL(e)})};if(!(e.size>1048576&&"image/gif"!==e.type)||"function"!=typeof createImageBitmap)return t();let n=await createImageBitmap(e).catch(()=>null);if(!n)return t();try{let r=Math.min(1,1024/Math.max(n.width,n.height)),i=document.createElement("canvas");i.width=Math.max(1,Math.round(n.width*r)),i.height=Math.max(1,Math.round(n.height*r));let o=i.getContext("2d");if(!o)return t();o.fillStyle="#fff",o.fillRect(0,0,i.width,i.height),o.drawImage(n,0,0,i.width,i.height);let l=i.toDataURL("image/jpeg",.85).split(",")[1];return l&&l.length<4*Math.ceil(e.size/3)?{data:l,mimeType:"image/jpeg"}:t()}catch{return t()}finally{n.close()}}function n5(e){return{data:e.data,mimeType:e.mimeType}}function n6(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function n3(e){return(e??[]).filter(nd).slice(0,10).map(n6)}function n9(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function n7({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:999,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 re({tone:e,title:t,body:n,onClose:i}){let o="error"===e?"239,68,68":"234,179,8";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid rgba(${o},0.3)`,borderRadius:6,background:`rgba(${o},0.07)`,color:`rgb(${o})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]}),i&&(0,r.jsx)("button",{type:"button",onClick:i,"aria-label":"Dismiss",style:{flexShrink:0,background:"none",border:"none",padding:"0 2px",cursor:"pointer",color:"inherit",opacity:.7,fontSize:13,lineHeight:1},children:"\xd7"})]})}function rt({error:e}){let{t}=(0,T.s)();return e?(0,r.jsx)(re,{tone:"error",title:t("chat.modelError"),body:e}):null}function rn({warnings:e}){let{t}=(0,T.s)();return e&&0!==e.length?(0,r.jsx)(re,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let rr=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:o,isStreaming:l,model:s,isAutoModelSelection:a,modelNames:d,modelList:c,modelError:u,modelScopeWarnings:p,onModelChange:h,modelSwitching:g,onCompact:f,onAbortCompaction:x,isCompacting:m,compactError:v,compactResult:y,toolPreset:b,onToolPresetChange:j,thinkingLevel:w,onThinkingLevelChange:k,availableThinkingLevels:S,thinkingLevelMap:C,retryInfo:M,queuedMessages:E,inputHistory:I=[],onRecallQueue:R,slashCommands:L,slashCommandsLoading:$,onLoadSlashCommands:N,onBuiltinCommand:W,soundEnabled:P,onSoundToggle:F,onAudioUnlock:B,onPromptWithStreamingBehavior:D,draftKey:H,cwd:O,compact:U=!1},_){let q,K,V,J,Y,Z,G,{t:X}=(0,T.s)(),{fontSize:Q}=nA(),ee=ec(),[et,en]=(0,i.useState)(()=>H?nh(H)?.value??"":""),[er,ei]=(0,i.useState)(!1),[eo,el]=(0,i.useState)(!1),[es,ea]=(0,i.useState)(!1),[ed,eu]=(0,i.useState)(()=>H?n3(nh(H)?.images):[]),ep=et.trimStart(),eh=0===ed.length&&ep.startsWith("!"),eg=eh&&ep.startsWith("!!"),[ef,ex]=(0,i.useState)(!1),[em,ev]=(0,i.useState)(0),[ey,eb]=(0,i.useState)(null),[ej,ew]=(0,i.useState)(null),[ek,eS]=(0,i.useState)(!1),[eC,eT]=(0,i.useState)(null),[eM,eE]=(0,i.useState)(0),[eI,eR]=(0,i.useState)(!1),[eL,e$]=(0,i.useState)(!1),[eN,ez]=(0,i.useState)(0),[eW,eP]=(0,i.useState)(!1),eA=(0,i.useRef)(!1),[eF,eB]=(0,i.useState)(null),[eD,eH]=(0,i.useState)(!1),[eO,eU]=(0,i.useState)(null),[e_,eq]=(0,i.useState)(null),eK=O&&e_?.cwd===O?e_.values:{},eV=(0,i.useRef)(null),eJ=(0,i.useRef)(null),eY=(0,i.useRef)(null),eZ=(0,i.useRef)(null),eG=(0,i.useRef)(null),eX=(0,i.useRef)(null),eQ=(0,i.useRef)(!1),e0=(0,i.useRef)(0),e1=(0,i.useRef)(!1),e2=(0,i.useRef)(null),e4=(0,i.useRef)([]),e8=(0,i.useRef)(null),e5=(0,i.useRef)([]),e6=(0,i.useRef)([]),e3=(0,i.useRef)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(H),te=(0,i.useRef)(et),tt=(0,i.useRef)(ed),tn=(0,i.useRef)(0);te.current=et,tt.current=ed,(0,i.useImperativeHandle)(_,()=>({insertIfEmpty(e){let t=eV.current;(t?t.value:et).trim()||(te.current=e,en(e),ew(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){var t,n,r;let i=eV.current;if(t=i?i.value:et,n=tt.current.length,r=tn.current,t.trim()||0!==n||0!==r)return;let o="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),l=n3("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 nd(r)?[r]:[]}));te.current=o,tt.current=l,en(o),ew(null),e$(!1),eu(e=>(e.forEach(n9),l)),requestAnimationFrame(()=>{i&&(i.focus(),i.style.height="auto",i.style.height=`${Math.min(i.scrollHeight,200)}px`)})},prependText(e){if(!e.trim())return;let t=eV.current,n=[e,t?t.value:et].filter(e=>e.trim()).join("\n\n");te.current=n,en(n),ew(null),requestAnimationFrame(()=>{t&&(t.focus(),t.setSelectionRange(n.length,n.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(e7.current!==e)return void nv(e,t);let n={value:te.current,images:tt.current.map(n5)},r=nv(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(e7.current=t,i)return;let o=n3(r.images);te.current=r.value,tt.current=o,en(r.value),eu(e=>(e.forEach(n9),o)),ew(null),e$(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=e7.current,i=n??r,o=i===r,l=!o&&i?nh(i):null,s=nm(e,t,o?te.current:l?.value??"",o?tt.current.map(n5):l?.images??[]);if(i&&ng(i,s),!o)return;let a=t?.length?[...n3(t).slice(0,Math.max(0,10-tt.current.length)),...tt.current].slice(0,10):tt.current;te.current=s.value,tt.current=a,en(t=>{let n=nx(e,t);return te.current=n,n}),ew(null),e$(!1),t?.length&&eu(e=>{let n=Math.max(0,10-e.length),r=n3(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tt.current=i,i}),requestAnimationFrame(()=>{let e=eV.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=eV.current;if(!t)return void en(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),o=t.value.slice(r),l=i.length>0&&!i.endsWith(" ")?" ":"",s=i+l+e+o;te.current=s,en(s),ew(null),requestAnimationFrame(()=>{if(!t)return;let r=n+l.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){tr(e)}}));let tr=(0,i.useCallback)(async e=>{if(U)return;let t=Math.max(0,10-tt.current.length-tn.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tn.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await n8(e),previewUrl:URL.createObjectURL(e)})));eu(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(n9);let r=[...t,...n];return tt.current=r,r})}finally{tn.current-=n.length}}},[U]),ti=(0,i.useCallback)(e=>{eu(t=>{let n=[...t],[r]=n.splice(e,1);return r&&n9(r),tt.current=n,n})},[]),to=(0,i.useCallback)(()=>{tt.current=[],eu(e=>(e.forEach(n9),[]))},[]),tl=(0,i.useCallback)(()=>{te.current="",en(""),ew(null),e$(!1),H&&nf(H),e7.current&&e7.current!==H&&nf(e7.current),to(),eV.current&&(eV.current.style.height="auto")},[to,H]);(0,i.useEffect)(()=>{H&&e7.current===H&&ng(H,{value:et,images:ed.map(n5)})},[ed,H,et]),(0,i.useEffect)(()=>{let e=e7.current;if(e===H)return;e&&ng(e,{value:te.current,images:tt.current.map(n5)});let t=H?nh(H):null;e7.current=H;let n=t?.value??"",r=n3(t?.images);te.current=n,tt.current=r,en(n),ew(null),e$(!1),eu(e=>(e.forEach(n9),r))},[H]);let ts=(0,i.useCallback)(()=>{let e=eV.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(ts,[et,Q,ts]),(0,i.useEffect)(()=>{let e=eV.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,ts())});return n.observe(e),()=>n.disconnect()},[ts]),(0,i.useEffect)(()=>()=>{tt.current.forEach(n9)},[]);let ta=(0,i.useCallback)(async e=>{if(ed.length||!e.startsWith("/")||!W)return!1;if(eA.current)return!0;eA.current=!0,eP(!0);try{var t,n;let r=await W(e);if(!r.handled)return!1;return r.error||(t=te.current,n=tt.current.length,0!==n||t.trim()!==e)||tl(),!0}finally{eA.current=!1,eP(!1)}},[ed.length,tl,W]),td=(0,i.useCallback)(async()=>{let t=et.trim();!t&&!ed.length||(B?.(),(!l||nG(t))&&await ta(t)||l||(tl(),e(t,ed.length?ed:void 0)))},[et,ed,l,ta,e,tl,B]),tc=!U&&et.startsWith("/")&&!/\s/.test(et.slice(1))?et.slice(1).toLowerCase():null,tu=null===tc?[]:[...l?nZ.filter(e=>e.availableWhileStreaming):nZ,...L??[]].filter(e=>{let t=e.name.toLowerCase(),n=n2(e,X).toLowerCase();return t.includes(tc)||n.includes(tc)}).sort((e,t)=>{let n=n1(e,tc,X)-n1(t,tc,X);return 0!==n?n:n0[e.source]-n0[t.source]||n_.compare(e.name,t.name)}),{commands:tp,groups:th}=(q=0,{commands:(K=nX.map(e=>{let t=tu.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!n4(e,eK)),...t.filter(e=>n4(e,eK))]:t;return{source:e,items:n.map(e=>({command:e,index:q++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:K}),tg=1===tu.length?X(tc?"chat.match":"chat.command"):X(tc?"chat.matches":"chat.commands",{count:tu.length}),tf=!!et.trim()||ed.length>0,tx=ed.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")}(s,c)&&!eI;(0,i.useEffect)(()=>{0===ed.length&&eR(!1)},[ed.length]);let tm=(0,i.useCallback)((e,t)=>{if(!O)return void ew(null);let n=t??e.length;ew(ny(e.slice(0,n)))},[O]),tv=ej?.query??null,ty=i.useMemo(()=>null!==tv&&eF&&eF.cwd===O?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:nj(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:nj(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||nb(e.entry.path)-nb(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eF.entries,tv):[],[tv,eF,O]),tb=!!(tv&&eF?.truncated&&eF.cwd===O);(0,i.useEffect)(()=>{if(!tb||!O||!tv)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(O)}&q=${encodeURIComponent(tv)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>eU({cwd:O,query:tv,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tb,tv,O]);let tj=tb&&null!==eO&&eO.cwd===O&&eO.query===tv,tw=tj?eO.matches:ty,tk=null===ej?null:`${ej.start}:${+!!ej.quoted}:${ej.query}`;(0,i.useEffect)(()=>{if(null===tk){eS(!1),eE(0);return}eS(!0),eE(0)},[tk]);let tS=null!==ej;(0,i.useEffect)(()=>{if(!tS||!O)return;let e=e3.current;e&&e.cwd===O&&Date.now()-e.fetchedAt<1e4||e9.current===O||(e9.current=O,eH(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(O)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eB({cwd:O,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)=>nb(e.path)-nb(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),e3.current={cwd:O,fetchedAt:Date.now()}}).catch(()=>{e3.current=null}).finally(()=>{e9.current=null,eH(!1)}))},[tS,O]);let tC=(0,i.useCallback)(e=>{if(!ej)return;let t=eV.current,n=t?.selectionStart??et.length,r=et.slice(0,ej.start),i=et.slice(n);ej.quoted&&i.startsWith('"')&&(i=i.slice(1));let o=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let o=i?`@"${r}" `:`@${r} `;return{text:o,cursorOffset:o.length}}(e.path,e.isDir,ej.quoted),l=r+o.text+i,s=r.length+o.cursorOffset;en(l),ew(ny(l.slice(0,s))),requestAnimationFrame(()=>{let e=eV.current;e&&(e.focus(),e.setSelectionRange(s,s),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[ej,et]);(0,i.useEffect)(()=>{eM>=tw.length&&eE(Math.max(0,tw.length-1))},[tw.length,eM]),(0,i.useEffect)(()=>{e5.current.length=tw.length},[tw.length]),(0,i.useEffect)(()=>{ek&&e5.current[eM]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eM,ek]),(0,i.useEffect)(()=>{eN>=I.length&&ez(Math.max(0,I.length-1))},[I.length,eN]),(0,i.useEffect)(()=>{e6.current.length=I.length},[I.length]),(0,i.useEffect)(()=>{eL&&e6.current[eN]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eN,eL]);let tT=(0,i.useCallback)(e=>{en(e),e$(!1),ez(0),ew(null),requestAnimationFrame(()=>{let t=eV.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),tM=(0,i.useCallback)(e=>{let t=`/${e.name} `;en(t),ex(!1),ev(0),requestAnimationFrame(()=>{let e=eV.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tE=(0,i.useCallback)(e=>{let t=et.trim();if(t||ed.length){if(B?.(),!ed.length&&W&&nG(t))return void ta(t);if(t.startsWith("/")&&D){tl(),D(t,"steer"===e?"steer":"followUp",ed.length?ed:void 0);return}tl(),"steer"===e&&n?n(t,ed.length?ed:void 0):"followup"===e&&o&&o(t,ed.length?ed:void 0)}},[et,ed,W,D,n,o,tl,B,ta]),tI=(0,i.useCallback)(e=>{let t=tp.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,em-1);if("right"===e)return Math.min(t,em+1);let n=e4.current[em];if(!n)return"down"===e?Math.min(t,em+1):Math.max(0,em-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,o=r.top+r.height/2,l=-1,s=1/0;for(let n=0;n<=t;n+=1){if(n===em)continue;let t=e4.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-o;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<s&&(l=n,s=d)}return l>=0?l:"down"===e?Math.min(t,em+1):Math.max(0,em-1)},[tp.length,em]),tR=(0,i.useCallback)(e=>{let r=e.nativeEvent,i="Enter"===e.key&&!e.shiftKey&&(!ee||e.ctrlKey||e.metaKey),s=Date.now()-e0.current<100,a=eQ.current||r.isComposing||229===r.keyCode;if(i&&(a||s)){s&&e.preventDefault();return}if(eL&&!a){if("ArrowDown"===e.key){e.preventDefault(),ez(e=>Math.min(Math.max(0,I.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),ez(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e$(!1);return}if(("Tab"===e.key||i)&&I[eN]){e.preventDefault(),tT(I[eN]);return}}if(ef&&null!==tc){if("ArrowDown"===e.key){e.preventDefault(),ev(tI("down"));return}if("ArrowUp"===e.key){e.preventDefault(),ev(tI("up"));return}if("ArrowRight"===e.key){e.preventDefault(),ev(tI("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),ev(tI("left"));return}if("Escape"===e.key){e.preventDefault(),ex(!1);return}let t=tp[em];if("Tab"===e.key&&t){e.preventDefault(),tM(t);return}if(i&&t)return void((e.preventDefault(),l&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||et.trim()!==`/${t.name}`)?tM(t):(ex(!1),td()))}if(ek&&null!==ej&&!a){if("ArrowDown"===e.key){e.preventDefault(),eE(e=>nq(e,tw.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eE(e=>nq(e,tw.length,-1));return}if("Escape"===e.key){e.preventDefault(),eS(!1);return}if(("Tab"===e.key||i)&&tw[eM]){e.preventDefault(),tC(tw[eM]);return}}if("ArrowUp"===e.key&&!a&&!l&&I.length>0&&0===et.trim().length){e.preventDefault(),ex(!1),eS(!1),ez(I.length-1),e$(!0);return}if("Escape"===e.key&&!a&&l&&t){e.preventDefault(),t();return}i&&(e.preventDefault(),l&&(n||o)?tE(e.altKey&&o||!n?"followup":"steer"):td())},[ee,l,n,o,t,ef,tc,tp,em,tM,tE,td,tI,ek,ej,tw,eM,tC,eL,I,eN,tT,et]),tL=(0,i.useCallback)(()=>{let e=eV.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),t$=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!U&&t.length){e.preventDefault(),tr(t.map(e=>e.getAsFile()).filter(e=>null!==e));return}let n=e.clipboardData.getData("text/html"),r=e.clipboardData.getData("text/plain");if(!n||!r)return;let i=new DOMParser().parseFromString(n,"text/html"),o=function(e,t){let n="",r=0,i=!1;for(let{label:o,href:l,occurrence:s}of t){if(!o||!l)continue;let t=0;for(let n=0;n<=s&&!((t=e.indexOf(o,n?t+o.length:0))<0);n++);if(t<r)continue;let a=o.replace(/([\\[\]])/g,"\\$1"),d=l.replace(/([\\()])/g,"\\$1");n+=`${e.slice(r,t)}[${a}](${d})`,r=t+o.length,i=!0}return i?n+e.slice(r):null}(r,Array.from(i.querySelectorAll("a[href]"),e=>{let t=e.textContent??"",n=i.createRange();return n.setStart(i.body,0),n.setEndBefore(e),{label:t,href:e.getAttribute("href")?.trim()??"",occurrence:t?n.toString().split(t).length-1:0}}));if(null===o)return;let l=e.currentTarget,s=l.selectionStart,a=l.value.slice(0,s)+o+l.value.slice(l.selectionEnd);e.preventDefault(),te.current=a,en(a),e$(!1),tm(a,s+o.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(s+o.length,s+o.length)})},[U,tr,tm]);(0,i.useEffect)(()=>{if(null===tc){ex(!1),ev(0),e1.current=!1;return}ex(!0),ev(0),!e1.current&&N&&(e1.current=!0,Promise.resolve(N()).catch(()=>{e1.current=!1}))},[tc,N]),(0,i.useEffect)(()=>{if(!ef||!O)return;let e=!1;return eq({cwd:O,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(O)}`).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;eq({cwd:O,values:n})}).catch(()=>{e||eq({cwd:O,values:{}})}),()=>{e=!0}},[ef,O]),(0,i.useEffect)(()=>{em>=tp.length&&ev(Math.max(0,tp.length-1))},[tp.length,em]),(0,i.useEffect)(()=>{e4.current.length=tp.length},[tp.length]),(0,i.useEffect)(()=>{ef&&e4.current[em]?.scrollIntoView({block:"nearest",inline:"nearest"})},[em,ef]),(0,i.useLayoutEffect)(()=>{if(!ef||null===tc)return void eb(null);let e=e2.current;if(e)return nK(e,e=>{eb(t=>t===e?t:e)})},[ef,tc]),(0,i.useLayoutEffect)(()=>{if(!ek||null===ej)return void eT(null);let e=e8.current;if(e)return nK(e,e=>{eT(t=>t===e?t:e)})},[ek,ej]);let tN=c&&c.length>0?c.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(d??{}).map(([e,t])=>({provider:s?.provider??"unknown",modelId:e,name:t})),tz=y?Math.max(0,y.tokensBefore-y.estimatedTokensAfter):0,tW=y?`${y.reason&&"manual"!==y.reason?`${y.reason[0].toUpperCase()}${y.reason.slice(1)} `:X("chat.compacted")} ${nY(y.tokensBefore)} -> ${nY(y.estimatedTokensAfter)} tokens (${X("chat.tokensSaved",{saved:nY(tz)})})`:null,tP="auto"!==(V=w??"auto")&&C?C[V]??V:V,tA=Object.entries(nU).find(([,e])=>e===(b??"default"))?.[0]??"default",tF="chat-only"===tA?X("chat.chatOnly"):tA;return(0,i.useEffect)(()=>{let e=e=>{eJ.current&&!eJ.current.contains(e.target)&&ei(!1),eY.current&&!eY.current.contains(e.target)&&el(!1),eZ.current&&!eZ.current.contains(e.target)&&ea(!1),!eG.current||eG.current.contains(e.target)||eV.current?.contains(e.target)||e$(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{ee||ea(!1)},[ee]),(0,r.jsxs)("fieldset",{disabled:eW,"aria-busy":eW,style:{flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:U?0:"0 16px 8px",paddingRight:U?0:ee?16:52,opacity:eW?.5:1,transition:"opacity 0.15s"},children:[!U&&(0,r.jsx)("input",{ref:eX,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:e=>{tr(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)(rt,{error:u}),(0,r.jsx)(rn,{warnings:p}),tx&&(J=c?.find(e=>e.provider===s?.provider&&e.id===s?.modelId),(0,r.jsx)(re,{tone:"warning",title:X("chat.imageNotSupportedTitle"),body:X("chat.imageNotSupportedBody",{model:J?.name||s?.modelId||""}),onClose:()=>eR(!0)})),(E?.steering.length??0)+(E?.followUp.length??0)>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:6,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:X("chat.queued",{count:(E?.steering.length??0)+(E?.followUp.length??0)})}),R&&(0,r.jsxs)("button",{onClick:R,title:X("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:7,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"})]}),X("chat.recall")]})]}),E?.steering.map((e,t)=>(0,r.jsx)(n7,{kind:"steer",text:e},`steer-${t}`)),E?.followUp.map((e,t)=>(0,r.jsx)(n7,{kind:"follow-up",text:e},`followup-${t}`))]}),M&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.25)",borderRadius:6,fontSize:12,color:"rgba(180,130,0,0.9)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),X("chat.retrying",{attempt:M.attempt,max:M.maxAttempts}),M.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",M.errorMessage]})]}),tW&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(16,185,129,0.08)",border:"1px solid rgba(16,185,129,0.24)",borderRadius:6,fontSize:12,color:"rgba(5,150,105,0.95)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),tW]}),v&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"rgba(239,68,68,0.07)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:6,color:"#ef4444",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:v}),ed.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:ed.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{onClick:()=>ti(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),(0,r.jsxs)("div",{style:{position:"relative",minWidth:0},children:[eL&&I.length>0&&(0,r.jsxs)("div",{ref:eG,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",maxHeight:"min(44vh, 360px)"},children:[(0,r.jsx)("div",{title:X("chat.inputHistory"),style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:"calc(min(44vh, 360px) - 31px)",overflowY:"auto",padding:4},children:I.map((e,t)=>{let n=t===eN;return(0,r.jsxs)("button",{ref:e=>{e6.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tT(e)},onMouseEnter:()=>ez(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),ef&&null!==tc&&(0,r.jsxs)("div",{ref:e2,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===ey?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${ey}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:$?X("chat.loadingCommands"):X("chat.slashCommands",{label:tg})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:X("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:$||0!==tu.length?th.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:X(nQ[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===em,i=n4(e,eK);return(0,r.jsxs)("button",{ref:e=>{e4.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tM(e)},onMouseEnter:()=>ev(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:7,background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:X("chat.dormant")})]}),e.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:n2(e,X)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:X("chat.noCommands")})})]}),ek&&null!==ej&&(Y=eD&&(!eF||eF.cwd!==O),Z=1===tw.length?X("chat.match"):X("chat.matches",{count:tw.length}),G=eF?.truncated&&!tj?ej.query?X("chat.searchingAll"):X("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:e8,style:{position:"absolute",left:0,right:0,bottom:"calc(100% + 8px)",zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -6px 20px rgba(0,0,0,0.12)",overflow:"hidden",boxSizing:"border-box",display:"flex",flexDirection:"column",maxHeight:null===eC?"min(48vh, 400px)":`min(48vh, 400px, ${eC}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:Y?X("chat.loadingFiles"):X("chat.files",{label:Z,hint:G})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:X("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:Y||0!==tw.length?tw.map((e,t)=>{let n=t===eM,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{e5.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tC(e)},onMouseEnter:()=>eE(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(z,{size:14}):A(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:o}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:tb&&!tj?X("chat.searching"):X("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{style:{minWidth:0,display:"flex",flexDirection:U?"column":"row",gap:8,alignItems:U?"stretch":"center",background:"var(--bg)",border:U?"none":`1px solid ${eh?"var(--tool-bg)":l&&(n||o)?"rgba(234,179,8,0.4)":"color-mix(in srgb, var(--border) 70%, transparent)"}`,borderRadius:14*!U,padding:U?0:"10px 10px 10px 14px",boxShadow:U?"none":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{ref:eV,className:"chat-input-textarea","aria-label":U?X("chat.quoteQuestion"):void 0,value:et,onChange:e=>{te.current=e.target.value,en(e.target.value),e$(!1),tm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tm(t.value,t.selectionStart)},onKeyDown:tR,onCompositionStart:()=>{eQ.current=!0},onCompositionEnd:e=>{eQ.current=!1,e0.current=Date.now();let t=e.currentTarget;tm(t.value,t.selectionStart)},onInput:tL,onPaste:t$,placeholder:l&&(n||o)?X("chat.steerPlaceholder"):l?X("chat.agentPlaceholder"):X("chat.messagePlaceholder"),rows:1,style:{flex:U?"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.6,fontFamily:"inherit",minHeight:U?96:24,maxHeight:200,overflow:"auto"}}),l?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[n&&(0,r.jsxs)("button",{onClick:()=>tE("steer"),disabled:!tf,title:X("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tf?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:tf?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),X("chat.steer")]}),o&&(0,r.jsxs)("button",{onClick:()=>tE("followup"),disabled:!tf,title:`${X("chat.followUpHint")} (${ee?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-keyshortcuts":ee?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:tf?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:tf?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tf?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),X("chat.followUp")]})]}):(0,r.jsxs)("button",{onClick:td,disabled:!et.trim()&&!ed.length,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:et.trim()||ed.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:et.trim()||ed.length?"var(--accent-contrast)":"var(--text-dim)",cursor:et.trim()||ed.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:et.trim()||ed.length?"0 1px 3px color-mix(in srgb, var(--accent) 25%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),X("chat.send")]})]})]}),eh&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eg?"var(--text-muted)":"var(--accent)",marginTop:4},children:[X("chat.shell")," \xb7 ",eg?X("chat.outputLocal"):X("chat.outputModel")]}),!U&&(0,r.jsxs)("div",{style:{marginTop:8,display:ee?"grid":"flex",gridTemplateColumns:ee?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:ee?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2},children:[(0,r.jsx)("button",{onClick:()=>eX.current?.click(),title:X("chat.attachImage"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ed.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ed.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ed.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",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"})]})}),(tN.length>0||s||u)&&h&&(0,r.jsx)(nD,{options:tN,value:s,onChange:h,disabled:l,busy:g,isAutoSelection:a})]}),!ee&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:eZ,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:ee?0:"auto"},children:[ee&&(0,r.jsx)("button",{type:"button",title:es?void 0:X("chat.moreControls"),"aria-label":X("chat.moreControls"),"aria-expanded":es,"aria-hidden":es||void 0,tabIndex:es?-1:void 0,onClick:()=>{ea(!0)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:32,padding:"8px 10px",background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:es?"default":"pointer",fontSize:12,fontWeight:500,visibility:es?"hidden":"visible",pointerEvents:es?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{es||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{es||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:X("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:ee?es?"flex":"none":"flex",alignItems:"center",gap:ee?1:2,...ee?{position:"absolute",right:0,bottom:0,zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"nowrap",justifyContent:"flex-end",border:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:10,background:"color-mix(in srgb, var(--bg-panel) 92%, var(--bg))",boxShadow:"0 8px 24px rgba(0,0,0,0.14)",backdropFilter:"blur(10px)"}:null},children:[!l&&k&&(0,r.jsxs)("div",{ref:eY,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!l&&el(e=>!e),disabled:l,title:X("chat.changeReasoning",{level:tP}),"aria-label":X("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ee?"0 6px":"8px 12px",width:ee?"auto":void 0,height:32,background:eo?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eo?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(!ee||es)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tP})]}),eo&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...ee?{left:0}:{right:0},zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:180},children:nV.filter(e=>!S||"auto"===e||S.includes(e)).map(e=>{let t=(w??"auto")===e,n=X(nJ[e]),i="auto"!==e&&C?C[e]:void 0,o=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{el(!1),t||k(e)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[o,l&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:n})]},e)})})]}),!l&&j&&(0,r.jsxs)("div",{ref:eJ,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!l&&ei(e=>!e),disabled:l,title:X("chat.changeToolPreset")+`: ${tF}`,"aria-label":X("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ee?"0 6px":"8px 12px",width:ee?"auto":void 0,height:32,background:er?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=er?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",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"})}),(!ee||es)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:tF})]}),er&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:ee?void 0:0,left:ee?0:void 0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:120},children:nO.map(e=>{let t,n=nU[e],i=(b??"default")===n;return t="chat-only"===e?X("chat.chatOnly"):"read-only"===e?X("chat.readOnlyTools",{count:4}):"default"===e?X("chat.builtInTools",{count:4}):X("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ei(!1),i||j(n)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:t})]},e)})})]}),!l&&f&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:m?x:f,disabled:l&&!m,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ee?"0 6px":"8px 12px",width:ee?"auto":void 0,height:32,background:m?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:m?"#ef4444":"var(--text-muted)",cursor:l&&!m?"not-allowed":"pointer",fontSize:12,opacity:l&&!m?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||m)&&(e.currentTarget.style.background=m?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=m?"#ef4444":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=m?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=m?"#ef4444":"var(--text-muted)"},title:m?X("chat.stopCompaction"):X("chat.compactContext"),"aria-label":m?X("chat.stopCompaction"):X("chat.compactContext"),children:m?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(!ee||es)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:X("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",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"})]}),(!ee||es)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:X("chat.compact")})]})})}),l&&(0,r.jsxs)("button",{onClick:t,title:X("chat.stopAgent"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.16)"},onMouseLeave:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),X("chat.stop")]}),void 0!==F&&(0,r.jsx)("button",{onClick:F,title:P?X("chat.disableSound"):X("chat.enableSound"),"aria-label":P?X("chat.disableSound"):X("chat.enableSound"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:P?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:P?1:.55,transition:"background 0.12s, color 0.12s, opacity 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.opacity="1"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=P?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=P?"1":"0.55"},children:P?(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("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:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",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"})]})}),ee&&es&&(0,r.jsx)("button",{type:"button",title:X("chat.collapseControls"),"aria-label":X("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ei(!1),el(!1),ea(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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"})]})})]})]})]})]})]})});var ri=n(88576),ro=n.n(ri);function rl({level:e,children:t,headingIndex:n,onClick:i}){return(0,r.jsx)("button",{type:"button",className:ro().heading,"data-level":e,"data-preview-heading-index":n??void 0,disabled:null===n||!i,onClick:e=>{e.stopPropagation(),null!==n&&i?.(n)},children:t})}let rs=[...tc??[],function(){return e=>{if(!Array.isArray(e.children))return;let t=e.children.filter(e=>"heading"===e.type&&"number"==typeof e.depth&&e.depth<=3);if(t.length>0){t.forEach((e,t)=>{e.data={...e.data,hProperties:{...e.data?.hProperties,"data-preview-heading-index":t}}}),e.children=t;return}let n=e.children.find(e=>"paragraph"===e.type);e.children=n?[n]:[]}}],ra=[[e5.A,{throwOnError:!1,strict:!1}]];function rd(e){let t=e?.properties,n=t?.dataPreviewHeadingIndex??t?.["data-preview-heading-index"];return"number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):null}let rc=(0,i.memo)(function({markdown:e,onHeadingClick:t,onAnswerClick:n}){let o=(0,i.useMemo)(()=>to(e),[e]);return e?(0,r.jsx)("div",{className:ro().outline,children:(0,r.jsx)(e8.oz,{remarkPlugins:rs,rehypePlugins:ra,components:{h1:({children:e,node:n})=>(0,r.jsx)(rl,{level:1,headingIndex:rd(n),onClick:t,children:e}),h2:({children:e,node:n})=>(0,r.jsx)(rl,{level:2,headingIndex:rd(n),onClick:t,children:e}),h3:({children:e,node:n})=>(0,r.jsx)(rl,{level:3,headingIndex:rd(n),onClick:t,children:e}),h4:()=>null,h5:()=>null,h6:()=>null,p:({children:e})=>(0,r.jsx)("button",{type:"button",className:ro().paragraph,onClick:n,children:e}),blockquote:()=>null,ul:()=>null,ol:()=>null,pre:()=>null,table:()=>null,hr:()=>null,a:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),code:({children:e})=>(0,r.jsx)(r.Fragment,{children:e})},children:o})}):null});function ru({messages:e,streamingMessage:t,scrollContainer:n,messageRefs:o,onRevealHistory:l}){let{t:s}=(0,T.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(null),[g,f]=(0,i.useState)(600),[x,m]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),b=(0,i.useRef)(!1),j=(0,i.useRef)(null),w=(0,i.useRef)([]),k=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),S=(0,i.useRef)(null),C=(0,i.useRef)(new Map),M=(0,i.useRef)(null),E=(0,i.useRef)(null),I=(0,i.useRef)(null),R=(0,i.useMemo)(()=>t?[...e,t]:e,[e,t]),L=(0,i.useRef)(R);L.current=R;let $=(0,i.useMemo)(()=>(function(e,t){if(0===e.length)return{nodes:[],gap:50,fillsHeight:!1};let n=Math.max(1,t),r=Math.max(0,n-24);if(1===e.length)return{nodes:[{...e[0],topRatio:12/n}],gap:50,fillsHeight:!1};let i=r/(e.length-1),o=Math.min(50,i);return{nodes:e.map((e,t)=>({...e,topRatio:(12+t*o)/n})),gap:o,fillsHeight:i<=50}})(c,g),[c,g]),{nodes:N,gap:z}=$;k.current=$;let W=(0,i.useCallback)(e=>{E.current={index:e,until:Date.now()+1600},h(e)},[]),P=(0,i.useCallback)((e,t)=>{let n=E.current;if(n&&Date.now()<n.until)return void h(n.index);E.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void h(null);let i=e.scrollTop+.3*e.clientHeight;h(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),A=(0,i.useCallback)(()=>{let e=n.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,r=w.current;d(t>20),P(e,r)},[n,P]),F=(0,i.useRef)(null),B=(0,i.useCallback)(()=>{F.current||(F.current=setTimeout(()=>{F.current=null;let e=n.current,t=j.current;if(!e||!t)return;let r=o.current,i=e.getBoundingClientRect(),l=[],s=0,a=null;for(let t of L.current){let n=eK(t);if(!n&&"assistant"!==t.role)continue;let o=r?.[s];if(s++,n){a=null;let n=o?.getBoundingClientRect();a={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null},l.push(a);continue}if(!a)continue;let d=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=eZ(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);d&&a.assistantPreviews.push({markdown:d,element:o})}let c=l.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));f(t.clientHeight),w.current=c,u(c),d(e.scrollHeight-e.clientHeight>20),P(e,c);let p=I.current,h=p?c[p.nodeIndex]:null;if(p&&h){let t=void 0===p.assistantIndex?null:h.targetTurn.assistantPreviews[p.assistantIndex],n=h.targetTurn.scrollTop;if("assistant"===p.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===p.target){let r=void 0===p.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(p.headingIndex),o=r?.getBoundingClientRect();n=o?o.top-i.top+e.scrollTop:null}if(null===n)return;I.current=null,W(h.index);let r=.3*e.clientHeight;e.scrollTo({top:Math.max(0,n-r),behavior:"smooth"})}},150))},[W,o,n,P]);(0,i.useEffect)(()=>{let e=n.current;if(e)return e.addEventListener("scroll",A,{passive:!0}),()=>e.removeEventListener("scroll",A)},[n,A]),(0,i.useEffect)(()=>{let e=n.current;if(!e)return;let t=()=>{B(),A()},r=new ResizeObserver(t);return r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild),t(),()=>{r.disconnect(),F.current&&(clearTimeout(F.current),F.current=null)}},[B,n,A]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{B(),A()},50);return()=>clearTimeout(e)},[e.length,B,A]);let D=(0,i.useCallback)((e,t)=>{let r=n.current;if(!r)return;if(W(e.index),null===e.targetTurn.scrollTop){I.current={nodeIndex:e.index,target:"user"},l();return}let i=Math.max(0,e.targetTurn.scrollTop-.3*r.clientHeight);r.scrollTo({top:i,behavior:t})},[W,l,n]),H=(0,i.useCallback)((e,t)=>{let r=n.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){I.current={nodeIndex:e.index,target:"assistant",assistantIndex:t},l();return}let o=r.getBoundingClientRect(),s=i.getBoundingClientRect().top-o.top+r.scrollTop-.3*r.clientHeight;W(e.index),r.scrollTo({top:Math.max(0,s),behavior:"smooth"})},[W,l,n]),O=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=k.current,i=j.current?.clientHeight??0;if(0===t.length||i<=0)return null;let o=Math.max(0,Math.min(i,e*i)),l=t[0].topRatio*i,s=n>0?Math.round((o-l)/n):0,a=Math.max(0,Math.min(t.length-1,s)),d=t[a];if(!r&&Math.abs(o-d.topRatio*i)>Math.max(10,n/2))return null;return d},[]),U=(0,i.useCallback)((e,t,r)=>{let i=n.current;if(!i)return;let o=e.targetTurn.assistantPreviews[t]?.element;if(!o){I.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:r},l();return}let s=o.querySelectorAll("h1, h2, h3").item(r);if(!s)return;let a=i.getBoundingClientRect(),d=s.getBoundingClientRect().top-a.top+i.scrollTop-.3*i.clientHeight;W(e.index),i.scrollTo({top:Math.max(0,d),behavior:"smooth"})},[W,l,n]),_=(0,i.useCallback)(()=>{M.current&&(clearTimeout(M.current),M.current=null)},[]),q=(0,i.useCallback)(()=>{_(),m(!0)},[_]),K=(0,i.useCallback)(()=>{_(),M.current=setTimeout(()=>{M.current=null,m(!1),y(null)},250)},[_]);(0,i.useEffect)(()=>()=>_(),[_]);let V=(0,i.useCallback)(e=>{if(!a)return;b.current=!0,q();let t=e.currentTarget.getBoundingClientRect();y(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=O(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&D(r,n)};n(e.clientY,"smooth");let r=e=>{b.current&&n(e.clientY,"auto")},i=()=>{b.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[O,D,q,a]),J=null===v?null:O(v),Y=J?.index??null;if((0,i.useEffect)(()=>{if(!x||null===Y)return;let e=S.current,t=C.current.get(Y);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[c,x,Y]),!a)return null;let Z=Math.max(1,(N.length>0?N[N.length-1].topRatio*g:12)-12);return(0,r.jsxs)("div",{ref:j,onMouseDown:V,onMouseEnter:q,onMouseLeave:K,onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();y((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"pointer",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:12,height:Z,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),N.map(e=>{let t=x&&J?.index===e.index,n=p===e.index;return(0,r.jsx)("div",{"data-minimap-node-index":e.index,"data-minimap-node-active":n?"":void 0,style:{position:"absolute",top:`${100*e.topRatio}%`,transform:"translateY(-50%)",left:0,right:0,height:Math.max(1,z),display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",zIndex:2},children:(0,r.jsx)("div",{style:{width:8,height:8,borderRadius:2,background:n?"rgba(128,128,128,0.42)":"rgba(128,128,128,0.16)",border:`1.5px solid ${n?"rgba(128,128,128,0.95)":"rgba(128,128,128,0.58)"}`,boxShadow:n?"0 0 0 2px var(--bg-panel)":"none",transition:"transform 0.1s, background 0.1s",transform:t?"scale(1.25)":"scale(1)"}})},e.index)}),x&&c.length>0&&(0,r.jsx)("div",{ref:S,className:ro().preview,"data-minimap-preview-box":"",onMouseEnter:q,onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>e.stopPropagation(),children:c.map(e=>{var t;let n=Y===e.index;return(0,r.jsxs)("div",{ref:t=>{t?C.current.set(e.index,t):C.current.delete(e.index)},className:ro().turn,"data-minimap-preview-index":e.index,"data-located":n?"true":void 0,children:[(0,r.jsx)("span",{className:ro().number,"aria-hidden":"true",children:String(e.index+1).padStart(2,"0")}),(0,r.jsxs)("div",{className:ro().content,children:[(0,r.jsx)("button",{type:"button",className:ro().user,"data-minimap-preview-user":e.index,onClick:()=>{D(e,"smooth")},children:(0,r.jsx)("span",{className:ro().userText,children:"string"==typeof(t=e.targetTurn.userMessage).content?t.content.trim():t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()})}),e.targetTurn.assistantPreviews.map((t,n)=>(0,r.jsxs)("div",{className:ro().assistant,children:[(0,r.jsx)("button",{type:"button",className:ro().assistantJump,"data-minimap-preview-assistant":`${e.index}-${n}`,onClick:()=>H(e,n),"aria-label":s("chatMinimap.locateAssistant"),title:s("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(rc,{markdown:t.markdown,onAnswerClick:()=>H(e,n),onHeadingClick:t=>U(e,n,t)})]},n))]})]},e.index)})})]})}var rp=n(42790);function rh({text:e}){let t=(0,i.useMemo)(()=>new rp.v().ansi_to_html(e),[e]);return(0,r.jsx)("span",{dangerouslySetInnerHTML:{__html:t}})}function rg({widgets:e}){let t,n,o,{t:l}=(0,T.s)(),s=(0,i.useId)(),a=(0,i.useRef)(null),d=(0,i.useRef)(new Map),[c,u]=(0,i.useState)(()=>e.find(e=>{let t=e.lines.length;return t>1&&t<=3})?.key??null),[p,h]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{var t;let n=new Map(e.map(e=>[e.key,[...e.lines]])),r=(t=a.current,t?Array.from(n,([e,n])=>{let r=t.get(e);return r&&r.length===n.length?n.some((e,t)=>e!==r[t])?e:null:r?e:null}).filter(e=>null!==e):[]);for(let[e,t]of(a.current=n,d.current))n.has(e)||(clearTimeout(t),d.current.delete(e));for(let e of(h(e=>{let t=new Set(Array.from(e).filter(e=>n.has(e)));for(let e of r)t.add(e);return t.size===e.size&&Array.from(t).every(t=>e.has(t))?e:t}),r)){let t=d.current.get(e);t&&clearTimeout(t),d.current.set(e,setTimeout(()=>{d.current.delete(e),h(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},1100))}},[e]),(0,i.useEffect)(()=>()=>{for(let e of d.current.values())clearTimeout(e);d.current.clear()},[]),0===e.length)return null;let g=e.find(e=>e.key===c&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=e.indexOf(g),n=`${s}-trigger-${t}`,o=`${s}-panel-${t}`,(0,r.jsxs)("section",{id:o,className:"extension-widget-panel","aria-labelledby":n,children:[(0,r.jsx)("div",{className:"extension-widget-panel-heading",children:g.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(rh,{text:g.lines.join("\n")})})]},g.key))}),(0,r.jsx)("div",{className:"extension-widget-triggers","aria-label":l("chat.extensionWidgets"),children:e.map((e,t)=>{let n=e.lines.length>0,i=n&&e.key===g?.key,o=p.has(e.key),a=l(1===e.lines.length?"chat.extensionWidgetLine":"chat.extensionWidgetLines",{count:e.lines.length}),d=l("belowEditor"===e.placement?"chat.extensionWidgetBelow":"chat.extensionWidgetAbove"),c=`${s}-trigger-${t}`,h=`${s}-panel-${t}`,f=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"extension-widget-update-pulse","aria-hidden":"true"}),(0,r.jsx)("span",{className:"extension-widget-placement","aria-hidden":"true",children:(0,r.jsx)("svg",{className:"extension-widget-placement-icon",viewBox:"0 0 8 6",width:"8",height:"6","data-direction":"belowEditor"===e.placement?"down":"up",focusable:"false",children:(0,r.jsx)("path",{d:"belowEditor"===e.placement?"M0 0h8L4 6z":"M4 0l4 6H0z"})})}),(0,r.jsx)("span",{className:"extension-widget-key",children:e.key})]});return n?(0,r.jsx)("button",{id:c,type:"button",className:`extension-widget-trigger${i?" is-expanded":""}${o?" is-updating":""}`,"aria-controls":h,"aria-expanded":i,"aria-label":`${d}: ${e.key}, ${a}`,title:`${e.key} - ${d} - ${i?l("i18n.collapse"):l("i18n.expand")}`,onClick:()=>{u(t=>{var n;return t===(n=e.key)?null:n})},children:f},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${o?" is-updating":""}`,"aria-label":`${d}: ${e.key}, ${a}`,title:`${e.key} - ${d}`,children:f},e.key)})})]})}function rf({statuses:e,widgets:t=[]}){if(0===e.length&&0===t.length)return null;let n=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/\r\n?/g,"\n").split("\n").map(e=>e.replace(/\t/g," ").replace(/ +/g," ").trim()).join("\n").trim()).join(" "),i=eD(n);return(0,r.jsxs)("div",{className:`extension-status-shelf${t.length>0?" has-widgets":""}${e.length>0?" has-status":""}`,children:[t.length>0&&(0,r.jsx)(rg,{widgets:t}),e.length>0&&(0,r.jsx)("div",{role:"status",className:"extension-status-line","aria-label":i,title:i,children:(0,r.jsx)("span",{className:"extension-status-text",children:(0,r.jsx)(rh,{text:n})})})]})}function rx(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function rm(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 rv(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...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 ry(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rb(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(!ry(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=ry(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=ry(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 rj extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function rw(e){return e instanceof rj&&"prompt_rejected"===e.code&&!1===e.accepted}async function rk(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 rj(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}var rS=n(14755);let rC="pi-tool-preset";function rT(){try{return window.localStorage}catch{return null}}function rM(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 rE(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,rM(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),rM(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function rI(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 rR(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(rI).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class rL 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 r${constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new rL("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof rL?"startup_error"===n.status?this.stopRetrying():this.scheduleRetry(e):this.options.onUnexpectedError?.(n))})}async ensureConnected(e){for(;;){let t=this.current;if(t&&t.sessionId===e){if(t.attempt.ready&&1===t.source.readyState)return}else t=this.open(e);if(await t.attempt.promise,this.current!==t){if(this.current?.sessionId===e)continue;throw new rL("closed")}if(1===t.source.readyState)return;this.discard(t,new rL("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new rL("closed"));try{t=this.options.createSource(e)}catch(e){throw new rL("closed",e instanceof Error?e.message:String(e))}let i=!1,o=new Promise((e,t)=>{n=e,r=t}),l=setTimeout(()=>{this.fail(a,new rL("ready_timeout"))},this.options.readinessTimeoutMs),s={promise:o,ready:!1,succeed(){i||(i=!0,clearTimeout(l),n())},fail(e){i||(i=!0,clearTimeout(l),r(e))}},a={sessionId:e,source:t,attempt:s};return this.current=a,t.onmessage=e=>{let t;if(this.current===a){try{t=JSON.parse(e.data)}catch{return}if("connected"===t.type)s.ready=!0,s.succeed(),this.stopRetrying();else if("startup_error"===t.type){let e="string"==typeof t.errorMessage?t.errorMessage:void 0;this.fail(a,new rL("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new rL("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 rN(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function rz(e,t,n,r=8){return e+t>=n-r}let rW={isStreaming:!1,streamingMessage:null};function rP(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],o=n(i[t]);return o?(i[t]=o,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function rA(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=rb(t.message,{includeStreamingRawInput:!0});return"assistant"===n.role?{isStreaming:!0,streamingMessage:n}:e}case"delta":var n=t.event;switch(n.type){case"text_start":return rP(e,n.contentIndex,e=>e?.type==="text"?e:{type:"text",text:""});case"text_delta":return rP(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return rP(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return rP(e,n.contentIndex,e=>e?.type==="thinking"?e:{type:"thinking",thinking:""});case"thinking_delta":return rP(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return rP(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return rP(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:e.rawInput??""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return rP(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id||e.toolCallId,toolName:n.toolName||e.toolName,rawInput:(e.rawInput??"")+n.delta}:null);case"toolcall_end":return rP(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return rW;default:return e}}function rF(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}let rB=[2e3,5e3,1e4];function rD(e){return new Promise(t=>setTimeout(t,e))}function rH(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function rO(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:rH(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:rH(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=rH(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function rU(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 r_({label:e}){let[t,n]=(0,i.useState)(null);if((0,i.useEffect)(()=>{let e=new AbortController;return fetch("/api/app-update",{signal:e.signal}).then(async e=>e.ok?e.json():null).then(e=>{e?.updateAvailable&&e.latestVersion&&e.releaseUrl&&n(e)}).catch(()=>{}),()=>e.abort()},[]),!t)return null;let o=e(t.latestVersion);return(0,r.jsxs)("a",{href:t.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:o,"aria-label":o,onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},style:{display:"inline-flex",alignItems:"center",alignSelf:"center",gap:3,minHeight:32,minWidth:0,padding:"0 4px",background:"transparent",borderRadius:5,color:"var(--accent)",fontSize:12,fontWeight:600,lineHeight:1.2,textDecoration:"none",transition:"background 0.12s",whiteSpace:"nowrap"},children:[(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:["v",t.latestVersion]}),(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M7 17 17 7"}),(0,r.jsx)("path",{d:"M7 7h10v10"})]})]})}function rq(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function rK({messageCount:e,toolCallCount:t,defaultExpanded:n=!1,reveal:o=!1,children:l,t:s}){let[a,d]=(0,i.useState)(n);(0,i.useLayoutEffect)(()=>{o&&d(!0)},[o]);let c=[s("chat.processDetails"),`${e} ${s(1===e?"chat.message":"chat.messages")}`];return t>0&&c.push(`${t} ${s(1===t?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("div",{style:{marginBottom:14},children:[(0,r.jsxs)("button",{type:"button","aria-expanded":a||o,onClick:()=>d(e=>!e),style:{display:"flex",alignItems:"center",gap:8,width:"auto",minHeight:24,padding:"2px 0",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},title:s(a?"chat.collapseProcess":"chat.expandProcess"),children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:a?"rotate(90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.join(" \xb7 ")})]}),(a||o)&&(0,r.jsx)("div",{style:{marginTop:8},children:l})]})}function rV({session:e,searchTarget:t,onSearchTargetHandled:o,initialScrollPosition:s,onScrollPositionChange:a,sessionRunning:d,newSessionCwd:c,newSessionDraftKey:u,onAgentEnd:p,onAttentionNeeded:h,onSessionCreated:g,onSessionForked:f,modelsRefreshKey:x,chatInputRef:m,onBranchDataChange:v,onSystemPromptChange:y,onSystemToolsChange:b,onSystemInfoLoaderChange:j,onSessionStatsChange:w,onSessionStatsPanelOpen:k,onContextUsageChange:S,onOpenFile:C,onOpenSession:E,onAskInNewChat:I,quoteSelectionEnabled:R=!1,initialPrompt:L,onInitialPromptConsumed:$,soundEnabled:N=!0,onSoundToggle:z,playDoneSound:W=()=>{},unlockAudio:P}){var A;let F,{t:B}=(0,T.s)(),D=ec(),H=e?.relation?.kind!=="subagent",O=(0,i.useRef)(W);O.current=W;let U=(0,i.useRef)(N);U.current=N;let _=(0,i.useRef)(null),q=(0,i.useCallback)(()=>{H&&U.current&&O.current(),p?.()},[H,p]),K=(0,i.useCallback)(e=>{m?.current?.replaceMessage(e)},[m]),V=(0,i.useRef)(t?null:s??null),[J,Y]=(0,i.useState)(()=>{let e=V.current;return e&&!e.atBottom?e:null}),[Z,G]=(0,i.useState)(!1),{loading:X,error:Q,messages:ee,activeToolResults:et,entryIds:en,historyCursor:er,hasEarlierMessages:ei,streamState:eo,agentRunning:el,bashRunning:es,pendingBash:ea,modelNames:ed,modelList:eu,modelError:ep,modelScopeWarnings:eh,modelThinkingLevels:eg,modelThinkingLevelMaps:ef,toolPreset:ex,thinkingLevel:em,retryInfo:ev,contextUsage:ey,forkingEntryId:eb,isCompacting:ej,compactError:ew,compactResult:ek,displayModel:eS,modelSwitching:eC,sessionStats:eT,slashCommands:eM,slashCommandsLoading:eE,queuedMessages:eI,notices:eR,extensionDialog:eL,extensionCustomUi:e$,extensionStatuses:eN,extensionWidgets:ez,respondToExtensionUi:eW,sendExtensionCustomInput:eA,setNoticePaused:eF,isAutoModelSelection:eB,agentPhase:eD,isNew:eH,sessionIdRef:eO,scrollContainerRef:eU,lastUserMsgRef:e_,promptAnchorActive:eq,handleSend:eV,handleAbort:eG,handleFork:eX,handleNavigate:eQ,handleModelChange:e1,handleCompact:e8,handleSteer:e5,handleFollowUp:e6,handlePromptWithStreamingBehavior:e3,handleAbortCompaction:e9,handleRecallQueue:e7,handleBuiltinSlashCommand:te,handleToolPresetChange:tt,handleThinkingLevelChange:tn,loadSlashCommands:tr,scrollUserMsgToTop:ti,loadContext:to,activeLeafId:tl,scrollToBottom:ts,scrollToMessage:ta}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:o,onAgentEnd:l,onAttentionNeeded:s,onSessionCreated:a,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSystemToolsChange:h,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:f}=e,x=null===t&&null!==r,[m,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(!x),[j,w]=(0,i.useState)(null),[k,S]=(0,i.useState)(null),[C,T]=(0,i.useState)([]),[M,E]=(0,i.useState)(new Map),[I,R]=(0,i.useState)([]),[L,$]=(0,i.useState)(null),[N,z]=(0,i.useState)(!1),[W,P]=(0,i.useReducer)(rA,rW),[A,F]=(0,i.useState)(!1),[B,D]=(0,i.useState)(!1),[H,O]=(0,i.useState)(null),[U,_]=(0,i.useState)({}),[q,K]=(0,i.useState)([]),[V,J]=(0,i.useState)(null),[Y,Z]=(0,i.useState)([]),[G,X]=(0,i.useState)({}),[Q,ee]=(0,i.useState)({}),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(null),[eo,el]=(0,i.useState)("default"),[es,ea]=(0,i.useState)("auto"),[ed,ec]=(0,i.useState)(null),[eu,ep]=(0,i.useState)(null),[eh,eg]=(0,i.useState)(null),[ef,ex]=(0,i.useState)(null),[em,ev]=(0,i.useState)(null),[ey,eb]=(0,i.useState)(null),[ej,ew]=(0,i.useState)(null),[ek,eS]=(0,i.useState)(!1),[eC,eT]=(0,i.useState)(!1),[eM,eE]=(0,i.useState)(null),[eI,eR]=(0,i.useState)(null),[eL,e$]=(0,i.useState)(null),[eN,ez]=(0,i.useState)(!1),[eW,eP]=(0,i.useState)([]),[eA,eF]=(0,i.useState)(!1),[eB,eD]=(0,i.useReducer)(rO,{visible:[],pending:[]}),[eH,eO]=(0,i.useState)(null),[eU,e_]=(0,i.useState)(null),[eq,eK]=(0,i.useState)(null),[eV,eJ]=(0,i.useState)([]),[eY,eZ]=(0,i.useState)([]),[eG,eX]=(0,i.useState)({steering:[],followUp:[]}),eQ=(0,i.useRef)(null),e0=(0,i.useRef)(null),e1=(0,i.useRef)(0),e2=(0,i.useRef)(!1),e4=(0,i.useRef)(t?.id??null),e8=(0,i.useRef)(t?.id??null),e5=(0,i.useRef)(!1),e6=(0,i.useRef)(!1),e3=(0,i.useRef)(!1),e9=(0,i.useRef)(-1),e7=(0,i.useRef)(!1),te=(0,i.useRef)(0),tt=(0,i.useRef)(null),tn=(0,i.useRef)(!!e.deferInitialScroll),tr=(0,i.useRef)(null),ti=(0,i.useRef)(!1),to=(0,i.useRef)(!0),tl=(0,i.useRef)(0),ts=(0,i.useRef)(null),ta=(0,i.useRef)(void 0),td=(0,i.useRef)(null),tc=(0,i.useRef)(null),tu=(0,i.useRef)(!1),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tg=(0,i.useRef)(0),tf=(0,i.useRef)(null),tx=(0,i.useRef)(!1),tm=(0,i.useRef)(new Map),tv=(0,i.useRef)(!0);e8.current=t?.id??null,eQ.current||(eQ.current=new r$({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tt.current?.(e),shouldMaintain:e=>tv.current&&e4.current===e&&(e5.current||e2.current||e8.current===e),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let ty=e.setToolPreset??el,tb=t?.id;(0,i.useLayoutEffect)(()=>{(tb||x&&!e4.current)&&ty(function(e=rT()){if(!e)return"default";try{let t=e.getItem(rC);return(0,rS.sn)(t)?t:"default"}catch{return"default"}}())},[tb,x,ty]);let tj=(0,i.useCallback)((e="smooth")=>{let t=td.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),tl.current=t.scrollTop)},[]),tw=em??ey??m?.context.model??ej??null,tk=x?et??er:tw??(m?.context.messages.length===0?er:null),tS=t?.id??o??void 0,tC=(0,i.useCallback)(e=>{eb(e?.model?{provider:e.model.provider,modelId:e.model.id}:null)},[]),tT=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tm.current.get(t);if(!e)break;t=e}return t},[]),tM=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=tT(r);if(!tv.current&&!tu.current&&r===o)return;let s=e.chatInputRef?.current;if(s)s.restoreSubmission(t,i,l);else{let e,n;l&&(n=nm(t,i,(e=nh(l)??{value:"",images:[]}).value,e.images),ng(l,n))}},[o,e.chatInputRef,tT]),tE=(0,i.useMemo)(()=>{if(eH)return{...eH,totalActiveMs:m?.totalActiveMs,...eu?{contextUsage:eu}:{}};let e=m?.stats,n=function(e,t,n){let r=rE(n);if(!e)return r;let i=rE(t),o=(e,t)=>Math.max(0,e-t),l={input:e.tokens.input+o(r.tokens.input,i.tokens.input),output:e.tokens.output+o(r.tokens.output,i.tokens.output),cacheRead:e.tokens.cacheRead+o(r.tokens.cacheRead,i.tokens.cacheRead),cacheWrite:e.tokens.cacheWrite+o(r.tokens.cacheWrite,i.tokens.cacheWrite),total:0};return l.total=l.input+l.output+l.cacheRead+l.cacheWrite,{userMessages:e.userMessages+o(r.userMessages,i.userMessages),assistantMessages:e.assistantMessages+o(r.assistantMessages,i.assistantMessages),toolCalls:e.toolCalls+o(r.toolCalls,i.toolCalls),toolResults:e.toolResults+o(r.toolResults,i.toolResults),totalMessages:e.totalMessages+o(r.totalMessages,i.totalMessages),tokens:l,cost:e.cost+o(r.cost,i.cost)}}(e,m?.context.messages??[],C);return 0!==n.tokens.total||0!==C.length||e?{sessionFile:m?.filePath||void 0,sessionId:e4.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:m?.totalActiveMs,...eu?{contextUsage:eu}:{}}:null},[C,eH,eu,m?.context.messages,m?.filePath,m?.totalActiveMs,m?.stats,t?.id,t?.name]),tI=(0,i.useCallback)(async(e,t=!1,n=!1)=>{let r=!1;try{t&&b(!0);let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),o=await fetch(`/api/sessions/${encodeURIComponent(e)}?${i}`);if(404===o.status)return t&&(v(null),S(null),T([]),R([]),$(null),z(!1),w(null)),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let l=await o.json();if(e4.current!==e)return null;let s=l.context.messages;if(v(l),S(l.leafId),T(s),R(l.context.entryIds??[]),$(l.context.oldestEntryId),z(l.context.hasMore),ty(void 0!==l.toolNames?(0,rS.YO)(l.toolNames):"default"),ev(e=>tx.current?e:null),w(null),l.context.thinkingLevel&&"off"!==l.context.thinkingLevel&&ea(l.context.thinkingLevel),r=!0,t&&b(!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(e4.current!==e)return null;let r=n.state;return tC(r),r?(void 0!==r.contextUsage&&ep(r.contextUsage??null),void 0!==r.systemPrompt&&eg(r.systemPrompt??null),void 0!==r.thinkingLevel&&ea(r.thinkingLevel??"auto"),void 0!==r.extensionStatuses&&eJ(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&eZ(r.extensionWidgets??[]),void 0!==r.queuedMessages&&eX(rF(r.queuedMessages))):n.running||eX({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!r&&b(!1)}},[ty,tC]),tR=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let o=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,l=await fetch(o,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let s=await l.json();if(e4.current!==e||r?.signal?.aborted||!tv.current)return;return $(s.context.oldestEntryId),z(s.context.hasMore),v(t=>{if(!t||t.sessionId!==e)return t;let r=n?{...t.context,messages:[...s.context.messages,...t.context.messages],entryIds:[...s.context.entryIds,...t.context.entryIds],oldestEntryId:s.context.oldestEntryId,hasMore:s.context.hasMore}:s.context;return{...t,context:r}}),n?(T(e=>[...s.context.messages,...e]),R(e=>[...s.context.entryIds,...e])):(T(s.context.messages),R(s.context.entryIds??[])),s.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),tL=(0,i.useCallback)(async e=>{try{let t=await rk(e,{type:"get_tools"});if(!t||!tv.current||e4.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return ty(r(t)),h?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[h,ty]),t$=(0,i.useCallback)((t=0,n="(no messages)")=>{let i=e4.current;if(x&&r&&i&&!tu.current&&(tu.current=!0,o)){if(o!==i){tm.current.set(o,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,i):nv(o,i)}a?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},o)}},[x,r,o,a,e.chatInputRef]),tN=(0,i.useCallback)(async()=>{if(e4.current||!x||!r)return e4.current;if(tc.current)return tc.current;let e=(async()=>{let e=tp.current,t=th.current;e&&ew(e);let n=(0,rS.xG)(eo),i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"ensure_session",toolNames:n,...e?{provider:e.provider,modelId:e.modelId}:{},...t?{thinkingLevel:t}:{}})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json(),l=o.sessionId;return e4.current=l,o.model&&tp.current===e&&(ew(o.model),e||ei(o.model)),o.thinkingLevel&&th.current===t&&ea(o.thinkingLevel),l})();tc.current=e;try{return await e}finally{tc.current=null}},[x,r,eo]),tz=(0,i.useCallback)(async()=>{let e=e4.current??await tN();if(!e)return;let[t]=await Promise.all([rk(e,{type:"get_state"}),tL(e)]);tv.current&&e4.current===e&&(tC(t),eg(t.systemPrompt??""))},[tN,tL,tC]),tW=(0,i.useCallback)(async()=>{let e=e4.current??await tN();if(!e)return eP([]),[];eF(!0);try{let t=await rk(e,{type:"get_commands"}),n=t?.commands??[];return eP(n),n}catch(e){return console.error("Failed to load slash commands:",e),eP([]),[]}finally{eF(!1)}},[tN]),tP=(0,i.useCallback)(()=>{e1.current+=1,e2.current=!1,e0.current&&(clearTimeout(e0.current),e0.current=null)},[]),tA=(0,i.useCallback)(()=>{eQ.current?.close()},[]),tF=(0,i.useCallback)(e=>eQ.current.ensureConnected(e),[]),tB=(0,i.useCallback)(e=>{eQ.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return tB(e),()=>{e4.current===e&&eQ.current?.close()}},[tB,t?.id]),(0,i.useEffect)(()=>{let e=t?.id;if(!e)return;let n=!1,r=!1,i=async()=>{if(!n&&!r){r=!0;try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/lease`,{method:"POST",cache:"no-store"});if(!t.ok||n)return;let r=await t.json();n||0!==r.renewed||e4.current!==e||e8.current!==e||(tA(),tB(e))}catch{}finally{r=!1}}},o=setInterval(()=>void i(),3e4),l=()=>{"visible"===document.visibilityState&&i()};return document.addEventListener("visibilitychange",l),()=>{n=!0,clearInterval(o),document.removeEventListener("visibilitychange",l)}},[tA,tB,t?.id]);let tD=(0,i.useCallback)(async(e,t)=>{let n=e4.current;if(e_(t=>t?.id===e.id?null:t),n)try{await rk(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),tH=(0,i.useCallback)(async(e,t)=>{let n=e4.current;if(n)try{await rk(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),tO=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eD({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"}})},[]),tU=(0,i.useCallback)(t=>{switch(rm(t)&&s?.(t),t.method){case"select":case"confirm":case"input":case"editor":e_(t);break;case"notify":tO({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":eJ(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":eZ(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":eK(e=>t.closed?e?.id===t.id?null:e:t)}},[tO,s,e.chatInputRef]),t_=(0,i.useCallback)(()=>{let e=e5.current;return e5.current=!1,F(!1),e$(null),ec(null),E(new Map),P({type:"end"}),e},[]),tq=(0,i.useCallback)(e=>e9.current!==e&&(e9.current=e,l?.(),!0),[l]),tK=(0,i.useCallback)(e=>{if(e8.current===e)return void tP();tP(),e2.current=!0;let t=e1.current,n=async()=>{if(t===e1.current&&e4.current===e&&e2.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!==e1.current||e4.current!==e||!e2.current)return;let o=i.state;if(tC(o),i.running&&o&&(o.isStreaming||o.isPromptRunning)){e2.current=!1,e0.current=null,e6.current=!!o?.isStreaming,e3.current=!!o?.isPromptRunning,e5.current=!0,F(!0),e$(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eT(!0),e0.current=setTimeout(()=>void n(),600);return}e2.current=!1,e0.current=null,tA()}catch{if(t!==e1.current||e4.current!==e||!e2.current)return;e0.current=setTimeout(()=>void n(),600)}};e0.current=setTimeout(()=>void n(),3e4)},[tP,tA,tC]),tV=(0,i.useCallback)(async(e=e4.current,t=tg.current)=>{if(tg.current===t)try{e&&await tI(e)}finally{if(tg.current!==t)return;let n=e3.current,r=e6.current;e3.current=!1,e6.current=!1,tf.current=null;let i=t_();n?tq(t):r&&i&&l?.(),e&&tK(e)}},[tI,tq,l,tK,t_]),tJ=(0,i.useCallback)(async(e,t)=>{await rD(800);let n=Date.now();for(;e5.current&&Date.now()-n<2e4;){if(void 0!==t&&tg.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(tC(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await tV(e,t)}}catch{}await rD(600)}},[tV,tC]),tY=(0,i.useCallback)(async e=>{let t=te.current+1;for(te.current=t;e7.current&&te.current===t&&e4.current===e;){await rD(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(tC(r.state),r.state?.isBashRunning)continue;if(await tI(e),te.current!==t||e4.current!==e)return;e7.current=!1,D(!1),O(null);return}catch{}}},[tI,tC]),tZ=(0,i.useCallback)(async e=>{if(!e5.current||e4.current!==e)return;let t=tg.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(e4.current!==e||tg.current!==t)return;let i=r.state;if(tC(i),eT(i?.isCompacting??!1),eX(rF(i?.queuedMessages)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){e6.current=!!i.isStreaming,e3.current=!!i.isPromptRunning;return}if(!e5.current)return;i&&(void 0!==i.contextUsage&&ep(i.contextUsage??null),void 0!==i.systemPrompt&&eg(i.systemPrompt??null),void 0!==i.extensionStatuses&&eJ(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&eZ(i.extensionWidgets??[])),await tV(e,t)}catch{}},[tV,tC]);(0,i.useEffect)(()=>{if(!A)return;let e=()=>{let e=e4.current;e&&tZ(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)}},[A,tZ]),(0,i.useEffect)(()=>{e5.current=A},[A]),tt.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":P({type:"end"}),!0===e.isStreaming&&(tP(),e6.current=!0,e5.current=!0,F(!0),e$({kind:"waiting_model"}));break;case"agent_start":tP(),e6.current=!0,e5.current=!0,F(!0),e$({kind:"waiting_model"}),P({type:"start"});break;case"agent_end":if(!e5.current)break;e$(null),ec(null),P({type:"end"}),e4.current&&(tI(e4.current),fetch(`/api/agent/${encodeURIComponent(e4.current)}`).then(e=>e.json()).then(e=>{tC(e.state),e.state?.contextUsage!==void 0&&ep(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&eg(e.state.systemPrompt??null),e.state?.extensionStatuses!==void 0&&eJ(e.state.extensionStatuses??[]),e.state?.extensionWidgets!==void 0&&eZ(e.state.extensionWidgets??[]),eX(rF(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=e6.current;if(e6.current=!1,!e||e3.current)break;let t=e4.current,n=t_();eT(!1),t&&(tI(t),tK(t)),n&&l?.();break}case"prompt_done":{let e=tg.current,t=e3.current;e3.current=!1,tf.current=null;let n=tq(e);if(!t&&!n)break;let r=e4.current;r&&tI(r),!e6.current&&(t_(),r&&tK(r))}break;case"prompt_error":tO({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tO({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!e5.current)break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(P({type:"snapshot",message:t}),t.content.length>0&&e$(null)):t&&e$(null)}else{let t=e.assistantMessageEvent;t&&(P({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&e$(null))}!ti.current&&to.current&&null===ts.current&&(ts.current=requestAnimationFrame(()=>{ts.current=null,to.current&&tj("auto")}));break;case"message_end":{if(!e5.current)break;let t=e.message;if(t&&"user"===t.role){let e=rb(t),n=rR(e),r=tf.current;tf.current=null,T(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&rR(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else t&&T(e=>[...e,rb(t)]);P({type:"end"}),e$({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;e$(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)&&E(e=>{let o=new Map(e);return o.set(t,{role:"toolResult",toolCallId:t,toolName:n,content:i,isError:r?.isError,details:r?.details}),o});let o=function(e){if(!rN(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>rN(e)&&"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n").split(/\r?\n/),r="";for(let e=n.length-1;e>=0&&!(r=n[e].trim());e-=1);if(!r)return null;let i=r.replace(/\s+/g," ");return i.length<=500?i:`...${i.slice(-497)}`}(e.partialResult);e$(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[],i=r.find(e=>e.id===t),l={id:t,name:n||i?.name||"tool",progress:o??i?.progress};return{kind:"running_tools",tools:[...r.filter(e=>e.id!==t),l]}});break}case"tool_execution_end":{let t=e.toolCallId;E(e=>{if(!e.has(t))return e;let n=new Map(e);return n.delete(t),n}),e$(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":eX({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ec({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ec(null);break;case"auto_compaction_start":case"compaction_start":eT(!0),eE(null),eR(null);break;case"auto_compaction_end":case"compaction_end":eT(!1),e.errorMessage?(eE(e.errorMessage),eR(null)):!e.aborted&&(eR(rU(e.result,e.reason??"auto")),e4.current&&tI(e4.current));break;case"extension_ui_request":tU(e);break;case"extension_ui_closed":e_(t=>t?.id===e.id?null:t)}},[tO,tP,tU,tI,tq,l,tK,tj,t_,tC]);let tG=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(e5.current||e7.current)return void tM(e,n,tS);let o=!n?.length&&i.startsWith("/");if(!n?.length&&i.startsWith("!")){let t=i.startsWith("!!"),r=(t?i.slice(2):i.slice(1)).trim();return r?void await ta.current?.(r,t):void tM(e,n,tS)}let l=tg.current+1;tP(),e3.current=!0;let s=n?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),a={role:"user",content:s?.length?[...e.trim()?[{type:"text",text:e}]:[],...s]:e,timestamp:Date.now()};T(e=>[...e,a]),tf.current=rR(a),tg.current=l,e5.current=!0,F(!0),e$(o?{kind:"running_command"}:{kind:"waiting_model"}),P({type:"start"}),ti.current=!0,ez(!0);let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=null,u=!1;try{if(x&&r){let t=e4.current??await tc.current,n=t??await tN();if(!n)throw Error("Unable to create a session for the prompt");c=n,et&&(ew(et),t&&await rk(n,{type:"set_model",provider:et.provider,modelId:et.modelId})),await tF(n),u=!0,await rk(n,{type:"prompt",message:e,...d?.length?{images:d}:{}}),t$(1,e)}else if(t)c=t.id,await tF(t.id),u=!0,await rk(t.id,{type:"prompt",message:e,...d?.length?{images:d}:{}});else throw Error("No active session for the prompt");o&&c&&tJ(c,l)}catch(t){if(console.error("Failed to send message:",t),!(!u||rw(t))&&c)return void tJ(c,l);if(e3.current=!1,T(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),tO({type:"error",message:t instanceof Error?t.message:String(t)}),tM(e,n,tS),tf.current=null,c)return void tZ(c);e5.current=!1,tA(),F(!1),e$(null),P({type:"end"})}},[x,r,et,t,tN,tF,t$,tJ,tO,tP,tA,tS,tZ,tM]);ta.current=(0,i.useCallback)(async(e,n)=>{if(e5.current||e7.current)return;let r=`${n?"!!":"!"}${e}`;e7.current=!0,O({command:e,excludeFromContext:n}),D(!0);try{let i=e4.current??t?.id??await tN();if(!i)throw Error("Unable to create a session for the shell command");await rk(i,{type:"bash",command:e,excludeFromContext:n}),await tI(i),t$(1,r)}catch(e){console.error("Failed to execute shell command:",e),tO({type:"error",message:e instanceof Error?e.message:String(e)}),tM(r,void 0,tS)}finally{e7.current=!1,O(null),D(!1)}},[tO,tS,tN,tI,t$,tM,t]);let tX=(0,i.useCallback)(async()=>{let e=e4.current;if(e){if(e7.current){try{await rk(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await rk(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),tQ=(0,i.useCallback)(async e=>{if(e7.current)return;let t=e4.current;if(t){ex(e);try{let{cancelled:n,newSessionId:r}=await rk(t,{type:"fork",entryId:e})??{};!n&&r&&d?.(r)}catch(e){console.error("Fork failed:",e)}finally{ex(null)}}},[d]),t0=(0,i.useCallback)(async e=>{if(e7.current)return!1;let t=e4.current;if(!t)return!1;try{let n=await rk(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||e4.current!==t)return!1;return await tI(t),e4.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[tI]),t1=(0,i.useCallback)(async e=>{if(e7.current)return;S(e);let t=e4.current;t&&(await tR(t,e),e&&rk(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tR]),t2=(0,i.useCallback)(async(e,t)=>{if(x){let n={provider:e,modelId:t};tp.current=n,en(n),ew(n);let r=e4.current??await tc.current;if(!r)return;try{await rk(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=e4.current;if(n&&!tx.current){tx.current=!0,ev({provider:e,modelId:t}),eS(!0);try{let r=await rk(n,{type:"set_model",provider:e,modelId:t});eb({provider:r.provider,modelId:r.id}),tx.current=!1,await tI(n)}catch(e){console.error("Failed to set model:",e),tx.current=!1,ev(em),tO({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await tI(n,!1,!0)}finally{tx.current=!1,eS(!1)}}},[tO,em,x,tI,en]),t4=(0,i.useCallback)(async()=>{let e=e4.current;if(e&&!eC){eT(!0),eE(null),eR(null);try{let t=await rk(e,{type:"compact"});eR(rU(t,"manual")),await tI(e,!0)}catch(e){eE(e instanceof Error?e.message:String(e)),eR(null)}finally{eT(!1)}}},[eC,tI]),t8=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"",o=i?`/api/models?cwd=${encodeURIComponent(i)}`:"/api/models";try{let t=await fetch(o,e?{signal:e}:void 0);if(!t.ok){let e="";try{let n=await t.json();n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error&&(e=n.error)}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)throw e}throw Error(e||`Failed to load models (HTTP ${t.status})`)}n=await t.json(),e?.throwIfAborted()}catch(t){throw e?.aborted||t instanceof DOMException&&"AbortError"===t.name||J(t instanceof Error?t.message:String(t)),t}_(n.models),J(n.modelError??null),Z(n.modelScopeWarnings??[]),X(n.thinkingLevels??{}),ee(n.thinkingLevelMaps??{});let l=n.modelList??[];K(l);let s=n.defaultModel?l.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(ei(s?{provider:s.provider,modelId:s.id}:null),x&&!e4.current){let e=s&&n.thinkingLevelPins?.[`${s.provider}/${s.id}`];null===th.current&&ea(e??"auto")}},[x,r,t?.cwd]),t5=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),o=e4.current??await tN(),l=e=>(e.handled&&(e.error?tO({type:"error",message:e.error}):"openSessionStats"!==e.action&&tO({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||eC)return l({handled:!0,error:"No active session to compact"});eT(!0),eE(null),eR(null);let e=await rk(o,{type:"compact",...i?{customInstructions:i}:{}});return eR(rU(e,"manual")),await tI(o,!0)&&t$(),l({handled:!0,message:"Compacted context"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await rk(o,{type:"reload"}),await Promise.all([tI(o,!1,!0),tL(o),tW(),t8()]),l({handled:!0,message:"Reloaded session resources"});case"name":if(!o)return l({handled:!0,error:"No active session to name"});if(!i)return l({handled:!0,error:"Usage: /name <name>"});return await rk(o,{type:"set_session_name",name:i}),await tI(o)&&t$(),l({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});let e=await rk(o,{type:"get_session_stats"});return e&&eO(e),f?.(),l({handled:!0,action:"openSessionStats"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await rk(o,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return l({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),l({handled:!0,message:"Copied last assistant message"})}case"clone":{if(!o)return l({handled:!0,error:"No active session to clone"});if(e5.current||e7.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=await rk(o,{type:"clone",leafId:k});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 d?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return l({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eT(!1)}},[k,tO,tN,eC,t8,tI,tW,tL,t$,d,f]),t6=(0,i.useCallback)(async(e,t,n)=>{let r=e4.current;if(!r){tM(e,n,tS),tO({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 rk(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}})}catch(t){console.error("Failed to submit streaming prompt:",t),rw(t)&&tM(e,n,tS),tO({type:"error",message:t instanceof Error?t.message:String(t)})}},[tO,tS,tM]),t3=(0,i.useCallback)(async(e,t)=>{await t6(e,"steer",t)},[t6]),t9=(0,i.useCallback)(async(e,t,n)=>{await t6(e,t,n)},[t6]),t7=(0,i.useCallback)(async(e,t)=>{await t6(e,"followUp",t)},[t6]),ne=(0,i.useCallback)(async()=>{let e=e4.current;if(e)try{await rk(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nt=(0,i.useCallback)(async()=>{let t=e4.current;if(t)try{let n=await rk(t,{type:"clear_queue"});eX({steering:[],followUp:[]});let r=[...n?.steering??[],...n?.followUp??[]];r.length>0&&e.chatInputRef?.current?.prependText(r.join("\n\n"))}catch(e){console.error("Failed to recall queued messages:",e),tO({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,tO]),nn=(0,i.useCallback)(async e=>{if(ea(e),x&&!e4.current&&(th.current="auto"===e?null:e),"auto"===e)return;let t=e4.current??await tc.current;if(t)try{await rk(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[x]),nr=(0,i.useCallback)(async e=>{let t=(0,rS.xG)(e);!function(e,t=rT()){if(t)try{t.setItem(rC,e)}catch{}}(e),ty(e);let n=e4.current??await tc.current;if(n)try{let e=await rk(n,{type:"set_tools",toolNames:t}),r=e?.sessionId??n;(r!==n||e?.recreated)&&(tP(),tA(),e4.current=r,e?.recreated&&e8.current===r&&tB(r)),eP([]),eJ([]),eZ([]);let[i]=await Promise.all([rk(r,{type:"get_state"}),tL(r)]);tv.current&&e4.current===r&&(eg(i.systemPrompt??""),tC(i))}catch(e){console.error("Failed to set tools:",e)}},[tP,tA,tL,tB,ty,tC]),ni=(0,i.useCallback)((e,t=16)=>{let n=td.current;n&&(null!==ts.current&&(cancelAnimationFrame(ts.current),ts.current=null),tn.current=!0,ti.current=!1,to.current=!1,ez(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tl.current=n.scrollTop)},[]),no=(0,i.useCallback)(()=>{let e=td.current,t=tr.current;if(!e||!t)return;let n=Math.min(Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-16),Math.max(0,e.scrollHeight-e.clientHeight));null!==ts.current&&(cancelAnimationFrame(ts.current),ts.current=null),to.current=!0,tl.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),nl=(0,i.useCallback)(()=>{let e=td.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=e5.current,o=to.current,l=function(e,t,n,r,i,o=96){return!!rz(n,r,i)||!(n<t)&&(!!(!e&&n>t&&rz(n,r,i,o))||e)}(o,tl.current,t,n,r,i?96:8);to.current=l,tl.current=t,!o&&l&&i?tj("auto"):l||null===ts.current||(cancelAnimationFrame(ts.current),ts.current=null)}},[tj]);(0,i.useEffect)(()=>(tv.current=!0,t&&(e4.current=t.id,tI(t.id,!0,!0).then(e=>{e?.running&&(tL(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(e6.current=!!e.state.isStreaming,e3.current=!!e.state.isPromptRunning,e5.current=!0,F(!0),e$(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),P({type:"resume"}),!e.state.isStreaming&&e.state.isPromptRunning&&tJ(t.id)),e.state?.isBashRunning&&(e7.current=!0,D(!0),tY(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eT(e.state.isCompacting),void 0!==e.state.contextUsage&&ep(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&eg(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&ea(e.state.thinkingLevel??"auto"),void 0!==e.state.extensionStatuses&&eJ(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&eZ(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&eX(rF(e.state.queuedMessages)))})),()=>{tv.current=!1;let e=x?o:null;e&&queueMicrotask(()=>{tv.current||tu.current||nf(e)}),null!==ts.current&&(cancelAnimationFrame(ts.current),ts.current=null),te.current+=1,tP(),tA()}),[]),(0,i.useEffect)(()=>{p?.(eh)},[eh,p]),(0,i.useEffect)(()=>(g?.(tz),()=>g?.(null)),[tz,g]),(0,i.useEffect)(()=>{u&&u(m?.tree??[],k,t1)},[m?.tree,k,t1,u]),(0,i.useEffect)(()=>{let e=td.current;if(e)return tl.current=e.scrollTop,e.addEventListener("scroll",nl,{passive:!0}),()=>{e.removeEventListener("scroll",nl)}},[C.length,y,nl]),(0,i.useEffect)(()=>{A||ez(!1)},[A]),(0,i.useLayoutEffect)(()=>{C.length>0&&(ti.current?(ti.current=!1,tn.current=!0,no()):tn.current?!e5.current&&to.current&&tj("auto"):(tn.current=!0,tj("instant")))},[C.length,A,tj,no]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await t8(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=rB.length||(await rD(rB[t]),e.signal.aborted))return}})(),()=>e.abort()},[t8,c]),(0,i.useEffect)(()=>{if(!eI)return;let e=setTimeout(()=>eR(null),6e3);return()=>clearTimeout(e)},[eI]);let[ns,na]=(0,i.useState)(null),nd=(0,i.useRef)(5e3),nc=(0,i.useRef)(null),nu=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===eB.visible.length){nu.current=null;return}let e=eB.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eD({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=eB.visible[0];if(!t||(nu.current!==t.id&&(nu.current=t.id,nd.current=5e3),eB.visible.some(e=>e.id===ns)))return;nc.current=Date.now();let n=setTimeout(()=>{eD({type:"mark_oldest_exiting"})},nd.current);return()=>{clearTimeout(n),null!==nc.current&&(nd.current=Math.max(0,nd.current-(Date.now()-nc.current)),nc.current=null)}},[eB.visible,ns]),(0,i.useEffect)(()=>{eO(null)},[C.length,eu?.tokens,eu?.percent,eu?.contextWindow]),{data:m,loading:y,error:j,activeLeafId:k,messages:C,activeToolResults:M,entryIds:I,historyCursor:L,hasEarlierMessages:N,streamState:W,agentRunning:A,modelNames:U,modelList:q,modelError:V,modelScopeWarnings:Y,modelThinkingLevels:G,modelThinkingLevelMaps:Q,newSessionModel:et,toolPreset:eo,thinkingLevel:es,retryInfo:ed,contextUsage:eu,systemPrompt:eh,forkingEntryId:ef,isCompacting:eC,compactError:eM,compactResult:eI,currentModel:tw,displayModel:tk,modelSwitching:ek,sessionStats:tE,slashCommands:eW,slashCommandsLoading:eA,queuedMessages:eG,notices:eB.visible,extensionDialog:eU,extensionCustomUi:eq,extensionStatuses:eV,extensionWidgets:eY,respondToExtensionUi:tD,sendExtensionCustomInput:tH,isAutoModelSelection:x&&null===et,agentPhase:eL,isNew:x,promptAnchorActive:eN,sessionIdRef:e4,scrollContainerRef:td,lastUserMsgRef:tr,pendingScrollToUserRef:ti,initialScrollDoneRef:tn,handleSend:tG,handleAbort:tX,handleFork:tQ,handleNavigate:t0,handleModelChange:t2,handleCompact:t4,handleSteer:t3,handleFollowUp:t7,handlePromptWithStreamingBehavior:t9,handleAbortCompaction:ne,handleRecallQueue:nt,handleBuiltinSlashCommand:t5,setNoticePaused:na,handleToolPresetChange:nr,handleThinkingLevelChange:nn,loadTools:tL,loadSlashCommands:tW,setActiveLeafId:S,setData:v,setMessages:T,loadContext:tR,scrollToBottom:tj,scrollUserMsgToTop:no,scrollToMessage:ni,dispatch:P,setAgentRunning:F,setForkingEntryId:ex,bashRunning:B,pendingBash:H,handleAgentEventRef:tt}}({session:e,sessionRunning:d,newSessionCwd:c,newSessionDraftKey:u,onAgentEnd:q,onAttentionNeeded:h,onSessionCreated:g,onSessionForked:f,modelsRefreshKey:x,chatInputRef:m,onBranchDataChange:v,onSystemPromptChange:y,onSystemToolsChange:b,onSystemInfoLoaderChange:j,onSessionStatsPanelOpen:k,deferInitialScroll:!!J}),td=el||es,[tc,tu]=(0,i.useState)(null),[tp,th]=(0,i.useState)(!1),[tg,tf]=(0,i.useState)(!1),[tx,tm]=(0,i.useState)(null),tv=(0,i.useRef)(null),ty=(0,i.useRef)(null),tb=(0,i.useCallback)(()=>{tu(null),th(!1),tm(null)},[]);(0,i.useEffect)(()=>{R||tb()},[R,tb]);let tj=(0,i.useCallback)(()=>{if(!R||tp)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=tE.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tu(null);let r=e.toString().trim();if(!r)return void tu(null);let i=t.getBoundingClientRect(),o=[t.commonAncestorContainer.nodeType===Node.ELEMENT_NODE?t.commonAncestorContainer:t.commonAncestorContainer.parentElement,t.startContainer.nodeType===Node.ELEMENT_NODE?t.startContainer:t.startContainer.parentElement,t.endContainer.nodeType===Node.ELEMENT_NODE?t.endContainer:t.endContainer.parentElement].map(e=>e?.closest('[data-message-role="assistant"]')?.dataset.entryId).find(e=>!!e);tu({text:r,top:Math.min(window.innerHeight-44,i.bottom+8),left:Math.max(64,Math.min(window.innerWidth-64,i.left+i.width/2)),sourceEntryId:o})},[R,tp]);(0,i.useEffect)(()=>{tp&&tc&&ty.current?.insertIfEmpty(e4(tc.text,B("chat.quoteIntro"),B("chat.quoteQuestion")))},[tp,tc,B]),(0,i.useLayoutEffect)(()=>{let e=tv.current;if(!e||!tc)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(tc.top,r+(t?.height??window.innerHeight)-n.height-8))}px`,e.style.left=`${Math.max(i+8,Math.min(tc.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)}},[tc,tp,tx]),(0,i.useEffect)(()=>{if(!tc)return;let e=e=>{tp||tv.current?.contains(e.target)||tb()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tg||tb())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tc,tp,tg,tb]);let tw=(0,i.useCallback)(()=>{tc&&(m?.current?.insertText(e4(tc.text,B("chat.quoteIntro"),B("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),tb())},[m,tc,tb,B]),tk=(0,i.useCallback)(async t=>{let n=eO.current??e?.id;if(!tg&&t.trim()&&tc?.sourceEntryId&&n&&I){tf(!0),tm(null),P?.();try{await I(t,n,tc.sourceEntryId),tb()}catch(e){ty.current?.restoreSubmission(t),tm(e instanceof Error?e.message:String(e))}finally{tf(!1)}}},[I,tc,tg,e?.id,eO,tb,P]),tS=(0,i.useRef)(!1);(0,i.useEffect)(()=>{X||Q||!L||tS.current||(tS.current=!0,$?.(),eV(L))},[L,X,Q,eV,$]),(0,i.useEffect)(()=>{H&&eL&&_.current!==eL.id&&(_.current=eL.id,O.current())},[H,eL]),(0,i.useEffect)(()=>{l=td?eG:null},[td,eG]);let[tC,tT]=(0,i.useState)(50),tM=(0,i.useRef)(null),tE=(0,i.useRef)(null),tI=(0,i.useRef)(null),tR=(0,i.useRef)(!1),tL=(0,i.useRef)(!1),t$=(0,i.useRef)(J);t$.current=J;let[tN,tz]=(0,i.useState)(null),tW=ee[en.indexOf(tN?.entryId??"")],tP=tW?.role==="assistant"?tN?.blockIndex===void 0?tW.content.find(e=>"text"===e.type):tW.content[tN.blockIndex]:void 0,tA=(0,i.useRef)({entryIds:en,historyCursor:er,hasEarlierMessages:ei});tA.current={entryIds:en,historyCursor:er,hasEarlierMessages:ei},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=eU.current,r=tE.current;if(t&&a&&n&&r)return()=>{if(t$.current)return;if(rz(n.scrollTop,n.clientHeight,n.scrollHeight))return void a(t,{atBottom:!0});let e=n.getBoundingClientRect().top,i=function(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}(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&&a(t,{atBottom:!1,...i,oldestEntryId:tA.current.historyCursor})}},[X,a,eU,e?.id]),(0,i.useEffect)(()=>{t&&Y(null)},[t]),(0,i.useEffect)(()=>{let n=e?.id;if(!J||!n||X||t||tL.current)return;tL.current=!0;let r=new AbortController;return(async()=>{let e=tA.current;if(e.entryIds.includes(J.anchorEntryId)){tT(t=>Math.max(t,2*e.entryIds.length)),G(!0);return}tR.current=!0;let t=e.historyCursor,i=e.hasEarlierMessages;try{for(;i&&t&&!r.signal.aborted;){let e=await to(n,tl,t,{signal:r.signal});if(r.signal.aborted)return;if(!e){ts("instant"),Y(null);return}if(tT(t=>t+Math.max(50,2*e.messages.length)),e.entryIds.includes(J.anchorEntryId))return void G(!0);if(e.oldestEntryId===J.oldestEntryId)break;t=e.oldestEntryId,i=e.hasMore}r.signal.aborted||(ts("instant"),Y(null))}finally{tR.current=!1}})(),()=>{r.abort(),Y(null)}},[tl,to,X,J,ts,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=tE.current;if(!J||!e||t)return;let n=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===J.anchorEntryId);if(n instanceof HTMLElement){ta(n,J.anchorOffset),Y(null);return}Z&&(ts("instant"),Y(null))},[en,J,Z,ts,ta,t,tC]),(0,i.useEffect)(()=>{if(!t||X)return;let e=new AbortController;return(async()=>{let n=tA.current,r=n.entryIds.includes(t.entryId);if(!r&&!td&&n.hasEarlierMessages&&n.historyCursor&&!tR.current){tR.current=!0;let i=eU.current;i&&(tI.current=i.scrollHeight-i.scrollTop);let o=await to(t.sessionId,tl,n.historyCursor,{tail:200,signal:e.signal});tR.current=!1,r=!!o?.entryIds.includes(t.entryId)}e.signal.aborted||(r?(tI.current=null,tT(e=>Math.max(e,(tA.current.entryIds.length+200)*2)),tz(t)):o?.(t))})(),()=>e.abort()},[t,X,tl,td,to,o,eU]),(0,i.useLayoutEffect)(()=>{if(!tN||tN!==t)return;let e=`[data-entry-id="${CSS.escape(tN.entryId)}"]`,n=eU.current?.querySelector(tW?.role==="user"?e:`${e} [data-search-target]`);n&&(ta(n),n.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),tz(null),o?.(tN)},[tN,t,tW,eU,ta,o]),(0,i.useEffect)(()=>{let t=tM.current,n=eU.current;if(!t||!n)return;let r=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||tR.current||!ei||!er)return;let r=e?.id??eO.current;r&&(tR.current=!0,tI.current=n.scrollHeight-n.scrollTop,to(r,tl,er).finally(()=>{tR.current=!1}))},{root:n,threshold:0});return r.observe(t),()=>r.disconnect()},[er,ei,e,tl,to,eO,eU]),(0,i.useEffect)(()=>{tT(e=>Math.max(e,ee.length))},[ee.length]),(0,i.useEffect)(()=>{if(null==tI.current)return;let e=eU.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-tI.current),tI.current=null}},[tC,eU]);let tF=eT?[eT.sessionId,eT.sessionFile??"",eT.sessionName??"",eT.userMessages,eT.assistantMessages,eT.toolCalls,eT.toolResults,eT.totalMessages,eT.tokens.input,eT.tokens.output,eT.tokens.cacheRead,eT.tokens.cacheWrite,eT.tokens.total,eT.cost??0,eT.totalActiveMs??0].join("|"):null,tB=(0,i.useRef)(eT);tB.current=eT,(0,i.useEffect)(()=>{w?.(tB.current)},[tF,w]),(0,i.useEffect)(()=>()=>{w?.(null)},[w]);let tD=ey?`${ey.percent??"null"}|${ey.contextWindow}|${ey.tokens??"null"}`:null,tH=(0,i.useRef)(ey);tH.current=ey,(0,i.useEffect)(()=>{S?.(tH.current)},[tD,S]),(0,i.useEffect)(()=>()=>{S?.(null)},[S]);let{isDragOver:tO,handleDragEnter:tU,handleDragOver:t_,handleDragLeave:tq,handleDrop:tK}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&(e.preventDefault(),r.current+=1,n(!0))},[]),l=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:o,handleDragOver:l,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{m?.current?.addImages(e)},[m])),tV=ee.filter(e=>eK(e)||"assistant"===e.role),tJ=(0,i.useMemo)(()=>{let e=new Map(et);for(let t of ee)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[et,ee]),tY=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=ee.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}(ee[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[ee]),tZ=(A=tV.length,(F=(0,i.useRef)([])).current=Array(A).fill(null).map((e,t)=>F.current[t]??null),F),tG=(0,i.useCallback)(()=>{tT(e=>Math.max(e,2*ee.length))},[ee.length]),tQ=eH&&0===ee.length&&!eo.isStreaming&&!td,t0=!!eo.streamingMessage?.content.length,t1=e?.cwd??c??void 0,t2=(0,i.useRef)(null),t4=(0,i.useRef)(0),t8=(0,i.useRef)(null),t5=(0,i.useRef)(!1),t6=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=t2.current;if(!el||!eq){t6.current=null,t4.current=0,t5.current=!1,e&&(e.style.height="");return}let t=eU.current,n=tE.current,r=e_.current;if(!t||!n||!r||!e)return;let i=!1,o=()=>{var o;let l;if(i||eU.current!==t||tE.current!==n||e_.current!==r||t2.current!==e)return;let s=t.getBoundingClientRect().top,a=Math.max(0,r.getBoundingClientRect().top-s+t.scrollTop-16),d=e.getBoundingClientRect().top-s+t.scrollTop,c=(o=t.clientHeight,0===(l=Math.max(0,a))?0:Math.max(0,Math.ceil(l+o-Math.max(0,d)))),u=!t5.current;u&&(t5.current=!0),c!==t4.current&&(t4.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&ti())};t6.current=o,o();let l="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==t8.current||(t8.current=requestAnimationFrame(()=>{t8.current=null,o()}))});return l?.observe(t),l?.observe(n),l?.observe(r),()=>{i=!0,t6.current===o&&(t6.current=null),l?.disconnect(),null!==t8.current&&(cancelAnimationFrame(t8.current),t8.current=null)}},[el,e_,ee.length,eq,eU,ti]),(0,i.useLayoutEffect)(()=>{t6.current?.()},[eo.streamingMessage]);let t3=eS?eg[`${eS.provider}:${eS.modelId}`]??null:null,t9=eS?ef[`${eS.provider}:${eS.modelId}`]??null:null,t7=(0,r.jsx)(rr,{ref:m,onSend:eV,onAbort:eG,onSteer:el?e5:void 0,onFollowUp:el?e6:void 0,onPromptWithStreamingBehavior:el?e3:void 0,isStreaming:td,model:eS,isAutoModelSelection:eB,modelNames:ed,modelList:eu,modelError:ep,modelScopeWarnings:eh,onModelChange:e1,modelSwitching:eC,onCompact:e||eH?e8:void 0,onAbortCompaction:e9,isCompacting:ej,compactError:ew,compactResult:ek,toolPreset:ex,onToolPresetChange:e||eH?tt:void 0,thinkingLevel:em,onThinkingLevelChange:e||eH?tn:void 0,availableThinkingLevels:t3,thinkingLevelMap:t9,retryInfo:ev,queuedMessages:eI,inputHistory:tY,onRecallQueue:e7,slashCommands:eM,slashCommandsLoading:eE,onLoadSlashCommands:tr,onBuiltinCommand:te,soundEnabled:N,onSoundToggle:z,onAudioUnlock:P,draftKey:e?.id??u??void 0,cwd:e?.cwd??c});return X?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:B("chat.loadingSession")}):Q?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:Q}):(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:tU,onDragOver:t_,onDragLeave:tq,onDrop:tK,children:[tO&&(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",{style:{position:"absolute",top:12,left:0,right:36*!D,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(rJ,{notices:eR,floating:!0,onPauseChange:eF})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eL&&(0,r.jsx)(rY,{request:eL,onRespond:eW},eL.id),e$&&(0,r.jsx)(rZ,{request:e$,onInput:eA},e$.id),!tQ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{ref:eU,className:"min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",style:{visibility:J?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:tE,onPointerUp:tj,style:{width:"100%",minWidth:0,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto"},children:[(()=>{var t;let n,i,o=-1;for(let e=ee.length-1;e>=0;e--)if("user"===ee[e].role){o=e;break}let l=-1;for(let e=ee.length-1;e>=0;e--)if(eK(ee[e])){l=e;break}let s=new Map,a=0;ee.forEach((e,t)=>{(eK(e)||"assistant"===e.role)&&s.set(t,a++)});let d=(t,n={})=>{let i=n.messageOverride??ee[t],l=eK(i)||"assistant"===i.role,a=s.get(t),d=n.keyPrefix??"message",c=en[t]??t,u=!1;if("assistant"===i.role){u=!0;for(let e=t+1;e<ee.length;e++){let t=ee[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&eo.isStreaming&&t===ee.length-1&&(u=!1)}void 0!==n.showTimestamp&&(u=n.showTimestamp);let p=(0,r.jsx)(tX,{message:i,toolResults:tJ,modelNames:ed,cwd:t1,onOpenFile:C,onOpenSession:E,entryId:en[t],searchBlock:en[t]===tN?.entryId?tP:void 0,onFork:td||eH?void 0:eX,forking:eb===en[t],onNavigate:td?void 0:eQ,onEditContent:K,showTimestamp:u,prevTimestamp:t>0?ee[t-1].timestamp:void 0,sessionId:e?.id??eO.current??void 0,writtenFiles:n.writtenFiles},`${d}-view-${c}`);return l&&void 0!==a?(0,r.jsx)("div",{"data-entry-id":en[t],ref:!1===n.attachRef?void 0:e=>{tZ.current[a]=e,t===o&&(e_.current=e)},children:p},`${d}-${c}`):p},c=[];for(let e=0;e<ee.length;){let t;if(!eK(ee[e])){c.push(d(e)),e+=1;continue}let n=e,i=n+1;for(;i<ee.length&&!eK(ee[i]);)i+=1;let o=function(e,t,n){for(let i=n-1;i>t;i--){var r;if("assistant"===(r=e[i]).role&&eZ(r).answerBlocks.some(e=>"image"===e.type||"text"===e.type&&e.text.trim().length>0))return i}for(let r=n-1;r>t;r--)if(e[r]?.role==="assistant")return r;return -1}(ee,n,i);if(-1===o||(td||eo.isStreaming)&&i===ee.length&&n===l){for(let e=n;e<i;e++)c.push(d(e));e=i;continue}c.push(d(n));let a=ee[o],u=eZ(a),p=u.answerBlocks.length>0||eY(a)?rq(a,u.answerBlocks):null,h=a.content.indexOf(u.answerBlocks[0]),g=a.content.slice(0,h<0?void 0:h),f=[],x=0,m=!1;for(let e=n+1;e<=o;e++){let n=ee[e];if("custom"===n.role){m||=!!(tN&&tN.entryId===en[e]),f.push(d(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===o?rq(n,g,{omitUsage:!!p}):n,i=eJ(r);0!==i.length&&(t??=s.get(e),x+=i.filter(e=>"toolCall"===e.type).length,m||=!!(tN&&en[e]===tN.entryId&&(!tP||i.includes(tP))),f.push(d(e,{attachRef:!1,keyPrefix:"process",messageOverride:r,showTimestamp:!1})))}if(f.length>0&&c.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{tZ.current[t]=e},children:(0,r.jsx)(rK,{messageCount:f.length,toolCallCount:x,defaultExpanded:!p,reveal:m,t:B,children:f})},`process-group-${en[n]??n}`)),p){let e=[];for(let t=n+1;t<=o;t++){let n=ee[t];if(n?.role==="assistant")for(let t of n.content??[])e.push(t)}let t=function(e,t,n){let r=new Set,i=[];for(let o of e){if("toolCall"!==o.type||!function(e){let t;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||e2(e)}(o.toolName))continue;let e=t?.get(o.toolCallId);if(!e||e.isError)continue;let l=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(o.input);if(!l)continue;let s=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,o=i(e),l=t?i(t).replace(/\/+$/,""):void 0,s=/^[a-zA-Z]:\//.test(o),a=o.startsWith("//");if(s||a)n=o;else if(o.startsWith("/")){let e=l?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??l?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${o}`:o}else{if(!l)return null;n=`${l}/${o}`}return e0(n)}(l,n);s&&(r.has(s)||(r.add(s),i.push({filePath:s})))}return i}(e,tJ,t1);c.push(d(o,{messageOverride:p,writtenFiles:t}))}for(let e=o+1;e<i;e++)c.push(d(e));e=i}let{startIndex:u}=(n=Math.min(Math.max(tC,0),Math.max(t=c.length,0)),{startIndex:i=Math.max(0,t-n),hasMore:i>0}),p=u>0||ei;return(0,r.jsxs)(r.Fragment,{children:[p&&(0,r.jsx)("div",{ref:tM,className:"py-3 text-center text-xs text-text-muted",children:B("chat.loadEarlier")}),c.slice(u)]})})(),eo.isStreaming&&t0&&eo.streamingMessage&&(0,r.jsx)(tX,{message:eo.streamingMessage,toolResults:tJ,isStreaming:!0,modelNames:ed,cwd:t1,onOpenFile:C,onOpenSession:E}),el&&!t0&&eD&&(0,r.jsx)("div",{className:"break-words py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e,t){if(e?.kind==="running_tools"){let n=e.tools[e.tools.length-1];if(n?.progress)return`${t("chat.runningNamedTool",{name:n.name})} ${n.progress}`;let r=e.tools.map(e=>e.name);return 0===r.length?t("chat.runningTool"):1===r.length?t("chat.runningNamedTool",{name:r[0]}):r.length<=3?t("chat.runningTools",{names:r.join(", ")}):t("chat.runningToolsMore",{names:r.slice(0,2).join(", "),count:r.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(eD,B)})}),es&&!ea&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:B("chat.runningCommand")})}),ea&&(0,r.jsx)(tX,{message:{role:"bashExecution",command:ea.command,output:"",excludeFromContext:ea.excludeFromContext},sessionId:e?.id??eO.current??void 0,onOpenSession:E}),(0,r.jsx)("div",{ref:t2,"aria-hidden":"true"})]})})}),D||J?null:(0,r.jsx)(ru,{messages:ee,streamingMessage:eo.streamingMessage,scrollContainer:eU,messageRefs:tZ,onRevealHistory:tG})]})]}),R&&tc&&(0,M.createPortal)((0,r.jsx)("div",{ref:tv,role:tp?"dialog":"toolbar","aria-label":B(tp?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tc.top,left:tc.left,zIndex:130,display:"flex",flexWrap:"wrap",gap:3,width:tp?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tp?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tp?(0,r.jsxs)("fieldset",{disabled:tg,"aria-busy":tg,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:B("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:B("i18n.close"),"aria-label":B("i18n.close"),disabled:tg,onClick:tb,style:{border:"none"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 6 12 12M18 6 6 18"})})})]}),(0,r.jsx)(rr,{ref:ty,compact:!0,onSend:tk,onAbort:tb,isStreaming:!1}),tx&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tx})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:B("chat.askInCurrent"),"aria-label":B("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tw,style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{fontSize:15},children:"@"}),(0,r.jsx)("span",{children:B("chat.askInCurrent")})]}),I&&tc.sourceEntryId&&!td&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:B("chat.askInNewChat"),"aria-label":B("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{th(!0),window.getSelection()?.removeAllRanges()},style:{width:"auto",height:35,flex:"0 0 auto",gap:5,padding:"0 10px",border:"none",fontSize:12,fontWeight:500},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("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:B("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[tQ&&(0,r.jsx)("div",{className:"mb-3 w-full",style:{paddingLeft:16,paddingRight:D?16:52},children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,maxWidth:"var(--chat-content-max-width, 820px)",margin:"0 auto",fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:D?7:10,minWidth:0,flex:1,lineHeight:1.4,overflow:"hidden"},children:[(0,r.jsx)(eP.default,{src:"/icons/apple-touch-icon.png",width:32,height:32,alt:"",priority:!0,style:{flexShrink:0}}),(0,r.jsx)("span",{style:{fontSize:22,color:"var(--text)",fontWeight:700,flexShrink:0,whiteSpace:"nowrap"},children:"Pi Web"}),(0,r.jsx)(r_,{label:e=>B("appUpdate.releaseNotes",{version:e})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.9.8"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["pi ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.85.1"]})]})]})]})}),t7,(0,r.jsx)(rf,{statuses:eN,widgets:ez})]}),tQ&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function rJ({notices:e,floating:t=!1,onPauseChange:n}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",marginBottom:10*!t},children:e.map((i,o)=>{let l="error"===i.type?"#ef4444":"warning"===i.type?"#d97706":"success"===i.type?"#10b981":"var(--accent)";return(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:10,minHeight:60,height:"auto",maxHeight:500,pointerEvents:"auto",marginBottom:6*(o!==e.length-1),overflow:"hidden",borderRadius:14,border:"1px solid color-mix(in srgb, var(--border) 70%, transparent)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"0 1px 2px rgba(15,23,42,0.05), 0 10px 28px -14px rgba(15,23,42,0.24)":"0 1px 2px rgba(15,23,42,0.04), 0 8px 24px -12px rgba(15,23,42,0.10)",fontSize:14,lineHeight:1.5,transformOrigin:"top right",animation:i.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out backwards",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l,flexShrink:0,marginTop:21}}),(0,r.jsx)("span",{tabIndex:0,style:{padding:"14px 0",minWidth:0,maxWidth:"100%",maxHeight:470,overflowY:"auto",scrollbarWidth:"thin",whiteSpace:"pre-line",wordBreak:"break-word"},children:i.message})]},i.id)})})}function rY({request:e,onRespond:t}){let{t:n}=(0,T.s)(),[o,l]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(()=>Date.now()),u=(0,i.useCallback)(e=>e?.focus(),[]),p=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),h=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 g=null!==h&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionExpiresIn",{seconds:h})}),f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};return(0,r.jsx)("div",{onKeyDown:n=>{"Escape"!==n.key||n.nativeEvent.isComposing||(n.preventDefault(),n.stopPropagation(),t(e,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(0,r.jsxs)("button",{type:"button",onClick:()=>a(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:e.title}),p&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:p}),g,(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:8,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)",maxHeight:"50%",overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:14,fontWeight:650,lineHeight:1.45,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},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")}),g]})]}),(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:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})]}),(0,r.jsxs)("div",{style:{padding:14,flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:["confirm"===e.method&&(0,r.jsx)(tP,{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:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13,overflowWrap:"anywhere",scrollMargin:14},children:(0,r.jsx)("div",{inert:!0,children:(0,r.jsx)(tP,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||f()},style:{width:"100%",padding:"9px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",outline:"none",fontSize:13}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!e.nativeEvent.isComposing&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:7,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:6,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:f,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:n("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:f,style:{padding:"6px 10px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-contrast)",cursor:"pointer"},children:n("chat.submit")}):null]})]})})}function rZ({request:e,onInput:t}){let{t:n}=(0,T.s)(),o=(0,i.useRef)(null),l=(0,i.useRef)(!1),[s,a]=(0,i.useState)(!1),d=function(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(eB,""),i=eD(e).trimEnd();if(t.test(i))continue;let o=e,l=eU(o);("│"===l||"┃"===l)&&" "===eU(o=eO(o,0))&&(o=eO(o,0));let s=function(e){let t=eH(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=s>=0?eH(o)[s]?.char:void 0;("│"===a||"┃"===a)&&(o=eO(o,s)),n.push(function(e){let t=e;for(;;){let e=eH(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(o))}for(;n.length>0&&""===eD(n[0]).trim();)n.shift();for(;n.length>0&&""===eD(n[n.length-1]).trim();)n.pop();return n.length?n:e}(e.lines),c=d.find(e=>e.trim())?.trim();return(0,i.useEffect)(()=>{s||o.current?.focus()},[s]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(0,r.jsxs)("button",{type:"button",onClick:()=>a(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(920px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 12px 32px rgba(0,0,0,0.18)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{fontSize:11,fontWeight:650,color:"var(--accent)",flexShrink:0},children:n("chat.extensionPending")}),(0,r.jsx)("span",{style:{fontSize:13,fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:n("chat.extensionPanel")}),c&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"34%",flexShrink:1},children:c}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:n("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog",onClick:e=>{e.target.closest("button")||o.current?.focus()},style:{pointerEvents:"auto",position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 20px 60px rgba(0,0,0,0.28)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:o,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(l.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=eq[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":" ":e_[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(l.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{l.current=!0},onCompositionEnd:n=>{l.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("button",{type:"button",onClick:()=>a(!0),"aria-expanded":!0,title:n("chat.extensionCollapse"),"aria-label":n("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,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)(rh,{text:d.join("\n")})})]})})}var rG=n(50640);let rX={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"},rQ={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"},r0={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function r1(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}var r2=n(73620);let r4=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function r8(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)}let r5=["tags","categories","keywords","tag","category"];function r6({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,o=r5.find(t=>Array.isArray(e[t])),l=o?e[o].map(r8).filter(Boolean):[],s=n.filter(([e])=>e!==o&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),l.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:l.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),s.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:s.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=r8(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))})]})}let r3={source:"Source",preview:"Preview",diff:"Diff"},r9={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},r7={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:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function ie(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function it(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function ir(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=it(n.startContainer),i=it(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let o=Number(r.dataset.lineNumber),l=Number(i.dataset.lineNumber);if(!Number.isInteger(o)||!Number.isInteger(l))return null;if(o<l){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(o=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(l=Number((i=e).dataset.lineNumber))}}}return o>l?null:{startLine:o,endLine:l}}function ii({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,o)=>{let l=e.children??[],s=l[0]?.properties?.className,a=Array.isArray(s)&&s.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":o+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,rG.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${o}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,rG.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${o}-${r}`}))})]},`source-line-${o}`)})}function io(e,t,n,r={}){let i=B(e),o=new URLSearchParams({type:t});for(let[e,t]of(n&&o.set("sessionId",n),Object.entries(r)))void 0!==t&&o.set(e,String(t));return`/api/files/${i}?${o.toString()}`}function il({filePath:e,sourceSessionId:t}){let{t:n}=(0,T.s)();return(0,r.jsx)("a",{href:io(e,"download",t),download:D(e),title:n("i18n.downloadFile"),"aria-label":n("i18n.downloadFile"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function is(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ia({patch:e}){let t,{t:n}=(0,T.s)(),i=(t=tH(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];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})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let o=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),l=new Set;for(let e of o)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)l.add(t);let s=[],a=0;for(;a<i.length;)if(l.has(a)){let e=[];for(;a<i.length&&l.has(a);)e.push(i[a]),a++;s.push({hidden:!1,lines:e})}else{let e=0;for(;a<i.length&&!l.has(a);)e++,a++;s.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...r9},children:s.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:r7,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:o,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function id({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v=(0,i.useRef)(0),y=D(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),p(null),g(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),m.current&&(m.current.close(),m.current=null),!o)return;let t=!0,r=new EventSource(io(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(io(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&p(e.size),g(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}g(null),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,n,o]);let b=io(e,"read",n,d?{v:d}:void 0),j=null!=u?is(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:O(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"image"}),h&&(0,r.jsxs)("span",{children:[h.w," \xd7 ",h.h]}),j&&(0,r.jsx)("span",{children:j}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(il,{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:f?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:f}):(0,r.jsx)("img",{src:b,alt:e,onLoad:e=>{let t=e.currentTarget;g({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function ic(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 iu({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v=(0,i.useRef)(0),y=D(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),p(null),g(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),m.current&&(m.current.close(),m.current=null),!o)return;let t=!0,r=new EventSource(io(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(io(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&p(e.size),g(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}g(null),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,n,o]);let b=io(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:O(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=h&&(0,r.jsx)("span",{children:ic(h)}),null!=u&&(0,r.jsx)("span",{children:is(u)}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(il,{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:[f&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:f}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:b,onLoadedMetadata:e=>g(e.currentTarget.duration),onError:()=>x("Failed to load audio"),style:{width:"100%"}},b)]})})]})}function ip({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v=(0,i.useRef)(0),y=D(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),p(null),g(null),x(null),a(!1)},[e,n]),(0,i.useEffect)(()=>{if(a(!1),m.current&&(m.current.close(),m.current=null),!o)return;let t=!0,r=new EventSource(io(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(io(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===v.current){if(e.error)return void x(e.error);"number"==typeof e.size&&p(e.size),g(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}g(null),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,n,o]);let b=io(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:O(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=h&&(0,r.jsx)("span",{children:ic(h)}),null!=u&&(0,r.jsx)("span",{children:is(u)}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]}),(0,r.jsx)(il,{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:[f&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:f}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:b,onLoadedMetadata:e=>g(e.currentTarget.duration),onError:()=>x("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},b)]})})]})}function ih({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(null),f=(0,i.useRef)(null),x=(0,i.useRef)(0),m=r1(e),v="pdf"===m,y=v?io(e,"read",n,d?{v:d}:void 0):io(e,"preview",n,d?{v:d}:void 0);return(0,i.useEffect)(()=>{c(0),p(null),g(null),a(!1);let t=!0,r=++x.current;return fetch(io(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),!v&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===x.current&&g(String(e))}),()=>{t=!1}},[e,v,n]),(0,i.useEffect)(()=>{if(a(!1),f.current&&(f.current.close(),f.current=null),!o)return;let t=!0,r=new EventSource(io(e,"watch",n));f.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++x.current,fetch(io(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===x.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(p(e.size),!v&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),c(e=>e+1)}}).catch(e=>{t&&r===x.current&&g(String(e))})}),r.addEventListener("change",e=>{x.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(p(t.size),!v&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),f.current===r&&(f.current=null)}},[e,v,n,o]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:O(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===m?"docx preview":"pdf"}),null!=u&&(0,r.jsx)("span",{children:is(u)}),(0,r.jsx)(il,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:l(s?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:s?"#4ade80":"var(--border)",display:"inline-block",boxShadow:s?"0 0 4px #4ade80":"none"}}),s?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:h?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:h}):(0,r.jsx)("iframe",{src:y,sandbox:v?void 0:"allow-same-origin",title:l("i18n.previewFile",{file:D(e)}),style:{width:"100%",height:"100%",border:"none",background:v?"var(--bg)":"#eef1f5"}},y)})]})}function ig({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u=!0}){let p;return null!==(rX[r1(e)]??null)?(0,r.jsx)(id,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):null!==(rQ[r1(e)]??null)?(0,r.jsx)(iu,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):null!==(r0[r1(e)]??null)?(0,r.jsx)(ip,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):null!==("pdf"===(p=r1(e))||"docx"===p?p:null)?(0,r.jsx)(ih,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:u}):(0,r.jsx)(ix,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:c,watchEnabled:u})}function ix({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:o,onMentionLines:l,onAtMention:s,gitRefreshKey:a,initialDisplayMode:d,initialState:c,onStateChange:u,watchEnabled:p=!0}){let{isDark:h}=tL(),{t:g}=(0,T.s)(),[f,x]=(0,i.useState)(null),[m,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(!1),[j,w]=(0,i.useState)(!1),[k,S]=(0,i.useState)(!0),[C,M]=(0,i.useState)(!1),[E,I]=(0,i.useState)(null),R=c?.displayMode??d??"source",L=c?.wrapLines??!1,$=c?.scrollTop??0,N=c?.scrollLeft??0,[z,W]=(0,i.useState)(R),[P,A]=(0,i.useState)(L),[F,B]=(0,i.useState)(!1),D=(0,i.useRef)(null),U=(0,i.useRef)(0),_=(0,i.useRef)(0),q=(0,i.useRef)(null),K=(0,i.useRef)(!1),V=(0,i.useRef)(void 0===c&&void 0===d),J=(0,i.useRef)(!0),Y=(0,i.useRef)({displayMode:R,wrapLines:L,scrollTop:$,scrollLeft:N}),Z=(0,i.useRef)(u),[G,X]=(0,i.useState)(null);Z.current=u;let Q=(0,i.useCallback)(e=>{Y.current.displayMode=e,W(e)},[]),ee=(0,i.useCallback)(()=>{A(e=>{let t=!e;return Y.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(Y.current={displayMode:R,wrapLines:L,scrollTop:$,scrollLeft:N},J.current=!0,K.current=!1,W(R),A(L),()=>{Z.current?.({...Y.current})}),[e,n,R,L,$,N]);let et=(0,i.useCallback)((e,t=0)=>{let r=++U.current;return fetch(io(e,"read",n,{offset:t||void 0})).then(e=>e.json()).then(e=>r!==U.current?null:e.error?(I(e.error),null):(I(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(r!==U.current||I(String(e)),null))},[n]),en=(0,i.useCallback)(async e=>{let n=++_.current;if(b(!0),!t){v(null),b(!1),w(!0);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),o=await i.json();if(n!==_.current)return;v(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch{n===_.current&&v(null)}finally{n===_.current&&(b(!1),w(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;return S(!0),I(null),x(null),v(null),w(!1),B(!1),et(e).finally(()=>{t&&S(!1)}),()=>{t=!1}},[e,et,n]),(0,i.useEffect)(()=>{if(B(!1),D.current&&(D.current.close(),D.current=null),!p)return;let t=()=>{et(e),en(e)},r=new EventSource(io(e,"watch",n));D.current=r,r.addEventListener("connected",()=>{B(!0),t()}),r.addEventListener("change",t);let i=()=>{B(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{r.close(),D.current===r&&(D.current=null)}},[e,et,en,n,p]),(0,i.useEffect)(()=>{en(e)},[en,e,a]),(0,i.useEffect)(()=>{V.current&&!f?.truncated&&(f?.language==="markdown"||f?.language==="html")&&(V.current=!1,Q("preview"))},[f?.language,f?.truncated,Q]);let er=m?.supported===!0&&"string"==typeof m.patch,ei=er&&"deleted"===m.status;(0,i.useEffect)(()=>{j&&!er&&"diff"===z&&Q("source")},[z,j,er,Q]),(0,i.useEffect)(()=>{"diff"===R&&er&&!K.current&&(K.current=!0,Q("diff"))},[R,er,Q]);let eo=(0,i.useMemo)(()=>f?.language==="markdown"?to(f.content):"",[f]),el=(0,i.useMemo)(()=>f?.language==="markdown"?function(e){let t=function(e){let t=r4.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,r2.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(f.content):null,[f]),es=f?.content??"",ea=(0,i.useMemo)(()=>es.split("\n"),[es]),ed=f?.language??"text",ec="html"===ed,eu="markdown"===ed,ep=!f?.truncated&&(ec||eu),eh=ei?"diff":z,eg=ea.length>1e3&&!("diff"===eh&&er)&&!("preview"===eh&&ep),ef=(0,i.useMemo)(()=>(0,r.jsx)(th.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"===ed?"plaintext":ed,style:h?tg.xJ:tg.vs,showLineNumbers:!0,lineNumberStyle:{...r7},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...r9,width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:P?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(ii,{...e,wrapLines:P}),wrapLongLines:P,children:es}),[h,ed,es,P]),ex=(0,i.useMemo)(()=>eg?ea.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:r7,children:t+1}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:P?"anywhere":"normal",whiteSpace:P?"pre-wrap":"pre"},children:e})]},`source-line-${t}`)):null,[ea,eg,P]);(0,i.useEffect)(()=>{let e=()=>{let e=q.current;X(t=>{let n=l&&"source"===z&&e?ir(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"===z)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[f?.content,z,l]);let em=(0,i.useCallback)(n=>{l&&n&&l(O(e,t),n.startLine,n.endLine)},[t,e,l]);if((0,i.useEffect)(()=>{if(!l||"source"!==z)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=q.current,r=n?ir(n,window.getSelection()):null;r&&(e.preventDefault(),em(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[z,em,l]),(0,i.useEffect)(()=>{if(!J.current||k||E&&!ei||"diff"===R&&!j||"diff"===R&&er&&"diff"!==z)return;let e=q.current;e&&(e.scrollTop=Y.current.scrollTop,e.scrollLeft=Y.current.scrollLeft,J.current=!1)},[f?.content,z,E,j,er,ei,k,R]),k||"diff"===R&&y&&!f)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:g("i18n.loading")});if(E&&!ei)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:E});if(!f&&!ei)return null;let ev=H(e),ey=ei?["diff"]:["source",...ep?["preview"]:[],...er?["diff"]:[]],eb=ei?g("files.deleted"):`${ed} \xb7 ${ea.length} lines \xb7 ${is(f.size)}`;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:O(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eb,children:eb}),!ei&&(0,r.jsx)("span",{title:F?g("i18n.liveSync"):g("i18n.notWatching"),"aria-label":F?g("i18n.liveSync"):g("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:F?"#4ade80":"var(--border)",boxShadow:F?"0 0 4px #4ade80":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",children:[ey.length>1&&(0,r.jsx)("div",{className:"file-viewer-mode-switch","aria-label":g("i18n.fileViewMode"),children:ey.map(e=>{let t=eh===e;return(0,r.jsx)("button",{type:"button",onClick:()=>Q(e),title:"diff"===e?g("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:r3[e]},e)})}),(0,r.jsxs)("div",{className:"file-viewer-actions",children:[(s||l)&&(0,r.jsx)("button",{type:"button",onPointerDown:e=>e.preventDefault(),onClick:()=>{G&&l?em(G):s?.(O(e,t),!1)},title:G&&l?`${g("i18n.mentionSelectedLines")} (L${G.startLine}${G.startLine!==G.endLine?`-L${G.endLine}`:""})`:g("files.insertPath"),"aria-label":g("files.mention"),disabled:!s&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(ie,{})}),"source"===eh&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:ee,title:P?g("i18n.disableWrap"):g("i18n.enableWrap"),"aria-label":P?g("i18n.disableWrap"):g("i18n.enableWrap"),"aria-pressed":P,className:"file-viewer-icon-button",style:{background:P?"var(--bg-selected)":"transparent",color:P?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})})})]}),!ei&&(0,r.jsx)(il,{filePath:e,sourceSessionId:n})]})]}),f?.truncated&&(0,r.jsxs)("div",{className:"file-viewer-load-more",style:{display:"flex",alignItems:"center",justifyContent:"center",gap:10,padding:"5px 8px",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-dim)",fontSize:11},children:[(0,r.jsxs)("span",{children:[is(f.nextOffset)," / ",is(f.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:C,onClick:()=>{M(!0),et(e,f.nextOffset).finally(()=>M(!1))},children:C?g("i18n.loading"):g("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:q,className:"file-viewer-content",onScroll:e=>{Y.current.scrollTop=e.currentTarget.scrollTop,Y.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:f?.truncated?48:void 0},children:"diff"===eh&&er?(0,r.jsx)(ia,{patch:m.patch}):ec&&"preview"===eh?(0,r.jsx)("iframe",{srcDoc:es,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:g("i18n.htmlPreview")}):eu&&"preview"===eh?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[el?.data&&(0,r.jsx)(r6,{data:el.data}),(0,r.jsx)(e8.oz,{remarkPlugins:tc,rehypePlugins:tp,urlTransform:o?tr:void 0,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",o=String(t);return e?.includes("language-")||o.includes("\n")?"mermaid"===i?(0,r.jsx)(tN,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tW,{code:o.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let l=o?e1(e,ev,t??ev):null;return l&&o?(0,r.jsx)("a",{href:e,...i,onClick:e=>{eG(e)&&(e.preventDefault(),o(l))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...o}){delete o.node;let l="string"==typeof e?e1(e,ev,t??ev):null,s=l?io(l,"read",n):e;return(0,r.jsx)("img",{src:s,alt:i??"",loading:"lazy",...o})}},children:eo})]}):eg?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...r9},children:ex}):ef})]})}function im({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:o}){let{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(null);return(0,r.jsx)("div",{role:"tablist",style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(i=>{let d=i.id===t;return(0,r.jsxs)("div",{role:"tab","aria-label":"terminal"===i.kind?l("terminal.tabLabel",{name:i.label}):i.label,"aria-selected":d,tabIndex:d||!t&&e[0].id===i.id?0:-1,onKeyDown:t=>{if(t.target===t.currentTarget){if("Enter"===t.key||" "===t.key)t.preventDefault(),n(i.id);else if(["ArrowLeft","ArrowRight","Home","End"].includes(t.key)){t.preventDefault();let r=e.findIndex(e=>e.id===i.id),o="Home"===t.key?0:"End"===t.key?e.length-1:(r+("ArrowRight"===t.key?1:-1)+e.length)%e.length;n(e[o].id),t.currentTarget.parentElement?.children[o]?.focus()}}},onClick:()=>n(i.id),onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),e.stopPropagation(),i.closing||o(i.id))},style:{display:"flex",alignItems:"center",gap:6,height:36,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:d?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:d?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:d?1:.7,display:"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","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,fontWeight:d?500:400},title:i.filePath,children:i.label}),(0,r.jsx)("button",{disabled:i.closing,onClick:e=>{e.stopPropagation(),o(i.id)},onMouseEnter:()=>a(i.id),onMouseLeave:()=>a(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:s===i.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:s===i.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:l("terminal"===i.kind?"terminal.close":"i18n.close"),"aria-label":`${l("terminal"===i.kind?"terminal.close":"i18n.close")} ${i.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},i.id)})})}function iv({preference:e,size:t=17}){let n={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"light"===e?(0,r.jsxs)("svg",{...n,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",{...n,children:(0,r.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"})}):"mist"===e?(0,r.jsxs)("svg",{...n,children:[(0,r.jsx)("path",{d:"M12 3S6 10 6 14a6 6 0 0 0 12 0c0-4-6-11-6-11Z"}),(0,r.jsx)("path",{d:"M9 15c.5 1.4 1.5 2.2 3 2.5"})]}):"rose"===e?(0,r.jsxs)("svg",{...n,children:[(0,r.jsx)("path",{d:"M12 13.5c-3.2 0-5.5-1.8-5.5-4.6S8.6 4.2 11.8 4.2c2.7 0 4.8 1.7 4.8 4.2 0 2.2-1.6 3.7-3.8 3.7-1.8 0-3-1-3-2.4 0-1.2.9-2 2-2 1 0 1.6.5 1.6 1.3"}),(0,r.jsx)("path",{d:"M12 13.5v7.5M12 18c-1.7-1.8-3.6-2.2-5.2-1.2 1.1 1.9 3.1 2.6 5.2 1.2ZM12 17c1.3-2 3.3-2.4 5-1.5-1.1 1.8-3 2.4-5 1.5Z"})]}):"pine"===e?(0,r.jsxs)("svg",{...n,children:[(0,r.jsx)("path",{d:"M12 3c-.9 2.5-2.3 4.2-4.5 6h3c-1 2.1-2.6 3.7-5 5.3h4c-.7 2-1.9 3.8-3.7 5.4h12.4c-1.8-1.6-3-3.4-3.7-5.4h4c-2.4-1.6-4-3.2-5-5.3h3c-2.2-1.8-3.6-3.5-4.5-6Z"}),(0,r.jsx)("path",{d:"M12 20v2"})]}):(0,r.jsxs)("svg",{...n,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M8 21h8M12 17v4"})]})}let iy=["general","models","archives","skills","agents","plugins"],ib="pi-web:settings-navigation",ij=new Set(["skills","agents","plugins"]);function iw(){try{return window.localStorage}catch{return null}}function ik(e){let t=e.getItem(ib);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 iS(e,t){return"models"===e?e:t?JSON.stringify([e,t]):null}function iC(e,t=iw()){if(t)try{let n=ik(t);n.section=e,t.setItem(ib,JSON.stringify(n))}catch{}}function iT(e,t,n=iw()){if(!n)return null;let r=iS(e,t);if(!r)return null;try{let e=ik(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function iM(e,t,n,r=iw()){if(!r||!t)return;let i=iS(e,n);if(i)try{let e=ik(r);e.selections={...e.selections,[i]:t},r.setItem(ib,JSON.stringify(e))}catch{}}let iE=["input","output","cacheRead","cacheWrite"];function iI(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 iR(e){if(!iL(e))return;let t=e=>{if(!e.trim())return 0;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0},n=t(e.input),r=t(e.output),i=t(e.cacheRead),o=t(e.cacheWrite);if(void 0!==n&&void 0!==r&&void 0!==i&&void 0!==o)return{input:n,output:r,cacheRead:i,cacheWrite:o}}function iL(e){return iE.some(t=>""!==e[t].trim())}function i$({embedded:e,title:t,subtitle:n,closeLabel:i="Close",onClose:o,children:l,width:s=900,height:a="78vh"}){let d=e?void 0:{"--config-panel-width":`${s}px`,"--config-panel-height":a};return(0,r.jsx)("div",{role:e?void 0:"dialog","aria-modal":e?void 0:"true","aria-label":t,className:`config-panel-root ${e?"is-embedded":"is-modal"}`,onClick:t=>{e||t.target!==t.currentTarget||o()},children:(0,r.jsxs)("div",{className:"config-panel-surface",style:d,children:[!e&&(0,r.jsxs)("div",{className:"config-panel-header",children:[(0,r.jsx)("strong",{className:"config-panel-title",children:t}),n&&(0,r.jsx)("code",{className:"config-panel-subtitle",title:n,children:n}),(0,r.jsx)("button",{type:"button",className:"config-close-button",onClick:o,title:i,"aria-label":i,children:"\xd7"})]}),l]})})}function iN({children:e}){return(0,r.jsx)("div",{className:"config-split-view",children:e})}function iz({children:e}){return(0,r.jsx)("aside",{className:"config-sidebar",children:e})}function iW({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-list",children:e})}function iP({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-group-label",children:e})}function iA({active:e=!1,className:t,children:n,...i}){return(0,r.jsx)("button",{type:"button",...i,"aria-current":e?"page":void 0,className:["config-sidebar-item",t].filter(Boolean).join(" "),children:n})}function iF({className:e,...t}){return(0,r.jsx)("span",{...t,className:["config-sidebar-text",e].filter(Boolean).join(" ")})}function iB({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-stack",e].filter(Boolean).join(" ")})}function iD({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header",e].filter(Boolean).join(" ")})}function iH({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header-info",e].filter(Boolean).join(" ")})}function iO({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-actions",e].filter(Boolean).join(" ")})}function iU({children:e}){return(0,r.jsx)("div",{className:"config-detail-title",children:e})}function i_({children:e}){return(0,r.jsx)("div",{className:"config-section-title",children:e})}function iq({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 iK({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function iV({children:e,style:t}){return(0,r.jsx)("div",{className:"config-detail",style:t,children:e})}function iJ({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 iY({variant:e="secondary",size:t="default",className:n,children:i,...o}){return(0,r.jsx)("button",{type:"button",...o,className:["config-button",`config-button-${e}`,`config-button-${t}`,n].filter(Boolean).join(" "),children:i})}function iZ({checked:e,disabled:t=!1,loading:n=!1,label:i,onChange:o}){let l=t||n;return(0,r.jsx)("button",{type:"button",role:"switch","aria-checked":e,"aria-busy":n||void 0,"aria-label":i,title:i,disabled:l,className:`config-switch${n?" is-loading":""}`,onClick:()=>o(!e),children:(0,r.jsx)("span",{className:"config-switch-knob","aria-hidden":"true"})})}function iG({active:e=!1,children:t,className:n,...i}){return(0,r.jsx)("div",{className:"config-list-action",children:(0,r.jsxs)("button",{type:"button",...i,"aria-current":e?"page":void 0,className:["config-list-action-button",n].filter(Boolean).join(" "),children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})}),t]})})}function iX({active:e,color:t}){return(0,r.jsx)("span",{"aria-hidden":"true",className:`config-status-dot${e?" is-active":!1===e?" is-inactive":""}`,style:t?{backgroundColor:t}:void 0})}let iQ={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 i0({id:e,size:t}){let n=iQ[e];if(n)return(0,r.jsx)("svg",{"aria-hidden":"true",width:t,height:t,viewBox:"0 0 24 24",fill:n.color?void 0:"currentColor",style:{color:"var(--text-muted)",flexShrink:0},children:(0,r.jsx)("use",{href:`/provider-icons.svg#${n.symbol}`})});let i=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:i})}let i1=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway"],i2="pi-web:provider-usage:";function i4({providerId:e,enabled:t}){return i1.includes(e)?(0,r.jsx)(i8,{providerId:e,enabled:t}):null}function i8({providerId:e,enabled:t}){let[n,o]=(0,i.useState)(null),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),p=(0,i.useRef)(null),{t:h}=(0,T.s)();(0,i.useEffect)(()=>{p.current&&clearTimeout(p.current),u(!1),o(null);try{let t=localStorage.getItem(`${i2}${e}`);if(t){let e=JSON.parse(t);e?.status==="ready"&&e.report&&Array.isArray(e.report.buckets)&&Array.isArray(e.report.metrics)&&o(e)}}catch{try{localStorage.removeItem(`${i2}${e}`)}catch{}}return d(null),()=>{p.current&&clearTimeout(p.current)}},[e]);let g=(0,i.useCallback)(async()=>{s(!0),d(null);try{let t=await fetch("/api/provider-usage/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);if("ready"===n.status){o(n);try{localStorage.setItem(`${i2}${e}`,JSON.stringify(n))}catch{}u(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>u(!1),2e3)}else d(n.message??h("providerUsage.queryFailed"))}catch(e){d(e instanceof Error?e.message:h("providerUsage.queryFailed"))}finally{s(!1)}},[e,h]),f=n?.status==="ready"?n.report:void 0;return(0,r.jsxs)("section",{style:{paddingTop:10,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:13,color:"var(--text)",fontWeight:600,lineHeight:1.35},children:h("providerUsage.usage")}),(0,r.jsx)("button",{type:"button",onClick:g,disabled:!t||l,title:h(l?"providerUsage.refreshing":"providerUsage.refresh"),"aria-label":h(l?"providerUsage.refreshing":"providerUsage.refresh"),style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:32,height:30,padding:0,background:"none",border:"none",color:c?"#4ade80":"var(--text-dim)",cursor:t&&!l?"pointer":"default",borderRadius:5,flexShrink:0,opacity:t?1:.6,transition:"color 0.3s"},children:c?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:l?{animation:"spin 0.8s linear infinite"}:void 0,"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 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:h("providerUsage.updated",{time:new Date(f.capturedAt).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})})]}),!f&&!a&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-dim)"},children:h("providerUsage.notQueried")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171"},children:a}),f&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr)",columnGap:14,rowGap:8,alignItems:"baseline",minWidth:0,width:"min(100%, 420px)",maxWidth:"100%",fontSize:12},children:[f.buckets.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.groupLabel?`${e.groupLabel} / ${e.label}`:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:function(e,t){if("percent"===e.unit&&void 0!==e.remaining){let t=e.resetsAt?` / ${new Date(1e3*e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:"";return`${Math.round(e.remaining)}%${t}`}return"currency"===e.unit?`${"CNY"===e.currency?"CNY ":"$"}${i5(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${i5(e.remaining)} / ${i5(e.limit)}`:e.period??t}(e,h("providerUsage.available"))})]},e.id)),f.metrics.map(e=>{var t;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("span",{style:{color:"var(--text)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:"currency"===(t=e).unit?`${"CNY"===t.currency?"CNY ":"$"}${t.value}`:String(t.value)})]},e.id)})]})]})}function i5(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function i6(){let e=iT("models");if(!e)return null;try{let t=JSON.parse(e);if(null===t||"object"!=typeof t)return null;if("provider"===t.type&&"string"==typeof t.name)return{type:"provider",name:t.name};if("model"===t.type&&"string"==typeof t.providerName&&"number"==typeof t.index&&Number.isInteger(t.index)&&t.index>=0)return{type:"model",providerName:t.providerName,index:t.index};if(("oauth"===t.type||"apikey"===t.type)&&"string"==typeof t.providerId)return{type:t.type,providerId:t.providerId}}catch{}return null}let i3=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function i9({label:e,children:t}){return(0,r.jsx)(iq,{label:e,children:t})}let i7={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function oe({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...i7,fontFamily:i?"var(--font-mono)":"inherit"}})}function ot({value:e,onChange:t,placeholder:n,mono:o,onKeyDown:l,autoComplete:s="off",spellCheck:a=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,T.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:n,style:{...i7,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:s,spellCheck:a}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(c?"i18n.hideDetails":"i18n.showDetails"),title:p(c?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:c?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function on({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:i7})}function or({value:e,onChange:t,options:n,required:i}){let{t:o}=(0,T.s)();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...i7,color:e?"var(--text)":"var(--text-dim)"},children:[!i&&(0,r.jsxs)("option",{value:"",children:["— ",o("i18n.default")," / none —"]}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function oi({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function oo({children:e}){return(0,r.jsx)(i_,{children:e})}function ol({name:e,provider:t,onChange:n,onRename:o,onDelete:l,onAddModels:s}){let{t:a}=(0,T.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,g]=(0,i.useState)(""),[f,x]=(0,i.useState)([]),m=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let y=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{m.current+=1,p({phase:"idle"}),g(""),x([])},[e,t.baseUrl,t.api,t.apiKey]);let b=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++m.current;p({phase:"loading"}),x([]);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!==m.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==m.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),j=new Set((t.models??[]).map(e=>e.id)),w="success"===u.phase?u.models:[],k=h.trim().toLocaleLowerCase(),S=w.filter(e=>!k||e.id.toLocaleLowerCase().includes(k)||e.name?.toLocaleLowerCase().includes(k)),C=S.slice(0,300),M=C.filter(e=>!j.has(e.id)).map(e=>e.id),E=f.filter(e=>!j.has(e)).length,I=M.length>0&&M.every(e=>f.includes(e)),R=!I&&M.some(e=>f.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=R)},[R]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(iD,{children:[(0,r.jsx)(iH,{children:(0,r.jsx)(oo,{children:a("i18n.provider")})}),(0,r.jsx)(iO,{children:(0,r.jsx)(iY,{variant:"danger",size:"small",onClick:l,children:a("i18n.delete")})})]}),(0,r.jsxs)(i9,{label:a("i18n.providerName"),children:[(0,r.jsx)(oe,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>o(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"var(--accent-contrast)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:a("i18n.rename")})]}),(0,r.jsx)(i9,{label:"Base URL",children:(0,r.jsx)(oe,{value:t.baseUrl??"",onChange:e=>y("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(i9,{label:"API Key",children:[(0,r.jsx)(ot,{value:t.apiKey??"",onChange:e=>y("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(i9,{label:"API",children:(0,r.jsx)(or,{value:t.api??"openai-completions",onChange:e=>y("api",e),options:i3,required:!0})}),(0,r.jsxs)(i9,{label:"Headers",children:[(0,r.jsx)(op,{headers:t.headers,onChange:e=>y("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:b,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?a("models.discoveryFetching"):a("models.discoveryFetch")}),"error"===u.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>g(e.target.value),placeholder:a("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":a("models.discoveryFilter"),style:{...i7,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:M.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:I,disabled:0===M.length,onChange:()=>{let e=new Set(M);x(t=>I?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...M])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),a("models.discoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:a("models.discoveryNoMatches")}):C.map((e,t)=>{let n=j.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void x(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:a("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?a("models.discoveryShowing",{shown:C.length,total:S.length}):a("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!j.has(t.id));0!==t.length&&(s(t),x([]))},disabled:0===E,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:E?"var(--accent)":"var(--bg-panel)",color:E?"var(--accent-contrast)":"var(--text-dim)",cursor:E?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:E?a("models.discoveryAddSelectedCount",{count:E}):a("models.discoveryAddSelected")})]})]})]})]})}let os=["off","minimal","low","medium","high","xhigh","max"],oa={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function od({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:os.map(e=>{let t=n[e],o=e in n?null===t?"null":"string":"omit",l="string"==typeof t?t:"",s=oa[e],a={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--accent)",color:"var(--accent-contrast)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:s,flexShrink:0,opacity:"null"===o?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===o?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===o?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...a,..."omit"===o?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...a,borderLeft:"1px solid var(--border)",..."null"===o?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===o?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,l||e),style:{...a,..."string"===o?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:l,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==o&&i(e,l||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===o?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===o?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let oc={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function ou(e){return e.compat?.thinkingFormat==="deepseek"}function op({headers:e,onChange:t}){let[n,o]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),l=(0,i.useRef)(n.length),s=e=>{o(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},a=(e,t)=>{s(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>a(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...i7,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>a(e.id,{value:t.target.value}),placeholder:"value",style:{...i7,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void s(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>o(e=>[...e,{id:l.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function oh({providerName:e,provider:t,model:n,onChange:o,onDelete:l}){let[s,a]=(0,i.useState)({phase:"idle"}),{t:d}=(0,T.s)(),[c,u]=(0,i.useState)({phase:"idle"}),[p,h]=(0,i.useState)(!1),[g,f]=(0,i.useState)(()=>iI(n.cost)),x=(0,i.useRef)(g),[m,v]=(0,i.useState)(!1),y=(0,i.useRef)(0),b=(0,i.useRef)(null),j=(0,i.useRef)(n.cost),w=(e,t)=>o({...n,[e]:t}),k=(()=>{if("idle"===s.phase)return null;if("testing"===s.phase)return d("i18n.testingModel");let e=[void 0!==s.latencyMs?`${s.latencyMs}ms`:null,void 0!==s.status?`HTTP ${s.status}`:null].filter(Boolean);return"success"===s.phase?[d("i18n.connected"),...e,s.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,s.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{a({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{y.current+=1,u({phase:"idle"}),b.current=null},[e,t.baseUrl,n.id]);let S=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==s.phase){a({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})}),i=await r.json();if(!r.ok||!i.ok)return void a({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});a({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){a({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,s.phase]),C=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===c.phase)return;let i=++y.current;u({phase:"loading"});try{let l=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&l.set("baseUrl",t.baseUrl.trim());let s=await fetch(`/api/models-config/catalog?${l}`),a=await s.json();if(i!==y.current)return;if(!s.ok||a.error||!a.recommendation)return void u({phase:"error",message:a.error??`HTTP ${s.status}`});let d=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},o=0;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],o+=1);let l=iR(iI(i));o>0&&l&&(n.cost={...i,...l},r+=o)}return{model:n,appliedCount:r}}(n,a.recommendation.preset);d.appliedCount>0&&(b.current=n,o(d.model)),h(!1),u({phase:"success",recommendation:a.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==y.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,n,o,t.baseUrl,e]),M=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:n}=c,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?d("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?d("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):d("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),E="error"===c.phase?c.message:M,I="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)",R=[{key:"input",label:d("models.costInput")},{key:"output",label:d("models.costOutput")},{key:"cacheRead",label:d("models.costCacheRead")},{key:"cacheWrite",label:d("models.costCacheWrite")}],L=new Set(Object.keys(n.compat??{})),$=0;ou(n)&&($+=1,L.delete("thinkingFormat"),L.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&($+=1,L.delete("supportsDeveloperRole")),$+=L.size;let N=[n.api?`API: ${n.api}`:null,Object.keys(n.headers??{}).length?d("models.headersSummary",{count:Object.keys(n.headers??{}).length}):null,$?d("models.compatSummary",{count:$}):null,Object.keys(n.thinkingLevelMap??{}).length?d("models.thinkingSummary",{count:Object.keys(n.thinkingLevelMap??{}).length}):null].filter(e=>!!e),z=N.length?N.join(" \xb7 "):d("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(iD,{children:[(0,r.jsx)(iH,{children:(0,r.jsx)(oo,{children:d("i18n.model")})}),(0,r.jsxs)(iO,{children:[k&&(0,r.jsx)("span",{title:k,style:{maxWidth:260,height:28,padding:"0 8px",border:`1px solid ${"error"===s.phase?"#fecaca":"success"===s.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===s.phase?"#fee2e2":"success"===s.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:k}),(0,r.jsxs)(iY,{size:"small",variant:"success"===s.phase?"primary":"secondary",onClick:"success"===s.phase?()=>a({phase:"idle"}):S,disabled:!n.id.trim()||"testing"===s.phase,title:d("i18n.testConnection"),className:"success"===s.phase?"is-success":void 0,children:["success"===s.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===s.phase?d("i18n.checking"):"success"===s.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)(iY,{variant:"danger",size:"small",onClick:l,children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(i9,{label:"ID *",children:(0,r.jsx)(oe,{value:n.id,onChange:e=>w("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(i9,{label:"Name",children:(0,r.jsx)(oe,{value:n.name??"",onChange:e=>w("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"2px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void C(),disabled:!n.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),E&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:I,fontSize:10},children:[(0,r.jsx)("span",{title:E,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E}),b.current&&(0,r.jsx)("button",{onClick:()=>{let e=b.current;e&&(b.current=null,o(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(oo,{children:d("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(oi,{label:d("models.reasoning"),checked:n.reasoning??!1,onChange:e=>w("reasoning",e||void 0)}),(0,r.jsx)(oi,{label:d("models.imageInput"),checked:n.input?.includes("image")??!1,onChange:e=>w("input",e?["text","image"]:void 0)})]})]}),(0,r.jsxs)("section",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[(0,r.jsx)(oo,{children:d("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(p)return void h(!1);j.current=n.cost;let e=iI(n.cost);x.current=e,f(e),h(!0)},"aria-expanded":p,style:{padding:"2px 4px",border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:10},children:p?d("models.finishEditingCosts"):d("models.editCosts")})]}),(0,r.jsxs)("div",{style:{marginTop:10,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10},children:[(0,r.jsx)(i9,{label:d("models.contextWindow"),children:(0,r.jsx)(on,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>w("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(i9,{label:d("models.maxOutputTokens"),children:(0,r.jsx)(on,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>w("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{style:{marginTop:16},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontWeight:600,textTransform:"uppercase"},children:d("models.costPerMillion")}),p?(0,r.jsxs)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(110px, 1fr))",gap:8},children:[R.map(({key:e,label:t})=>(0,r.jsx)(i9,{label:t,children:(0,r.jsx)(on,{value:g[e],onChange:t=>{let r,i,l;return i=iR(r={...x.current,[e]:t}),l={...n},void(x.current=r,f(r),i?(l.cost={...j.current??{},...i},j.current=l.cost):delete l.cost,o(l))},placeholder:"0"})},e)),iL(g)&&!iR(g)&&(0,r.jsx)("div",{"aria-live":"polite",style:{gridColumn:"1 / -1",color:"#d97706",fontSize:10},children:d("models.costAllRequired")})]}):(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(105px, 1fr))",gap:"8px 16px"},children:R.map(({key:e,label:t})=>{let i,o=n.cost?.[e]===void 0;return(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t}),(0,r.jsx)("div",{style:{marginTop:3,color:o?"var(--text-dim)":"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums"},children:void 0===(i=n.cost?.[e])?d("models.notProvided"):`$${String(i)}`})]},e)})})]})]}),(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",paddingTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>v(e=>!e),"aria-expanded":m,"aria-controls":"model-advanced-settings",style:{width:"100%",minHeight:48,padding:"8px 0",border:"none",background:"transparent",display:"grid",gridTemplateColumns:"minmax(0, 1fr) 18px",alignItems:"center",gap:10,color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:11,fontWeight:600},children:d("models.advancedSettings")}),(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-dim)",fontSize:10,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z})]}),(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{color:"var(--text-dim)",transform:m?"rotate(180deg)":"none",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),m&&(0,r.jsxs)("div",{id:"model-advanced-settings",style:{display:"flex",flexDirection:"column",gap:14,padding:"4px 0 16px"},children:[(0,r.jsx)(i9,{label:d("models.apiOverride"),children:(0,r.jsx)(or,{value:n.api??"",onChange:e=>w("api",e||void 0),options:i3})}),(0,r.jsxs)(i9,{label:d("models.headers"),children:[(0,r.jsx)(op,{headers:n.headers,onChange:e=>w("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("models.headersHelp")})]}),n.reasoning&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(oo,{children:d("models.compatibility")}),(0,r.jsx)(oi,{label:d("models.deepSeekThinkingCompat"),checked:ou(n),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oc}};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)(oi,{label:d("models.developerRole"),checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>o({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{style:{marginTop:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,marginBottom:8},children:[(0,r.jsx)(oo,{children:d("models.thinkingLevelMap")}),n.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>w("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 5px",background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer"},children:d("models.clearAll")})]}),(0,r.jsx)(od,{value:n.thinkingLevelMap,onChange:e=>w("thinkingLevelMap",e)})]})]})]})]})]})}function og({provider:e,onRefresh:t}){let[n,o]=(0,i.useState)({phase:"idle"}),{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(""),d=(0,i.useRef)(null),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===n.phase||"prompt"===n.phase)&&setTimeout(()=>c.current?.focus(),50)},[n.phase]),(0,i.useEffect)(()=>{o({phase:"idle"}),a(""),d.current?.close(),d.current=null},[e.id]),(0,i.useEffect)(()=>()=>{d.current?.close()},[]);let u=(0,i.useCallback)(()=>{d.current?.close(),o({phase:"connecting"}),a("");let n=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);d.current=n,n.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(o({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(o({phase:"device_code",userCode:r.userCode,verificationUri:r.verificationUri,intervalSeconds:r.intervalSeconds??null,expiresInSeconds:r.expiresInSeconds??null}),window.open(r.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===r.type?o({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?o({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?o({phase:"progress",message:r.message}):"success"===r.type?(n.close(),o({phase:"success"}),t()):"error"===r.type?(n.close(),o({phase:"error",message:r.message})):"cancelled"===r.type&&(n.close(),o({phase:"idle"}))},n.onerror=()=>{n.close(),o(e=>"success"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,t]),p=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),o({phase:"idle"}),t()},[e.id,t]),h=(0,i.useCallback)(async(t,n)=>{if(n.trim()){o({phase:"progress",message:"Verifying…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n.trim()})});if(!r.ok){let e=await r.json().catch(()=>({}));o({phase:"error",message:e.error??`Server error ${r.status}`});return}a("")}catch(e){o({phase:"error",message:e instanceof Error?e.message:"Network error"})}}},[e.id]),g=(0,i.useCallback)(async(t,n)=>{o({phase:"progress",message:"Continuing…"});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!r.ok){let e=await r.json().catch(()=>({}));o({phase:"error",message:e.error??`Server error ${r.status}`})}}catch(e){o({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id]),f="connecting"===n.phase||"progress"===n.phase||"auth"===n.phase||"device_code"===n.phase||"prompt"===n.phase||"select"===n.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:e.loggedIn&&"idle"===n.phase?0:16},children:[(0,r.jsxs)(iD,{children:[(0,r.jsx)(iH,{children:(0,r.jsx)(oo,{children:l("i18n.subscription")})}),(0,r.jsxs)(iO,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:l(e.loggedIn?"i18n.connected":"i18n.notConnected")})]}),f?(0,r.jsx)(iY,{size:"small",onClick:()=>{d.current?.close(),o({phase:"idle"})},children:l("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(iY,{variant:"primary",size:"small",onClick:u,children:l(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&(0,r.jsx)(iY,{variant:"danger",size:"small",onClick:p,children:l("i18n.disconnect")})]})]})]}),(0,r.jsxs)("div",{style:{minHeight:e.loggedIn&&"idle"===n.phase?0:48},children:["idle"===n.phase&&!e.loggedIn&&(0,r.jsxs)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:["Connect your ",e.name," account."]}),"connecting"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:l("i18n.openingBrowser")}),"select"===n.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:n.options.map(e=>(0,r.jsx)("button",{onClick:()=>g(n.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===n.phase||"prompt"===n.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===n.phase?"Complete sign-in in the browser, then copy the redirect URL from the address bar and paste it below.":n.message}),"auth"===n.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:c,value:s,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(n.token,s)},placeholder:"auth"===n.phase?"http://localhost:1455/auth/callback?code=…":n.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>h(n.token,s),disabled:!s.trim(),style:{padding:"6px 12px",background:s.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:s.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:s.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:l("i18n.submit")})]})]}),"device_code"===n.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:n.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:n.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:n.verificationUri}),n.expiresInSeconds?` Expires in ${Math.ceil(n.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:n.message}),"success"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:l("i18n.connectedSuccessfully")}),"error"===n.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:n.message})]}),(0,r.jsx)(i4,{providerId:e.id,enabled:e.loggedIn})]})}function of({provider:e,onRefresh:t}){let[n,o]=(0,i.useState)(""),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:g}=(0,T.s)();(0,i.useEffect)(()=>{o(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){s(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(o(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{s(!1)}}},[n,e.id,t]),x=(0,i.useCallback)(async()=>{d(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(iD,{children:[(0,r.jsx)(iH,{children:(0,r.jsx)(oo,{children:"API Key"})}),(0,r.jsxs)(iO,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:g(e.configured?"i18n.configured":"i18n.notConfigured")})]}),e.configured&&(0,r.jsx)(iY,{variant:"danger",size:"small",onClick:x,disabled:a,children:g(a?"i18n.removing":"i18n.disconnect")})]})]}),!e.configured&&(0,r.jsxs)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:["Enter your ",e.displayName," API key to enable ",e.modelCount," model",1!==e.modelCount?"s":"","."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(ot,{value:n,onChange:o,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:l||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--accent-contrast)":"var(--text-dim)",cursor:l||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),g(p?"i18n.saved":l?"i18n.saving":"i18n.save")]})]}),c&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),(0,r.jsx)(i4,{providerId:e.id,enabled:e.configured})]})}function ox({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:o,onAddCustom:l,onClose:s}){let[a,d]=(0,i.useState)(""),{t:c}=(0,T.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=a.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),g=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),x=h.length+g.length+ +!!f,m={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&s()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),s())},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:u,value:a,onChange:e=>d(e.target.value),placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===x?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{l(),s()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),s()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(i0,{id:e.id,size:28})]},e.id)),g.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),g.map(e=>(0,r.jsxs)("button",{onClick:()=>{o(e.id),s()},style:m,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(i0,{id:e.id,size:28})]},e.id))]})})]})})}function om({onClose:e,embedded:t=!1}){let{t:n}=(0,T.s)(),[o,l]=(0,i.useState)({providers:{}}),[s,a]=(0,i.useState)(!0),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,g]=(0,i.useState)(!1),[f,x]=(0,i.useState)(i6),[m,v]=(0,i.useState)([]),[y,b]=(0,i.useState)([]),[j,w]=(0,i.useState)(!1),k=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>{Array.isArray(e.oauthProviders)&&v(e.oauthProviders),Array.isArray(e.apiKeyProviders)&&b(e.apiKeyProviders)}).catch(()=>{})},[]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};l(t);let n=Object.keys(t.providers??{});x(e=>e&&("provider"===e.type?t.providers?.[e.name]:"model"!==e.type||t.providers?.[e.providerName]?.models?.[e.index])?e:n[0]?{type:"provider",name:n[0]}:null)}).catch(()=>l({providers:{}})).finally(()=>a(!1)),k()},[k]),(0,i.useEffect)(()=>{f&&iM("models",JSON.stringify(f))},[f]);let S=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;o.providers?.[e];)e=`new-provider-${t++}`;l(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),x({type:"provider",name:e})},[o.providers]),C=(0,i.useCallback)((e,t)=>{l(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),M=(0,i.useCallback)((e,t)=>{l(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),x(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),E=(0,i.useCallback)(e=>{l(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),l(e=>{let t=Object.keys(e.providers??{});return x(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),I=(0,i.useCallback)(e=>{l(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),l(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return x({type:"model",providerName:e,index:n}),t})},[]),R=(0,i.useCallback)((e,t)=>{l(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],o=new Set(i.map(e=>e.id));for(let e of t)o.has(e.id)||(o.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),L=(0,i.useCallback)((e,t,n)=>{l(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),$=(0,i.useCallback)((e,t)=>{l(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}}}}),x({type:"provider",name:e})},[]),N=(0,i.useCallback)(async()=>{c(!0),p(null),g(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),t=await e.json();!e.ok||t.error?p(t.error??`HTTP ${e.status}`):(g(!0),setTimeout(()=>g(!1),2e3))}catch(e){p(String(e))}finally{c(!1)}},[o]),z=Object.entries(o.providers??{}),W=m.filter(e=>e.loggedIn),P=y.filter(e=>e.configured),A=(()=>{if(!f)return null;if("oauth"===f.type){let e=m.find(e=>e.id===f.providerId);return e?(0,r.jsx)(og,{provider:e,onRefresh:k},e.id):null}if("apikey"===f.type){let e=y.find(e=>e.id===f.providerId);return e?(0,r.jsx)(of,{provider:e,onRefresh:k},e.id):null}if("provider"===f.type){let e=o.providers?.[f.name];return e?(0,r.jsx)(ol,{name:f.name,provider:e,onChange:e=>C(f.name,e),onRename:e=>M(f.name,e),onDelete:()=>E(f.name),onAddModels:e=>R(f.name,e)},f.name):null}let e=o.providers?.[f.providerName],t=e?.models?.[f.index];return t?(0,r.jsx)(oh,{providerName:f.providerName,provider:e,model:t,onChange:e=>L(f.providerName,f.index,e),onDelete:()=>$(f.providerName,f.index)},`${f.providerName}-${f.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(i$,{embedded:t,title:n("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:n("i18n.close"),onClose:e,children:[(0,r.jsxs)(iN,{children:[(0,r.jsxs)(iz,{children:[(0,r.jsxs)(iW,{children:[W.map(e=>{let t=f?.type==="oauth"&&f.providerId===e.id;return(0,r.jsxs)(iA,{active:t,onClick:()=>x({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(i0,{id:e.id,size:16}),(0,r.jsx)(iF,{className:"is-grow",children:e.name})]},e.id)}),P.map(e=>{let t=f?.type==="apikey"&&f.providerId===e.id;return(0,r.jsxs)(iA,{active:t,onClick:()=>x({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(i0,{id:e.id,size:16}),(0,r.jsx)(iF,{className:"is-grow",children:e.displayName})]},e.id)}),(W.length>0||P.length>0)&&z.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),s?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):z.map(([e,t])=>{let i=f?.type==="provider"&&f.name===e,o=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(iA,{onClick:()=>x({type:"provider",name:e}),active:i,children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)(iF,{className:"is-grow",children:e})]}),o.map((t,i)=>{let o=f?.type==="model"&&f.providerName===e&&f.index===i;return(0,r.jsxs)(iA,{active:o,className:"models-sidebar-indented-item",onClick:()=>x({type:"model",providerName:e,index:i}),children:[(0,r.jsx)(iF,{className:"is-grow",style:{color:t.id?"var(--text-muted)":"var(--text-dim)"},children:t.id||n("i18n.newModel")}),t.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},i)}),(0,r.jsx)(iA,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:t=>{t.stopPropagation(),I(e)},children:(0,r.jsxs)(iF,{children:["+ ",n("i18n.model")]})})]},e)})]}),(0,r.jsx)(iG,{onClick:()=>w(!0),children:n("i18n.addProvider")})]}),(0,r.jsx)(iV,{children:(0,r.jsx)(iB,{className:"is-fill",children:s?null:A??(0,r.jsx)(iK,{children:n("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(iJ,{status:u&&(0,r.jsx)("span",{style:{color:"#f87171"},children:u}),children:[!t&&(0,r.jsx)(iY,{onClick:e,children:n("i18n.cancel")}),(0,r.jsxs)(iY,{variant:"primary",onClick:N,disabled:d||h,className:h?"is-success":void 0,children:[h&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:h?n("i18n.saved"):d?n("i18n.saving"):n("i18n.save")})]})]})]}),j&&(0,r.jsx)(ox,{oauthProviders:m,apiKeyProviders:y,onSelectOAuth:e=>x({type:"oauth",providerId:e}),onSelectApiKey:e=>x({type:"apikey",providerId:e}),onAddCustom:S,onClose:()=>w(!1)})]})}let ov=null;async function oy(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(ov)return ov;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 ov=null,!1}})();return ov=t,t.then(e=>{e||ov!==t||(ov=null)}),t}function ob(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oj(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function ow(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function ok(e){return e?e.slice(0,8):"unknown"}function oS({skill:e,cwd:t,onToggle:n,toggling:i,saveError:o,updateStatus:l,checkingUpdate:s,updating:a,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,T.s)(),h=oj(e),g=!e.disableModelInvocation;return(0,r.jsxs)(iB,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(iD,{children:[(0,r.jsxs)(iH,{children:[(0,r.jsx)("span",{className:`config-scope-tag${"project"===h?" is-project":""}`,children:h}),(0,r.jsx)("span",{className:"config-detail-path",children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return ob(e)}(e.filePath)})]}),(0,r.jsx)(iO,{children:(0,r.jsx)(iZ,{checked:g,loading:i,label:p(g?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>n(e)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!g&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),e.install?.skillsShUrl&&(0,r.jsx)(iq,{label:"Source",children:(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,className:"skill-source-link",children:(0,r.jsxs)("span",{className:"skill-source-link-text",children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})}),e.install&&(0,r.jsxs)(iq,{label:"Version",children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:ok(l?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)(iY,{size:"small",onClick:c,disabled:s||a,children:p("i18n.check")}),l?.state==="update-available"&&(0,r.jsx)("span",{className:"skill-version-value is-update",children:ok(l.latestVersion)}),(s||l&&"update-available"!==l.state)&&(0,r.jsx)("span",{className:`skill-update-status ${s?"is-checking":l?.state==="up-to-date"?"is-success":l?.state==="error"?"is-error":"is-muted"}`,children:s?p("i18n.checking"):l?.state==="up-to-date"?p("i18n.upToDate"):l?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):l?.message||p("i18n.checkFailed")}),l?.state==="update-available"&&(0,r.jsx)(iY,{variant:"primary",size:"small",onClick:u,disabled:a||s,children:p(a?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)(iq,{label:"Name",children:(0,r.jsx)("span",{className:"skill-name-value",children:e.name})}),(0,r.jsx)(iq,{label:"Description",children:(0,r.jsx)("span",{className:"skill-description",children:e.description})})]})}function oC({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:o}){let{t:l}=(0,T.s)(),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(null),[f,x]=(0,i.useState)(null),[m,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(new Set),[j,w]=(0,i.useState)("global"),k=(0,i.useRef)(null);(0,i.useEffect)(()=>{k.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),g(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 g(n.error);c(n.results??[]),0===(n.results??[]).length&&g("No skills found")}catch(e){g(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{x(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:j,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(`${j}:${t}`)),o()}catch(e){v(String(e))}finally{x(null)}},[o,j,e]),M="global"===j?"~/.pi/agent/skills/":`${ob(e)}/.pi/skills/`;return(0,r.jsxs)(iB,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(iU,{children:l("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:k,value:s,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(s)},placeholder:l("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:12,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)(iY,{variant:"primary",onClick:()=>S(s),disabled:u||!s.trim(),children:u?l("i18n.searching"):l("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&w(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:l("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:j===e?"var(--bg-selected)":"none",color:j===e?"var(--text)":"var(--text-dim)",fontWeight:j===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",M]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:m})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[j].has(e.package)||y.has(`${j}:${e.package}`),i=f===e.package,o=e.package.indexOf("@"),s=o>-1?e.package.slice(0,o):e.package,a=o>-1?e.package.slice(o+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:a??s}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:s}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(iY,{size:"small",onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:n?`✓ ${l("i18n.installed")}`:i?l("i18n.installing"):l("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function oT({cwd:e,onClose:t,embedded:n=!1}){let{t:o}=(0,T.s)(),[l,s]=(0,i.useState)([]),[a,d]=(0,i.useState)(!0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(()=>iT("skills",e)),[g,f]=(0,i.useState)(new Set),[x,m]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),[b,j]=(0,i.useState)({}),[w,k]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(!1),[M,E]=(0,i.useState)(null),[I,R]=(0,i.useState)(null),[L,$]=(0,i.useState)(!0),N=(0,i.useCallback)(async()=>{d(!0),u(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];return s(r),$(n.projectResourcesLoaded??!0),h(e=>{if(e&&r.some(t=>t.filePath===e))return e;let t=r.find(e=>!e.disableModelInvocation)??r[0];return t?.filePath??null}),r}catch(e){return u(String(e)),[]}finally{d(!1)}},[e]);(0,i.useEffect)(()=>{j({}),R(null),N()},[e]),(0,i.useEffect)(()=>{p&&iM("skills",p,e)},[e,p]);let z=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(ow).filter(e=>!!e);if(0!==n.length){R(null),k(e=>new Set([...e,...n])),t||C(!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}`);j(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){R(e instanceof Error?e.message:String(e))}finally{k(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||C(!1)}}},[e,l]),W=(0,i.useCallback)(async t=>{if(!t.install)return;let n=ow(t);E(n),R(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 N();let o=i.skill?.install?.versionHash;j(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){R(e instanceof Error?e.message:String(e))}finally{E(null)}},[e,N]),P=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;f(t=>new Set(t).add(e.filePath)),m(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void m(r.error??`HTTP ${n.status}`);s(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n))}catch(e){m(String(e))}finally{f(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),A=l.find(e=>e.filePath===p)??null;return(0,r.jsxs)(i$,{embedded:n,title:o("common.skills"),subtitle:ob(e),closeLabel:o("i18n.close"),onClose:t,children:[!L&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:o("trust.skillsNotLoaded")}),(0,r.jsxs)(iN,{children:[(0,r.jsxs)(iz,{children:[(0,r.jsx)(iW,{children:a?(0,r.jsx)("div",{className:"config-sidebar-message",children:o("i18n.loading")}):c?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:c}):0===l.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:o("i18n.noSkills")}):(()=>{let e=[],t={project:o("skills.scope.project"),global:o("skills.scope.global"),path:o("skills.scope.path")};for(let{label:n,matches:r}of[{label:`${t.project} / skills.sh`,matches:e=>"project"===oj(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===oj(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===oj(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===oj(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===oj(e)}]){let t=l.filter(r);t.length>0&&e.push({label:n,skills:t})}let n=e=>{let t,n,i=!v&&p===e.filePath,l=e.disableModelInvocation;return(0,r.jsxs)(iA,{active:i,onClick:()=>{h(e.filePath),y(!1)},children:[(0,r.jsx)(iX,{active:!l}),(0,r.jsx)(iF,{className:`is-grow${l?" is-muted":""}`,children:e.name}),(n=(t=ow(e))?b[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:o("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:t})=>(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(iP,{children:e}),[...t.filter(e=>!e.disableModelInvocation),...t.filter(e=>e.disableModelInvocation)].map(n)]},e))})()}),(0,r.jsx)(iG,{onClick:()=>y(!0),active:v,children:o("i18n.addSkill")})]}),(0,r.jsx)(iV,{children:(0,r.jsx)(iB,{className:"is-fill",children:v?(0,r.jsx)(oC,{cwd:e,projectResourcesLoaded:L,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:()=>{N()}}):a?null:A?(0,r.jsx)(oS,{skill:A,cwd:e,onToggle:P,toggling:g.has(A.filePath),saveError:x,updateStatus:ow(A)?b[ow(A)]:void 0,checkingUpdate:!!ow(A)&&w.has(ow(A)),updating:M===ow(A),updateError:I,onCheckUpdate:()=>void z(A),onUpdate:()=>void W(A)},A.filePath):(0,r.jsx)(iK,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(iJ,{status:Object.values(b).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(b).filter(e=>"update-available"===e.state).length," ",1===Object.values(b).filter(e=>"update-available"===e.state).length?o("i18n.update"):o("i18n.updates")]}),children:[!n&&(0,r.jsx)(iY,{onClick:t,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(iY,{variant:"secondary",onClick:()=>void z(),disabled:S||null!==M,children:S?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let oM={builtin:0,global:1,workspace:2,project:3},oE=["read","bash","edit","write","grep","find","ls"],oI=["","off","minimal","low","medium","high","xhigh","max"],oR={name:"custom-agent",displayName:"Custom agent",description:"",systemPrompt:"",tools:["read","bash","edit","write","grep","find","ls"],loadSkills:!1,loadExtensions:!1,promptMode:"append",inheritContext:!1,runInBackground:!1,enabled:!0},oL={width:"100%",minWidth:0,height:34,padding:"0 9px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"},o$={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function oN(e){return{name:e.name,displayName:e.displayName,description:e.description,systemPrompt:e.systemPrompt,tools:[...e.tools],loadSkills:e.loadSkills,loadExtensions:e.loadExtensions,promptMode:e.promptMode,...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 oz(e){return`${e.scope}:${e.name}`}function oW(e){return"global"===e||"project"===e}function oP(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oA({label:e,children:t}){return(0,r.jsx)(iq,{label:e,children:t})}function oF({checked:e,disabled:t,label:n,onChange:i}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:7,color:t?"var(--text-dim)":"var(--text-muted)",fontSize:12,cursor:t?"default":"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:e,disabled:t,onChange:e=>i(e.target.checked)}),n]})}function oB({cwd:e,sessionId:t=null,onClose:n,onReloaded:o,embedded:l=!1}){let s=ec(),{t:a}=(0,T.s)(),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)([]),[h,g]=(0,i.useState)(!0),[f,x]=(0,i.useState)(null),[m,v]=(0,i.useState)(()=>iT("agents",e)),[y,b]=(0,i.useState)(oR),[j,w]=(0,i.useState)("view"),[k,S]=(0,i.useState)("global"),[C,M]=(0,i.useState)(!0),[E,I]=(0,i.useState)(!1),[R,L]=(0,i.useState)(!1),[$,N]=(0,i.useState)(!1),[z,W]=(0,i.useState)(null),[P,A]=(0,i.useState)(!1),[F,B]=(0,i.useState)(10),[D,H]=(0,i.useState)(!0),[O,U]=(0,i.useState)(!1),[_,q]=(0,i.useState)(null),[K,V]=(0,i.useState)(!1),[J,Y]=(0,i.useState)(!1),Z=(0,i.useMemo)(()=>d.find(e=>oz(e)===m)??null,[d,m]),G=(0,i.useMemo)(()=>u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})),[u]),X=(0,i.useCallback)(async t=>{M(!0),W(null);try{let n=await fetch(`/api/subagents/profiles?cwd=${encodeURIComponent(e)}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);let i=r.profiles??[];c(i);let o=t??iT("agents",e),l=i.find(e=>oz(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;v(l?oz(l):null),l&&(b(oN(l)),w(oW(l.scope)?"edit":"view"),oW(l.scope)&&S(l.scope))}catch(e){W(e instanceof Error?e.message:String(e))}finally{M(!1)}},[e]);(0,i.useEffect)(()=>{X()},[X]),(0,i.useEffect)(()=>{let e=new AbortController;return H(!0),q(null),(async()=>{try{let t=await fetch("/api/subagents/settings",{cache:"no-store",signal:e.signal}),n=await t.json();if(!t.ok||n.error||"boolean"!=typeof n.enabled)throw Error(n.error??`HTTP ${t.status}`);A(n.enabled),"number"==typeof n.maxConcurrent&&B(n.maxConcurrent)}catch(t){if(e.signal.aborted)return;q(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||H(!1)}})(),()=>e.abort()},[]),(0,i.useEffect)(()=>{m&&iM("agents",m,e)},[e,m]),(0,i.useEffect)(()=>{let t=new AbortController;return g(!0),x(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(e)}`,{signal:t.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);p(r.modelList??[]),x(r.modelError??null)}catch(e){if(t.signal.aborted)return;x(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||g(!1)}})(),()=>t.abort()},[e]);let Q=async()=>{I(!0),W(null),L(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:k,profile:y})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await X(oz(n.profile)),L(!0),setTimeout(()=>L(!1),2e3)}catch(e){W(e instanceof Error?e.message:String(e))}finally{I(!1)}},ee=async()=>{if(Z&&oW(Z.scope)&&window.confirm(a("agents.deleteConfirm",{name:Z.displayName}))){I(!0),W(null);try{let t=await fetch("/api/subagents/profiles",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Z.scope,name:Z.name})}),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);await X()}catch(e){W(e instanceof Error?e.message:String(e))}finally{I(!1)}}},et="view"!==j,en="create"===j,er=!et||E||$,ei=en?k:Z?.scope,eo=en?"global"===k?`~/.pi/agent/agents/${y.name||"..."}.md`:`./.pi/agents/${y.name||"..."}.md`:Z?function(e,t){if(!e.filePath)return null;if(("project"===e.scope||"workspace"===e.scope)&&e.filePath.startsWith(t)){let n=e.filePath.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return oP(e.filePath)}(Z,e)??a("agents.builtinPath"):"",el=en?eo:Z?.filePath??eo,es=!y.model||u.some(e=>`${e.provider}/${e.id}`===y.model),ea=(()=>{if(!y.model)return null;let e=y.model.indexOf("/");return e<0?{provider:"",modelId:y.model}:{provider:y.model.slice(0,e),modelId:y.model.slice(e+1)}})(),ed=er?{...oL,...o$}:oL,eu=(e,t)=>{b(n=>({...n,[e]:t}))},ep=async t=>{if(en)return void eu("enabled",t);if(Z&&oW(Z.scope)){N(!0),W(null);try{let n=await fetch("/api/subagents/profiles",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:Z.scope,name:Z.name,enabled:t})}),r=await n.json();if(!n.ok||r.error||!r.profile)throw Error(r.error??`HTTP ${n.status}`);let i=r.profile;c(e=>e.map(e=>oz(e)===oz(i)?i:e)),b(e=>({...e,enabled:i.enabled}))}catch(e){W(e instanceof Error?e.message:String(e))}finally{N(!1)}}},eh=async e=>{U(!0),q(null);try{let n=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok||r.error||"boolean"!=typeof r.enabled)throw Error(r.error??`HTTP ${n.status}`);A(r.enabled),V(!!t)}catch(e){q(e instanceof Error?e.message:String(e))}finally{U(!1)}},eg=async e=>{B(e),q(null);try{let t=await fetch("/api/subagents/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxConcurrent:e})}),n=await t.json();if(!t.ok||n.error||"number"!=typeof n.maxConcurrent)throw Error(n.error??`HTTP ${t.status}`);B(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ef=async()=>{if(t){Y(!0),q(null);try{await rk(t,{type:"reload"}),V(!1),o?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(i$,{embedded:l,title:a("common.agents"),subtitle:oP(e),closeLabel:a("agents.close"),onClose:n,children:[(0,r.jsxs)("div",{className:"agents-feature-setting",children:[(0,r.jsxs)("div",{className:"agents-feature-copy",children:[(0,r.jsx)("strong",{children:a("agents.builtInTitle")}),(0,r.jsx)("span",{children:a("agents.builtInDescription")}),K&&(0,r.jsx)("span",{role:"status",className:"agents-feature-reload-notice",children:a("agents.reloadRequired")})]}),(0,r.jsxs)("div",{className:"agents-feature-actions",children:[K&&t&&(0,r.jsx)(iY,{size:"small",onClick:()=>void ef(),disabled:J||O,children:J?a("agents.reloading"):a("agents.reloadSession")}),(0,r.jsxs)("label",{className:"agents-concurrency-control",title:a("agents.maxConcurrentDescription"),children:[(0,r.jsx)("span",{children:a("agents.maxConcurrent")}),(0,r.jsx)("input",{"aria-label":a("agents.maxConcurrent"),type:"number",min:1,max:32,value:F,disabled:D||O,onChange:e=>B(Number(e.target.value)),onBlur:()=>void eg(F)})]}),(0,r.jsx)(iZ,{checked:P,disabled:D||J,loading:O,label:a("agents.builtInTitle"),onChange:e=>void eh(e)})]})]}),(0,r.jsxs)(iN,{children:[(0,r.jsxs)(iz,{children:[(0,r.jsx)(iW,{children:C?(0,r.jsx)("div",{style:{padding:10,color:"var(--text-dim)",fontSize:12},children:a("agents.loading")}):["project","global","workspace","builtin"].map(e=>{let t=d.filter(t=>t.scope===e);return 0===t.length?null:(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(iP,{children:a(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=oM[e.scope],d.some(e=>e.name.toLowerCase()===t&&oM[e.scope]>n));return(0,r.jsxs)(iA,{active:m===oz(e)&&!en,onClick:()=>{v(oz(e)),b(oN(e)),w(oW(e.scope)?"edit":"view"),oW(e.scope)&&S(e.scope),W(null)},children:[(0,r.jsx)(iX,{active:e.enabled}),(0,r.jsx)(iF,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:a("agents.overridden")})]},oz(e))})]},e)})}),(0,r.jsx)(iG,{active:en,onClick:()=>{let e="custom-agent",t=2;for(;d.some(t=>t.name===e);)e=`custom-agent-${t++}`;v(null),b({...oR,name:e,displayName:e}),w("create"),S("global"),W(null)},children:a("agents.new")})]}),(0,r.jsx)(iV,{children:(0,r.jsx)(iB,{className:"is-fill",children:Z||en?(0,r.jsxs)(iB,{children:[(0,r.jsxs)(iD,{children:[(0,r.jsxs)(iH,{children:[ei&&(0,r.jsx)("span",{className:`config-scope-tag${"project"===ei?" is-project":""}`,children:a(`agents.scope.${ei}`)}),(0,r.jsx)("span",{title:el,className:"config-detail-path",children:eo})]}),(0,r.jsxs)(iO,{children:[Z&&("view"===j||"edit"===j)&&(0,r.jsx)(iY,{size:"small",onClick:()=>{if(!Z)return;let e=function(e,t){let n=new Set(t.map(e=>e.name.toLowerCase())),r=`${e}-copy`,i=r,o=2;for(;n.has(i.toLowerCase());)i=`${r}-${o++}`;return i}(Z.name,d);v(null),b({...oN(Z),name:e,displayName:a("agents.copyName",{name:Z.displayName})}),w("create"),S(oW(Z.scope)?Z.scope:"global"),W(null)},disabled:E||$,children:a("agents.duplicate")}),Z&&oW(Z.scope)&&"edit"===j&&(0,r.jsx)(iY,{variant:"danger",size:"small",onClick:()=>void ee(),disabled:E||$,children:a("agents.delete")}),(0,r.jsx)(iZ,{checked:y.enabled,disabled:er,label:y.enabled?a("agents.disable"):a("agents.enable"),onChange:e=>void ep(e)})]})]}),en&&(0,r.jsx)(oA,{label:a("agents.saveScope"),children:(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:3,padding:3,border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)"},children:["global","project"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>S(e),disabled:E,style:{height:28,border:"none",borderRadius:4,background:k===e?"var(--bg-selected)":"transparent",color:k===e?"var(--text)":"var(--text-muted)",cursor:E?"default":"pointer",fontSize:11,fontWeight:k===e?600:400},children:a(`agents.scope.${e}`)},e))})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1fr) minmax(0, 1fr)",gap:12},children:[(0,r.jsx)(oA,{label:a("agents.name"),children:en?(0,r.jsx)("input",{"aria-label":a("agents.name"),value:y.name,disabled:er,onChange:e=>eu("name",e.target.value),style:oL}):(0,r.jsx)("code",{style:{minHeight:34,display:"flex",alignItems:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:y.name})}),(0,r.jsx)(oA,{label:a("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":a("agents.displayName"),value:y.displayName,disabled:er,onChange:e=>eu("displayName",e.target.value),style:ed})})]}),(0,r.jsx)(oA,{label:a("agents.description"),children:(0,r.jsx)("input",{"aria-label":a("agents.description"),value:y.description,disabled:er,onChange:e=>eu("description",e.target.value),style:ed})}),(0,r.jsx)(oA,{label:a("agents.prompt"),children:(0,r.jsx)("textarea",{className:"agents-system-prompt","aria-label":a("agents.prompt"),value:y.systemPrompt,disabled:er,onChange:e=>eu("systemPrompt",e.target.value),style:{...ed,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:er?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(oA,{label:a("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:oE.map(e=>(0,r.jsx)(oF,{label:e,disabled:er,checked:y.tools.includes(e),onChange:t=>eu("tools",t?[...y.tools,e]:y.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(oA,{label:a("agents.resources"),children:(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(oF,{label:a("agents.loadSkills"),disabled:er,checked:y.loadSkills,onChange:e=>eu("loadSkills",e)}),(0,r.jsx)(oF,{label:a("agents.loadExtensions"),disabled:er,checked:y.loadExtensions,onChange:e=>eu("loadExtensions",e)})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(oA,{label:a("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(nD,{options:G,value:ea,onChange:(e,t)=>eu("model",`${e}/${t}`),onClear:()=>eu("model",void 0),emptyLabel:h?a("agents.modelsLoading"):a("agents.inherit"),selectedLabel:y.model&&!es?a("agents.modelUnavailable",{model:y.model}):void 0,disabled:er||h||0===u.length&&!y.model,ariaLabel:a("agents.model"),variant:"field",placement:"auto"}),f&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:f})]})}),(0,r.jsx)(oA,{label:a("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":a("agents.thinking"),value:y.thinking??"",disabled:er,onChange:e=>eu("thinking",e.target.value||void 0),style:ed,children:oI.map(e=>(0,r.jsx)("option",{value:e,children:e||a("agents.inherit")},e||"default"))})}),(0,r.jsx)(oA,{label:a("agents.maxTurns"),children:(0,r.jsx)("input",{"aria-label":a("agents.maxTurns"),type:"number",min:1,value:y.maxTurns??"",disabled:er,onChange:e=>eu("maxTurns",e.target.value?Number(e.target.value):void 0),style:ed})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(oF,{label:a("agents.inheritContext"),disabled:er,checked:y.inheritContext,onChange:e=>eu("inheritContext",e)}),(0,r.jsx)(oF,{label:a("agents.background"),disabled:er,checked:y.runInBackground,onChange:e=>eu("runInBackground",e)})]})]}):(0,r.jsx)(iK,{children:a("agents.empty")})})})]}),(0,r.jsx)(iJ,{status:(_||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:_||z}),children:et&&(0,r.jsxs)(iY,{variant:"primary",onClick:()=>void Q(),disabled:E||R||$||!y.name.trim(),className:R?"is-success":void 0,children:[R&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"config-button-success-icon",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:R?a("i18n.saved"):E?a("agents.saving"):a("agents.save")})]})})]})}function oD(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function oH(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function oO(e){return`${e.scope}\0${e.source}`}function oU(e){return`extension\0${e.path}`}function o_(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function oq({pkg:e}){let{t}=(0,T.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function oK({scope:e}){return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function oV({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,T.s)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(o=>{let l=e===o,s="project"===o&&!t;return(0,r.jsx)("button",{onClick:()=>{s||n(o)},disabled:s,title:s?i("trust.projectScopeUnavailable"):void 0,style:{width:76,border:"none",borderRight:"global"===o?"1px solid var(--border)":"none",background:l?"var(--bg-selected)":"none",color:l?"var(--text)":"var(--text-muted)",cursor:s?"not-allowed":"pointer",opacity:s?.45:1,fontSize:12},children:o},o)})})}function oJ({cwd:e,source:t,scope:n,projectResourcesLoaded:o,busy:l,actionError:s,onSourceChange:a,onScopeChange:d,onInstall:c}){let{t:u}=(0,T.s)(),p=(0,i.useRef)(null);return(0,i.useEffect)(()=>{p.current?.focus()},[]),(0,r.jsxs)(iB,{className:"is-fill",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)(iU,{children:u("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://pi.dev/packages",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"pi.dev/packages"]})]}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===n?`${oD(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsx)(iq,{label:"Source",children:(0,r.jsx)("input",{id:"plugin-source",ref:p,value:t,onChange:e=>a(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=oH(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(oH(e.currentTarget.value)),placeholder:"npm:@scope/package",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!l&&c()}})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(oV,{value:n,projectResourcesLoaded:o,onChange:d}),(0,r.jsx)(iY,{variant:"primary",onClick:c,disabled:l||!t.trim(),className:"is-pushed-right",children:u(l?"i18n.installing":"i18n.install")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>a(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),s&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:s})]})}function oY({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:o,sessionId:l,updateStatus:s,checkingUpdate:a,updateError:d,onAction:c,onCheckUpdate:u,onReloadSession:p}){let h,{t:g}=(0,T.s)(),f=oO(e),x=n?.endsWith(f)??!1,m="reload"===n,v=!e.disabled,y=e.canCheckForUpdates,b=s?.state==="update-available";return(0,r.jsxs)(iB,{children:[(0,r.jsxs)(iD,{className:"is-top-aligned",children:[(0,r.jsxs)(iH,{children:[(0,r.jsx)(oK,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:g("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:g("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)(iO,{children:[(0,r.jsx)(iY,{size:"small",variant:b?"primary":void 0,onClick:b||!y?()=>c("update",e):u,disabled:x||m||a,title:b?g("i18n.updateAvailable"):void 0,children:g(n===`update:${f}`?"i18n.updating":a?"i18n.checking":b||!y?"i18n.update":"i18n.check")}),(0,r.jsx)(iY,{size:"small",onClick:p,disabled:!l||m||x,title:g(l?"i18n.reloadSession":"i18n.openSessionToReload"),children:g(m?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(iY,{variant:"danger",size:"small",onClick:()=>c("remove",e),disabled:x||m,children:g(n===`remove:${f}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(iZ,{checked:v,loading:x||m,onChange:()=>c(e.disabled?"enable":"disable",e),label:g(e.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:g("i18n.status")}),(0,r.jsx)("div",{style:{color:o_(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:g("i18n.version")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(h=[],e.version&&h.push(g("i18n.installedVersion",{version:e.version})),e.configuredVersion&&h.push(g("i18n.configuredVersion",{version:e.configuredVersion})),h.length?h.join(" \xb7 "):g("i18n.unknown"))}),b&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:s.displayName,children:g("i18n.updateAvailable")}),y&&(a||s&&!b)&&(0,r.jsx)("span",{className:`skill-update-status ${a?"is-checking":s?.state==="up-to-date"?"is-success":s?.state==="error"?"is-error":"is-muted"}`,children:a?g("i18n.checking"):s?.state==="up-to-date"?g("i18n.upToDate"):s?.state==="unsupported"?g("i18n.automaticChecksUnavailable"):s?.message||g("i18n.checkFailed")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:g("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??g("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:g("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(e,g)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:g("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?oD(e.installedPath):g("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:g("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:oD(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(i_,{children:g("i18n.resolvedResources")}),(0,r.jsx)(oq,{pkg:e})]}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:o}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function oZ({extension:e}){let{t}=(0,T.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsxs)(iB,{children:[(0,r.jsx)(iD,{children:(0,r.jsxs)(iH,{children:[(0,r.jsx)(oK,{scope:e.scope}),(0,r.jsx)(iU,{children:e.name})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:t("i18n.status")}),(0,r.jsx)("div",{style:{color:e.enabled?"var(--accent)":"var(--text-dim)"},children:n}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:t("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:oD(e.path)})]})]})}function oG({cwd:e,sessionId:t,onClose:n,onReloaded:o,embedded:l=!1}){let{t:s}=(0,T.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[g,f]=(0,i.useState)(()=>iT("plugins",e)),[x,m]=(0,i.useState)(!1),[v,y]=(0,i.useState)(""),[b,j]=(0,i.useState)("global"),[w,k]=(0,i.useState)(null),[S,C]=(0,i.useState)(null),[M,E]=(0,i.useState)(null),[I,R]=(0,i.useState)({}),[L,$]=(0,i.useState)(new Set),[N,z]=(0,i.useState)(!1),[W,P]=(0,i.useState)(null),[A,F]=(0,i.useState)(!1),B=(0,i.useMemo)(()=>a?.packages??[],[a?.packages]),D=(0,i.useMemo)(()=>a?.standaloneExtensions??[],[a?.standaloneExtensions]),H=B.find(e=>oO(e)===g)??null,O=D.find(e=>oU(e)===g)??null,U=a?.projectResourcesLoaded??!0,_=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:B.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[B]),q=(0,i.useCallback)(async()=>{u(!0),h(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),m(e=>0===n.packages.length&&0===n.standaloneExtensions.length||e),f(e=>e&&(n.packages.some(t=>oO(t)===e)||n.standaloneExtensions.some(t=>oU(t)===e))?e:n.packages[0]?oO(n.packages[0]):n.standaloneExtensions[0]?oU(n.standaloneExtensions[0]):null)}catch(e){h(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{R({}),P(null),q()},[e]),(0,i.useEffect)(()=>{g&&iM("plugins",g,e)},[e,g]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:B.filter(e=>e.canCheckForUpdates)).map(oO);if(0!==n.length){P(null),$(e=>new Set([...e,...n])),t||z(!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}`);R(e=>{let t={...e};for(let e of r.updates??[])t[oO(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||z(!1)}}},[e,B]),V=(0,i.useCallback)(async()=>{F(!0),C(null),E(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),R({}),E(s("i18n.packagesUpdated")),t&&E(`${s("i18n.packagesUpdated")} ${s("agents.reloadRequired")}`)}catch(e){C(e instanceof Error?e.message:String(e))}finally{F(!1)}},[e,t,s]),J=(0,i.useCallback)(async(t,n)=>{let r=oO(n);k(`${t}:${r}`),C(null),E(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),o=await i.json();if(!i.ok||o.error)throw Error(o.error??`HTTP ${i.status}`);d(o),"remove"===t?(f(o.packages[0]?oO(o.packages[0]):o.standaloneExtensions[0]?oU(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&m(!0),E("Package removed."),R(e=>{let t={...e};return delete t[r],t})):(E({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&R(e=>{let t={...e};return delete t[r],t}))}catch(e){C(e instanceof Error?e.message:String(e))}finally{k(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=oH(v).trim();if(!t)return;y(t);let n=`${b}\0${t}`;k(`install:${n}`),C(null),E(null);try{var r;let i,o,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:b,cwd:e})}),s=await l.json();if(!l.ok||s.error)throw Error(s.error??`HTTP ${l.status}`);d(s);let a=(r=s.packages,o=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===b&&e.source===i)??r.find(e=>e.scope===b&&e.source===`npm:${o}`)??r.find(e=>e.scope===b&&e.source.endsWith(i)));f(a?oO(a):n),m(!1),y(""),E("Package installed.")}catch(e){C(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,v]),Z=(0,i.useCallback)(async()=>{if(t){k("reload"),C(null),E(null);try{await rk(t,{type:"reload"}),o?.(),await q(),E("Session reloaded.")}catch(e){C(e instanceof Error?e.message:String(e))}finally{k(null)}}},[q,o,t]),G=w?.startsWith("install:")??!1,X=Object.values(I).filter(e=>"update-available"===e.state).length,Q=B.some(e=>e.canCheckForUpdates),ee=c||null!==w||L.size>0||A;return(0,r.jsxs)(i$,{embedded:l,title:s("common.plugins"),subtitle:oD(e),closeLabel:s("i18n.close"),onClose:n,children:[!U&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:s("trust.pluginsNotLoaded")}),(0,r.jsxs)(iN,{children:[(0,r.jsxs)(iz,{children:[(0,r.jsx)(iW,{children:c?(0,r.jsx)("div",{className:"config-sidebar-message",children:"Loading..."}):p?(0,r.jsx)("div",{className:"config-sidebar-message is-error",children:p}):0===B.length&&0===D.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:"No plugins configured"}):(0,r.jsxs)(r.Fragment,{children:[D.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(iP,{children:s("i18n.extensions")}),D.map(e=>{let t=oU(e);return(0,r.jsxs)(iA,{active:!x&&g===t,title:e.path,onClick:()=>{f(t),m(!1),C(null),E(null)},children:[(0,r.jsx)(iX,{active:e.enabled}),(0,r.jsx)(iF,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.name})]},t)})]}),_.map(e=>(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(iP,{children:e.scope}),e.packages.map(e=>{let t=oO(e),n=!x&&g===t;return(0,r.jsxs)(iA,{active:n,onClick:()=>{f(t),m(!1),C(null),E(null)},children:[(0,r.jsx)(iX,{active:!e.disabled,color:o_(e.status)}),(0,r.jsx)(iF,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),I[oO(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:s("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope))]})}),(0,r.jsx)(iG,{active:x,onClick:()=>{m(!0),C(null),E(null)},children:s("i18n.addPlugin")})]}),(0,r.jsx)(iV,{children:(0,r.jsx)(iB,{className:"is-fill",children:x?(0,r.jsx)(oJ,{cwd:e,source:v,scope:b,projectResourcesLoaded:U,busy:G,actionError:S,onSourceChange:y,onScopeChange:j,onInstall:Y}):c?null:O?(0,r.jsx)(oZ,{extension:O}):H?(0,r.jsx)(oY,{pkg:H,cwd:e,busyKey:w,actionError:S,actionMessage:M,sessionId:t,updateStatus:I[oO(H)],checkingUpdate:L.has(oO(H)),updateError:W,onAction:J,onCheckUpdate:()=>void K(H),onReloadSession:Z},oO(H)):(0,r.jsx)(iK,{children:s("i18n.selectPackage")})})})]}),(0,r.jsxs)(iJ,{status:X>0?(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--accent)"},children:[X," ",1===X?s("i18n.update"):s("i18n.updates")]}):a?.diagnostics.length?(0,r.jsxs)("span",{title:a.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:a.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[a.diagnostics.length," diagnostic",1===a.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:a?`${a.totals.extensions} ext \xb7 ${a.totals.skills} skills \xb7 ${a.totals.prompts} prompts \xb7 ${a.totals.themes} themes`:""}),children:[!l&&(0,r.jsx)(iY,{onClick:n,children:s("i18n.close")}),Q&&(0,r.jsx)(iY,{variant:X>0?"primary":"secondary",onClick:()=>void(X>0?V():K()),disabled:ee,title:X>0?s("i18n.updateAllPluginsHint"):void 0,children:A?s("i18n.updating"):N?s("i18n.checking"):X>0?`${s("i18n.updateAllPlugins")} (${X})`:s("i18n.checkUpdates")}),(0,r.jsx)(iY,{variant:"secondary",onClick:()=>void q(),disabled:ee,children:s("i18n.refresh")})]})]})}let oX={en:{title:"Archives",empty:"No archived projects.",loadFailed:"Could not load archives.",sessions:"{count} sessions",unarchive:"Unarchive",deleteSessions:"Delete",deleteConfirmLead:"Deletes {count} chat sessions. Does not delete the code folder.",deleteConfirmHint:"Type confirm to continue.",deleteConfirmName:"confirm",cancel:"Cancel",busy:"Working…",runningBlocked:"Stop the running agent in this project first.",deleteFailed:"Could not delete those sessions.",path:"Path",untitled:"Untitled session",messages:"{count} messages"},"zh-CN":{title:"归档",empty:"没有已归档的项目。",loadFailed:"无法加载归档列表。",sessions:"{count} 个会话",unarchive:"取消归档",deleteSessions:"删除",deleteConfirmLead:"将删除该项目下 {count} 个聊天会话,不会删除磁盘上的代码目录。",deleteConfirmHint:"输入「确认」继续。",deleteConfirmName:"确认",cancel:"取消",busy:"处理中…",runningBlocked:"请先停止该项目中正在运行的 agent。",deleteFailed:"删除会话失败。",path:"路径",untitled:"未命名会话",messages:"{count} 条消息"},"zh-TW":{title:"封存",empty:"沒有已封存的專案。",loadFailed:"無法載入封存清單。",sessions:"{count} 個工作階段",unarchive:"取消封存",deleteSessions:"刪除",deleteConfirmLead:"將刪除該專案下 {count} 個聊天工作階段,不會刪除磁碟上的程式碼目錄。",deleteConfirmHint:"輸入「確認」繼續。",deleteConfirmName:"確認",cancel:"取消",busy:"處理中…",runningBlocked:"請先停止該專案中正在執行的 agent。",deleteFailed:"刪除工作階段失敗。",path:"路徑",untitled:"未命名工作階段",messages:"{count} 則訊息"}};function oQ(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>void 0===t[n]?e:String(t[n]))}function o0(e){let t=e.replace(/[\\/]+$/,""),n=t.split(/[\\/]/);return n[n.length-1]||t}function o1({onClose:e,embedded:t=!1}){var n;let o,{locale:l}=(0,T.s)(),s=oX[l]??oX.en,[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(""),[g,f]=(0,i.useState)(!1),[x,m]=(0,i.useState)(!1),[v,y]=(0,i.useState)(!1),[b,j]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),M=(0,i.useCallback)(async()=>{f(!1);try{let[e,t,n]=await Promise.all([fetch("/api/archives",{cache:"no-store"}),fetch("/api/sessions",{cache:"no-store"}),fetch("/api/home",{cache:"no-store"})]);if(!e.ok||!t.ok)throw Error("load failed");let r=ej(await e.json()),i=await t.json(),o=Array.isArray(i.sessions)?i.sessions:[],l=await n.json().catch(()=>({}));"string"==typeof l.home&&h(l.home);let s=eb(r),a=[];for(let e of s){let t=S(o,e).filter(e=>e.relation?.kind!=="subagent").sort((e,t)=>t.modified.localeCompare(e.modified));a.push({key:e,root:t[0]?.projectRoot??t[0]?.cwd??e,modified:t[0]?.modified??"",sessions:t})}a.sort((e,t)=>t.modified.localeCompare(e.modified)),d(a),u(e=>e&&a.some(t=>t.key===e)?e:a[0]?.key??null)}catch{f(!0)}},[]);(0,i.useEffect)(()=>{M()},[M]);let E=a.find(e=>e.key===c)??null,I=async e=>{m(!0),k(null);try{if(!(await fetch("/api/archives",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e,archived:!1})})).ok)throw Error("unarchive failed");y(!1),j(""),d(t=>t.filter(t=>t.key!==e)),u(t=>t===e?null:t)}catch{k(s.loadFailed)}finally{m(!1)}},R=async e=>{m(!0),k(null);try{let t=await fetch("/api/archives/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectKey:e.key,confirm:b.trim()})}),n=await t.json().catch(()=>({}));if(409===t.status&&n.runningSessionIds?.length)return void k(s.runningBlocked);if(!t.ok)throw Error(n.error??"delete failed");y(!1),j(""),d(t=>t.filter(t=>t.key!==e.key)),u(t=>t===e.key?null:t)}catch{k(s.deleteFailed)}finally{m(!1)}};return(0,r.jsx)(i$,{embedded:t,title:s.title,onClose:e,children:g?(0,r.jsx)(iK,{children:s.loadFailed}):0===a.length?(0,r.jsx)(iK,{children:s.empty}):(0,r.jsxs)(iN,{children:[(0,r.jsx)(iz,{children:(0,r.jsx)(iW,{children:a.map(e=>(0,r.jsx)(iA,{active:e.key===c,onClick:()=>{u(e.key),y(!1),j(""),k(null)},children:(0,r.jsx)(iF,{title:e.root,children:o0(e.root)})},e.key))})}),(0,r.jsx)(iV,{children:E?(0,r.jsxs)(iB,{children:[(0,r.jsxs)(iD,{children:[(0,r.jsx)(iH,{children:(0,r.jsx)(iU,{children:o0(E.root)})}),(0,r.jsxs)(iO,{children:[(0,r.jsx)(iY,{variant:"secondary",size:"small",disabled:x,onClick:()=>void I(E.key),children:x?s.busy:s.unarchive}),!v&&(0,r.jsx)(iY,{variant:"danger",size:"small",disabled:x||0===E.sessions.length,onClick:()=>{y(!0),j(""),k(null)},children:s.deleteSessions})]})]}),(0,r.jsx)(iq,{label:s.path,children:(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",wordBreak:"break-all"},children:(n=E.root,p&&n.startsWith(p)?"~"+n.slice(p.length):n)})}),v&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:oQ(s.deleteConfirmLead,{count:E.sessions.length})}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:s.deleteConfirmHint}),(0,r.jsx)("input",{value:b,onChange:e=>j(e.target.value),placeholder:s.deleteConfirmName,"aria-label":s.deleteConfirmName,autoComplete:"off",style:{alignSelf:"flex-start",width:"min(220px, 100%)",fontFamily:"var(--font-mono)",fontSize:12,padding:"6px 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)(iY,{variant:"danger",size:"small",disabled:x||"confirm"!==(o=b.trim().toLowerCase())&&"确认"!==o&&"確認"!==o,onClick:()=>void R(E),children:x?s.busy:s.deleteSessions}),(0,r.jsx)(iY,{variant:"ghost",size:"small",disabled:x,onClick:()=>{y(!1),j("")},children:s.cancel})]})]}),(0,r.jsx)(i_,{children:oQ(s.sessions,{count:E.sessions.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto"},children:E.sessions.map(e=>{let t=function(e,t){let n=e.name?.trim();if(n)return n;let r=e.firstMessage?.replace(/\s+/g," ").trim();return r&&"(no messages)"!==r?r:t}(e,s.untitled);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,padding:"8px 10px",borderRadius:6,background:"var(--bg-hover)"},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t,children:t}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsx)("span",{children:(0,C.fw)(e.modified,l)}),(0,r.jsx)("span",{children:oQ(s.messages,{count:e.messageCount})})]})]},e.id)})}),w&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:w})]}):(0,r.jsx)(iK,{children:s.empty})})]})})}function o2({section:e,size:t=16,strokeWidth:n=1.8}){let i={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"skills"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"m12 2-10 5 10 5 10-5-10-5Z"}),(0,r.jsx)("path",{d:"m2 12 10 5 10-5M2 17l10 5 10-5"})]}):"agents"===e?(0,r.jsxs)("svg",{...i,className:"settings-section-icon is-agent",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}):"archives"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]}):(0,r.jsx)("svg",{...i,children:(0,r.jsx)("path",{d:"M9 7V2M15 7V2M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0ZM12 19v3"})})}function o4({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:o}){let{locale:l,setLocale:s,supportedLocales:a,t:d}=(0,T.s)(),{preference:c,setThemePreference:u}=tL(),{width:p,setWidth:h,fontSize:g,setFontSize:f}=nA(),[x,m]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),[b,j]=(0,i.useState)(null),[w,k]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[M,E]=(0,i.useState)(null),[I,R]=(0,i.useState)(!1),[L,$]=(0,i.useState)(!1),[N,z]=(0,i.useState)("");(0,i.useEffect)(()=>{k(tq()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>R(e?.enabled===!0)).catch(()=>{})},[]);let W=async()=>{$(!0),z("");try{let e=await fetch("/api/web-auth",{method:"DELETE"});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.replace("/login")}catch{z(d("auth.logoutFailed"))}finally{$(!1)}};(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||m(n)}).catch(t=>{e||j(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let P=async n=>{y(!0),j(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}`);m(i),e&&(await rk(e,{type:"reload"}),t())}catch(e){j(e instanceof Error?e.message:String(e))}finally{y(!1)}},A=async()=>{if(!S){C(!0),E(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 oy(l))throw Error("unsupported or not permitted");E({kind:"ok",message:d("settings.pushRegistered")})}catch(e){E({kind:"error",message:`${d("settings.pushRegisterFailed")} ${e instanceof Error?e.message:String(e)}`})}finally{C(!1)}}};return(0,r.jsxs)("div",{className:"settings-general",children:[(0,r.jsx)("h2",{className:"settings-general-title",children:d("settings.general")}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.appearance")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("settings.appearance"),className:"settings-theme-options",children:tf.map(e=>{let t=c===e.id;return(0,r.jsxs)("label",{className:"settings-theme-option",children:[(0,r.jsx)("input",{type:"radio",name:"theme",value:e.id,checked:t,onChange:()=>u(e.id),className:"sr-only"}),(0,r.jsx)(iv,{preference:e.id}),(0,r.jsx)("span",{className:"settings-theme-option-label",children:d(e.label)})]},e.id)})})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.chat")}),(0,r.jsxs)("div",{className:"settings-chat-options",children:[(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.thinkingExpandedDefault")}),(0,r.jsx)(iZ,{checked:w,label:d("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(tU,String(e)),window.dispatchEvent(new Event(t_)),k(e)}})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-width",children:d("settings.chatContentWidth")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-width",children:[p,"px"]}),(0,r.jsx)(iY,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentWidth"),"aria-label":d("settings.resetChatContentWidth"),disabled:820===p,onClick:()=>h(820),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-width",type:"range",min:820,max:2e3,step:10,value:p,onChange:e=>h(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-range-option",children:[(0,r.jsxs)("div",{className:"settings-chat-range-header",children:[(0,r.jsx)("label",{htmlFor:"settings-chat-content-font-size",children:d("settings.chatContentFontSize")}),(0,r.jsxs)("output",{htmlFor:"settings-chat-content-font-size",children:[g,"px"]}),(0,r.jsx)(iY,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("settings.resetChatContentFontSize"),disabled:14===g,onClick:()=>f(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:g,onChange:e=>f(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(iZ,{checked:n,label:d("settings.quoteSelection"),onChange:o})]})]})]}),x?.isWindows&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.shellTool")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.shellToolDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.usePowerShell")}),(0,r.jsx)(iZ,{checked:x.powerShellEnabled,loading:v,label:d("settings.usePowerShell"),onChange:e=>void P(e)})]}),b&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:b})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("settings.pushPermission")}),(0,r.jsx)("p",{className:"settings-general-description",children:d("settings.pushPermissionDescription")}),(0,r.jsxs)("div",{className:"settings-shell-option",children:[(0,r.jsx)("span",{children:d("settings.pushPermission")}),(0,r.jsx)("button",{type:"button",className:"config-button config-button-small config-button-secondary",disabled:S,onClick:()=>void A(),children:S?d("settings.pushRegisterLoading"):d("settings.pushRegister")})]}),M&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===M.kind?{color:"var(--accent)"}:void 0,children:M.message})]}),(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsx)("h3",{className:"settings-general-heading",children:d("common.language")}),(0,r.jsx)("div",{role:"radiogroup","aria-label":d("common.language"),className:"settings-language-options",children:a.map(e=>{let t=l===e.id;return(0,r.jsxs)("button",{type:"button",role:"radio","aria-checked":t,onClick:()=>s(e.id),className:"settings-language-option",children:[(0,r.jsx)("span",{className:"settings-language-radio",children:t&&(0,r.jsx)("span",{className:"settings-language-radio-dot"})}),(0,r.jsx)("span",{className:"settings-language-label",children:e.label}),(0,r.jsx)("span",{className:"settings-language-code",children:e.id})]},e.id)})})]}),I&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(iY,{variant:"secondary",disabled:L,onClick:()=>void W(),children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 17l5-5-5-5M15 12H3M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"})}),L?d("auth.loggingOut"):d("auth.logOut")]}),N&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:N})]})]})}let o8={en:"Archives","zh-CN":"归档","zh-TW":"封存"};function o5({cwd:e,sessionId:t,initialSection:n,onClose:o,onSessionReloaded:l,quoteSelectionEnabled:s,onQuoteSelectionChange:a}){let{t:d,locale:c}=(0,T.s)(),[u,p]=(0,i.useState)(n),[h,g]=(0,i.useState)(()=>new Set([u])),f=[{id:"general",label:d("settings.general"),requiresProject:!1},{id:"models",label:d("common.models"),requiresProject:!1},{id:"archives",label:o8[c]??o8.en,requiresProject:!1},{id:"skills",label:d("common.skills"),requiresProject:!0},{id:"agents",label:d("common.agents"),requiresProject:!0},{id:"plugins",label:d("common.plugins"),requiresProject:!0}];(0,i.useEffect)(()=>iC(n),[n]),(0,i.useEffect)(()=>{let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),o())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o]),(0,i.useEffect)(()=>{e||"skills"!==u&&"agents"!==u&&"plugins"!==u||(p("general"),g(e=>new Set(e).add("general")),iC("general"))},[e,u]);let x=e=>{g(t=>new Set(t).add(e)),p(e),iC(e)},m=(e,t)=>h.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":d("settings.title"),onClick:e=>{e.target===e.currentTarget&&o()},className:"settings-dialog-backdrop",children:(0,r.jsxs)("div",{className:"settings-dialog-surface",children:[(0,r.jsxs)("div",{className:"settings-dialog-header",children:[(0,r.jsx)("strong",{className:"settings-dialog-title",children:d("settings.title")}),(0,r.jsx)("select",{"aria-label":d("settings.title"),value:u,onChange:e=>x(e.target.value),className:"settings-mobile-section-picker",children:f.map(t=>(0,r.jsx)("option",{value:t.id,disabled:t.requiresProject&&!e,children:t.label},t.id))}),(0,r.jsx)("nav",{"aria-label":d("settings.title"),className:"settings-section-tabs",children:f.map(t=>{let n=u===t.id,i=t.requiresProject&&!e;return(0,r.jsxs)("button",{type:"button",className:"settings-section-tab",disabled:i,title:i?d("settings.projectRequired"):t.label,"aria-current":n?"page":void 0,onClick:()=>x(t.id),children:[(0,r.jsx)(o2,{section:t.id}),(0,r.jsx)("span",{children:t.label})]},t.id)})}),(0,r.jsx)("button",{type:"button",onClick:o,title:d("i18n.close"),"aria-label":d("i18n.close"),className:"config-close-button settings-dialog-close",children:"\xd7"})]}),(0,r.jsxs)("main",{className:"settings-dialog-main",children:[m("general",(0,r.jsx)(o4,{sessionId:t,onSessionReloaded:l,quoteSelectionEnabled:s,onQuoteSelectionChange:a})),m("models",(0,r.jsx)(om,{embedded:!0,onClose:o})),m("archives",(0,r.jsx)(o1,{embedded:!0,onClose:o})),e&&m("skills",(0,r.jsx)(oT,{embedded:!0,cwd:e,onClose:o},e)),e&&m("agents",(0,r.jsx)(oB,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e)),e&&m("plugins",(0,r.jsx)(oG,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e))]})]})})}function o6({cwd:e,busy:t,error:n,onCancel:i,onConfirm:o}){let{t:l}=(0,T.s)();return(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||i()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("trust.dialogTitle")}),(0,r.jsx)("div",{style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:l("trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),n&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:n})]})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:i,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"transparent",color:"var(--text-muted)",cursor:t?"not-allowed":"pointer",fontSize:12},children:l("trust.cancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,style:{height:32,padding:"0 12px",border:"1px solid var(--accent)",borderRadius:5,background:"var(--accent)",color:"var(--accent-contrast)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontSize:12,fontWeight:600},children:l(t?"trust.trusting":"trust.trustProject")})]})]})})}function o3(e){return"message"===e.type&&"message"in e}function o9(e){let t=e,n=t.branchPreview,r=o3(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&o3(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function o7(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 le({node:e,activePathIds:t,depth:n,isLast:i,parentLines:o,onSelect:l}){let{node:s,skipped:a,branchPreview:d,labelEntry:c}=o9(e),u=t.has(s.entry.id),p=t.has(e.entry.id)||t.has(s.entry.id),h=d?.text??function(e){if("message"===e.type&&"message"in 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),g=d?d.role??null:o3(c)?c.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>l(s.entry.id),children:[o.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:i?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":p?"var(--text-muted)":"var(--border)",border:u?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),g&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===g?"var(--accent)":"var(--text-dim)",background:"user"===g?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===g?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===g?"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)":p?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:h})]}),s.children.map((e,a)=>(0,r.jsx)(le,{node:e,activePathIds:t,depth:n+1,isLast:a===s.children.length-1,parentLines:[...o,!i],onSelect:l},e.entry.id))]})}function lt({tree:e,activeLeafId:t,onLeafChange:n,inline:o,containerRef:l,open:s,onToggle:a,hasSession:d,compact:c,hideInlineButton:u}){let{t:p}=(0,T.s)(),[h,g]=(0,i.useState)(!1),f=void 0!==s?s:h,x=(0,i.useRef)(null),[m,v]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!f||!o)return;let e=l?.current??x.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();v({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[f,o,l]);let y=(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]),b=(0,i.useCallback)(e=>{n(e)},[n]),j=d?o7(e)?null:p("i18n.noBranches"):p("i18n.noActiveSession"),w=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=o9(e[0]).node;return t.children.length>1?t.children:[]}(e),k=!j&&w.length>0,S=(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:k?"var(--accent)":"var(--text-dim)",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"})]}),C=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:f?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return o?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:x,onClick:()=>a?a():g(e=>!e),style:{display:u?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:f?"var(--bg-selected)":"none",border:"none",borderTop:f?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:f?"var(--text)":"var(--text-muted)",fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=f?"var(--text)":"var(--text-muted)"},title:p("i18n.branches"),"aria-label":p("i18n.branches"),"aria-pressed":f,children:[S,!c&&(0,r.jsx)("span",{children:p("i18n.branches")})]}),f&&m&&(0,r.jsx)("div",{style:{position:"fixed",top:m.top,left:m.left,width:m.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:k?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:w.map((e,t)=>(0,r.jsx)(le,{node:e,activePathIds:y,depth:0,isLast:t===w.length-1,parentLines:[],onSelect:b},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:j})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[S,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:p("i18n.branches")}),C]}),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:k?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:w.map((e,t)=>(0,r.jsx)(le,{node:e,activePathIds:y,depth:0,isLast:t===w.length-1,parentLines:[],onSelect:b},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:j??p("i18n.noBranches")})})]})}function ln({loading:e,prompt:t,translate:n}){return(0,r.jsxs)("section",{className:"system-prompt-panel","aria-label":n("system.prompt"),children:[(0,r.jsx)("div",{className:"system-prompt-scroll",children:t?(0,r.jsx)("div",{className:"system-prompt-text",children:t}):(0,r.jsx)("div",{className:"system-prompt-empty",children:n(""===t?"system.empty":e?"system.loading":"system.load")})}),(0,r.jsx)("style",{children:`
9
- .system-prompt-panel {
10
- display: flex;
11
- height: min(600px, 75dvh);
12
- min-height: 220px;
13
- flex-direction: column;
14
- background: var(--bg-panel);
15
- border-bottom: 1px solid var(--border);
16
- }
17
- .system-prompt-scroll {
18
- min-height: 0;
19
- flex: 1;
20
- overflow: auto;
21
- padding: 12px 16px;
22
- }
23
- .system-prompt-text {
24
- color: var(--text-muted);
25
- font-family: var(--font-mono);
26
- font-size: 12px;
27
- line-height: 1.6;
28
- overflow-wrap: anywhere;
29
- white-space: pre-wrap;
30
- }
31
- .system-prompt-empty {
32
- padding: 10px 0;
33
- color: var(--text-muted);
34
- font-size: 12px;
35
- font-style: italic;
36
- }
37
- `})]})}function lr(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function li({children:e}){return(0,r.jsx)("div",{className:"tool-definitions-empty",children:e})}function lo({loading:e,tools:t,translate:n}){let o=(0,i.useMemo)(()=>t?.filter(e=>e.active)??null,[t]),[l,s]=(0,i.useState)(null);(0,i.useEffect)(()=>{s(e=>o?.some(t=>t.name===e)?e:o?.[0]?.name??null)},[o]);let a=o?.find(e=>e.name===l)??o?.[0]??null,d=a?function(e){if(!e||!e.properties||"object"!=typeof e.properties)return[];let t=e.properties,n=new Set(Array.isArray(e.required)?e.required.filter(e=>"string"==typeof e):[]);return Object.entries(t).map(([e,t])=>{let r=t&&"object"==typeof t?t:{};return{name:e,type:function e(t){let n=Array.isArray(t.anyOf)?t.anyOf:Array.isArray(t.oneOf)?t.oneOf:null;if(n)return n.map(t=>t&&"object"==typeof t?e(t):"unknown").filter((e,t,n)=>n.indexOf(e)===t).join(" | ");if(void 0!==t.const)return lr(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(lr).join(", "):void 0,defaultValue:void 0===r.default?void 0:lr(r.default)}})}(a.parameters):[];return(0,r.jsxs)("div",{className:"tool-definitions-panel",children:[(0,r.jsx)("nav",{className:"tool-definitions-sidebar","aria-label":n("tools.title"),children:(0,r.jsx)("div",{className:"tool-definitions-list",children:o&&o.length>0?o.map(e=>{let t=e.name===a?.name;return(0,r.jsx)("button",{type:"button",className:`tool-definitions-item${t?" selected":""}`,"aria-pressed":t,onClick:()=>s(e.name),children:(0,r.jsx)("code",{children:e.name})},e.name)}):o?(0,r.jsx)(li,{children:n("tools.noTools")}):(0,r.jsx)(li,{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)(li,{children:o?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
- font-style: italic;
183
- overflow-wrap: anywhere;
184
- }
185
- @media (max-width: 640px) {
186
- .tool-definitions-panel {
187
- grid-template-columns: 112px minmax(0, 1fr);
188
- }
189
- .tool-definitions-item {
190
- padding: 8px 10px;
191
- }
192
- .tool-definition-scroll {
193
- padding: 12px;
194
- }
195
- .tool-definition-field {
196
- grid-template-columns: minmax(74px, 0.7fr) minmax(0, 1.3fr);
197
- gap: 9px;
198
- }
199
- }
200
- `})]})}function ll(e){return e.name||e.firstMessage||e.id.slice(0,12)}function ls({status:e}){return"running"===e||"starting"===e?(0,r.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):"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"})]}):"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 la({session:e,main:t,selected:n,running:i,onSelect:o}){let{locale:l,t:s}=(0,T.s)(),a=e.relation?.kind==="subagent"?e.relation:null,d=i?"running":a?.status??"completed",c=t?s("agentSwitcher.main"):a?.description||ll(e),u=t?ll(e):`${a?.profile??s("agentSwitcher.subagent")} \xb7 ${function(e,t){let n=new Date(e).getTime();if(!Number.isFinite(n))return"";let r=Math.round((n-Date.now())/1e3),i=new Intl.RelativeTimeFormat(t,{numeric:"auto"});if(60>Math.abs(r))return i.format(r,"second");let o=Math.round(r/60);if(60>Math.abs(o))return i.format(o,"minute");let l=Math.round(o/60);return 24>Math.abs(l)?i.format(l,"hour"):i.format(Math.round(l/24),"day")}(e.modified,l)}`;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,onClick:o,style:{width:"100%",minHeight:56,display:"grid",gridTemplateColumns:"28px minmax(0, 1fr) auto",alignItems:"center",gap:9,padding:"7px 12px",border:"none",borderBottom:"1px solid var(--border)",borderLeft:n?"2px solid var(--accent)":"2px solid transparent",background:n?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="transparent")},children:[(0,r.jsx)("span",{style:{width:28,height:28,display:"grid",placeItems:"center",color:t?"var(--text-muted)":"var(--accent)"},children:t?(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"4"}),(0,r.jsx)("path",{d:"M4 21a8 8 0 0 1 16 0"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]})}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:n?600:500},title:c,children:c}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},title:u,children:u})]}),(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",gap:6,color:t&&!i?"var(--text-dim)":"running"===d||"starting"===d?"var(--accent)":"completed"===d?"#16a34a":"failed"===d?"#dc2626":"aborted"===d?"#d97706":"var(--text-dim)",fontSize:11,whiteSpace:"nowrap"},children:t&&!i?n?s("agentSwitcher.current"):null:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ls,{status:d}),(0,r.jsx)("span",{children:s(`agentSwitcher.status.${d}`)})]})})]})}function ld({rootSession:e,subagents:t,selectedSessionId:n,runningSessionIds:o,onSelectSession:l}){let{t:s}=(0,T.s)(),[a,d]=(0,i.useState)(""),c=(0,i.useMemo)(()=>[...t].sort((e,t)=>{let n=o.has(e.id);return n!==o.has(t.id)?n?-1:1:t.modified.localeCompare(e.modified)}),[o,t]),u=a.trim().toLowerCase(),p=u?c.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(u))}):c,h=t.filter(e=>o.has(e.id)).length;return(0,r.jsx)("div",{role:"listbox","aria-label":s("agentSwitcher.title"),style:{background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",borderRight:"1px solid var(--border)",borderBottom:"1px solid var(--border)",borderRadius:"0 0 6px 6px",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",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:s("agentSwitcher.title")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:s("agentSwitcher.count",{count:t.length})}),h>0&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--accent)",fontSize:11},children:s("agentSwitcher.runningCount",{count:h})})]}),t.length>8&&(0,r.jsx)("div",{style:{padding:8,borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{type:"search",value:a,onChange:e=>d(e.target.value),placeholder:s("agentSwitcher.search"),"aria-label":s("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)(la,{session:e,main:!0,selected:e.id===n,running:o.has(e.id),onSelect:()=>l(e)}),p.map(e=>(0,r.jsx)(la,{session:e,selected:e.id===n,running:o.has(e.id),onSelect:()=>l(e)},e.id)),0===p.length&&(0,r.jsx)("div",{style:{padding:"22px 12px",color:"var(--text-dim)",fontSize:12,textAlign:"center"},children:s("agentSwitcher.noMatches")})]})]})})}var lc=n(63606),lu=n(8422);async function lp(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 lh({tab:e,active:t,onRestart:n,onClosed:o,onCloseError:l}){let{t:s}=(0,T.s)(),{id:a,cwd:d,restored:c}=e,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(Promise.resolve()),g=(0,i.useRef)(null),f=(0,i.useRef)({onClosed:o,onCloseError:l});f.current={onClosed:o,onCloseError:l};let[x,m]=(0,i.useState)("connecting"),[v,y]=(0,i.useState)(null),[b,j]=(0,i.useState)(null),[w,k]=(0,i.useState)(0);return(0,i.useEffect)(()=>{var e;let t,n,r,i,o,l=u.current;if(!l)return;let s=!1,f=null,x=!1,v=!1,b=!1;m("connecting"),y(null),j(null);let k=new lu.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"}});p.current=k;let S=new lc.Y;k.loadAddon(S),k.open(l),k.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&&k.hasSelection())});let C=(e=e=>{s||(b=!0,k.options.disableStdin=!0,y(e.message),m("error"))},n=Promise.resolve(),r=!1,i=null,o=t=>{r||(n=n.then(async()=>{r||(t===i&&(i=null),await lp(`/api/terminal/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:o(i={type:"input",data:t})},resize(e,t){i=null,o({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});g.current=C;let T=k.onData(e=>{!x||v||b||C.write(e)}),M=()=>{l.offsetWidth&&l.offsetHeight&&S.fit()},E=k.onResize(({cols:e,rows:t})=>{!x||v||b||C.resize(e,t)}),I=new ResizeObserver(M);I.observe(l);let R=()=>{s||v||!navigator.onLine||(f?.close(),(f=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)k.reset();else if(void 0!==t&&n.offset<=t)return;k.write(n.data),t=n.offset}else v=!0,x=!1,k.options.disableStdin=!0,f?.close(),j("exit"===n.type?n.exitCode:null),m("exited")},f.onopen=()=>{x=!0,!b&&(k.options.disableStdin=!1,m("ready"),M(),C.resize(k.cols,k.rows),l.offsetWidth&&l.offsetHeight&&k.focus())},f.onerror=()=>{s||v||(x=!1,k.options.disableStdin=!0,m(f?.readyState===EventSource.CLOSED?"error":"connecting"))})};h.current=(async()=>{M(),c||w>0?await lp(`/api/terminal/${encodeURIComponent(a)}`):await lp("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:a,cwd:d,cols:k.cols,rows:k.rows})}),R()})().catch(e=>{s||(y(e.message),m("error"))});let L=()=>{x=!1,k.options.disableStdin=!0,f?.close(),v||b||m("connecting")},$=e=>{e.persisted&&R()};return window.addEventListener("pagehide",L),window.addEventListener("pageshow",$),window.addEventListener("offline",L),window.addEventListener("online",R),()=>{s=!0,f?.close(),C.stop(),I.disconnect(),T.dispose(),E.dispose(),window.removeEventListener("pagehide",L),window.removeEventListener("pageshow",$),window.removeEventListener("offline",L),window.removeEventListener("online",R),k.dispose(),p.current=null}},[a,d,c,w]),(0,i.useEffect)(()=>{t&&p.current?.focus()},[t]),(0,i.useEffect)(()=>{if(!e.closing)return;let t=!1;return p.current&&(p.current.options.disableStdin=!0),(async()=>{await h.current,await g.current?.stop(),await lp(`/api/terminal/${encodeURIComponent(a)}`,{method:"DELETE",keepalive:!0}),t||f.current.onClosed()})().catch(e=>{t||(y(e.message),m("error"),f.current.onCloseError())}),()=>{t=!0}},[a,e.closing]),(0,r.jsxs)("section",{className:"terminal-panel","aria-label":s("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-${x}`,title:s(`terminal.${x}`)}),(0,r.jsx)("span",{title:d,children:d})]}),"error"===x&&(0,r.jsx)("button",{type:"button",onClick:()=>k(e=>e+1),disabled:!!e.closing,title:s("terminal.reconnect"),"aria-label":s("terminal.reconnect"),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})})}),(0,r.jsx)("button",{type:"button",onClick:n,disabled:!!e.closing,title:s("terminal.restart"),"aria-label":s("terminal.restart"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M20 11a8 8 0 1 0-2.34 5.66"}),(0,r.jsx)("polyline",{points:"20 4 20 11 13 11"})]})})]}),(0,r.jsxs)("div",{children:[v&&(0,r.jsx)("div",{className:"terminal-panel-error",role:"alert",children:v}),"exited"===x&&(0,r.jsx)("div",{className:"terminal-panel-exit",role:"status",children:null===b?s("terminal.exited"):s("terminal.exitCode",{code:b})})]}),(0,r.jsx)("div",{className:"terminal-xterm",children:(0,r.jsx)("div",{ref:u,className:"terminal-xterm-host"})})]})}let lg="pi-web:terminal-tabs";function lf(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function lx(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 lm(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function lv(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,getDefaultWidth:o,getMaxWidth:l,growthDirection:s,maxWidth:a,minWidth:d,storageKey:c,widthRef:u}=e,p=(0,i.useRef)(null),h=(0,i.useRef)(null),g=(0,i.useRef)(!1),[f,x]=(0,i.useState)(r),[m,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1);(0,i.useEffect)(()=>{b(!0)},[]);let j=(0,i.useCallback)(()=>Math.min(a,Math.max(d,l())),[l,a,d]),w=(0,i.useCallback)(e=>lx(e,d,j()),[j,d]),k=(0,i.useCallback)(e=>{u.current=e,p.current?.style.setProperty(n,`${e}px`)},[n,u]),S=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=w(e),o=i!==u.current;return k(i),x(i),r&&(o||n)&&lm(c,i),i},[k,w,c,u]),C=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),T=(0,i.useCallback)(e=>{let t=h.current;if(t&&t.pointerId===e){h.current=null,C(t),v(!1),S(u.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[S,C,u]),M=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=h.current;t&&T(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),h.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)},[T,u]),E=(0,i.useCallback)(e=>{let t=h.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void T(e.pointerId);e.preventDefault();let n="right"===s?1:-1,r=w(t.startWidth+(e.clientX-t.startX)*n);k(r),e.currentTarget.setAttribute("aria-valuenow",String(r)),e.currentTarget.setAttribute("aria-valuetext",`${r} px`)},[k,w,T,s]),I=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),R=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),L=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),$=(0,i.useCallback)(()=>{S(o?.()??r,{forcePersist:!0})},[S,r,o]),N=(0,i.useCallback)(()=>{S(u.current)},[S,u]),z=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===s?"ArrowRight":"ArrowLeft",r="right"===s?"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(j(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),$())},[S,j,s,d,$,u]);return(0,i.useEffect)(()=>{if(g.current)return;g.current=!0;let e=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),t=S(e??o?.()??r,{persist:!1});null!==e&&e!==t&&lm(c,t)},[S,r,o,c]),(0,i.useEffect)(()=>{if(!g.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(!m)return;let e=()=>{let e=h.current;e&&T(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[T,m]),(0,i.useEffect)(()=>()=>{let e=h.current;e&&(h.current=null,C(e))},[C]),{isResizing:m,panelRef:p,reclampWidth:N,resetWidth:$,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":y?j():a,"aria-valuemin":d,"aria-valuenow":f,"aria-valuetext":`${f} px`,onDoubleClick:$,onKeyDown:z,onLostPointerCapture:L,onPointerCancel:R,onPointerDown:M,onPointerMove:E,onPointerUp:I,role:"separator",tabIndex:0},width:f}}function ly(e){return`parked-new:${e}`}function lb(){let e,t,n,s,a,d,c,u,p,g,f,x,m,k=(0,o.useRouter)(),S=(0,o.useSearchParams)(),[C]=(0,i.useState)(()=>{let e;return{requestedCwd:e=S.get("cwd")?.trim()||null,sessionId:e?null:S.get("session"),sidebarCollapsed:"collapsed"===S.get("sidebar")}});tL();let{locale:M,t:E}=(0,T.s)(),I=ec(),R=(0,i.useSyncExternalStore)(es,ea,ed);(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{let r;n=null,!function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let i=.01>Math.abs(r-1);return e&&i&&t-n>1}({hasFocusedEditable:(r=document.activeElement)instanceof HTMLElement&&(r.isContentEditable||"INPUT"===r.tagName||"SELECT"===r.tagName||"TEXTAREA"===r.tagName),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.removeProperty("--app-viewport-height"):t.style.setProperty("--app-viewport-height",`${e.height}px`);let i=0!==window.scrollX||0!==window.scrollY,o=.01>Math.abs(e.scale-1);i&&o&&window.scrollTo(0,0)},i=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return i(),e.addEventListener("resize",i),e.addEventListener("scroll",i),window.addEventListener("resize",i),window.addEventListener("focusin",i),window.addEventListener("focusout",i),window.addEventListener("pageshow",i),()=>{e.removeEventListener("resize",i),e.removeEventListener("scroll",i),window.removeEventListener("resize",i),window.removeEventListener("focusin",i),window.removeEventListener("focusout",i),window.removeEventListener("pageshow",i),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]),(0,i.useEffect)(()=>{"Notification"in window&&"granted"===Notification.permission&&oy(M)},[M]);let{soundEnabled:L,onSoundToggle:$,playDoneSound:N,unlockAudio:z,soundEnabledRef:W}=function(){let[e,t]=(0,i.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]);let r=(0,i.useRef)(null),o=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),l=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=o();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[o]);return{soundEnabled:e,onSoundToggle:(0,i.useCallback)(()=>{let e=!n.current;e&&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=o();if(!e)return;let t=()=>{try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),o=e.createGain();i.connect(o),o.connect(e.destination),i.type="sine",i.frequency.value=n;let l=t+.18*r;o.gain.setValueAtTime(0,l),o.gain.linearRampToValueAtTime(.18,l+.02),o.gain.exponentialRampToValueAtTime(.001,l+.45),i.start(l),i.stop(l+.45)})}catch{}};"suspended"===e.state?e.resume().then(t).catch(()=>{}):t()},[o]),unlockAudio:l,soundEnabledRef:n}}(),[P,A]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{A("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let F=(0,i.useCallback)(e=>{A(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),B=(0,i.useRef)(new Set),H=(0,i.useCallback)(()=>{W.current&&N()},[N,W]),[O,U]=(0,i.useState)(null),[_,q]=(0,i.useState)([]),K=(0,i.useCallback)(e=>{q(e)},[]),V=(0,i.useMemo)(()=>O?[..._.filter(e=>e.id!==O.id),O]:_,[O,_]),J=(0,i.useMemo)(()=>{var e;return(e=O?.id)?h(V).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[O?.id,V]),Y=!!J?.subagents.length,[Z,G]=(0,i.useState)(()=>new Set),X=(0,i.useCallback)(e=>{G(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[Q,ee]=(0,i.useState)(null),[et,en]=(0,i.useState)("initial"),er=(0,i.useRef)(null),[ei,eo]=(0,i.useState)(()=>C.requestedCwd?"validating":"idle"),[el,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(0),[eg,ef]=(0,i.useState)(0),ex=(0,i.useRef)(new Map),em=(0,i.useCallback)((e,t)=>{ex.current.set(e,t)},[]),[ev,ey]=(0,i.useState)(null),eb=(0,i.useCallback)(e=>{ey(t=>t===e?null:t)},[]),[ej,ew]=(0,i.useState)(0),[ek,eS]=(0,i.useState)(null),[eC,eT]=(0,i.useState)(0),[eM,eE]=(0,i.useState)(null),[eI,eR]=(0,i.useState)(!1),[eL,eN]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(null),[eP,eA]=(0,i.useState)(()=>!C.sidebarCollapsed),[eF,eB]=(0,i.useState)(!1),[eD,eH]=(0,i.useState)(!1),[eO,eU]=(0,i.useState)(!1),e_=(0,i.useRef)(260),eq=(0,i.useRef)(560),eK=(0,i.useCallback)(()=>lx(.42*window.innerWidth,360,640),[]),eV=(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:eF,rightPanelWidth:eq.current}),[eF]),eJ=(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:eP,sidebarWidth:e_.current}),[eP]),eY=lv({ariaLabel:E("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:eV,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:e_}),eZ=lv({ariaLabel:E("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:eK,getMaxWidth:eJ,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:eq}),eG=eY.reclampWidth,eX=eZ.reclampWidth;(0,i.useEffect)(()=>{I&&eA(!1)},[I]),(0,i.useEffect)(()=>{eU(!0)},[]),(0,i.useEffect)(()=>{eF&&(eG(),eX())},[eX,eG,eF]);let eQ=(0,i.useRef)(null),[e0,e1]=(0,i.useState)(null),e2=(0,i.useRef)(null),e4=(0,i.useRef)(null),[e8,e5]=(0,i.useState)([]),[e6,e3]=(0,i.useState)(null),e9=(0,i.useRef)(null),e7=o7(e8),te=(0,i.useCallback)((e,t,n)=>{e5(e),e3(t),e9.current=n},[]),tt=(0,i.useCallback)(e=>{e9.current?.(e)},[]),[tn,tr]=(0,i.useState)(null),[ti,to]=(0,i.useState)(null),[tl,ts]=(0,i.useState)(!1),ta=(0,i.useRef)(null),td=(0,i.useRef)(0),tc=(0,i.useRef)(null),tu=(0,i.useCallback)(e=>{tr(e),ts(!1)},[]),tp=(0,i.useCallback)(e=>{to(e)},[]),th=(0,i.useCallback)(e=>{td.current+=1,ta.current=e,ts(!1)},[]),[tg,tf]=(0,i.useState)(null),[tx,tm]=(0,i.useState)({kind:"idle"}),tv=(0,i.useRef)(null),ty=(0,i.useRef)(O?.id??null);ty.current=O?.id??null;let tb=(0,i.useCallback)(e=>{tf(e)},[]),[tj,tw]=(0,i.useState)(null),tk=(0,i.useRef)(null),tS=(0,i.useCallback)((e,t)=>{t$(t).then(()=>{tk.current&&clearTimeout(tk.current),tw(e),tk.current=setTimeout(()=>tw(null),1400)})},[]);(0,i.useEffect)(()=>()=>{tk.current&&clearTimeout(tk.current),tv.current&&clearTimeout(tv.current)},[]);let[tC,tT]=(0,i.useState)(null),tM=(0,i.useCallback)(e=>{tT(e)},[]),[tE,tI]=(0,i.useState)(null),[tR,tN]=(0,i.useState)(null);(0,i.useEffect)(()=>{e7||tI(e=>"branches"===e?null:e)},[e7]),(0,i.useEffect)(()=>{Y||tI(e=>"agents"===e?null:e)},[Y]);let tz=(0,i.useCallback)((e,t=!1)=>{I&&eA(!1),tI(t=>t===e?null:e),I&&R&&t&&eH(!0)},[I,R]),tW=(0,i.useCallback)((e,t=!1)=>{let n=tE!==e;if(tz(e,t),!n||tl)return;let r=ta.current;if(!r)return;let i=++td.current;ts(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{td.current===i&&ts(!1)})},[tE,tl,tz]),tP=(0,i.useCallback)(()=>{I&&eA(!1),eH(!1),tI("session")},[I]),tA=(0,i.useCallback)(()=>{I&&(tI(null),eH(!1)),eA(e=>!e)},[I]),tF=(0,i.useCallback)(()=>{eA(!1),tI(null),eH(e=>!e)},[]),tB=(0,i.useCallback)(()=>{I&&(eA(!1),tI(null),eH(!1)),eB(e=>!e)},[I]);(0,i.useEffect)(()=>{if(!eD)return;let e=e=>{let t=e4.current;t&&e.composedPath().includes(t)||eH(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),eH(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[eD]),(0,i.useEffect)(()=>{eH(!1)},[I,R,O?.id,et]),(0,i.useEffect)(()=>{if(!tE||!e2.current)return;let e=()=>{let e=e2.current.getBoundingClientRect();"agents"===tE?tN({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):tN({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(e2.current),()=>t.disconnect()},[tE,I]);let[tD,tH]=(0,i.useState)([]),[tO,tU]=(0,i.useState)(null),[t_,tq]=(0,i.useState)([]),[tK,tV]=(0,i.useState)(!1),tJ=[...tD,...t_.map(e=>({id:e.id,label:D(e.cwd)||e.cwd,filePath:e.cwd,kind:"terminal",closing:!!e.closing}))];(0,i.useEffect)(()=>{try{let e=function(e){try{let t=JSON.parse(e??"null"),n=[];for(let e of Array.isArray(t?.tabs)?t.tabs:[])e&&"string"==typeof e.id&&/^[a-f0-9]{32}$/.test(e.id)&&"string"==typeof e.cwd&&e.cwd.trim()&&!n.some(t=>t.id===e.id||t.cwd===e.cwd)&&n.push({id:e.id,cwd:e.cwd,restored:!0});return{tabs:n,activeId:n.some(e=>e.id===t.activeId)?t.activeId:null,open:t?.open===!0}}catch{return{tabs:[],activeId:null,open:!1}}}(window.sessionStorage.getItem(lg));tq(e.tabs),e.activeId&&(tU(e.activeId),eB(e.open))}catch{}tV(!0)},[]),(0,i.useEffect)(()=>{if(tK)try{window.sessionStorage.setItem(lg,JSON.stringify({tabs:t_.map(({id:e,cwd:t})=>({id:e,cwd:t})),activeId:tO,open:eF}))}catch{}},[t_,tO,eF,tK]);let tY=(0,i.useCallback)((e,t,n)=>{tH(r=>(function(e,t,n,r){let i=e.findIndex(e=>e.id===t);if(-1===i||(e[i].viewerRevision??0)!==n)return e;let o=[...e];return o[i]={...o[i],viewerState:r},o})(r,e,t,n))},[]),tZ=(0,i.useCallback)((e,t)=>{eQ.current?.insertText(nw(e,t)),I&&(eB(!1),eA(!1))},[I]),tG=(0,i.useCallback)(e=>{let t=e.map(e=>nw(e,!1)).join("");t&&eQ.current?.insertText(t),I&&(eB(!1),eA(!1))},[I]),tX=(0,i.useCallback)((e,t,n)=>{let r,i,o,l;eQ.current?.insertText((r=Math.max(1,Math.min(t,n)),i=Math.max(1,Math.max(t,n)),o=e.includes(" ")?`@"${e}"`:`@${e}`,l=r===i?`:${r}`:`:${r}-${i}`,`${o}${l} `)),I&&(eB(!1),eA(!1))},[I]),tQ=C.sessionId,[t0,t1]=(0,i.useState)(null),t2=(0,i.useRef)(null),[t4,t8]=(0,i.useState)(()=>!tQ),t5=(0,i.useRef)(!1),t6=(0,i.useRef)(0),t3=(0,i.useCallback)(()=>{t6.current+=1},[]);(0,i.useEffect)(()=>{O&&function(e,t,n=y()){if(n)try{let r=b(n);r[e]=t,n.setItem(v,JSON.stringify(r))}catch{}}(O.projectKey??t2.current??w(O),O.id)},[O]),(0,i.useEffect)(()=>{let e=C.requestedCwd;if(!e)return;let t=new AbortController;return eo("validating"),eu(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}`);t5.current=!0;let r=`initial:${e}`;en(r),er.current=`new:${r}:${n.cwd}`,ee(n.cwd),eo("ready")}).catch(e=>{t.signal.aborted||(eu(e instanceof Error?e.message:String(e)),eo("error"))}),()=>t.abort()},[C]);let t9=(0,i.useCallback)((e,t)=>{let n=++t6.current,r=function(e,t=y()){if(!t)return null;try{let n=b(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);r&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(i=>{if(n!==t6.current)return;let o=i?.sessions.find(e=>e.id===r);if(!o){i&&j(e);return}if(w(o)!==e)return void j(e);let l=er.current;l&&nv(l,ly(t)),er.current=null,U(o),ef(e=>e+1),new URLSearchParams(window.location.search).get("session")!==o.id&&k.replace(`?session=${encodeURIComponent(o.id)}`,{scroll:!1})}).catch(()=>{})},[k]),t7=(0,i.useCallback)((e,t,n)=>{t3();let r=Q??t0;if(t1(e),!e)return;let i=n??t??e,o=t2.current??(O?w(O):null);if(t2.current=i,t5.current){t5.current=!1;return}if(r===e&&o!==i||o===i&&(null!==O||r===e))return;let l=er.current;l&&r&&nv(l,ly(r));let s="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${s}:${e}`;nv(ly(e),a),en(s),er.current=a,U(null),ee(t=>t&&t!==e?null:t),ef(e=>e+1),e5([]),e3(null),tr(null),to(null),ts(!1),tI(null),o!==i&&(tH([]),(!tO||tO.startsWith("file:"))&&(tU(null),eB(!1)),t9(i,e)),k.replace(window.location.pathname,{scroll:!1})},[t0,tO,t3,Q,k,O,t9]),ne=(0,i.useCallback)((e,t=!1,n,r)=>{ey(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),t3();let i=er.current,o=Q??(null===O?t0:null);i&&o&&nv(i,ly(o)),er.current=null;let l=w(e);if(t2.current!==l&&(tH([]),(!tO||tO.startsWith("file:"))&&(tU(null),eB(!1)),tI(null)),t2.current=l,!t&&O){let t=w(O)===w(e);if(O.id===e.id&&t){I&&eA(!1);return}}ee(null),U(e),ef(e=>e+1),e5([]),e3(null),e9.current=null,tr(null),to(null),ts(!1),t8(!0),I&&!t&&eA(!1),t&&(t5.current=!0),t||k.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[t0,tO,t3,k,I,Q,O]),nt=(0,i.useCallback)((e,t)=>{t3();let n=`new:${e}:${t}`;nv(ly(t),n),er.current=n,en(e),U(null),ee(t),ef(e=>e+1),e5([]),e3(null),tr(null),to(null),ts(!1),tI(null),I&&eA(!1),k.replace(window.location.pathname,{scroll:!1})},[t3,k,I]);!function(e){let{onNewSession:t,activeCwd:n}=e;(0,i.useEffect)(()=>{let e=e=>{if("Escape"===e.key){if(!l)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),l();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!n||!t)return;e.preventDefault(),t(n)}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[n,t])}({onNewSession:e=>nt(`kb-${Date.now()}`,e),activeCwd:t0});let nn=(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&&U(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),nr=(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}`);ne(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[ne]),ni=(0,i.useCallback)((e,t)=>{eh(e=>e+1),er.current===t&&(t3(),er.current=null,ee(null),U(e),nn(e.id),k.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1}))},[t3,k,nn]),no=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{if(!("Notification"in window))return;let i=()=>{rv({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&ne(e)}})};"granted"===Notification.permission?(i(),oy(M)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(i(),oy(M))})},[ne,M]),nl=(0,i.useCallback)(()=>{eh(e=>e+1),ew(e=>e+1),O&&nn(O.id),O?.relation?.kind!=="subagent"&&rx()&&no({targetSession:O,title:O?.name??E("i18n.sessionComplete"),body:E("i18n.taskFinished"),tag:O?`pi-session-complete:${O.id}`:"pi-session-complete"})},[no,nn,O,E]),ns=(0,i.useCallback)(e=>{var t;O?.relation?.kind!=="subagent"&&rx()&&(t=B.current,!(!rm(e)||t.has(e.id))&&(t.add(e.id),1)&&no({targetSession:O,title:E("i18n.attentionNeeded"),body:"custom"===e.method?E("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[no,O,E]),na=(0,i.useCallback)(async()=>{let e=O?.id;if(e&&"naming"!==tx.kind){tv.current&&clearTimeout(tv.current),tI(null),tm({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(eh(e=>e+1),ty.current!==e)return;U(t=>t?.id===e?{...t,name:r}:t),tf(t=>t?.sessionId===e?{...t,sessionName:r}:t),tm({kind:"success"}),tv.current=setTimeout(()=>tm({kind:"idle"}),1800)}catch(t){if(ty.current!==e)return;tm({kind:"error",message:t instanceof Error?t.message:String(t)}),tv.current=setTimeout(()=>tm({kind:"idle"}),5e3)}}},[tx.kind,O?.id]);(0,i.useEffect)(()=>{tv.current&&clearTimeout(tv.current),tm({kind:"idle"})},[O?.id]);let nd=(0,i.useCallback)(()=>{ew(e=>e+1)},[]),nc=(0,i.useCallback)(e=>{t3(),er.current=null,eh(e=>e+1),ef(e=>e+1),ee(null),U(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),nn(e),k.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[t3,k,nn]),nu=(0,i.useCallback)(async(e,t,n)=>{let r=await rk(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(E("chat.quoteForkFailed"));e1({sessionId:r.newSessionId,text:e}),nc(r.newSessionId)},[nc,E]),np=(0,i.useCallback)(()=>{t8(!0)},[]),nh=(0,i.useCallback)(e=>{if(t3(),eh(e=>e+1),O?.id===e){let e=O.cwd,t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;en(t),er.current=e?`new:${t}:${e}`:null,U(null),ee(e??null),ef(e=>e+1),e5([]),e3(null),tr(null),to(null),ts(!1),tI(null),k.replace(window.location.pathname,{scroll:!1})}},[t3,O,k]),ng=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,o=`file:${e}`;tH(n=>(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,sourceSessionId:t.sourceSessionId,initialDisplayMode:t.modeHint,viewerState:t.modeHint?{displayMode:t.modeHint,wrapLines:!1,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId);return r||t.modeHint?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e};return r&&(n.sourceSessionId=t.sourceSessionId),t.modeHint?(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines??!1,scrollTop:0,scrollLeft:0},n.viewerRevision=(e.viewerRevision??0)+1):r&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:i,sourceSessionId:r,tabId:o})),tU(o),eB(!0),I&&eA(!1)},[I]),nf=(0,i.useCallback)(e=>{ng(e,D(e),{sourceSessionId:O?.id??null})},[ng,O?.id]),nx=(0,i.useCallback)(e=>{let t=t_.find(t=>t.cwd===e),n=t??lf(e);t||tq(e=>[...e,n]),tU(n.id),eB(!0),I&&eA(!1)},[t_,I]),nm=(0,i.useCallback)(e=>{t_.some(t=>t.id===e)?tq(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"})):(tH(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===t_.length&&eB(!1),n}),tU(t=>{if(t!==e)return t;let n=tD.filter(t=>t.id!==e);return n.at(-1)?.id??t_.at(-1)?.id??null}))},[tD,t_]),ny=(0,i.useCallback)(()=>{O&&window.open(`/api/sessions/${encodeURIComponent(O.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[O]),nb=Q??(null===O&&t0?t0:null),nj=null===O&&nb?`new:${et}:${nb}`:null;(0,i.useLayoutEffect)(()=>{er.current=nj},[nj]);let nk=null!==O||null!==nb,nS=O?.cwd??nb,nC=t4&&!nk;(0,i.useEffect)(()=>{if(eE(null),eR(!1),eW(null),!nS)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(nS)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eE(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[nS]);let nT=(0,i.useCallback)(async()=>{if(nS&&!eL){eN(!0),eW(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:nS})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);eE(t),eR(!1),eT(e=>e+1),ef(e=>e+1)}catch(e){eW(e instanceof Error?e.message:String(e))}finally{eN(!1)}}},[eL,nS]),nM=tD.find(e=>e.id===tO)??null,nE=t0?D(t0)||t0:null,nI=nE?`${nE} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==nI&&(document.title=nI)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[nI]);let nR=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(e$,{selectedSessionId:O?.id??null,onSelectSession:ne,onNewSession:nt,initialSessionId:tQ,skipInitialProjectSelection:null!==C.requestedCwd,onInitialRestoreDone:np,refreshKey:ep,onSessionDeleted:nh,selectedCwd:O?.cwd??Q??null,onCwdChange:t7,onOpenFile:ng,onOpenTerminal:nx,explorerRefreshKey:ej,onExplorerRefresh:nd,onAtMention:tZ,onAtMentions:tG,onBackgroundTaskDone:H,onRunningSessionIdsChange:X,onSessionsChange:K}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",E("common.models")],["skills",E("common.skills")]].map(([e,t])=>{let n="models"!==e&&!nS;return(0,r.jsxs)("button",{type:"button",onClick:()=>eS(e),disabled:n,title:n?E("settings.projectRequired"):t,"aria-label":t,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:12,opacity:n?.35:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{n||(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-muted)"},children:[(0,r.jsx)(o2,{section:e,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:t})]},e)}),(0,r.jsxs)("button",{type:"button",onClick:()=>eS(function(e,t=iw()){if(!t)return"general";try{let n=ik(t).section;if(!("string"==typeof n&&iy.includes(n)))return"general";return ij.has(n)&&!e?"general":n}catch{return"general"}}(nS)),title:E("common.settings"),"aria-label":E("common.settings"),style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,transition:"background 0.12s, color 0.12s"},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-muted)"},children:[(0,r.jsx)(o2,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:E("common.settings")})]})]})]}),nL=e=>nk&&eM?.requiresTrust&&!eM.trusted?(0,r.jsxs)("button",{type:"button",onClick:()=>{eW(null),eR(!0)},title:E("trust.resourcesNotLoaded"),"aria-label":E("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:1.35,textAlign:"left"},"data-mobile-trust-banner":e?"true":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),(0,r.jsx)("span",{children:E("trust.resourcesNotLoaded")})]}):null,n$=e=>{let t,n,i,o,l,s;return e||nk?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{ny(),e&&R&&eH(!0)},disabled:!O,title:O?E("history.full"):E("history.unsaved"),"aria-label":E("history.full"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:O?"var(--text-muted)":"var(--text-dim)",cursor:O?"pointer":"not-allowed",opacity:O?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{O&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=O?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"history":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:O?"var(--text-muted)":"var(--text-dim)",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"})]}),!e&&(0,r.jsx)("span",{children:E("history.label")})]}),(t=!!(O&&((tg?.userMessages??0)>0||O.messageCount>0)),n=!O||O.transient||!t||"naming"===tx.kind,i="success"===tx.kind,o="error"===tx.kind,l="naming"===tx.kind?E("title.generating"):i?E("title.updated"):o?E("title.failed"):E("title.generate"),s=!O||O.transient?E("title.unsaved"):t?o?tx.message:E("title.generateSession"):E("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{na(),e&&R&&eH(!0)},disabled:n,title:s,"aria-label":l,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"none",border:"none",borderTop:"2px solid transparent",borderRight:"1px solid var(--border)",color:o?"#dc2626":i?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",cursor:n?"not-allowed":"pointer",opacity:n&&"naming"!==tx.kind?.45:1,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{n||(e.currentTarget.style.color=o?"#dc2626":"var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=o?"#dc2626":i?"var(--accent)":n?"var(--text-dim)":"var(--text-muted)",e.currentTarget.style.background="none"},"data-mobile-toolbar-action":e?"name":void 0,children:["naming"===tx.kind?(0,r.jsxs)("svg",{className:"animate-spin",width:"13",height:"13",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):i?(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)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m15 4 5 5L7 22l-5-5Z"}),(0,r.jsx)("path",{d:"m14 5 5 5"}),(0,r.jsx)("path",{d:"M6 4V2M5 3H3M19 19v3M17.5 20.5h3"})]}),!e&&(0,r.jsx)("span",{children:l})]})),Y&&(0,r.jsxs)("button",{type:"button",onClick:()=>tz("agents",e),title:E("agentSwitcher.title"),"aria-label":E("agentSwitcher.title"),"aria-pressed":"agents"===tE,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"agents"===tE?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===tE?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===tE?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},"data-mobile-toolbar-action":e?"agents":void 0,children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"7",width:"14",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M9 11h.01M15 11h.01M9 15h6M12 7V4M10 4h4"})]}),!e&&(0,r.jsx)("span",{children:E("agentSwitcher.title")}),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:15,height:15,padding:"0 4px",display:"grid",placeItems:"center",borderRadius:7,background:"var(--bg-selected)",color:"var(--accent)",fontSize:10,lineHeight:1,fontVariantNumeric:"tabular-nums",...e?{position:"absolute",top:2,right:2,minWidth:13,height:13,padding:"0 3px",fontSize:9}:{}},children:J.subagents.length})]}),e7&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>tz("branches",!0),title:E("i18n.branches"),"aria-label":E("i18n.branches"),"aria-pressed":"branches"===tE,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:"branches"===tE?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===tE?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===tE?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0},"data-mobile-toolbar-action":"branches",children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:e8.length>0?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}):(0,r.jsx)(lt,{tree:e8,activeLeafId:e6,onLeafChange:tt,inline:!0,containerRef:e2,open:"branches"===tE,onToggle:()=>tz("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tc,type:"button",onClick:()=>tW("system",e),disabled:e&&!nk,title:E("system.prompt"),"aria-label":E("system.prompt"),"aria-pressed":"system"===tE,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===tE?"var(--bg-selected)":"none",border:"none",borderTop:"system"===tE?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!nk?"not-allowed":"pointer",color:"system"===tE?"var(--text)":"var(--text-muted)",opacity:e&&!nk?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||nk)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===tE?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"system":void 0,children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:tn?"var(--accent)":"var(--text-dim)",flexShrink:0},"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"})]}),!e&&(0,r.jsx)("span",{children:E("system.label")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>tW("tools",e),disabled:e&&!nk,title:E("tools.title"),"aria-label":E("tools.title"),"aria-pressed":"tools"===tE,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===tE?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===tE?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!nk?"not-allowed":"pointer",color:"tools"===tE?"var(--text)":"var(--text-muted)",opacity:e&&!nk?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||nk)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===tE?"var(--text)":"var(--text-muted)"},"data-mobile-toolbar-action":e?"tools":void 0,children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:ti?.some(e=>e.active)?"var(--accent)":"var(--text-dim)",flexShrink:0},"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"})}),!e&&(0,r.jsx)("span",{children:E("tools.label")})]})]}):null},nN=e=>{if(!e&&(!nk||!tg&&!tC))return null;let t=tg?.tokens,n=tg?.cost??0,i=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),o=n>0?n>=.01?`$${n.toFixed(2)}`:"<$0.01":null,l="var(--text-muted)",s=null,a=null;if(tC?.contextWindow){let e=tC.percent;null!==e&&e>90?l="#ef4444":null!==e&&e>70&&(l="rgba(234,179,8,0.95)"),s=null!==e?`${e.toFixed(0)}% / ${i(tC.contextWindow)}`:`? / ${i(tC.contextWindow)}`,a=null!==e?`${e.toFixed(0)}%`:null}let d=[];if(t&&(d.push(`in: ${t.input.toLocaleString(M)}`),d.push(`out: ${t.output.toLocaleString(M)}`),d.push(`cache read: ${t.cacheRead.toLocaleString(M)}`),d.push(`cache write: ${t.cacheWrite.toLocaleString(M)}`),n>0&&d.push(`cost: $${n.toFixed(4)}`)),tC?.contextWindow){let e=tC.percent;d.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${tC.contextWindow.toLocaleString()} tokens`)}let c=d.join(" | "),u=e&&R&&eD,p=!!(t&&(t.input>0||t.output>0)||o||a);return(0,r.jsx)("button",{type:"button",onClick:()=>tz("session"),disabled:!nk||u,tabIndex:u?-1:void 0,title:c||E("session.title"),"aria-label":E("session.title"),"aria-pressed":"session"===tE,"aria-hidden":!!u||void 0,className:e?"mobile-session-stats":void 0,"data-mobile-toolbar-stats":e?"true":void 0,style:{marginLeft:e?0:"auto",display:"flex",alignItems:"center",justifyContent:"flex-end",flex:e?1:void 0,minWidth:0,gap:e?7:10,paddingLeft:e?6:12,paddingRight:e?6:12,height:"100%",overflow:"hidden",visibility:u?"hidden":"visible",pointerEvents:u?"none":"auto",background:"session"===tE?"var(--bg-selected)":"none",border:"none",borderTop:"session"===tE?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:nk?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{nk&&!u&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===tE?"var(--text)":"var(--text-muted)"},children:e?(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),i(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{className:"mobile-session-stat-io",style:{display:"flex",alignItems:"center",gap:2,flexShrink:0},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),i(t.output)]}),o&&(0,r.jsx)("span",{className:"mobile-session-stat-cost",style:{color:"var(--text)",fontWeight:500,flexShrink:0},children:o}),a&&(0,r.jsx)("span",{style:{color:l,flexShrink:0},children:a}),!p&&nk&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:E("session.title")})]}):(0,r.jsxs)(r.Fragment,{children:[t&&t.input>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"8.5",x2:"5",y2:"1.5"}),(0,r.jsx)("polyline",{points:"2 4 5 1.5 8 4"})]}),i(t.input)]}),t&&t.output>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),i(t.output)]}),t&&t.cacheRead>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8.5 5a3.5 3.5 0 1 1-1-2.45"}),(0,r.jsx)("polyline",{points:"6.5 1.5 8.5 2.5 7.5 4.5"})]}),i(t.cacheRead)]}),o&&(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",color:"var(--text)",fontWeight:500},children:o}),s&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:l},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M1 9 L1 5 Q1 1 5 1 Q9 1 9 5 L9 9"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"9",y2:"9"})]}),s]})]})})},nz=e=>{let t=e&&R&&eD;return(0,r.jsx)("button",{type:"button",onClick:tB,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":eF,"aria-hidden":!!t||void 0,title:eF?E("files.hidePanel"):E("files.showPanel"),"aria-label":eF?E("files.hidePanel"):E("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||tg||tC?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:eF?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:eF?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{t||(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color=eF?"var(--text)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",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"})]})})};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
201
- @keyframes session-info-pop {
202
- 0% {
203
- opacity: 0;
204
- transform: translateY(-24px);
205
- filter: blur(6px);
206
- box-shadow: 0 2px 8px rgba(0,0,0,0);
207
- }
208
- 55% {
209
- opacity: 1;
210
- transform: translateY(0);
211
- filter: blur(0);
212
- background: color-mix(in srgb, var(--accent) 8%, var(--bg-panel));
213
- box-shadow: 0 18px 44px rgba(37,99,235,0.16);
214
- }
215
- 100% {
216
- opacity: 1;
217
- transform: translateY(0);
218
- filter: blur(0);
219
- background: var(--bg-panel);
220
- box-shadow: 0 10px 28px rgba(0,0,0,0.10);
221
- }
222
- }
223
- @keyframes session-info-light-wash {
224
- 0% {
225
- opacity: 0;
226
- transform: translateX(-110%) skewX(-16deg);
227
- }
228
- 24% {
229
- opacity: 0.42;
230
- }
231
- 100% {
232
- opacity: 0;
233
- transform: translateX(115%) skewX(-16deg);
234
- }
235
- }
236
- .session-info-popover {
237
- position: relative;
238
- overflow: hidden;
239
- transform-origin: top right;
240
- animation: session-info-pop 360ms ease-out both;
241
- will-change: transform, opacity, filter, background, box-shadow;
242
- }
243
- .session-info-popover::after {
244
- content: "";
245
- position: absolute;
246
- top: 0;
247
- bottom: 0;
248
- left: 0;
249
- width: 44%;
250
- pointer-events: none;
251
- background: linear-gradient(90deg, transparent, color-mix(in srgb, var(--accent) 24%, transparent), transparent);
252
- animation: session-info-light-wash 620ms ease-out both;
253
- }
254
- @media (prefers-reduced-motion: reduce) {
255
- .session-info-popover,
256
- .session-info-popover::after {
257
- animation: none;
258
- }
259
- }
260
- .mobile-session-stats {
261
- container-type: inline-size;
262
- }
263
- @container (max-width: 158px) {
264
- .mobile-session-stat-io {
265
- display: none !important;
266
- }
267
- }
268
- @container (max-width: 88px) {
269
- .mobile-session-stat-cost {
270
- display: none !important;
271
- }
272
- }
273
- @media (max-width: 640px) {
274
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
275
- opacity: 0 !important;
276
- pointer-events: none !important;
277
- }
278
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
279
- transform: translateX(calc(-100% - env(safe-area-inset-left)));
280
- box-shadow: none;
281
- }
282
- }
283
- `}),(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${eO?"":" sidebar-mobile-pending"}`,onClick:()=>eA(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!eP,pointerEvents:eP?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:eY.panelRef,id:"session-sidebar",className:`sidebar-container${eP?" sidebar-open":" sidebar-closed"}${eO?"":" sidebar-mobile-pending"}${eY.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${eY.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:nR}),eP&&(0,r.jsx)("div",{...eY.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${eY.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${E("layout.resizeSidebar")}: ${E("layout.resizeHint")}`}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:e2,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",position:"relative",borderBottom:"1px solid var(--border)",height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)"},children:[(0,r.jsx)("button",{onClick:tA,title:eP?E("sidebar.hide"):E("sidebar.show"),"aria-label":eP?E("sidebar.hide"):E("sidebar.show"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",borderRight:"1px solid var(--border)",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:eP?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",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:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",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"})]})}),I&&(0,r.jsxs)("div",{ref:e4,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[R&&(0,r.jsx)("button",{type:"button",onClick:tF,title:eD?E("chat.close"):E("chat.moreControls"),"aria-label":eD?E("chat.close"):E("chat.moreControls"),"aria-controls":"mobile-toolbar-actions","aria-expanded":eD,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:eD?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:eD?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:eD?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:eD?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"5",y1:"5",x2:"19",y2:"19"}),(0,r.jsx)("line",{x1:"19",y1:"5",x2:"5",y2:"19"})]}):(0,r.jsxs)("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.5"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1.5"})]})}),!R&&n$(!0),nN(!0),nz(!0),R&&eD&&(0,r.jsx)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":E("chat.moreControls"),"data-mobile-toolbar-actions":"true",style:{position:"absolute",top:0,right:0,bottom:0,left:36,zIndex:20,display:"flex",alignItems:"stretch",background:"color-mix(in srgb, var(--bg-panel) 94%, var(--bg))",boxShadow:"4px 0 18px rgba(0,0,0,0.12)",backdropFilter:"blur(10px)"},children:n$(!0)})]}),!I&&(0,r.jsxs)(r.Fragment,{children:[nL(!1),n$(!1),nN(!1)]}),!I&&nz(!1),I&&e7&&(0,r.jsx)(lt,{tree:e8,activeLeafId:e6,onLeafChange:tt,inline:!0,compact:!0,containerRef:e2,open:"branches"===tE,onToggle:()=>tz("branches"),hasSession:nk,hideInlineButton:!0}),tE&&tR&&(0,r.jsxs)("div",{style:{position:"fixed",top:tR.top,left:tR.left,width:tR.width,maxHeight:`calc(100dvh - ${tR.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===tE&&J&&O&&(0,r.jsx)(ld,{rootSession:J.root,subagents:J.subagents,selectedSessionId:O.id,runningSessionIds:Z,onSelectSession:ne}),"system"===tE&&(0,r.jsx)(ln,{loading:tl,prompt:tn,translate:E}),"tools"===tE&&(0,r.jsx)(lo,{loading:tl,tools:ti,translate:E}),"session"===tE&&(0,r.jsx)("div",{className:"session-info-popover",style:{background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",boxShadow:"0 10px 28px rgba(0,0,0,0.10)",padding:"12px 16px"},children:tg?(e=tg.totalActiveMs??0,t=[...tg.sessionName?[{label:E("session.name"),value:tg.sessionName,copyField:null}]:[],{label:E("session.file"),value:tg.sessionFile??E("session.inMemory"),copyField:"file"},{label:E("session.id"),value:tg.sessionId,copyField:"id"},...e>0?[{label:E("session.totalActive"),value:(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`})(e),copyField:null}]:[]],n=[...O?[{label:E("session.projectDir"),value:O.projectRoot??O.cwd,copyField:"projectDir"}]:[],...O?.branch?[{label:E("session.gitBranch"),value:O.branch,copyField:"gitBranch"}]:[],...O?.isWorktree?[{label:E("session.gitWorktree"),value:O.cwd,copyField:"gitWorktree"}]:[]],s=[[E("session.user"),tg.userMessages.toLocaleString(M)],[E("session.assistant"),tg.assistantMessages.toLocaleString(M)],[E("session.toolCalls"),tg.toolCalls.toLocaleString(M)],[E("session.toolResults"),tg.toolResults.toLocaleString(M)],[E("session.total"),tg.totalMessages.toLocaleString(M)]],a=[[E("session.input"),tg.tokens.input.toLocaleString(M)],[E("session.output"),tg.tokens.output.toLocaleString(M)],...tg.tokens.cacheRead>0?[[E("session.cacheRead"),tg.tokens.cacheRead.toLocaleString(M)]]:[],...tg.tokens.cacheWrite>0?[[E("session.cacheWrite"),tg.tokens.cacheWrite.toLocaleString(M)]]:[],[E("session.total"),tg.tokens.total.toLocaleString(M)]],d=tC??tg.contextUsage,u=[...tg.cost>0?[[E("session.cost"),`$${tg.cost.toFixed(4)}`]]:[],...d?.contextWindow?[[E("session.context"),`${null!==d.percent?`${d.percent.toFixed(1)}%`:"?"} / ${(c=d.contextWindow)>=1e6?`${(c/1e6).toFixed(1)}M`:c>=1e3?`${(c/1e3).toFixed(0)}k`:String(c)}`]]:[],...tg.tokens.cacheRead+tg.tokens.cacheWrite>0&&tg.tokens.cacheRead+tg.tokens.cacheWrite+tg.tokens.input>0?[[E("session.cacheHitRate"),`${(tg.tokens.cacheRead/(tg.tokens.cacheRead+tg.tokens.cacheWrite+tg.tokens.input)*100).toFixed(1)}%`]]:[]],p=(e,t,n="left",i=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:i?"max-content max-content":"auto minmax(0, 1fr)",columnGap:i?14:12,rowGap:4,justifyContent:i?"start":void 0},children:t.map(([t,o])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:i?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:o})]},`${e}:${t}`))})]}),g={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},f=(e,t)=>{let n=tj===e;return(0,r.jsx)("button",{type:"button",title:n?E("session.copied"):E(g[e]),onClick:()=>tS(e,t),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:n?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=n?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:n?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",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",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"})]})})},x=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:E("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:t.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?f(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),m=n.length>0?(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:E("session.projectSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:n.map(e=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?f(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:I?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:I?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:I?16:20},children:[x,m]}),p(E("session.messages"),s),p(E("session.tokens"),[...a,...u],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:E("session.load")})})]})]}),I&&nL(!0)]}),(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:nk?(0,r.jsx)(rV,{session:O,searchTarget:ev?.sessionId===O?.id?ev:null,onSearchTargetHandled:eb,initialScrollPosition:O?ex.current.get(O.id)??null:null,onScrollPositionChange:em,sessionRunning:!!(O&&Z.has(O.id)),newSessionCwd:nb,newSessionDraftKey:nj,onAgentEnd:nl,onAttentionNeeded:ns,onSessionCreated:ni,onSessionForked:nc,modelsRefreshKey:eC,chatInputRef:eQ,onBranchDataChange:te,onSystemPromptChange:tu,onSystemToolsChange:tp,onSystemInfoLoaderChange:th,onSessionStatsChange:tb,onSessionStatsPanelOpen:tP,onContextUsageChange:tM,onOpenFile:nf,onOpenSession:nr,onAskInNewChat:nu,quoteSelectionEnabled:P,initialPrompt:e0?.sessionId===O?.id?e0?.text:void 0,onInitialPromptConsumed:()=>e1(null),soundEnabled:L,onSoundToggle:$,playDoneSound:N,unlockAudio:z},eg):"validating"===ei?(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:E("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:C.requestedCwd})]}):"error"===ei?(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:E("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:C.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:el})]}):nC?t0?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:E("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:E("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),E("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),E("workspace.addModels")]})]})]}):null})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${eF?" is-open":""}`,onClick:()=>eB(!1)}),eF&&(0,r.jsx)("div",{...eZ.separatorProps,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${eZ.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${E("layout.resizeFilePanel")}: ${E("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:eZ.panelRef,id:"file-panel",className:`right-panel-container${eF?" right-panel-open":" right-panel-closed"}${eZ.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${eZ.width}px`,display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,height:"calc(36px + env(safe-area-inset-top))",paddingTop:"env(safe-area-inset-top)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,r.jsx)(im,{tabs:tJ,activeTabId:tO??"",onSelectTab:tU,onCloseTab:nm})}),(0,r.jsx)("button",{type:"button",onClick:()=>eB(!1),"aria-controls":"file-panel","aria-expanded":eF,title:E("files.hidePanel"),"aria-label":E("files.hidePanel"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"var(--bg-selected)",border:"none",borderLeft:"1px solid var(--border)",color:"var(--text)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",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:[nM?.filePath?(0,r.jsx)(ig,{filePath:nM.filePath,cwd:t0??void 0,sourceSessionId:nM.sourceSessionId,gitRefreshKey:ej,initialDisplayMode:nM.initialDisplayMode,initialState:nM.viewerState,watchEnabled:eF,onStateChange:e=>tY(nM.id,nM.viewerRevision??0,e),onMentionLines:eF?tX:void 0,onAtMention:tZ,onOpenFile:e=>ng(e,D(e),{sourceSessionId:nM.sourceSessionId})},`${nM.id}:${nM.viewerRevision??0}`):t_.some(e=>e.id===tO)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:E("files.noneOpen")}),t_.map(e=>(0,r.jsx)("div",{hidden:e.id!==tO,style:{width:"100%",height:"100%"},children:(0,r.jsx)(lh,{tab:e,active:eF&&e.id===tO,onRestart:()=>tq(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?lf(e.cwd):null,n=t_.filter(t=>t.id!==e.id),void(tq(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),tU(r=>r!==e.id?r:t?.id??n.at(-1)?.id??tD.at(-1)?.id??null),!t&&!n.length&&!tD.length&&eB(!1))},onCloseError:()=>tq(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),ek&&(0,r.jsx)(o5,{cwd:nS,sessionId:O?.id??null,initialSection:ek,quoteSelectionEnabled:P,onQuoteSelectionChange:F,onClose:()=>{eS(null),eT(e=>e+1)},onSessionReloaded:()=>ef(e=>e+1)}),eI&&nS&&(0,r.jsx)(o6,{cwd:nS,busy:eL,error:ez,onCancel:()=>{eL||eR(!1)},onConfirm:()=>void nT()})]})}},88576:e=>{e.exports={preview:"ChatMinimap_preview__laAya",turn:"ChatMinimap_turn__fZuce",number:"ChatMinimap_number__3C_cY",content:"ChatMinimap_content__C7_ju",user:"ChatMinimap_user__WHJHv",userText:"ChatMinimap_userText__Nj9jo",assistant:"ChatMinimap_assistant__s6JLb",assistantJump:"ChatMinimap_assistantJump__3CM2M",outline:"ChatMinimap_outline__aleIF",heading:"ChatMinimap_heading__djZbv",paragraph:"ChatMinimap_paragraph__EqWlO"}}},e=>{e.O(0,[7523,7330,3888,5772,9445,1278,8441,3794,7358],()=>e(e.s=42927)),_N_E=e.O()}]);