@silgrid/pi-web 0.0.5 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +5 -5
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +4 -4
- package/.next/react-loadable-manifest.json +3 -5
- package/.next/required-server-files.js +2 -2
- package/.next/required-server-files.json +2 -2
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +3 -3
- package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/app-update/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +5 -5
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
- package/.next/server/app/index.segments/_full.segment.rsc +5 -5
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login.html +1 -1
- package/.next/server/app/login.rsc +4 -4
- package/.next/server/app/login.segments/_full.segment.rsc +4 -4
- package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +4 -4
- package/.next/server/app/page.js +20 -20
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +5 -5
- package/.next/server/chunks/2243.js +1 -1
- package/.next/server/chunks/3573.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/middleware-react-loadable-manifest.js +1 -1
- package/.next/server/next-font-manifest.js +1 -1
- package/.next/server/next-font-manifest.json +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/1278-ace42c71e9c71bee.js +1 -0
- package/.next/static/chunks/255-17cbcefee7dd62ba.js +7 -0
- package/.next/static/chunks/{3308.be8762955e7155d1.js → 3308.d63379fadcb93e81.js} +1 -1
- package/.next/static/chunks/7268.7bf6d531e3905a52.js +1 -0
- package/.next/static/chunks/app/{layout-1ec2a79712d0baf7.js → layout-17e263fe010a6a66.js} +1 -1
- package/.next/static/chunks/app/page-af6dfbc74f2191e6.js +283 -0
- package/.next/static/chunks/webpack-70f73ef4c4733a9b.js +1 -0
- package/.next/static/css/7b014bd2f1467e2f.css +1 -0
- package/.next/trace +40 -40
- package/.next/trace-build +1 -1
- package/deploy-piweb.sh +1 -1
- package/next.config.ts +9 -0
- package/package.json +1 -1
- package/.next/static/chunks/1278-b726924fe981dfeb.js +0 -1
- package/.next/static/chunks/2619.9431a3f48da8eef4.js +0 -1
- package/.next/static/chunks/7268.236544be8e242c16.js +0 -1
- package/.next/static/chunks/9445-fde6feabcb39142c.js +0 -7
- package/.next/static/chunks/app/page-7abbde455abf962c.js +0 -283
- package/.next/static/chunks/webpack-1b16208bb4ccd9c1.js +0 -1
- package/.next/static/css/bf8c57dddea37459.css +0 -1
- /package/.next/static/{hq1-OzAFMrVlhibzmMDT9 → KNYsOgoq--Ba6lozIl9be}/_buildManifest.js +0 -0
- /package/.next/static/{hq1-OzAFMrVlhibzmMDT9 → KNYsOgoq--Ba6lozIl9be}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{14242:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>l9});var r=n(95155),i=n(12115),o=n(73321);let l=null,s=new Set;function a(e){let t=function(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let r of e){if(n.has(r.id))continue;let e=[],i=new Set,o=r.id,l=null;for(;;){if(n.has(o)){l=n.get(o)??null;break}if(i.has(o))break;i.add(o),e.push(o);let r=t.get(o);if(!r)break;if(r.relation?.kind!=="subagent"){l=r.id;break}o=r.relation.parentSessionId}for(let t of e)n.set(t,l)}return n}(e),n=new Map;for(let t of e)t.relation?.kind!=="subagent"&&n.set(t.id,{root:t,subagents:[],latestModified:t.modified});for(let r of e){if(r.relation?.kind!=="subagent")continue;let e=t.get(r.id),i=e?n.get(e):void 0;i&&(i.subagents.push(r),r.modified>i.latestModified&&(i.latestModified=r.modified))}return[...n.values()].sort((e,t)=>t.latestModified.localeCompare(e.latestModified))}let d="pi-web:file-explorer:open";function c(){try{return window.localStorage}catch{return null}}let u=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function p(e){let t=e.match(u);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}let h="pi-web:last-open-by-workspace";function f(){try{return window.localStorage}catch{return null}}function g(e){let t=e.getItem(h);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function x(e,t=f()){if(t)try{let n=g(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(h):t.setItem(h,JSON.stringify(n))}catch{}}function m(e){return e.projectKey??e.projectRoot??e.cwd}function v(e){if(!e)return"?";let t=e.replace(/[/\\]+$/,"");if(!t)return"?";let n=t.split(/[/\\]/).filter(Boolean);return n[n.length-1]||"?"}function y(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=m(n),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{root:e,modified:n.modified})}return[...t.entries()].sort((e,t)=>t[1].modified.localeCompare(e[1].modified)).map(([e,{root:t}])=>({key:e,root:t}))}function b(e,t){return e.filter(e=>m(e)===t)}let w="pi-web:pinned-projects";function k(){try{return window.localStorage}catch{return null}}function j(e){let t,n=e.getItem(w);if(!n)return[];try{t=JSON.parse(n)}catch{return[]}if(!Array.isArray(t))return[];let r=[],i=new Set;for(let e of t){let t=null;if("string"==typeof e&&e.length>0)t={key:e,root:e};else if(e&&"object"==typeof e){let{key:n,root:r}=e;"string"==typeof n&&n.length>0&&(t={key:n,root:"string"==typeof r&&r.length>0?r:n})}t&&!i.has(t.key)&&(i.add(t.key),r.push(t))}return r}function S(e,t){0===t.length?e.removeItem(w):e.setItem(w,JSON.stringify(t))}function C(e=k()){if(!e)return[];try{return j(e)}catch{return[]}}let I="pi-web:file-explorer:section-expanded";function T(){try{return window.localStorage}catch{return null}}function M(e,t=T()){if(t)try{0===e.size?t.removeItem(I):t.setItem(I,JSON.stringify([...e]))}catch{}}function E(e){return e.trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}var R=n(2730),L=n(21278);function $(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 W(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function z(e){let{ariaLabel:t,axis:n="horizontal",cssVariable:r,defaultWidth:o,getDefaultWidth:l,getMaxWidth:s,growthDirection:a,maxWidth:d,minWidth:c,storageKey:u,widthRef:p}=e,h=(0,i.useRef)(null),f=(0,i.useRef)(null),g=(0,i.useRef)(!1),[x,m]=(0,i.useState)(o),[v,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(!1);(0,i.useEffect)(()=>{w(!0)},[]);let k=(0,i.useCallback)(()=>Math.min(d,Math.max(c,s())),[s,d,c]),j=(0,i.useCallback)(e=>$(e,c,k()),[k,c]),S=(0,i.useCallback)(e=>{p.current=e,h.current?.style.setProperty(r,`${e}px`)},[r,p]),C=(0,i.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,i=j(e),o=i!==p.current;return S(i),m(i),r&&(o||n)&&W(u,i),i},[S,j,u,p]),I=(0,i.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),T=(0,i.useCallback)(e=>{let t=f.current;if(t&&t.pointerId===e){f.current=null,I(t),y(!1),C(p.current,{forcePersist:!0});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[C,I,p]),M=(0,i.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=f.current;t&&T(t.pointerId);let r=e.currentTarget;r.focus({preventScroll:!0}),r.setPointerCapture(e.pointerId),f.current={pointerId:e.pointerId,startPosition:"vertical"===n?e.clientY:e.clientX,startWidth:p.current,target:r,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="vertical"===n?"row-resize":"col-resize",document.body.style.userSelect="none",y(!0)},[n,T,p]),E=(0,i.useCallback)(e=>{let t=f.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void T(e.pointerId);e.preventDefault();let r="right"===a||"down"===a?1:-1,i="vertical"===n?e.clientY:e.clientX,o=j(t.startWidth+(i-t.startPosition)*r);S(o),e.currentTarget.setAttribute("aria-valuenow",String(o)),e.currentTarget.setAttribute("aria-valuetext",`${o} px`)},[S,n,j,T,a]),R=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),L=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),z=(0,i.useCallback)(e=>{T(e.pointerId)},[T]),N=(0,i.useCallback)(()=>{C(l?.()??o,{forcePersist:!0})},[C,o,l]),P=(0,i.useCallback)(()=>{C(p.current)},[C,p]),A=(0,i.useCallback)(e=>{let t=e.shiftKey?32:12,r="right"===a||"down"===a,i="vertical"===n?"ArrowDown":"ArrowRight",o="vertical"===n?"ArrowUp":"ArrowLeft";e.key===(r?i:o)?(e.preventDefault(),C(p.current+t,{forcePersist:!0})):e.key===(r?o:i)?(e.preventDefault(),C(p.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),C(c,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),C(k(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),N())},[n,C,k,a,c,N,p]);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}}(u),t=C(e??l?.()??o,{persist:!1});null!==e&&e!==t&&W(u,t)},[C,o,l,u]),(0,i.useEffect)(()=>{if(!g.current)return;C(p.current);let e=()=>{C(p.current)};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[C,p]),(0,i.useEffect)(()=>{if(!v)return;let e=()=>{let e=f.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,v]),(0,i.useEffect)(()=>()=>{let e=f.current;e&&(f.current=null,I(e))},[I]),{isResizing:v,panelRef:h,reclampWidth:P,resetWidth:N,separatorProps:{"aria-label":t,"aria-orientation":"vertical"===n?"horizontal":"vertical","aria-valuemax":b?k():d,"aria-valuemin":c,"aria-valuenow":x,"aria-valuetext":`${x} px`,onDoubleClick:N,onKeyDown:A,onLostPointerCapture:z,onPointerCancel:L,onPointerDown:M,onPointerMove:E,onPointerUp:R,role:"separator",tabIndex:0},width:x}}var N=n(47650);async function P(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 A(){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 B(){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 D({onCancel:e,onSelect:t,initialPath:n,busy:o=!1,error:l}){let{t:s}=(0,L.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(""),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(n??""),[x,m]=(0,i.useState)([]),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(!0),S=(0,i.useCallback)(async e=>{j(!0),w(null);try{let t=await P(e),n=t.path??e??"/";u(n),h(t.parentPath??null),g(n),m(t.directories??[]),y(t.drives??null)}catch(e){w(e instanceof Error?e.message:String(e))}finally{j(!1)}},[]);(0,i.useEffect)(()=>{d(document.body),S(n||void 0)},[n,S]);let C=f.trim()!==c,I=!!c&&!C&&!o,T=!!p||/^[a-zA-Z]:[\\/]?$/.test(c);return a?(0,N.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||o||e()},onKeyDown:t=>{"Escape"!==t.key||o||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:o,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:o?"default":"pointer",opacity:o?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&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:k||!T,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:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),w(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:k||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:k||!f.trim()?"default":"pointer",opacity:k||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[k?(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)(B,{}),(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)(A,{}),(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:!I,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:I?1:.6,cursor:I?"pointer":"default"},children:s(o?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),a):null}let F="/icons/catppuccin";function H({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${F}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${F}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function O({size:e=14,open:t=!1}){return(0,r.jsx)(H,{name:t?"_folder_open":"_folder",size:e})}function U({size:e=14}){return(0,r.jsx)(H,{name:"_file",size:e})}let _={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 q(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)(H,{name:i,size:t});let o=_[n.split(".").pop()??""];return o?(0,r.jsx)(H,{name:o,size:t}):(0,r.jsx)(U,{size:t})}function K(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function V(e){let t=K(e),n=t.split("/").filter(Boolean);return t.startsWith("//")&&n.length>0&&(n[0]=`//${n[0]}`),n.map(encodeURIComponent).join("/")}function J(e){let t=K(e).replace(/\/+$/,"");return t.split("/").pop()??t}function Y(e){let t=K(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function Z(e,t){if(!t)return e;let n=K(e),r=K(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function G(e,t){return`${K(e).replace(/\/$/,"")}/${t}`}var X=n(92619).Buffer;let Q="base64";function ee(){return window.Capacitor}function et(){let e=ee();return e?.isNativePlatform?.()===!0}function en(e){if(!et())return null;let t=ee();if(!t)return null;let n=t.Plugins?.[e];if(n)return n;if("function"!=typeof t.registerPlugin)return null;try{return t.registerPlugin(e,{})??null}catch{return null}}function er(){return en("Camera")}function ei(){return en("FilePicker")}function eo(){return en("LocalNotifications")}function el(e){let t="function"==typeof atob?atob(e):X.from(e,"base64").toString("binary"),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function es(e,t="jpeg"){let n="jpg"===t?"jpeg":t,r=`image/${n}`,i="u">typeof Date?Date.now():0;return new File([el(e)],`camera-${i}.${n}`,{type:r})}function ea(e){let t=[];return e.forEach((e,n)=>{let r=e.blob??null;if(!r&&e.data)try{r=el(e.data)}catch{r=null}if(!r)return;let i=function(e,t){if(e.name)return e.name;if(e.path){let t=e.path.split("/").filter(Boolean).pop();if(t&&t.includes("."))return t}return`upload-${Date.now()}-${t+1}`}(e,n),o=r instanceof Blob?r.type:"",l=e.mimeType&&""!==e.mimeType?e.mimeType:o;t.push(new File([r],i,l?{type:l}:void 0))}),t}async function ed(e){let t=V(e),n=await fetch(`/api/files/${t}?type=list`);if(!n.ok){let e=`Failed to load files (HTTP ${n.status})`;try{let t=await n.json();t.error&&(e=t.error)}catch{}throw Error(e)}return((await n.json()).entries??[]).map(t=>({name:t.name,fullPath:G(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function ec(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 eu={modified:"files.modified",added:"files.added",deleted:"files.deleted",renamed:"files.renamed",untracked:"files.untracked",conflict:"files.conflict"},ep={modified:"#d6a84b",added:"#4ade80",deleted:"#f87171",renamed:"#60a5fa",untracked:"#4ade80",conflict:"#f87171"};function eh({status:e,t}){return(0,r.jsx)("span",{title:t(eu[e.status]),"aria-label":t(eu[e.status]),style:{width:14,height:14,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",color:ep[e.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600},children:e.code})}function ef({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 eg({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 ex({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 f=s.has(e.fullPath),g=c.has(e.fullPath),x=K(e.fullPath),m=u.get(x),v=e.isDir&&(void 0!==m||p.has(x)),[y,b]=(0,i.useState)(e.children??[]),[w,k]=(0,i.useState)(e.loaded??!1),[j,S]=(0,i.useState)(!1),[C,I]=(0,i.useState)(!1),T=(0,i.useCallback)(async(t=!1)=>{if(!w||t){S(!0);try{let t=await ed(e.fullPath);b(t),k(!0)}catch{}finally{S(!1)}}},[w,e.fullPath]);(0,i.useEffect)(()=>{void 0!==d&&f&&w&&T(!0)},[d]);let M=(0,i.useCallback)(()=>{if(e.isDir){let t=!f;a(e.fullPath,t),t&&!w&&T()}else o(e.fullPath,e.name)},[e.isDir,e.fullPath,e.name,w,f,T,o,a]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{onClick:M,onMouseEnter:()=>I(!0),onMouseLeave:()=>I(!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:f?"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)(O,{size:14,open:f}):q(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}),g&&(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)(eh,{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"}})}),j&&(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(Z(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)(ef,{}),h("files.mention")]}),C&&!e.isDir&&(0,r.jsx)("a",{href:`/api/files/${V(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&&f&&(0,r.jsxs)("div",{children:[y.map(e=>(0,r.jsx)(ex,{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&&w&&(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 em({status:e,cwd:t,onOpenFile:n,onAtMention:o,t:l}){let[s,a]=(0,i.useState)(!1),d=J(e.filePath),c=Z(e.filePath,t),u=c.lastIndexOf("/"),p=u>=0?c.slice(0,u+1):"",h=u>=0?c.slice(u+1):c;return(0,r.jsxs)("div",{onClick:()=>n(e.filePath,d,{modeHint:"diff"}),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,paddingLeft:10,paddingRight:8,height:24,cursor:"pointer",background:s?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none",position:"relative"},children:[(0,r.jsx)(eh,{status:e,t:l}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center",opacity:.85},children:q(d,13)}),(0,r.jsxs)("span",{title:e.filePath,style:{fontSize:12,color:"var(--text)",display:"flex",alignItems:"center",minWidth:0,flex:1},children:[p&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:"0 1 auto",minWidth:0,color:"var(--text-dim)"},children:p}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flexShrink:0,maxWidth:"100%"},children:h})]}),o&&s&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),o(c,!1)},title:l("files.insertPath"),style:{position:"absolute",right:4,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)(ef,{}),l("files.mention")]})]})}let ev=(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,L.s)(),[f,g]=(0,i.useState)([]),[x,m]=(0,i.useState)(!0),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(new Set),[k,j]=(0,i.useState)(0),[S,C]=(0,i.useState)(new Set),[I,T]=(0,i.useState)([]),[M,E]=(0,i.useState)({additions:0,deletions:0}),[R,$]=(0,i.useState)("idle"),[W,z]=(0,i.useState)(0),[N,P]=(0,i.useState)(null),[A,B]=(0,i.useState)(null),[D,F]=(0,i.useState)(null),[H,O]=(0,i.useState)(""),[U,_]=(0,i.useState)([]),[q,J]=(0,i.useState)(!1),[X,Q]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(new Set),en=(0,i.useRef)(null),er=(0,i.useRef)(null),eo=(0,i.useRef)(null),el=`${n??0}:${k}`,es="idle"!==R,eu=H.trim().length>0;(0,i.useEffect)(()=>{if(!c)return;let t=H.trim();if(!t){_([]),J(!1),Q(!1);return}let n=new AbortController;J(!0),Q(!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=>_((e.matches??[]).filter(e=>!e.isDir).map(e=>e.path))).catch(()=>{n.signal.aborted||(_([]),Q(!0))}).finally(()=>{n.signal.aborted||J(!1)})},150);return()=>{clearTimeout(r),n.abort()}},[e,c,H]),(0,i.useEffect)(()=>{c&&en.current?.focus()},[c]),(0,i.useEffect)(()=>{if(0===U.length)return;let t=new Set;for(let n of U){let r=n.split("/"),i="";for(let n=0;n<r.length-1;n++)i=i?`${i}/${r[n]}`:r[n],t.add(G(e,i))}et(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,U]);let eh=(0,i.useMemo)(()=>{let t=n=>({name:n.name,fullPath:G(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})(U).map(t)},[e,U]),ev=(0,i.useMemo)(()=>new Map(I.map(e=>[K(e.filePath),e])),[I]),ey=(0,i.useMemo)(()=>{let t=new Set,n=K(e).replace(/\/$/,"");for(let e of I){let r=Y(K(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=Y(r);if(e===r)break;r=e}}return t},[e,I]),eb=(0,i.useCallback)((e,t)=>{w(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},[]),ew=(0,i.useCallback)(t=>{let n=t.uploaded??[];B({uploaded:n,skipped:t.skipped??[],errors:t.errors??[]}),n.length>0&&(C(new Set(n.map(t=>G(e,t)))),j(e=>e+1))},[e]),ek=(0,i.useCallback)(async(t,n)=>{F(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/${V(e)}?type=upload&conflict=${n}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&z(Math.round(e.loaded/e.total*100))},l.onerror=()=>i(Error("Network error while uploading files")),l.onabort=()=>i(Error("Upload cancelled")),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}r({status:l.status,data:e})},l.send(o)});if(409===r&&i.conflicts?.length)return void F({files:t,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??`Upload failed (HTTP ${r})`);z(100),ew(i)}catch(e){P(e instanceof Error?e.message:String(e))}finally{$("idle")}},[ew,e]),ej=(0,i.useCallback)(async t=>{if(0!==t.length&&!es){B(null),C(new Set),F(null),P(null),z(0),$("checking");try{let n=await fetch(`/api/files/${V(e)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:t.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??`Upload check failed (HTTP ${n.status})`);if(r.conflicts?.length)return void F({files:t,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ek(t,"error")}catch(e){P(e instanceof Error?e.message:String(e))}finally{$("idle")}}},[e,ek,es]),eS=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",ej(t)},[ej]);(0,i.useImperativeHandle)(p,()=>({openUploadPicker(){if(es)return;let e=ei();e?(async()=>{try{let{files:t}=await e.pickFiles({readData:!0});await ej(ea(t))}catch{}})():eo.current?.click()}}),[es,ej]),(0,i.useEffect)(()=>{s?.(es)},[s,es]),(0,i.useEffect)(()=>()=>s?.(!1),[s]),(0,i.useEffect)(()=>{let t=er.current!==e;er.current=e,t&&(w(new Set),C(new Set),B(null),F(null),P(null)),m(t),y(null);let n=!1;return ed(e).then(e=>{n||g(e)}).catch(e=>{n||y(e instanceof Error?e.message:String(e))}).finally(()=>{n||m(!1)}),()=>{n=!0}},[e,n,k]),(0,i.useEffect)(()=>{let t=!1;return ec(e).then(e=>{t||(T(e.isGitRepository?e.files:[]),E(e.isGitRepository?{additions:e.additions,deletions:e.deletions}:{additions:0,deletions:0}))}).catch(()=>{t||(T([]),E({additions:0,deletions:0}))}),()=>{t=!0}},[e,n,k]),(0,i.useEffect)(()=>{d?.(I.length)},[I,d]);let eC=es||null!==D||null!==N||null!==A,eI=(0,i.useCallback)(()=>{A&&0!==A.uploaded.length&&l?.(A.uploaded.map(t=>Z(G(e,t),e)))},[e,l,A]);return(0,r.jsxs)("div",{style:{minHeight:"100%"},children:[(0,r.jsx)("input",{ref:eo,type:"file",multiple:!0,hidden:!0,onChange:eS}),eC&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[es&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===R?h("files.checking"):h("files.uploading",{progress:W}),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===R?(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"===R&&(0,r.jsxs)("span",{style:{fontSize:10},children:[W,"%"]})]}),"uploading"===R&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${W}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),D&&(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:D.conflicts.length,countSuffix:1===D.conflicts.length?"":"s",files:D.conflicts.join(", ")})}),D.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"#f59e0b",lineHeight:1.35,overflowWrap:"anywhere"},children:h("files.cannotReplace",{files:D.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ek(D.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 ek(D.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:()=>F(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")})]})]}),N&&(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:N}),(0,r.jsx)(eg,{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:eI,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)(ef,{}),h("files.mention")]}),(0,r.jsx)(eg,{onClick:()=>B(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:en,value:H,onChange:e=>O(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}}),H&&(0,r.jsx)("button",{type:"button",onClick:()=>O(""),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"})]})})]}),eu&&(0,r.jsxs)("div",{style:{paddingTop:3},children:[q&&(0,r.jsx)("div",{role:"status",style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:h("sidebar.searchingFiles")}),!q&&X&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 2px",fontSize:10,color:"#f87171"},children:h("i18n.networkError")}),!q&&!X&&0===U.length&&(0,r.jsx)("div",{style:{padding:"6px 2px",fontSize:10,color:"var(--text-dim)"},children:h("sidebar.noMatchingFiles")}),!q&&!X&&U.length>0&&(0,r.jsx)("div",{children:eh.map(n=>(0,r.jsx)(ex,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:ee,onToggleExpanded:(e,t)=>{et(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r})},highlightedPaths:S,gitStatusByPath:ev,changedDirectoryPaths:ey,t:h},`${H}:${n.fullPath}`))})]})]}),!a&&I.length>0&&(0,r.jsxs)("div",{style:{padding:"0 4px 2px"},children:[(0,r.jsxs)("div",{"aria-label":h("files.changeStats",{count:I.length,additions:M.additions,deletions:M.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:I.length})}),(0,r.jsxs)("span",{style:{color:ep.added,fontFamily:"var(--font-mono)"},children:["+",M.additions]}),(0,r.jsxs)("span",{style:{color:ep.deleted,fontFamily:"var(--font-mono)"},children:["-",M.deletions]})]}),I.map(n=>(0,r.jsx)(em,{status:n,cwd:e,onOpenFile:t,onAtMention:o,t:h},n.filePath))]}),(a||0===I.length)&&(!c||!eu)&&(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}):f.map(n=>(0,r.jsx)(ex,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:b,onToggleExpanded:eb,refreshToken:el,highlightedPaths:S,gitStatusByPath:ev,changedDirectoryPaths:ey,t:h},n.fullPath)),!x&&!v&&0===f.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:h("files.noFiles")})]})]})});function ey(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}let eb=(0,i.forwardRef)(function({roots:e,staleRoots:t=new Set,homeDir:n,refreshKey:o,onOpenFile:l,onAtMention:s,onAtMentions:a,changesCollapsed:d,onChangesCountChange:c,onUploadBusyChange:u,fileSearchOpen:p=!1,onFileSearchOpenChange:h,onSectionToggle:f},g){let{t:x}=(0,L.s)(),[m,v]=(0,i.useState)(()=>new Set);(0,i.useEffect)(()=>{v(function(e=T()){if(!e)return new Set;try{let t=e.getItem(I);if(!t)return new Set;let n=JSON.parse(t);if(!Array.isArray(n))return new Set;return new Set(n.filter(e=>"string"==typeof e))}catch{return new Set}}())},[]);let y=(0,i.useRef)(new Map),b=(0,i.useRef)(new Map),w=(0,i.useRef)(c);w.current=c;let k=(0,i.useRef)(u);k.current=u;let j=(0,i.useCallback)(()=>{let e=0;for(let t of y.current.values())e+=t;w.current?.(e)},[]),S=(0,i.useCallback)(()=>{let e=!1;for(let t of b.current.values())e=e||t;k.current?.(e)},[]),C=e.map(e=>e.key).join("\n");(0,i.useEffect)(()=>{for(let t of[...y.current.keys()])e.some(e=>e.key===t)||y.current.delete(t);for(let t of[...b.current.keys()])e.some(e=>e.key===t)||b.current.delete(t);j(),S()},[C]);let E=(0,i.useCallback)(e=>t=>{y.current.set(e,t),j()},[j]),R=(0,i.useCallback)(e=>t=>{b.current.set(e,t),S()},[S]),$=(0,i.useRef)(new Map),W=(0,i.useCallback)(e=>{v(t=>{let n=new Set(t),r=n.has(e);return r?n.delete(e):n.add(e),M(n),f?.(e,!r),n})},[f]),z=e.find(e=>m.has(e.key)&&!t.has(e.root))??e.find(e=>!t.has(e.root))??null,[N,P]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!N)return;if(!e.some(e=>e.key===N))return void P(null);let t=$.current.get(N);t&&(P(null),t.openUploadPicker())},[N,e,m]),(0,i.useImperativeHandle)(g,()=>({openUploadPicker(){if(!z)return;let e=z.key;v(t=>{if(t.has(e))return t;let n=new Set([...t,e]);return M(n),n}),P(e)},openFileSearch(){if(!z)return;let e=z.key;v(t=>{if(t.has(e))return t;let n=new Set([...t,e]);return M(n),n}),h?.(!0)}}),[z,h]),0===e.length)?(0,r.jsx)("div",{style:{padding:"12px 14px",fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:x("sidebar.explorerEmpty")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:e.map(e=>{let i=t.has(e.root),c=m.has(e.key);return i?(0,r.jsxs)("div",{"data-explorer-section":e.root,title:`${e.root} — ${x("sidebar.pinnedProjectMissing")}`,style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,cursor:"default",overflow:"hidden"},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:{flexShrink:0,transform:"rotate(-90deg)",opacity:.6},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0,flex:1},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:ey(e.root,n)})})]},e.key):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>W(e.key),"aria-expanded":c,"data-explorer-section":e.root,title:x(c?"sidebar.explorerSectionCollapse":"sidebar.explorerSectionExpand",{path:e.root}),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"6px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:600,fontFamily:"var(--font-mono)",letterSpacing:"0.05em",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:{flexShrink:0,transform:c?"none":"rotate(-90deg)",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",direction:"rtl",textAlign:"left",minWidth:0,flex:1},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:ey(e.root,n)})})]}),c&&(0,r.jsx)(ev,{ref:t=>{t?$.current.set(e.key,t):$.current.delete(e.key)},cwd:e.root,onOpenFile:l,refreshKey:o,onAtMention:s,onAtMentions:a,onUploadBusyChange:R(e.key),changesCollapsed:d,onChangesCountChange:E(e.key),fileSearchOpen:p&&z?.key===e.key,onFileSearchOpenChange:h})]},e.key)})})});function ew({open:e,query:t,refreshKey:n,children:o,selectedSessionId:l,onSelectSession:s}){let{t:a,locale:d}=(0,L.s)(),[c,u]=(0,i.useState)({query:""}),p=t.trim(),h=c.query===p?c.response:void 0,f=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&&!f,children:[(0,r.jsx)("div",{role:"status",className:"px-3 py-2 text-xs text-text-muted",children:f?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,R.fw)(e.modified,d)})]}),(0,r.jsxs)("span",{className:"mt-1 block text-xs leading-relaxed wrap-anywhere text-text-muted",children:[i,(0,r.jsx)("mark",{className:"rounded-sm bg-accent/20 text-text",children:o}),a]})]},e.id))]}):o}function 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 ej="pi-web:unread-session-ids",eS="pi-web:last-custom-cwd";function eC(){try{return window.localStorage.getItem(eS)??""}catch{return""}}function eI(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}let eT="pi-web:hide-pseudo-projects";function eM(){try{let e=window.localStorage.getItem(eT);return null===e||"false"!==e}catch{return!0}}let eE="pi-web:sidebar-pinned-expanded";function eR(e){try{window.localStorage.setItem(eE,JSON.stringify([...e]))}catch{}}function eL({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 e$({pinned:e}){return(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:[(0,r.jsx)("path",{d:"M3.6 1h2.8l-.4 2.6 1.5 1.4v.8H2.5v-.8L4 3.6z"}),(0,r.jsx)("line",{x1:"5",y1:"5.8",x2:"5",y2:"9"})]})}function eW({project:e,selected:t,pinned:n,stale:i=!1,activity:o,homeDir:l,t:s,onSelect:a,onTogglePin:d}){return(0,r.jsxs)("button",{onClick:i?void 0:a,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"var(--bg)",border:"none",borderBottom:"1px solid var(--border)",color:i?"var(--text-dim)":t?"var(--text)":"var(--text-muted)",cursor:i?"default":"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?`${e.root} — ${s("sidebar.pinnedProjectMissing")}`:e.root,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)(eL,{text:eI(e.root,l),style:{flex:1}}),eO(o,s),(0,r.jsx)("span",{role:"button",tabIndex:0,title:s(n?"sidebar.unpinProject":"sidebar.pinProject"),"aria-label":s(n?"sidebar.unpinProject":"sidebar.pinProject"),onClick:e=>{e.stopPropagation(),d()},onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),d())},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:16,height:16,flexShrink:0,marginLeft:4,borderRadius:3,color:n?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:(0,r.jsx)(e$,{pinned:n})})]})}function ez(e){return`pinned-group-${encodeURIComponent(e)}`}function eN({project:e,expanded:t,stale:n,activity:i,homeDir:o,t:l,onToggle:s,onUnpin:a,onNewSession:d}){let c=l("sidebar.newSessionTitle",{path:e.root});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:"100%",paddingRight:6,borderBottom:"1px solid var(--border)",background:"var(--bg)"},children:[(0,r.jsxs)("button",{onClick:s,"aria-expanded":t,"aria-controls":ez(e.key),title:n?`${e.root} — ${l("sidebar.pinnedProjectMissing")}`:l(t?"sidebar.pinnedGroupCollapse":"sidebar.pinnedGroupExpand",{path:e.root}),style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:6,height:"100%",padding:"0 4px 0 10px",background:"none",border:"none",color:n?"var(--text-dim)":"var(--text)",cursor:"pointer",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:{flexShrink:0,transform:t?"none":"rotate(-90deg)",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),(0,r.jsx)(eL,{text:eI(e.root,o),style:{flex:1,fontFamily:"var(--font-mono)",fontSize:11,lineHeight:1.35}})]}),eO(i,l),(0,r.jsx)("span",{role:"button",tabIndex:0,title:l("sidebar.unpinProject"),"aria-label":l("sidebar.unpinProject"),onClick:e=>{e.stopPropagation(),a()},onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),a())},style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:16,height:16,flexShrink:0,marginLeft:4,borderRadius:3,color:"var(--accent)",cursor:"pointer"},children:(0,r.jsx)(e$,{pinned:!0})}),(0,r.jsx)("button",{onClick:d,disabled:n,title:c,"aria-label":c,style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,padding:0,marginLeft:2,flexShrink:0,background:"none",border:"1px solid var(--border)",borderRadius:5,color:n?"var(--text-dim)":"var(--text-muted)",cursor:n?"default":"pointer",opacity:n?.6:1},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"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"})]})})]})}function eP({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 eA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function eB(){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:eA[Math.floor(Math.random()*eA.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.0.7p0.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 eD({selectedSessionId:e,onSelectSession:t,onNewSession:n,initialSessionId:o,skipInitialProjectSelection:l,onInitialRestoreDone:s,refreshKey:u,onSessionDeleted:p,selectedCwd:h,onCwdChange:f,onOpenFile:g,onOpenTerminal:x,explorerRefreshKey:v,onExplorerRefresh:w,onAtMention:I,onAtMentions:T,onBackgroundTaskDone:M,onRunningSessionIdsChange:R,onSessionsChange:$,onExternalSessionChange:W}){let{t:N}=(0,L.s)(),[P,A]=(0,i.useState)([]),[B,F]=(0,i.useState)(null),H=(0,i.useRef)(null),O=(0,i.useRef)(0),[U,_]=(0,i.useState)(!0),[q,K]=(0,i.useState)(null),V=(0,i.useRef)(null),J=(0,i.useRef)(!1),[Y,Z]=(0,i.useState)(null),[G,X]=(0,i.useState)(null),[Q,ee]=(0,i.useState)(""),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(!1),[eo,el]=(0,i.useState)(""),[es,ea]=(0,i.useState)(0),[ed,ec]=(0,i.useState)(()=>new Set),eu=(0,i.useRef)(new Set),[ep,eh]=(0,i.useState)(()=>new Set),[ef,eg]=(0,i.useState)(!1);(0,i.useEffect)(()=>{eg(!0),eh(function(){try{let e=window.localStorage.getItem(eE);if(!e)return new Set;let t=JSON.parse(e);if(!Array.isArray(t))return new Set;return new Set(t.filter(e=>"string"==typeof e))}catch{return new Set}}())},[]);let[ex,em]=(0,i.useState)(eM),[ev,ey]=(0,i.useState)(""),[e$,eA]=(0,i.useState)(!1),[eF,eH]=(0,i.useState)(eC),[eO,e_]=(0,i.useState)(null),[eq,eK]=(0,i.useState)(!1),[eV,eJ]=(0,i.useState)(null),eY=(0,i.useRef)(null),[eZ,eG]=(0,i.useState)(null),[eX,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(""),[e8,e6]=(0,i.useState)(null),[e5,e3]=(0,i.useState)(!1),[e9,e7]=(0,i.useState)(null),[te,tt]=(0,i.useState)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),[ti,to]=(0,i.useState)(!0),[tl,ts]=(0,i.useState)(0),[ta,td]=(0,i.useState)(!1),[tc,tu]=(0,i.useState)(!1),[tp,th]=(0,i.useState)(!1),[tf,tg]=(0,i.useState)(""),tx=tp&&!!tf.trim(),[tm,tv]=(0,i.useState)(0),[ty,tb]=(0,i.useState)(!0),[tw,tk]=(0,i.useState)(!1),[tj,tS]=(0,i.useState)(()=>new Set),[tC,tI]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(ej);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}})()),tT=(0,i.useRef)(new Set),tM=(0,i.useRef)(new Set),tE=(0,i.useRef)(new Set),tR=(0,i.useRef)(!1),tL=(0,i.useRef)(null),t$=(0,i.useRef)(e);t$.current=e;let tW=(0,i.useRef)(W);tW.current=W;let tz=(0,i.useRef)(null),tN=(0,i.useRef)(null),tP=(0,i.useRef)(null),tA=(0,i.useRef)(null),tB=(0,i.useRef)(null),tD=(0,i.useRef)(320),tF=(0,i.useCallback)(()=>{if(!ti)return 320;let e=tA.current?.getBoundingClientRect().height,t=tB.current?.getBoundingClientRect().height;return e&&t?Math.round((e+t)/2):320},[ti]),tH=(0,i.useCallback)(()=>ti&&(h||Y)?Math.max(80,(tA.current?.getBoundingClientRect().height??320)+(tB.current?.getBoundingClientRect().height??120)-120):1600,[ti,Y,h]),tO=z({ariaLabel:N("layout.resizeSidebarSections"),axis:"vertical",cssVariable:"--sidebar-session-pane-height",defaultWidth:320,getDefaultWidth:tF,getMaxWidth:tH,growthDirection:"down",maxWidth:1600,minWidth:80,storageKey:"pi-web:sidebar-session-pane-height",widthRef:tD}),[tU,t_]=(0,i.useState)(0),[tq,tK]=(0,i.useState)(0),[tV,tJ]=(0,i.useState)(null),tY=(0,i.useRef)(null),tZ=(0,i.useCallback)(e=>{let t=e.currentTarget.scrollTop;null==tY.current&&(tY.current=requestAnimationFrame(()=>{tY.current=null,tK(t)}))},[]);(0,i.useLayoutEffect)(()=>{let e=tP.current;if(!e)return;let t=new ResizeObserver(e=>{for(let t of e)t_(t.contentRect.height)});return t.observe(e),t_(e.clientHeight),tK(e.scrollTop),()=>t.disconnect()},[tx]);let tG=(0,i.useCallback)(async(e=!1,t=!1)=>{let n=++O.current;try{e&&_(!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!==O.current)return;H.current=i.sessionListVersion,F(i.sessionListVersion),A(i.sessions),tR.current||(tM.current=new Set(i.completionNotificationSuppressedSessionIds??[]),tS(new Set(i.runningSessionIds??[])));let o=new Set(i.sessions.filter(e=>e.relation?.kind!=="subagent").map(e=>e.id));tI(e=>{if(0===e.size)return e;let t=new Set([...e].filter(e=>o.has(e)));return t.size===e.size?e:t}),K(null)}catch(e){n===O.current&&K(String(e))}finally{n===O.current&&_(!1)}},[]),tX=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tX.current;tX.current=!0,tG(e,!e)},[tG,u]),(0,i.useEffect)(()=>{to(function(e=c()){if(!e)return!0;try{return"false"!==e.getItem(d)}catch{return!0}}())},[]),(0,i.useEffect)(()=>{try{0===tC.size?window.localStorage.removeItem(ej):window.localStorage.setItem(ej,JSON.stringify([...tC]))}catch{}},[tC]),(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;tR.current=!0,tM.current=new Set(r.completionNotificationSuppressedSessionIds??[]),tS(new Set(r.runningSessionIds??[]));let i=t$.current,l=(r.recentSessionWrites??[]).find(e=>void 0!==e.sessionId&&e.sessionId===i);if(i&&l){let e=tL.current;e&&e.sessionId===i&&l.generation>e.generation&&tW.current?.(i),tL.current={sessionId:i,generation:l.generation}}r.sessionListVersion!==H.current&&await tG()}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)}},[tG]),(0,i.useEffect)(()=>{R?.(tj)},[R,tj]),(0,i.useEffect)(()=>{$?.(P)},[P,$]),(0,i.useEffect)(()=>{let t=tT.current,n=[...t].filter(t=>!tj.has(t)&&t!==e),r=new Set(P.filter(e=>e.relation?.kind==="subagent").map(e=>e.id)),i=n.filter(e=>!tE.current.has(e)&&!r.has(e)),o=[...tj].filter(e=>!t.has(e));(i.length>0||o.length>0)&&tI(e=>{let t=new Set(e);return tj.forEach(e=>t.delete(e)),i.forEach(e=>t.add(e)),t});let l=o.some(e=>!P.some(t=>t.id===e));(n.length>0||l)&&tG(!1,!0),i.length>0&&M?.(),tT.current=tj,tE.current=new Set([...tj].filter(e=>tM.current.has(e)||r.has(e)))},[tj,e,P,tG,M]),(0,i.useEffect)(()=>{e&&tI(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{void 0!==v&&ts(e=>e+1)},[v]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&ee(e.home)}).catch(()=>{})},[]),(0,i.useEffect)(()=>{fetch("/api/default-cwd").then(e=>e.json()).then(e=>{e.cwd&&en(e.cwd)}).catch(()=>{})},[]);let tQ=(0,i.useRef)(!1),t0=(0,i.useCallback)((e,t)=>({root:e,key:t}),[]),t1=(0,i.useCallback)(e=>{if(!e)return null;if(eV?.cwd===e)return t0(eV.root,eV.key);if(eZ&&eZ.forCwd===e||eZ?.worktrees.some(t=>t.path===e))return t0(eZ.projectRoot,eZ.projectKey);let t=P.find(t=>t.cwd===e||(t.projectRoot??t.cwd)===e);return t?t0(t.projectRoot??t.cwd,m(t)):t0(e,e)},[eV,eZ,P,t0]),t2=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=t1(Y),t=t2.current;(t?.cwd!==Y||t.key!==(e?.key??null))&&(t2.current={cwd:Y,key:e?.key??null},f?.(Y,e?.root??null,e?.key??null))},[Y,f,t1]);let t4=(0,i.useRef)(null);(0,i.useEffect)(()=>{h&&h!==t4.current&&(t4.current=h,Z(h))},[h]);let[t8,t6]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!Y){eG(null),tt(null);return}let e=!1;return tt(Y),fetch(`/api/worktrees?cwd=${encodeURIComponent(Y)}`).then(e=>e.json()).then(t=>{if(!e){if(tt(null),t.error||!t.projectRoot)return void eG(null);eG({forCwd:Y,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||(tt(null),eG(null))}),()=>{e=!0}},[Y,t8,u]),(0,i.useEffect)(()=>{if(0!==P.length&&!l&&null===Y){if(o&&!tQ.current){tQ.current=!0;let e=P.find(e=>e.id===o);if(e){Z(e.cwd),X({root:e.projectRoot??e.cwd,key:m(e)}),t(e,!0);return}s?.()}let e=y(P);e.length>0&&(Z(e[0].root),X(e[0]))}},[P,Y,o,l,t,s]);let t5=eZ?eZ.worktrees.find(e=>e.path===Y)??(eZ.forCwd===Y&&eZ.currentWorktreePath?eZ.worktrees.find(e=>e.path===eZ.currentWorktreePath):void 0)??eZ.worktrees.find(e=>e.isMain):void 0,t3=t5?.path??null,t9=(0,i.useCallback)(async e=>{let t=(e??eF).trim();if(t&&!eq){eK(!0),e_(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 e_(r.error??`HTTP ${e.status}`);eJ({cwd:r.cwd,root:r.projectRoot,key:r.projectKey});var n=r.cwd;try{window.localStorage.setItem(eS,n)}catch{}eH(r.cwd),Z(r.cwd),X({root:r.projectRoot,key:r.projectKey}),eA(!1),ei(!1)}catch(e){e_(e instanceof Error?e.message:String(e))}finally{eK(!1)}}},[eF,eq]),t7=(0,i.useCallback)(()=>{eA(!0),e_(null),ei(!1)},[]),ne=(0,i.useCallback)(async()=>{try{let t=await fetch("/api/default-cwd",{method:"POST"}),n=await t.json();if(n.cwd){var e;Z(n.cwd),X(t1(n.cwd)??{root:e=n.cwd,key:e}),eA(!1),e_(null),ei(!1)}}catch{}},[t1]),nt=(0,i.useCallback)(async()=>{let e=e2.trim();if(e&&!e5&&eZ){e3(!0),e6(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eZ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e6(n.error??`HTTP ${t.status}`);e1(!1),e4(""),eQ(!1),eG(t=>t?{...t,forCwd:n.path,currentWorktreePath:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),Z(n.path),t6(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e3(!1)}}},[e2,e5,eZ]),nn=(0,i.useCallback)(async(e,t)=>{if(eZ&&!e5){e3(!0),e6(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eZ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e7(e);e6(r.error??`HTTP ${n.status}`);return}e7(null),t3===e&&Z(eZ.projectRoot),t6(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{e3(!1)}}},[eZ,e5,t3]);(0,i.useEffect)(()=>{let e=e=>{eY.current&&!eY.current.contains(e.target)&&(ei(!1),el("")),tn.current&&!tn.current.contains(e.target)&&(eQ(!1),e1(!1),e4(""),e6(null),e7(null),ey(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let nr=(0,i.useCallback)((e,n,r)=>{A(t=>t.some(t=>t.id===e.id)?t:[e,...t]),e.cwd&&Z(e.cwd),t(e,!1,n,r)},[t]),ni=(0,i.useCallback)(e=>{eh(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),eR(n),n})},[]),no=(0,i.useCallback)(e=>{ed.has(e.root)||(Z(e.root),eh(t=>{if(t.has(e.key))return t;let n=new Set([...t,e.key]);return eR(n),n}),n?.("function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`,e.root))},[ed,n]),nl=y(P),ns=(0,i.useMemo)(()=>ef?C():[],[es,ef]),na=(0,i.useMemo)(()=>ns.map(e=>{let t=nl.find(t=>t.key===e.key);return{key:e.key,root:t?t.root:e.root}}),[ns,nl]),nd=(0,i.useMemo)(()=>new Set(ns.map(e=>e.key)),[ns]),nc=(0,i.useMemo)(()=>null==et||""===et||0===na.length||na.some(e=>{var t;return t=e.root,E(t)===E(et)}),[na,et]),nu=(0,i.useMemo)(()=>(function(e,t){let n=[],r=new Set;for(let t of e)!t?.key||r.has(t.key)||(r.add(t.key),n.push({key:t.key,root:t.root||t.key}));return t?.key&&!r.has(t.key)&&n.push({key:t.key,root:t.root||t.key}),n})(na,G),[na,G]),np=(0,i.useMemo)(()=>(function(e,t){let n=new Set;for(let e of t)!0===e.pseudoProject&&n.add(m(e));let r=[],i=[];for(let t of e)(n.has(t.key)?i:r).push(t);return{ordinary:r,pseudo:i}})(nl,P),[nl,P]),nh=nl.length>8,nf=ex?np.ordinary.filter(e=>!nd.has(e.key)):nl.filter(e=>!nd.has(e.key)),ng=eo.trim()?nf.filter(e=>e.root.toLowerCase().includes(eo.trim().toLowerCase())):nf,nx=(0,i.useCallback)((e,t)=>{!function(e,t=k()){return(function(e=k()){return C(e).map(e=>e.key)})(t).includes(e)}(e)?function(e,t,n=k()){if(n&&e)try{let r=j(n).filter(t=>t.key!==e);S(n,[{key:e,root:t||e},...r])}catch{}}(e,t):function(e,t=k()){if(t&&e)try{S(t,j(t).filter(t=>t.key!==e))}catch{}}(e),ea(e=>e+1)},[]),nm=na.map(e=>e.root).join("\n");(0,i.useEffect)(()=>{if(!nm)return;let e=nm.split("\n").filter(e=>e&&!eu.current.has(e));if(0===e.length)return;for(let t of e)eu.current.add(t);let t=!1;return(async()=>{let n=await Promise.all(e.map(async e=>{try{let t=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})});return{root:e,exists:t.ok}}catch{return{root:e,exists:!0}}}));if(!t)for(let{root:e,exists:t}of(ec(e=>{let t=!1,r=new Set(e);for(let{root:e,exists:i}of n)i||r.has(e)||(r.add(e),t=!0),i&&r.has(e)&&(r.delete(e),t=!0);return t?r:e}),n))t||eu.current.delete(e)})(),()=>{t=!0}},[nm]);let nv=t1(Y),ny=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(ny.current||!nv||!nd.has(nv.key))return;if(ep.has(nv.key)){ny.current=!0;return}ny.current=!0;let e=nv.key;eh(t=>{let n=new Set([...t,e]);return eR(n),n})},[nv,nd]);let nb=(0,i.useMemo)(()=>(function(e,t,n){let r=new Map;for(let i of e){let e=m(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})(P,tj,tC),[P,tj,tC]),nw=(0,i.useMemo)(()=>[...nb.entries()].some(([e,{running:t,unread:n}])=>e!==nv?.key&&(t>0||n>0)),[nb,nv]),nk=a((nv?b(P,nv.key):P).filter(e=>!nd.has(m(e)))),nj=new Map;for(let e of na)nj.set(e.key,a(b(P,e.key)));let nS=function({pinnedProjects:e,familiesByProject:t,expandedKeys:n,mainFamilies:r}){let i=[],o=0,l=e=>{let t=e.height;i.push({...e,offset:o}),o+=t};for(let r of e){if(l({kind:"groupHeader",key:`group:${r.key}`,project:r,height:40}),!n.has(r.key))continue;let e=t.get(r.key)??[];if(0===e.length){l({kind:"groupEmpty",key:`group-empty:${r.key}`,groupKey:r.key,height:40});continue}for(let t of e)l({kind:"session",key:t.root.id,family:t,groupKey:r.key,height:54})}for(let e of r)l({kind:"session",key:e.root.id,family:e,groupKey:null,height:54});return i}({pinnedProjects:na,familiesByProject:nj,expandedKeys:ep,mainFamilies:nk}),nC=new Map;for(let e of nS){if("groupHeader"===e.kind)continue;let t=e.groupKey;if(!t)continue;let n=nC.get(t);n?n.push(e):nC.set(t,[e])}let nI=function(e,t,n,r=null){if(0===e.length)return[];let{start:i,end:o}=function(e,t,n){let r=t+(n||600),i=0,o=e.length-1,l=e.length;for(;i<=o;){let n=i+o>>1;e[n].offset+e[n].height>t?(l=n,o=n-1):i=n+1}i=0,o=e.length-1;let s=e.length;for(;i<=o;){let t=i+o>>1;e[t].offset>=r?(s=t,o=t-1):i=t+1}return{start:Math.max(0,l-8),end:Math.min(e.length,s+8)}}(e,t,n),l=e.slice(i,o);if(!r)return l;let s=e.findIndex(e=>"session"===e.kind&&e.family.root.id===r);return s<0||s>=i&&s<o?l:s<i?[e[s],...l]:[...l,e[s]]}(nS,tq,tU,tV),nT=!!(eZ?.isGit&&eZ.isTopLevel&&Y&&nv?.key===eZ.projectKey),nM=Y&&eZ&&nv?.key===eZ.projectKey&&!nT?eZ.isGit?{label:N("sidebar.openRepoRoot"),title:N("sidebar.openRepoRootTitle")}:{label:N("sidebar.gitRepoRootOnly"),title:N("sidebar.gitRepoRootOnlyTitle")}:null,nE=!!(Y&&te===Y),nR=nM??(nE&&!nT?{label:N("sidebar.worktrees"),title:N("sidebar.checkingWorktrees")}:null),nL=t=>{let n=[t.root,...t.subagents],i=t.latestModified===t.root.modified?t.root:{...t.root,modified:t.latestModified};return(0,r.jsx)(eU,{session:i,isSelected:n.some(t=>t.id===e),isRunning:n.some(e=>tj.has(e.id)),isUnread:n.some(e=>tC.has(e.id)),onClick:()=>nr(t.root),onRenamed:tG,onDeleted:e=>{p?.(e),tG()}})};return(0,r.jsxs)("div",{ref:tO.panelRef,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden","--sidebar-session-pane-height":`${tO.width}px`},children:[e$&&(0,r.jsx)(D,{initialPath:eF,busy:eq,error:eO,onCancel:()=>{eA(!1),e_(null)},onSelect:e=>void t9(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)(eB,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{tG(!1,!0)},title:N("sidebar.refresh"),"aria-label":N("sidebar.refresh"),className:"flex h-[32px] w-[32px] shrink-0 cursor-pointer items-center justify-center rounded-[7px] border border-border bg-bg-hover text-text-muted hover:bg-bg-selected focus-visible:outline-2 focus-visible:outline-accent",onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36L21 8"}),(0,r.jsx)("path",{d:"M21 3v5h-5"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>{th(e=>!e),eQ(!1)},title:N("sidebar.toggleSessionSearch"),"aria-label":N("sidebar.toggleSessionSearch"),"aria-expanded":tp,"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 ${tp?"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:eY,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>ei(e=>!e),"data-cwd-picker":"true",title:nv?.root??Y??"",style:{width:"100%",display:"flex",alignItems:"center",padding:"6px 10px",background:Y?"var(--bg-hover)":"rgba(37,99,235,0.06)",border:Y?"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:[Y?(0,r.jsx)(eL,{text:eI(nv?.root??Y,Q),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&&!tQ.current?"":N("sidebar.selectProject")}),nw&&(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)(eP,{open:er,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:[nh&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eo,onChange:e=>el(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(el(""),ei(!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:[ng.map(e=>(0,r.jsx)(eW,{project:e,selected:e.key===nv?.key,pinned:!1,activity:nb.get(e.key),homeDir:Q,t:N,onSelect:()=>{Z(e.root),X(e),el(""),eA(!1),e_(null),ei(!1)},onTogglePin:()=>nx(e.key,e.root)},e.key)),0===ng.length&&eo.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:N("sidebar.noMatchingProjects")})]}),np.pseudo.length>0&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation();let t=!ex;em(t);try{window.localStorage.setItem(eT,t?"true":"false")}catch{}},title:N("sidebar.hidePseudoProjectsTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderTop:"1px solid var(--border)",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:"var(--accent)",strokeWidth:"1.4",style:{flexShrink:0,opacity:ex?1:.35},children:[ex&&(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5",strokeWidth:"2"}),!ex&&(0,r.jsx)("rect",{x:"1",y:"1",width:"8",height:"8",rx:"1.5"})]}),(0,r.jsx)("span",{children:N("sidebar.hidePseudoProjects")}),(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:ex?N("sidebar.pseudoProjectsHidden",{count:np.pseudo.length}):N("sidebar.pseudoProjectsVisible",{count:np.pseudo.length})})]}),!e$&&nc&&(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),ne()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderTop:ng.length>0||np.pseudo.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(),t7()},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")})]})]})]}),tp&&(0,r.jsx)("input",{id:"session-search-input",type:"search",autoFocus:!0,value:tf,maxLength:200,"aria-label":N("sidebar.searchSessions"),placeholder:N("sidebar.searchSessions"),onChange:e=>tg(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),tg(""))},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"}),!tp&&nT&&(()=>{if(!eZ)return null;let e=eZ.worktrees.length>=8,t=e&&ev.trim()?eZ.worktrees.filter(e=>(e.branch??eI(e.path,Q)).toLowerCase().includes(ev.trim().toLowerCase())):eZ.worktrees;return(0,r.jsxs)("div",{ref:tn,style:{position:"relative",marginTop:6},children:[(0,r.jsxs)("button",{onClick:()=>eQ(e=>!e),title:t5?N("sidebar.switchWorktreeTitle",{path:t5.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:t5&&!t5.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)(eL,{text:t5?t5.branch??eI(t5.path,Q):"…",style:{flex:1,fontFamily:"var(--font-mono)",color:"var(--text)"}}),t5?.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:N("sidebar.main")}),eZ.worktrees.length>1&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:eZ.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)(eP,{open:eX,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:ev,onChange:e=>ey(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(ey(""),eQ(!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===t3;return e9===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 nn(e.path,!0),disabled:e5,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:()=>e7(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:()=>{Z(e.path),eQ(!1),e6(null),ey("")},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)(eL,{text:e.branch??eI(e.path,Q),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 nn(e.path,!1),disabled:e5,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&&ev.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:N("sidebar.noMatchingWorktrees")})]}),e0?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:tr,value:e2,onChange:e=>{e4(e.target.value),e6(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),nt()),"Escape"===e.key&&(e1(!1),e4(""),e6(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 nt(),disabled:e5||!e2.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--accent-contrast)",fontSize:11,fontWeight:600,cursor:e5||!e2.trim()?"not-allowed":"pointer",opacity:e5||!e2.trim()?.65:1},children:e5?N("sidebar.creating"):N("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e1(!1),e4(""),e6(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(),e1(!0),e6(null),setTimeout(()=>tr.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")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]})})(),!tp&&nR&&(0,r.jsxs)("button",{type:"button","aria-disabled":"true",tabIndex:-1,title:nR.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:nR.label})]})]}),(0,r.jsx)("div",{ref:tA,style:{display:"flex",flexDirection:"column",flex:ti?"0 1 var(--sidebar-session-pane-height, 320px)":"1 1 auto",minHeight:80,overflow:"hidden"},children:(0,r.jsx)(ew,{open:tp,query:tf,refreshKey:B,selectedSessionId:e,onSelectSession:nr,children:(0,r.jsxs)("div",{ref:tP,onScroll:tZ,onTouchStart:e=>{let t=tP.current;t&&!(t.scrollTop>0)&&(V.current=e.touches[0]?.clientY??null,J.current=!1)},onTouchMove:e=>{let t=V.current;null==t||J.current||(e.touches[0]?.clientY??t)-t>64&&(J.current=!0,tG(!1,!0))},onTouchEnd:()=>{V.current=null,J.current=!1},style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"0"},children:[U&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:N("sidebar.loading")}),q&&(0,r.jsx)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:q}),!U&&!q&&0===nS.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:N("sidebar.noSessions")}),nS.length>0&&(0,r.jsxs)("div",{style:{position:"relative",height:function(e){if(0===e.length)return 0;let t=e[e.length-1];return t.offset+t.height}(nS)},children:[na.map(e=>{if(!ep.has(e.key))return null;let t=nC.get(e.key)??[];if(0===t.length)return null;let n=t[0].offset,i=t[t.length-1],o=i.offset+i.height-n;return(0,r.jsx)("div",{id:ez(e.key),style:{position:"absolute",top:n,left:0,right:0,height:o},children:t.filter(e=>nI.includes(e)).map(e=>"groupEmpty"===e.kind?(0,r.jsx)("div",{style:{position:"absolute",top:e.offset-n,left:0,right:0,height:e.height,display:"flex",alignItems:"center",paddingLeft:28,fontSize:11,color:"var(--text-dim)"},children:N("sidebar.pinnedGroupNoSessions")},e.key):(0,r.jsx)("div",{onFocus:()=>tJ(e.family.root.id),onBlur:()=>tJ(null),style:{position:"absolute",top:e.offset-n,left:0,right:0},children:nL(e.family)},e.key))},`group-content:${e.key}`)}),nI.map(e=>{if("groupHeader"===e.kind)return(0,r.jsx)("div",{style:{position:"absolute",top:e.offset,left:0,right:0,height:e.height},children:(0,r.jsx)(eN,{project:e.project,expanded:ep.has(e.project.key),stale:ed.has(e.project.root),activity:nb.get(e.project.key),homeDir:Q,t:N,onToggle:()=>ni(e.project.key),onUnpin:()=>nx(e.project.key,e.project.root),onNewSession:()=>no(e.project)})},e.key);if("session"!==e.kind||null!==e.groupKey)return null;let t=e.family;return(0,r.jsx)("div",{onFocus:()=>tJ(t.root.id),onBlur:()=>tJ(null),style:{position:"absolute",top:e.offset,left:0,right:0},children:nL(t)},t.root.id)})]})]})})}),ti&&(0,r.jsx)("div",{className:`sidebar-section-resize-handle${tO.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar-sections",title:`${N("layout.resizeSidebarSections")}: ${N("layout.resizeHeightHint")}`,style:{position:"relative",zIndex:20,width:"100%",height:12,margin:"-6px 0",flex:"0 0 12px",cursor:"row-resize",touchAction:"none"},...tO.separatorProps}),(0,r.jsxs)("div",{ref:tB,style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:ti?"1 1 0":"0 0 auto",minHeight:120*!!ti,overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0},children:[(0,r.jsxs)("button",{onClick:()=>to(e=>{let t=!e;return!function(e,t=c()){if(t)try{t.setItem(d,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:ti?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),N("files.explorer")]}),x&&(0,r.jsx)(ek,{onClick:()=>x(Y??h),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"})]})}),ti&&tm>0&&(0,r.jsx)(ek,{onClick:()=>tb(e=>!e),title:N("sidebar.changedFiles",{count:tm}),ariaPressed:!ty,color:ty?"var(--text-dim)":"var(--accent)",background:ty?"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"})]})}),ti&&(0,r.jsx)(ek,{onClick:()=>{tc?tu(!1):tN.current?.openFileSearch()},disabled:0===nu.length,title:N("sidebar.searchFiles"),ariaPressed:tc,color:tc?"var(--accent)":"var(--text-dim)",background:tc?"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"})]})}),ti&&(0,r.jsx)(ek,{onClick:()=>tN.current?.openUploadPicker(),disabled:ta||0===nu.length,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:()=>{w?w():ts(e=>e+1),tk(!0),tz.current&&clearTimeout(tz.current),tz.current=setTimeout(()=>tk(!1),2e3)},title:N("sidebar.refreshExplorer"),skipHover:tw,color:tw?"#4ade80":"var(--text-dim)",background:tw?"rgba(74,222,128,0.18)":"none",marginRight:6,children:tw?(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"})]})})]}),ti&&(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(eb,{ref:tN,roots:nu,staleRoots:ed,homeDir:Q,refreshKey:tl,onOpenFile:g??(()=>{}),onAtMention:I,onAtMentions:T,onUploadBusyChange:td,changesCollapsed:ty,onChangesCountChange:tv,fileSearchOpen:tc,onFileSearchOpenChange:tu})})]})]})}function eF(){let{t:e}=(0,L.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 eH(){let{t:e}=(0,L.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 eO(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.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"})]})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.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"}}),e.unread]})]}):null}function eU({session:e,isSelected:t,isRunning:n,isUnread:o,onClick:l,onRenamed:s,onDeleted:a,depth:d=0,hasChildren:c=!1,collapsed:u=!1,onToggleCollapse:h}){let{locale:f,t:g}=(0,L.s)(),[x,m]=(0,i.useState)(!1),[v,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(""),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),I=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(v){let e=requestAnimationFrame(()=>I.current?.select());return()=>cancelAnimationFrame(e)}},[v]);let T=p(e.firstMessage)??e.firstMessage,M=e.name||T.slice(0,50)||e.id.slice(0,12),E=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(w(e.name||T.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,T,e.id]),$=(0,i.useCallback)(async()=>{let t=b.trim();if(y(!1),b!==M&&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{}},[b,e.id,e.name,s,M]),W=(0,i.useCallback)(async()=>{if(!e.transient){j(!1),C(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),a?.(e.id)}catch{C(!1)}}},[e.id,e.transient,a]),z=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?W():j(!0)},[W]),N=(0,i.useCallback)(e=>{e.stopPropagation(),W()},[W]),P=(0,i.useCallback)(e=>{e.stopPropagation(),j(!1)},[]),A=(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:k||v?void 0:l,onContextMenu:k||v?void 0:A,onMouseEnter:()=>m(!0),onMouseLeave:()=>{m(!1)},style:{height:54,display:"flex",alignItems:"center",paddingLeft:d>0?12*d+14:14,paddingRight:8,cursor:k||v?"default":"pointer",background:k?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:k?"2px solid #ef4444":t?"2px solid var(--accent)":"2px solid transparent",transition:"background 0.1s",opacity:S?.5:1,gap:6,overflow:"hidden"},children:k?(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:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:N,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"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:P,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:g("sidebar.cancel")})]})]}):v?(0,r.jsx)("input",{ref:I,value:b,onChange:e=>w(e.target.value),onBlur:$,onKeyDown:e=>{"Enter"===e.key&&$(),"Escape"===e.key&&y(!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:M,children:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:M})}),(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)(eF,{}):o?(0,r.jsx)(eH,{}):(0,r.jsx)("span",{title:e.modified,children:(0,R.fw)(e.modified,f)}),(0,r.jsx)("span",{children:g("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(),h?.()},title:g(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"})})}),x&&!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:E,title:g("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:z,title:g("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 e_=n(5772);let eq=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eK=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eV=/\x1B_pi:c\x07/g;function eJ(e){return e.replace(eV,"").replace(eq,"")}function eY(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eK);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 eZ(e,t){let n=eY(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eG(e){return eY(e)[0]?.char}let eX={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 e0(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}function e1(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}function e2(e,t={}){return(e.content??[]).filter(e=>!e1(e,t))}function e4(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function e8(e,t={}){return!t.isStreaming&&"length"===e.stopReason}function e6(e,t={}){let n=e2(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 e5(e){return!e.defaultPrevented&&0===e.button&&!e.shiftKey&&!e.altKey}function e3(e){try{return decodeURIComponent(e)}catch{return e}}function e9(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e7(e){let t=e9(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 te(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=e3(a),p=u.startsWith("\\\\"),h=e9(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=e3(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=`${e9(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let g=e7(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=e7(g).replace(/\/+$/,""),i=e7(n).replace(/\/+$/,""),l=(o=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(l===(s=o?i.toLowerCase():i)||l.startsWith(`${s}/`)))?null:g}let tt=/^page=(\d+)$/i;function tn(e){if(!e)return null;let t=e.indexOf("#");if(-1===t)return null;let n=e.slice(t+1).trim().match(tt);if(!n)return null;let r=Number.parseInt(n[1],10);return Number.isInteger(r)&&r>0?r:null}function tr(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 ti(e){let t=e.toLowerCase();return"apply_patch"===t||t.startsWith("apply_patch_")||t.endsWith(".apply_patch")||t.endsWith("_apply_patch")}function to(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function tl(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ts(e){if(!tl(e)||!tl(e.result))return!1;let t=e.result.failures;return Array.isArray(t)&&t.length>0}function ta(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let o=0;o<i;o++)e.push({type:"line",left:t[o]??r(),right:n[o]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},finish(){i();for(let t=e.length-1;t>=0;t--)"line"!==e[t].type&&e.splice(t,1)}}}function td(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let o of e.split(/\r?\n/)){let e=o.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let o=e[1]?.toLowerCase()??"update",l=(e[2]??"").trim();n?.finish(),i=o,r={oldPath:"add"===o?void 0:l,newPath:"delete"===o?void 0:l,rows:(n=ta()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(o)){let e=o.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let l=n;if(!o.startsWith("*** ")&&!("update"===i&&o.startsWith("@@"))){if("update"===i){let e=o[0],t=o.slice(1);"+"===e?l.added(t,null):"-"===e?l.removed(t,null):" "===e?l.context(t,null):""!==o&&l.context(o,null)}else if("add"===i){if(""===o)continue;n.added(o.startsWith("+")?o.slice(1):o,null)}else if("delete"===i){if(""===o)continue;n.removed(o.startsWith("-")?o.slice(1):o,null)}}}n?.finish();let o=t.filter(e=>e.rows.length>0);return o.length>0?o:null}function tc(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=ta();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,o]=e,l=Number(i);"+"===r?t.added(o,l):"-"===r?t.removed(o,l):t.context(o,l)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function tu(e){return e?e.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}function tp(e,t,n){let r=e.trim().split("\n").map(e=>`> ${e}`).join("\n");return`${t}
|
|
2
|
+
|
|
3
|
+
${r}
|
|
4
|
+
|
|
5
|
+
${n}`}var th=n(32316),tf=n(88374),tg=n(5924),tx=n(94764),tm=n(63835),tv=n(54152),ty=n(84678),tb=n(98164);let tw={...tx.j,attributes:{...tx.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},protocols:{...tx.j.protocols,href:[...tx.j.protocols?.href??[],"file"]},strip:[...tx.j.strip||[],"iframe","object","style","form"]};function tk(e){return/^file:/i.test(e)?e:(0,th.Lv)(e)}let tj=/(?<![\\`])`((?:[^`\n]|\\`)+?)(?<![\\`])`(?!`)/g;function tS(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(tj,(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 f=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(f){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(`${f[1]}$$`,...n.slice(e+1,t).map(e=>tI(e,f[1])),`${f[1]}$$`),e=t;continue}}let g=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(g){let e=g[2].trim();if(e){r.push(`${g[1]}$$`,`${g[1]}${e}`,`${g[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=tC(n,e+1,t,s);if(o){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<o.index;i++)r.push(tI(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=tC(n,e+1,t,s);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let o=e+1;o<i.index;o++)r.push(tI(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 tC(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 tI(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 tT={singleTilde:!1},tM=[[tv.A,["yaml"]],[ty.A,tT],tb.A],tE=[[tv.A,["yaml"]],[ty.A,tT],tb.A],tR=[tg.A,[tm.A,tw],[tf.A,{throwOnError:!1,strict:!1}]],tL=[tg.A,[tm.A,tw],[tf.A,{throwOnError:!1,strict:!1}]];function t$({src:e,alt:t="",children:n,className:o,style:l}){let{t:s}=(0,L.s)(),a=s("chat.previewImage"),d=t.trim()?`${a}: ${t}`:a,[c,u]=(0,i.useState)(!1),p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!c)return;let e=h.current;if(!e)return;let t=p.current,n=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),f.current?.focus({preventScroll:!0}),()=>{document.body.style.overflow=n,e.open&&e.close(),t?.isConnected&&t.focus({preventScroll:!0})}},[c]);let g=()=>{h.current?.open&&h.current.close(),u(!1)};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:p,type:"button",className:o,style:{display:"block",padding:0,border:"none",background:"none",color:"inherit",cursor:"zoom-in",...l},onClick:()=>u(!0),"aria-label":d,"aria-haspopup":"dialog","aria-expanded":c,title:a,children:n}),c&&(0,r.jsxs)("dialog",{ref:h,className:"image-preview-dialog","aria-label":s("chat.previewImage"),onCancel:e=>{e.preventDefault(),e.stopPropagation(),g()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),g())},onClick:e=>{e.target===e.currentTarget&&g()},children:[(0,r.jsx)("img",{className:"image-preview-image",src:e,alt:t}),(0,r.jsx)("button",{ref:f,type:"button",className:"image-preview-close",onClick:g,"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"})})})]})]})}var tW=n(65063),tz=n(7644);let tN=[{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 tP(e){return"dark"===e||"pine"===e}let tA="pi-theme",tB={preference:"auto",theme:"light"},tD=new Set,tF=null,tH=!1;function tO(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tU(e){return"auto"===e?tO():e}function t_(e){"u">typeof document&&(document.documentElement.dataset.theme=e,document.documentElement.classList.toggle("dark",tP(e)))}function tq(){if(tF)return tF;let e=function(){try{let e=localStorage.getItem(tA);if(tN.some(t=>t.id===e))return e}catch{}return"auto"}(),t=tU(e);return t_(t),tF={preference:e,theme:t}}function tK(e,t,n){if(t_(t),n)try{localStorage.setItem(tA,e)}catch{}tF={preference:e,theme:t},tD.forEach(e=>e())}function tV(){let e=tq();if("auto"!==e.preference)return;let t=tO();t!==e.theme&&tK("auto",t,!1)}function tJ(e){return tD.add(e),tq(),tH||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tV),window.addEventListener("focus",tV),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tV()}),tH=!0),tV(),()=>{tD.delete(e)}}function tY(){return tq()}function tZ(){return tB}function tG(){let e=(0,i.useSyncExternalStore)(tJ,tY,tZ),t=(0,i.useCallback)((e,t)=>{if(tq().preference===e)return;let n=tU(e),r=()=>{tK(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:tP(e.theme)}}function tX(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 tQ({code:e,isStreaming:t,defaultPreview:o=!1}){let{isDark:l}=tG(),{t:s}=(0,L.s)(),[a,d]=(0,i.useState)(o),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),f=(0,i.useRef)(null),g=`${l?"dark":"light"}
|
|
6
|
+
${e}`,x=a&&!t;(0,i.useEffect)(()=>{if(!x)return;let t=!1;return u({key:g,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(988),n.e(9425),n.e(3308)]).then(n.bind(n,43328));if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:l?"dark":"default"}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await r.render(i,e);t||u({key:g,status:"ready",svg:o.svg})})().catch(()=>{t||u({key:g,status:"error"})}),()=>{t=!0}},[e,g,l,x]);let 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)(t1,{code:e,lang:"mermaid",headerAction:m,isStreaming:t});let v=c?.key===g&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:s("i18n.invalidMermaid")}):c?.key!==g||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":s("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.jsx)("button",{ref:f,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)(t0,{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===g&&"ready"===c.status&&(0,r.jsx)("button",{type:"button",className:"markdown-code-action",title:`${s("i18n.downloadFile")} (SVG)`,"aria-label":`${s("i18n.downloadFile")} (SVG)`,onClick:()=>{let e,t,n,r=f.current?.querySelector("svg");r&&(e=new XMLSerializer().serializeToString(r),t=URL.createObjectURL(new Blob([e],{type:"image/svg+xml;charset=utf-8"})),(n=document.createElement("a")).href=t,n.download="mermaid-diagram.svg",n.click(),setTimeout(()=>URL.revokeObjectURL(t),0))},children:"SVG"}),m]})]}),v]})}function t0({svg:e,onClose:t}){let{t:n}=(0,L.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 t1=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:o}){let{isDark:l}=tG(),{t:s}=(0,L.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:()=>{tX(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)(tW.A,{language:t||"text",style:l?tz.xJ:tz.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})]})}),t2=(0,i.createContext)(!1);function t4({src:e,alt:t,cwd:n,...o}){let l=(0,i.useContext)(t2);delete o.node;let s="string"==typeof e?e:void 0,a=s?te(s,n):null,d=a?`/api/files/${V(a)}?type=read`:s,c=(0,r.jsx)("img",{src:d,alt:t??"",loading:"lazy",...o});return!d||l?c:(0,r.jsx)(t$,{src:d,alt:t??"",className:"markdown-image",children:c})}function t8({children:e,className:t,isStreaming:n,cwd:o,onOpenFile:l}){let s=(0,i.useMemo)(()=>tS(e),[e]),a=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let o=e?.replace("language-","").toLowerCase()??"",l=String(t);return e?.includes("language-")||l.includes("\n")?"mermaid"===o?(0,r.jsx)(tQ,{code:l.replace(/\n$/,""),isStreaming:n,defaultPreview:!0}):(0,r.jsx)(t1,{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?te(e,o):null;return i&&l?(0,r.jsx)(t2.Provider,{value:!0,children:(0,r.jsx)("a",{href:e,...n,onClick:t=>{if(!e5(t))return;let n=t.currentTarget.getAttribute("target");n&&"_self"!==n||(t.preventDefault(),l(i,tn(e)??void 0))},children:t})}):(0,r.jsx)(t2.Provider,{value:!0,children:(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})})},img:e=>(0,r.jsx)(t4,{cwd:o,...e}),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)(th.oz,{remarkPlugins:tM,rehypePlugins:tR,urlTransform:l?tk:void 0,components:a,children:s})})}function t6({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 t5=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,t3=/(?:\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 t9(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=t7(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:t7(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 t7(e){return e.split(" ")[0].trim()}let ne=new Set,nt="pi-thinking-expanded",nn="pi-thinking-expanded-changed";function nr(){return"true"===window.localStorage.getItem(nt)}function ni({files:e,onOpenFile:t}){let{t:n}=(0,L.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=J(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:[q(i,12),(0,r.jsx)("span",{children:i})]},e)})})}let no=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function nl(e){let t=0,n=0;for(let r of e)no.test(r)?t++:n++;return t+n/4}let ns=new Map;function na({children:e,className:t,...n}){let{t:o}=(0,L.s)(),[l,s]=(0,i.useState)(!1);if(e.length<=1e5)return(0,r.jsx)(t8,{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 nd(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 nc=(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:f,prevTimestamp:g,sessionId:x,writtenFiles:m}){return"user"===e.role?(0,r.jsx)(nu,{message:e,cwd:o,onOpenFile:l,entryId:a,onFork:c,forking:u,onNavigate:p,onEditContent:h}):"assistant"===e.role?(0,r.jsx)(np,{message:e,isStreaming:t,toolResults:n,modelNames:i,cwd:o,onOpenFile:l,onOpenSession:s,showTimestamp:f,prevTimestamp:g,sessionId:x,entryId:a,searchBlock:d,writtenFiles:m}):"toolResult"===e.role?null:"custom"===e.role?"compaction"===e.customType?(0,r.jsx)(nI,{message:e}):(0,r.jsx)(nE,{message:e,cwd:o,onOpenFile:l}):"bashExecution"===e.role?(0,r.jsx)(nW,{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 nu({message:e,cwd:t,onOpenFile:n,entryId:o,onFork:l,forking:s,onNavigate:a,onEditContent:d}){let{t:c}=(0,L.s)(),[u,h]=(0,i.useState)(!1),[f,g]=(0,i.useState)(!1),[x,m]=(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=p(v),w=b?.search(/\s/)??-1,k=b?-1===w?b:b.slice(0,w):"",j=b&&-1!==w?b.slice(w+1):"",S=nd(e.timestamp),C=!!o&&!!l,I=b??v,T=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,M=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)(t$,{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)})}),E=!!o&&!!a;return(0,r.jsxs)("div",{style:{marginBottom:16,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!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:[M,(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:8,flexWrap:"wrap"},children:[(0,r.jsxs)("button",{onClick:()=>m(e=>!e),title:c(x?"i18n.collapse":"i18n.expand"),"aria-expanded":x,style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,padding:0,background:"none",border:"none",cursor:"pointer",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:"calc(13px + var(--chat-font-size-offset, 0px))",textAlign:"left"},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.75,transform:x?"rotate(180deg)":"none",transition:"transform 0.15s"},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),j&&(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:j})]}),x&&(0,r.jsx)(t8,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:v})]}):(0,r.jsxs)(r.Fragment,{children:[M,v&&(0,r.jsx)(na,{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:()=>{tX(I).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:f?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11,fontWeight:400,whiteSpace:"nowrap",transition:"color 0.12s"},onMouseEnter:e=>{f||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{f||(e.currentTarget.style.color="var(--text-dim)")},children:[f?(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(f?"i18n.copied":"i18n.copy")]})}),(C||E)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:u||s?1:0,pointerEvents:u||s?"auto":"none",transition:"opacity 0.12s"},children:[E&&(0,r.jsxs)("button",{onClick:()=>void a(o).then(e=>{e&&d?.(T)}),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 np({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:f}){var g,x,m;let v,y,b,w,k,j,{t:S}=(0,L.s)(),C=d?nd(e.timestamp):null,I=(0,i.useMemo)(()=>(e.content??[]).map((e,t)=>({block:e,originalIndex:t})).filter(({block:e})=>!e1(e,{isStreaming:t})),[e.content,t]),T=(0,i.useMemo)(()=>I.map(({block:e})=>e),[I]),M=e4(e,{isStreaming:t}),E=e8(e,{isStreaming:t}),[R,$]=(0,i.useState)(!1),[W,z]=(0,i.useState)(!1),N=(0,i.useRef)(null),[P,A]=(0,i.useState)(null),B=(0,i.useRef)(I);B.current=I;let D=(0,i.useRef)(new Map),F=(0,i.useMemo)(()=>{if(!t)return D.current=new Map,0;let e=new Map,n=0;for(let{block:t,originalIndex:r}of I){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 nl(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+nl(t.slice(o))}(D.current.get(r),i);e.set(r,{text:i,tokens:o}),n+=o}return D.current=e,n},[I,t]),H=(0,i.useRef)(F);H.current=F;let O=(0,i.useRef)(new Map),[U,_]=(0,i.useState)(new Map),q=(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]),K=(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]),V=T.filter(e=>"text"===e.type).map(e=>e.text).join("\n");if((0,i.useEffect)(()=>{if(!t){let e=new Date().getTime();_(t=>{let n=new Map(t);for(let[t,r]of O.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),N.current=null,A(null);return}let e=setInterval(()=>{let e=B.current,t=Date.now();e.forEach(({originalIndex:e})=>{O.current.has(e)||O.current.set(e,t)}),_(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)&&O.current.has(o)){let e=O.current.get(o),n=O.current.get(l)??t;i.set(o,Math.round((n-e)/1e3)),r=!0}}return r?i:n});let n=H.current;if(0===n)return;null===N.current&&(N.current=t);let r=(t-N.current)/1e3;r>.5&&A(n/r)},300);return()=>clearInterval(e)},[t]),0===T.length&&!t&&!M&&!E)return null;return(0,r.jsxs)("div",{"data-message-role":"assistant","data-entry-id":p,style:{marginBottom:16},onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!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:(g=e.provider,x=e.model,y=g.toLowerCase(),b=x.toLowerCase(),w=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}]:[]}),w.find(e=>e.id===b)?.name??w.find(e=>b.endsWith(`/${e.id}`))?.name??Object.entries(o??{}).find(([e])=>e.toLowerCase()===b)?.[1]??`${g}/${x}`)}),t&&(k=Math.round(F),(0,r.jsx)(r.Fragment,{children:k>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"})]}),k]}),null!==P&&(j=P>=50?"#53b3cb":P>=30?"#9bc53d":P>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:j,color:"#fff",fontSize:11,fontWeight:400},children:[P.toFixed(1)," t/s"]}))]})}))]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:I.map(({block:e,originalIndex:i})=>(0,r.jsx)(nh,{block:e,searchTarget:e===h,toolResults:n,isStreaming:t,streamingDuration:U.get(i)??("thinking"===e.type?q:void 0),toolCallDurations:K,cwd:l,onOpenFile:s,onOpenSession:a,sessionId:u,entryId:p,blockIndex:i},`${p??"stream"}-${i}`))}),M&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:8*(T.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: ",M]}),E&&(0,r.jsx)("div",{role:"alert",style:{marginTop:T.length>0||M?8:0,padding:"7px 10px",border:"1px solid rgba(234,179,8,0.3)",borderRadius:6,background:"rgba(234,179,8,0.07)",color:"#ca8a04",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:S("chat.truncatedByOutputLimit")}),f&&f.length>0&&(0,r.jsx)(ni,{files:f,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 "))}),V&&!t&&(0,r.jsxs)("button",{onClick:()=>{tX(V).then(()=>{z(!0),setTimeout(()=>z(!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:W?"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=>{W||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{W||(e.currentTarget.style.color="var(--text-dim)")},children:[W?(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(W?"i18n.copied":"i18n.copy")]}),C&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:C})]})]})}function nh({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)(nf,{block:e,isStreaming:i,cwd:s,onOpenFile:a})});if("thinking"===e.type)return(0,r.jsx)(ng,{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)(nx,{block:e,result:t,duration:i,onOpenSession:d})}return null}function nf({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(na,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function ng({block:e,duration:t,sessionId:n,entryId:o,blockIndex:l}){var s;let{t:a}=(0,L.s)(),[d,c]=(0,i.useState)(nr),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[g,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(nr());return window.addEventListener(nn,e),()=>window.removeEventListener(nn,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 f(!0),x(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=ns.get(r);if(i)return ns.delete(r),ns.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 ns.delete(r),e});if(ns.set(r,o),ns.size>100){let e=ns.keys().next().value;e&&ns.delete(e)}return o})(n,o,l).then(e=>{t||(p(e),f(!1))}).catch(e=>{t||(x(e instanceof Error?e.message:String(e)),f(!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)(t6,{active:d}),!d&&(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v?(0,r.jsx)(th.oz,{allowedElements:[],unwrapDisallowed:!0,skipHtml:!0,children:v}):"..."})]}),d&&(0,r.jsx)("div",{style:{flex:1,minWidth:0,color:g?"#f87171":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:h?a("i18n.loadingThinking"):g??(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 nx({block:e,result:t,duration:n,onOpenSession:o}){var l,s,a;let d,{t:c}=(0,L.s)(),[u,p]=(0,i.useState)(()=>{var t;return void 0!==(t=e.toolCallId)&&ne.has(t)}),h=(s=e).rawInput??JSON.stringify(s.input,null,2),f=void 0!==e.rawInput,g=tr(e.toolName),x=t&&!t.isError?function(e){let t=e.details;if(!nj(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}(t):null,m=function(e,t){if(!ti(e.toolName))return null;let n=td(to(e.input,e.rawInput));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(nj(r)){let e=tc(r.preview);if(e)return e}return null}(e,t),v=ti(e.toolName)?0===(d=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(to((a=e).input,a.rawInput))).length?null:d.join(", ").slice(0,120):null,y=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,b=nL(t?.content??[]),w=null!==y&&("(no output)"===y.trim()||""===y.trim()),k=(t?.isError??!1)||ti(e.toolName)&&ts(t?.details),j=(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:k?"1px solid rgba(248,113,113,0.45)":"1px solid rgba(34,197,94,0.25)",background:k?"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:()=>{var t;let n=!u;t=e.toolCallId,t&&(n?ne.add(t):ne.delete(t)),p(n)},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:k?"#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:f?c("chat.generatingToolInput"):v??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:u?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),j&&o&&(0,r.jsx)("button",{type:"button",onClick:()=>o(j.sessionId),title:c("subagent.open"),"aria-label":c("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"})]})})]}),u&&(f||!g)&&!m&&(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:k?"1px solid rgba(248,113,113,0.25)":"1px solid rgba(34,197,94,0.2)",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:h}),b.length>0&&(0,r.jsx)(nS,{images:b,isError:k}),u&&m&&(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(ny,{files:m})}),u&&t&&m&&k&&(0,r.jsx)(nC,{text:y??"",isEmpty:w,isError:k}),u&&t&&!m&&(x?(0,r.jsx)(nm,{diff:x}):(!w||0===b.length)&&(0,r.jsx)(nC,{text:y??"",isEmpty:w,isError:k}))]})}function nm({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid rgba(34,197,94,0.15)",background:"var(--bg)"},children:(0,r.jsx)(nv,{text:e.text})})}function nv({text:e}){let t=(0,i.useMemo)(()=>t9(e),[e]);return t?(0,r.jsx)(ny,{files:t}):(0,r.jsx)(nk,{text:e})}function ny({files:e}){let{t}=(0,L.s)(),n=e.length>1;return(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden",background:"var(--bg)"},children:e.map((e,i)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===i?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:"calc(12px + var(--chat-font-size-offset, 0px))",lineHeight:1.55},children:[n&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(nb,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(nb,{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)(nw,{cell:e.left,side:"left"}),(0,r.jsx)(nw,{cell:e.right,side:"right"})]},t))})]},i))})}function nb({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 nw({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 nk({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 nj(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function nS({images:e,isError:t}){return(0,r.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",padding:"10px",background:"var(--bg)",borderTop:`1px solid ${t?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`},children:e.map((e,t)=>{let n=n$(e);return n?(0,r.jsx)(t$,{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})})}function nC({text:e,isEmpty:t,isError:n}){let{t:i}=(0,L.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"rgba(248,113,113,0.3)":"rgba(34,197,94,0.15)"}`,background:n?"rgba(248,113,113,0.04)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"#f87171":t?"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:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function nI({message:e}){let{t}=(0,L.s)(),n=nR(e.content),o=(0,i.useMemo)(()=>{let e,t,r,i,o;return e=[],t=[],r=n.match(t3),i=r?.[1]??"",o=r?.index===void 0?n:n.slice(0,r.index),i.replace(t5,(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=nd(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)(t8,{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)(nT,{readFiles:o.readFiles,modifiedFiles:o.modifiedFiles})]})]})})}function nT({readFiles:e,modifiedFiles:t}){let{t:n}=(0,L.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)(nM,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(nM,{title:n("i18n.readFiles"),files:e})]})}function nM({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 nE({message:e,cwd:t,onOpenFile:n}){let o,{t:l}=(0,L.s)(),s=!1===e.display,[a,d]=(0,i.useState)(!s),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!1),f=nR(e.content),g=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=nd(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:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=n$(e);return n?(0,r.jsx)(t$,{src:n,children:(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:6,objectFit:"contain",display:"block",border:"1px solid var(--border)"}})},t):null})}),f?(0,r.jsx)(t8,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>d(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(o=f.replace(/\s+/g," ").trim())?o.length>140?`${o.slice(0,140)}...`:o:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||m?(0,r.jsx)("button",{onClick:()=>{tX(f||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 nR(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 n$(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 nW({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,f=n??e.output;async function g(){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:f?[{type:"text",text:f}]:[],isError:u,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(nx,{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:g,disabled:l,style:{background:"none",border:"none",color:"var(--accent)",cursor:l?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:l?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${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 nz(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 nN=new Map;function nP(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function nA(e){return!e.value&&0===e.images.length}function nB(e){let t=nN.get(e);return t?nP(t):null}function nD(e,t){nA(t)?nN.delete(e):nN.set(e,nP(t))}function nF(e){nN.delete(e)}function nH(e,t){return e.trim()?t.trim()?`${e}
|
|
7
|
+
|
|
8
|
+
${t}`:e:t}function nO(e,t,n,r){let i=[...t??[],...r].filter(nz).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t}));return{value:nH(e,n),images:i}}function nU(e,t,n){if(e===t)return n?nP(n):nB(t);let r=nB(e),i=n&&!nA(n)?nP(n):r??(n?nP(n):null),o=nB(t);if(nF(e),!i)return o;let l=o?nO(o.value,o.images,i.value,i.images):i;return nD(t,l),nP(l)}function n_(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 nq(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function nK(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 nV(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}let nJ="(max-width: 640px)",nY="(max-width: 480px)";function nZ(e,t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)}function nG(e){return!!window.matchMedia&&window.matchMedia(e).matches}let nX=e=>nZ(nJ,e),nQ=()=>nG(nJ),n0=e=>nZ(nY,e),n1=()=>nG(nY);function n2(){return!1}function n4(){return(0,i.useSyncExternalStore)(nX,nQ,n2)}function n8(){return(0,i.useSyncExternalStore)(n0,n1,n2)}let n6="pi-chat-content-width",n5="pi-chat-content-font-size",n3={width:820,fontSize:14},n9=null,n7=new Set;function re(e){let t=Number(e);return Number.isFinite(t)?Math.max(820,Math.min(2e3,Math.round(t))):820}function rt(e){let t=Number(e??14);return Number.isFinite(t)?Math.max(12,Math.min(24,Math.round(t))):14}function rn(e){try{return window.localStorage.getItem(e)}catch{return null}}function rr({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 ri(){return n9||rr(n9={width:re(rn(n6)),fontSize:rt(rn(n5))}),n9}function ro(e){return n7.add(e),()=>{n7.delete(e)}}function rl(e,t){let n="width"===e?re(t):rt(t);rr(n9={...ri(),[e]:n});try{window.localStorage.setItem("width"===e?n6:n5,String(n))}catch{}n7.forEach(e=>e())}let rs=e=>rl("width",e),ra=e=>rl("fontSize",e);function rd(){return{...(0,i.useSyncExternalStore)(ro,ri,()=>n3),setWidth:rs,setFontSize:ra}}let rc=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function ru(e,t){return rc.compare(e.name||e.modelId,t.name||t.modelId)||rc.compare(e.provider,t.provider)||rc.compare(e.modelId,t.modelId)}function rp({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 f,g,x,m,v,y,b,w,k,{t:j}=(0,L.s)(),S=n4(),C=(0,i.useRef)(null),I=(0,i.useRef)(null),[T,M]=(0,i.useState)(!1),[E,R]=(0,i.useState)(null),[$,W]=(0,i.useState)(""),z=a||d,N=(0,i.useMemo)(()=>[...e].sort(ru),[e]),P=(f=$.trim().toLocaleLowerCase())?N.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(f)):N,A=N.length>8,B=[];for(let e of P){let t=B.find(t=>t.provider===e.provider);t?t.options.push(e):B.push({provider:e.provider,options:[e]})}let D=s??(t?N.find(e=>e.modelId===t.modelId&&e.provider===t.provider)?.name??t.modelId:l??(N.length>0?"Select model":"No models"));(0,i.useEffect)(()=>{let e=e=>{C.current&&!C.current.contains(e.target)&&I.current&&!I.current.contains(e.target)&&(M(!1),W(""))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{z&&(M(!1),W(""))},[z]);let F="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:T?"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&&T&&(e.preventDefault(),e.stopPropagation(),W(""),M(!1))},children:[(0,r.jsxs)("button",{type:"button","aria-label":u,"aria-haspopup":"listbox","aria-expanded":T,"aria-busy":d||void 0,disabled:z,title:d?"Switching model":z?D:N.length>0||o?"Change model":"No available models",style:F,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();R({top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width}),M(e=>(e&&W(""),!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=T?"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:D}),"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"})})]}),T&&E&&(g=window.visualViewport?.height??window.innerHeight,x=window.visualViewport?.width??window.innerWidth,m=E.top-8,v=g-E.bottom-8,b=Math.max(120,Math.min((y="up"===h||m>v)?m:v,.6*g)),w=y?{bottom:g-E.top+6}:{top:E.bottom+6},k=S?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:E.left,width:"max-content",minWidth:E.width,maxWidth:Math.max(E.width,x-E.left-8)},(0,r.jsxs)("div",{ref:I,role:"listbox","aria-label":u,style:{position:"fixed",...w,...k,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=>W(e.target.value),placeholder:j("chat.filterModels"),"aria-label":j("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)(rh,{active:!t,label:l??"Default",onClick:()=>{M(!1),W(""),o()}}),0===B.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:$.trim()?j("chat.noMatchingModels"):"No available models"}):B.map((e,i)=>(0,r.jsxs)("div",{children:[B.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)(rh,{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(M(!1),W(""),(!r||c)&&n(e.provider,e.modelId))}},`${e.provider}:${e.modelId}`))]},e.provider))]})]}))]})}function rh({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 rf=["chat-only","read-only","default","full"],rg={"chat-only":"none","read-only":"read-only",default:"default",full:"full"},rx=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),rm=(()=>{if("u"<typeof navigator)return!1;let e=navigator.userAgent.toLowerCase();return e.includes("; wv)")||e.includes("webview")&&!e.includes("chrome/")||/(iphone|ipad|ipod)/.test(e)&&!e.includes("safari/")})();function rv(e,t,n){return t<=0?0:((e+n)%t+t)%t}function ry(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 rb=["auto","off","minimal","low","medium","high","xhigh","max"],rw={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 rk(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rj=[{name:"compact",description:"chat.commandCompact",source:"builtin"},{name:"auto-compact",description:"chat.commandAutoCompact",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 rS(e){return function(e){let t=e.trim().match(/^\/([^\s]+)(?:\s|$)/);if(t)return rj.find(e=>e.name===t[1])}(e)?.availableWhileStreaming===!0}let rC=["builtin","extension","prompt","skill"],rI={builtin:"chat.builtIn",extension:"chat.extensions",prompt:"chat.prompts",skill:"chat.skills"},rT={builtin:0,extension:1,prompt:2,skill:3};function rM(e,t,n){let r=e.name.toLowerCase(),i=rE(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function rE(e,t){return"builtin"===e.source?t(e.description):e.description??""}function rR(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}async function rL(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 r$(e){return{data:e.data,mimeType:e.mimeType}}function rW(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function rz(e){return(e??[]).filter(nz).slice(0,10).map(rW)}function rN(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function rP({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 rA({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 rB({error:e}){let{t}=(0,L.s)();return e?(0,r.jsx)(rA,{tone:"error",title:t("chat.modelError"),body:e}):null}function rD({warnings:e}){let{t}=(0,L.s)();return e&&0!==e.length?(0,r.jsx)(rA,{tone:"warning",title:t(e.length>1?"chat.modelScopeWarnings":"chat.modelScopeWarning"),body:e.join("\n")}):null}let rF=(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:f,onCompact:g,onAbortCompaction:x,isCompacting:m,compactError:v,compactResult:y,toolPreset:b,onToolPresetChange:w,thinkingLevel:k,isAutoThinkingSelection:j=!1,onThinkingLevelChange:S,availableThinkingLevels:C,thinkingLevelMap:I,retryInfo:T,queuedMessages:M,inputHistory:E=[],onRecallQueue:R,slashCommands:$,slashCommandsLoading:W,onLoadSlashCommands:z,onBuiltinCommand:N,soundEnabled:P,onSoundToggle:A,onAudioUnlock:B,onPromptWithStreamingBehavior:D,draftKey:F,cwd:H,compact:U=!1},_){let K,V,J,Y,Z,G,X,{t:ee}=(0,L.s)(),{fontSize:en}=rd(),eo=n4(),el=n8(),[ed,ec]=(0,i.useState)(()=>F?nB(F)?.value??"":""),[eu,ep]=(0,i.useState)(!1),[eh,ef]=(0,i.useState)(!1),[eg,ex]=(0,i.useState)(!1),[em,ev]=(0,i.useState)(()=>F?rz(nB(F)?.images):[]),ey=ed.trimStart(),eb=0===em.length&&ey.startsWith("!"),ew=eb&&ey.startsWith("!!"),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(0),[eI,eT]=(0,i.useState)(null),[eM,eE]=(0,i.useState)(null),[eR,eL]=(0,i.useState)(!1),[e$,eW]=(0,i.useState)(null),[ez,eN]=(0,i.useState)(0),[eP,eA]=(0,i.useState)(!1),[eB,eD]=(0,i.useState)(!1),[eF,eH]=(0,i.useState)(!1),[eO,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(!1),[eJ,eY]=(0,i.useState)(0),[eZ,eG]=(0,i.useState)(!1),eX=(0,i.useRef)(!1),[eQ,e0]=(0,i.useState)(null),[e1,e2]=(0,i.useState)(!1),[e4,e8]=(0,i.useState)(null),[e6,e5]=(0,i.useState)(null),e3=H&&e6?.cwd===H?e6.values:{},e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),to=(0,i.useRef)(!1),tl=(0,i.useRef)(0),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(null),td=(0,i.useRef)([]),tc=(0,i.useRef)(null),tu=(0,i.useRef)([]),tp=(0,i.useRef)([]),th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(F),tx=(0,i.useRef)(ed),tm=(0,i.useRef)(em),tv=(0,i.useRef)(0);tx.current=ed,tm.current=em,(0,i.useImperativeHandle)(_,()=>({insertIfEmpty(e){let t=e9.current;(t?t.value:ed).trim()||(tx.current=e,ec(e),eE(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=e9.current;if(t=i?i.value:ed,n=tm.current.length,r=tv.current,t.trim()||0!==n||0!==r)return void eH(!0);let o="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),l=rz("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 nz(r)?[r]:[]}));tx.current=o,tm.current=l,ec(o),eE(null),eV(!1),ev(e=>(e.forEach(rN),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=e9.current,n=[e,t?t.value:ed].filter(e=>e.trim()).join("\n\n");tx.current=n,ec(n),eE(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(tg.current!==e)return void nU(e,t);let n={value:tx.current,images:tm.current.map(r$)},r=nU(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(tg.current=t,i)return;let o=rz(r.images);tx.current=r.value,tm.current=o,ec(r.value),ev(e=>(e.forEach(rN),o)),eE(null),eV(!1)},restoreSubmission(e,t,n){if(!e.trim()&&!t?.length)return;let r=tg.current,i=n??r,o=i===r,l=!o&&i?nB(i):null,s=nO(e,t,o?tx.current:l?.value??"",o?tm.current.map(r$):l?.images??[]);if(i&&nD(i,s),!o)return;let a=t?.length?[...rz(t).slice(0,Math.max(0,10-tm.current.length)),...tm.current].slice(0,10):tm.current;tx.current=s.value,tm.current=a,ec(t=>{let n=nH(e,t);return tx.current=n,n}),eE(null),eV(!1),t?.length&&ev(e=>{let n=Math.max(0,10-e.length),r=rz(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tm.current=i,i}),requestAnimationFrame(()=>{let e=e9.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=e9.current;if(!t)return void ec(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;tx.current=s,ec(s),eE(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){ty(e)}}));let ty=(0,i.useCallback)(async e=>{if(U)return;let t=Math.max(0,10-tm.current.length-tv.current),n=e.filter(e=>e.type.startsWith("image/")&&e.size<=0xa00000).slice(0,t);if(n.length){tv.current+=n.length;try{let e=await Promise.all(n.map(async e=>({...await rL(e),previewUrl:URL.createObjectURL(e)})));ev(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(rN);let r=[...t,...n];return tm.current=r,r})}finally{tv.current-=n.length}}},[U]),tb=(0,i.useCallback)(async e=>{try{if("camera"===e){let e=er();if(!e)return;let t=await e.getPhoto({resultType:Q,source:"CAMERA",quality:90,correctOrientation:!0});t.base64String&&await ty([es(t.base64String,t.format)]);return}let t=ei();if(t?.pickImages){let{files:e}=await t.pickImages({readData:!0}),n=ea(e);n.length&&await ty(n);return}let n=er();if(!n)return;let r=await n.getPhoto({resultType:Q,source:"PHOTOS",quality:90,correctOrientation:!0});r.base64String&&await ty([es(r.base64String,r.format)])}catch(t){let e;e=t instanceof Error?t.message:"string"==typeof t?t:"",/permission|denied|not authorized|unauthorized/i.test(e)&&eq(!0)}},[ty]),tw=(0,i.useCallback)(()=>{if(et())return void eU(e=>!e);let e=tr.current;if(!e)return;ti.current?.(),ti.current=null;let t=!1,n=!1,r=()=>{t=!0,eD(!1)},i=()=>{"hidden"===document.visibilityState&&(n=!0)},o=()=>{n=!0},l=()=>{e.removeEventListener("change",r),document.removeEventListener("visibilitychange",i),window.removeEventListener("blur",o)};if(rm&&(e.addEventListener("change",r),document.addEventListener("visibilitychange",i),window.addEventListener("blur",o)),e.click(),!rm)return;let s=window.setTimeout(()=>{ti.current=null,l(),t||n||e.files&&e.files.length>0||eD(!0)},200);ti.current=()=>{window.clearTimeout(s),l()}},[]);(0,i.useEffect)(()=>{if(!eB)return;let e=window.setTimeout(()=>eD(!1),6e3);return()=>window.clearTimeout(e)},[eB]),(0,i.useEffect)(()=>{if(!e_)return;let e=window.setTimeout(()=>eq(!1),6e3);return()=>window.clearTimeout(e)},[e_]),(0,i.useEffect)(()=>{if(!eF)return;let e=window.setTimeout(()=>eH(!1),6e3);return()=>window.clearTimeout(e)},[eF]);let tk=(0,i.useCallback)(e=>{ev(t=>{let n=[...t],[r]=n.splice(e,1);return r&&rN(r),tm.current=n,n})},[]),tj=(0,i.useCallback)(()=>{tm.current=[],ev(e=>(e.forEach(rN),[]))},[]),tS=(0,i.useCallback)(()=>{tx.current="",ec(""),eE(null),eV(!1),F&&nF(F),tg.current&&tg.current!==F&&nF(tg.current),tj(),e9.current&&(e9.current.style.height="auto")},[tj,F]);(0,i.useEffect)(()=>{F&&tg.current===F&&nD(F,{value:ed,images:em.map(r$)})},[em,F,ed]),(0,i.useEffect)(()=>{let e=tg.current;if(e===F)return;e&&nD(e,{value:tx.current,images:tm.current.map(r$)});let t=F?nB(F):null;tg.current=F;let n=t?.value??"",r=rz(t?.images);tx.current=n,tm.current=r,ec(n),eE(null),eV(!1),ev(e=>(e.forEach(rN),r))},[F]);let tC=(0,i.useCallback)(()=>{let e=e9.current;e&&(e.style.height="auto",e.value&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[]);(0,i.useLayoutEffect)(tC,[ed,en,tC]),(0,i.useEffect)(()=>{let e=e9.current;if(!e)return;let t=-1,n=new ResizeObserver(([e])=>{e.contentRect.width!==t&&(t=e.contentRect.width,tC())});return n.observe(e),()=>n.disconnect()},[tC]),(0,i.useEffect)(()=>()=>{tm.current.forEach(rN)},[]);let tI=(0,i.useCallback)(async e=>{if(em.length||!e.startsWith("/")||!N)return!1;if(eX.current)return!0;eX.current=!0,eG(!0);try{var t,n;let r=await N(e);if(!r.handled)return!1;return r.error||(t=tx.current,n=tm.current.length,0!==n||t.trim()!==e)||tS(),!0}finally{eX.current=!1,eG(!1)}},[em.length,tS,N]),tT=(0,i.useCallback)(async()=>{let t=ed.trim();!t&&!em.length||(B?.(),(!l||rS(t))&&await tI(t)||l||(tS(),e(t,em.length?em:void 0)))},[ed,em,l,tI,e,tS,B]),tM=!U&&ed.startsWith("/")&&!/\s/.test(ed.slice(1))?ed.slice(1).toLowerCase():null,tE=null===tM?[]:[...l?rj.filter(e=>e.availableWhileStreaming):rj,...$??[]].filter(e=>{let t=e.name.toLowerCase(),n=rE(e,ee).toLowerCase();return t.includes(tM)||n.includes(tM)}).sort((e,t)=>{let n=rM(e,tM,ee)-rM(t,tM,ee);return 0!==n?n:rT[e.source]-rT[t.source]||rx.compare(e.name,t.name)}),{commands:tR,groups:tL}=(K=0,{commands:(V=rC.map(e=>{let t=tE.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!rR(e,e3)),...t.filter(e=>rR(e,e3))]:t;return{source:e,items:n.map(e=>({command:e,index:K++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:V}),tW=1===tE.length?ee(tM?"chat.match":"chat.command"):ee(tM?"chat.matches":"chat.commands",{count:tE.length}),tz=!!ed.trim()||em.length>0,tN=em.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)&&!eP;(0,i.useEffect)(()=>{0===em.length&&eA(!1)},[em.length]);let tP=(0,i.useCallback)((e,t)=>{if(!H)return void eE(null);let n=t??e.length;eE(n_(e.slice(0,n)))},[H]),tA=eM?.query??null,tB=i.useMemo(()=>null!==tA&&eQ&&eQ.cwd===H?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:nK(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:nK(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||nq(e.entry.path)-nq(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eQ.entries,tA):[],[tA,eQ,H]),tD=!!(tA&&eQ?.truncated&&eQ.cwd===H);(0,i.useEffect)(()=>{if(!tD||!H||!tA)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(H)}&q=${encodeURIComponent(tA)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e8({cwd:H,query:tA,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[tD,tA,H]);let tF=tD&&null!==e4&&e4.cwd===H&&e4.query===tA,tH=tF?e4.matches:tB,tO=null===eM?null:`${eM.start}:${+!!eM.quoted}:${eM.query}`;(0,i.useEffect)(()=>{if(null===tO){eL(!1),eN(0);return}eL(!0),eN(0)},[tO]);let tU=null!==eM;(0,i.useEffect)(()=>{if(!tU||!H)return;let e=th.current;e&&e.cwd===H&&Date.now()-e.fetchedAt<1e4||tf.current===H||(tf.current=H,e2(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(H)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{e0({cwd:H,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)=>nq(e.path)-nq(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),th.current={cwd:H,fetchedAt:Date.now()}}).catch(()=>{th.current=null}).finally(()=>{tf.current=null,e2(!1)}))},[tU,H]);let t_=(0,i.useCallback)(e=>{if(!eM)return;let t=e9.current,n=t?.selectionStart??ed.length,r=ed.slice(0,eM.start),i=ed.slice(n);eM.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,eM.quoted),l=r+o.text+i,s=r.length+o.cursorOffset;ec(l),eE(n_(l.slice(0,s))),requestAnimationFrame(()=>{let e=e9.current;e&&(e.focus(),e.setSelectionRange(s,s),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[eM,ed]);(0,i.useEffect)(()=>{ez>=tH.length&&eN(Math.max(0,tH.length-1))},[tH.length,ez]),(0,i.useEffect)(()=>{tu.current.length=tH.length},[tH.length]),(0,i.useEffect)(()=>{eR&&tu.current[ez]?.scrollIntoView({block:"nearest",inline:"nearest"})},[ez,eR]),(0,i.useEffect)(()=>{eJ>=E.length&&eY(Math.max(0,E.length-1))},[E.length,eJ]),(0,i.useEffect)(()=>{tp.current.length=E.length},[E.length]),(0,i.useEffect)(()=>{eK&&tp.current[eJ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eJ,eK]);let tq=(0,i.useCallback)(e=>{ec(e),eV(!1),eY(0),eE(null),requestAnimationFrame(()=>{let t=e9.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),tK=(0,i.useCallback)(e=>{let t=`/${e.name} `;ec(t),ej(!1),eC(0),requestAnimationFrame(()=>{let e=e9.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),tV=(0,i.useCallback)(e=>{let t=ed.trim();if(t||em.length){if(B?.(),!em.length&&N&&rS(t))return void tI(t);if(t.startsWith("/")&&D){tS(),D(t,"steer"===e?"steer":"followUp",em.length?em:void 0);return}tS(),"steer"===e&&n?n(t,em.length?em:void 0):"followup"===e&&o&&o(t,em.length?em:void 0)}},[ed,em,N,D,n,o,tS,B,tI]),tJ=(0,i.useCallback)(e=>{let t=tR.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eS-1);if("right"===e)return Math.min(t,eS+1);let n=td.current[eS];if(!n)return"down"===e?Math.min(t,eS+1):Math.max(0,eS-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===eS)continue;let t=td.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,eS+1):Math.max(0,eS-1)},[tR.length,eS]),tY=(0,i.useCallback)(e=>{let r=e.nativeEvent,i="Enter"===e.key&&!e.shiftKey&&(!eo||e.ctrlKey||e.metaKey),s=Date.now()-tl.current<100,a=to.current||r.isComposing||229===r.keyCode;if(i&&(a||s)){s&&e.preventDefault();return}if(eK&&!a){if("ArrowDown"===e.key){e.preventDefault(),eY(e=>Math.min(Math.max(0,E.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eY(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eV(!1);return}if(("Tab"===e.key||i)&&E[eJ]){e.preventDefault(),tq(E[eJ]);return}}if(ek&&null!==tM){if("ArrowDown"===e.key){e.preventDefault(),eC(tJ("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eC(tJ("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eC(tJ("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eC(tJ("left"));return}if("Escape"===e.key){e.preventDefault(),ej(!1);return}let t=tR[eS];if("Tab"===e.key&&t){e.preventDefault(),tK(t);return}if(i&&t)return void((e.preventDefault(),l&&("builtin"!==t.source||!0!==t.availableWhileStreaming)||"builtin"!==t.source||ed.trim()!==`/${t.name}`)?tK(t):(ej(!1),tT()))}if(eR&&null!==eM&&!a){if("ArrowDown"===e.key){e.preventDefault(),eN(e=>rv(e,tH.length,1));return}if("ArrowUp"===e.key){e.preventDefault(),eN(e=>rv(e,tH.length,-1));return}if("Escape"===e.key){e.preventDefault(),eL(!1);return}if(("Tab"===e.key||i)&&tH[ez]){e.preventDefault(),t_(tH[ez]);return}}if("ArrowUp"===e.key&&!a&&!l&&E.length>0&&0===ed.trim().length){e.preventDefault(),ej(!1),eL(!1),eY(E.length-1),eV(!0);return}if("Escape"===e.key&&!a&&l&&t){e.preventDefault(),t();return}i&&(e.preventDefault(),l&&(n||o)?tV(e.altKey&&o||!n?"followup":"steer"):tT())},[eo,l,n,o,t,ek,tM,tR,eS,tK,tV,tT,tJ,eR,eM,tH,ez,t_,eK,E,eJ,tq,ed]),tZ=(0,i.useCallback)(()=>{let e=e9.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),tG=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(!U&&t.length){e.preventDefault(),ty(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(),tx.current=a,ec(a),eV(!1),tP(a,s+o.length),requestAnimationFrame(()=>{l.focus(),l.setSelectionRange(s+o.length,s+o.length)})},[U,ty,tP]);(0,i.useEffect)(()=>{if(null===tM){ej(!1),eC(0),ts.current=!1;return}ej(!0),eC(0),!ts.current&&z&&(ts.current=!0,Promise.resolve(z()).catch(()=>{ts.current=!1}))},[tM,z]),(0,i.useEffect)(()=>{if(!ek||!H)return;let e=!1;return e5({cwd:H,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(H)}`).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;e5({cwd:H,values:n})}).catch(()=>{e||e5({cwd:H,values:{}})}),()=>{e=!0}},[ek,H]),(0,i.useEffect)(()=>{eS>=tR.length&&eC(Math.max(0,tR.length-1))},[tR.length,eS]),(0,i.useEffect)(()=>{td.current.length=tR.length},[tR.length]),(0,i.useEffect)(()=>{ek&&td.current[eS]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eS,ek]),(0,i.useLayoutEffect)(()=>{if(!ek||null===tM)return void eT(null);let e=ta.current;if(e)return ry(e,e=>{eT(t=>t===e?t:e)})},[ek,tM]),(0,i.useLayoutEffect)(()=>{if(!eR||null===eM)return void eW(null);let e=tc.current;if(e)return ry(e,e=>{eW(t=>t===e?t:e)})},[eR,eM]);let tX=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})),tQ=y?Math.max(0,y.tokensBefore-y.estimatedTokensAfter):0,t0=y?`${y.reason&&"manual"!==y.reason?`${y.reason[0].toUpperCase()}${y.reason.slice(1)} `:ee("chat.compacted")} ${rk(y.tokensBefore)} -> ${rk(y.estimatedTokensAfter)} tokens (${ee("chat.tokensSaved",{saved:rk(tQ)})})`:null,t1=k&&"auto"!==k?k:null,t2="auto"!==(J=t1??"auto")&&I?I[J]??J:J,t4=Object.entries(rg).find(([,e])=>e===(b??"default"))?.[0]??"default",t8="chat-only"===t4?ee("chat.chatOnly"):t4;(0,i.useEffect)(()=>{let e=e=>{e7.current&&!e7.current.contains(e.target)&&ep(!1),te.current&&!te.current.contains(e.target)&&ef(!1),tt.current&&!tt.current.contains(e.target)&&ex(!1),!tn.current||tn.current.contains(e.target)||e9.current?.contains(e.target)||eV(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{l&&(ef(!1),ep(!1))},[l]),(0,i.useEffect)(()=>{eo||ex(!1)},[eo]);let t6=e=>(0,r.jsxs)("button",{onClick:t,title:ee("chat.stopAgent"),"aria-label":e?ee("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,flexShrink:0,padding:e?"0 10px":"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"})}),!e&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ee("chat.stop")})]}),t5=(e,t)=>(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{onClick:()=>tV("steer"),disabled:!tz,title:ee("chat.steerHint"),"aria-label":ee("chat.steerHint"),style:{display:"flex",alignItems:"center",gap:5,flexShrink:0,padding:t?"0 6px":e?"7px 12px":"7px 9px",height:t?32:void 0,background:tz?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:t?9:8,color:tz?"rgba(180,130,0,1)":"var(--text-dim)",cursor:tz?"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"})]}),e&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ee("chat.steer")})]}),o&&(0,r.jsxs)("button",{onClick:()=>tV("followup"),disabled:!tz,title:`${ee("chat.followUpHint")} (${eo?"Ctrl/Cmd+":""}Alt/Option+Enter)`,"aria-label":ee("chat.followUpHint"),"aria-keyshortcuts":eo?"Control+Alt+Enter Meta+Alt+Enter":"Alt+Enter",style:{display:"flex",alignItems:"center",gap:5,flexShrink:0,padding:t?"0 6px":e?"7px 12px":"7px 9px",height:t?32:void 0,background:tz?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:t?9:8,color:tz?"rgba(99,102,241,1)":"var(--text-dim)",cursor:tz?"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"})]}),e&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ee("chat.followUp")})]})]}),t3=(0,r.jsxs)("button",{onClick:tT,disabled:!ed.trim()&&!em.length,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:ed.trim()||em.length?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:ed.trim()||em.length?"var(--accent-contrast)":"var(--text-dim)",cursor:ed.trim()||em.length?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:ed.trim()||em.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"})]}),ee("chat.send")]});return(0,r.jsxs)("fieldset",{disabled:eZ,"aria-busy":eZ,style:{position:"relative",flexShrink:0,minWidth:0,margin:0,border:0,background:"transparent",padding:U?0:"0 16px 8px",paddingRight:U?0:eo?16:40,opacity:eZ?.5:1,transition:"opacity 0.15s"},children:[!U&&(0,r.jsx)("input",{ref:tr,type:"file",accept:rm?void 0:"image/*",multiple:!0,"aria-hidden":"true",tabIndex:-1,style:{position:"absolute",left:0,bottom:0,width:1,height:1,margin:-1,padding:0,border:0,opacity:0,overflow:"hidden",clipPath:"inset(50%)",pointerEvents:"none"},onChange:e=>{ty(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)(rB,{error:u}),(0,r.jsx)(rD,{warnings:p}),eB&&(0,r.jsx)(rA,{tone:"warning",title:ee("chat.filePickerUnsupportedTitle"),body:ee("chat.filePickerUnsupportedBody"),onClose:()=>eD(!1)}),e_&&(0,r.jsx)(rA,{tone:"warning",title:ee("chat.cameraPermissionDeniedTitle"),body:ee("chat.cameraPermissionDeniedBody"),onClose:()=>eq(!1)}),eF&&(0,r.jsx)(rA,{tone:"warning",title:ee("chat.draftKeptTitle"),body:ee("chat.draftKeptBody"),onClose:()=>eH(!1)}),tN&&(Y=c?.find(e=>e.provider===s?.provider&&e.id===s?.modelId),(0,r.jsx)(rA,{tone:"warning",title:ee("chat.imageNotSupportedTitle"),body:ee("chat.imageNotSupportedBody",{model:Y?.name||s?.modelId||""}),onClose:()=>eA(!0)})),(M?.steering.length??0)+(M?.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:ee("chat.queued",{count:(M?.steering.length??0)+(M?.followUp.length??0)})}),R&&(0,r.jsxs)("button",{onClick:R,title:ee("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"})]}),ee("chat.recall")]})]}),M?.steering.map((e,t)=>(0,r.jsx)(rP,{kind:"steer",text:e},`steer-${t}`)),M?.followUp.map((e,t)=>(0,r.jsx)(rP,{kind:"follow-up",text:e},`followup-${t}`))]}),T&&(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"})]}),ee("chat.retrying",{attempt:T.attempt,max:T.maxAttempts}),T.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",T.errorMessage]})]}),t0&&(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"})}),t0]}),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}),em.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:em.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)(t$,{src:e.previewUrl,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"}})},e.previewUrl),(0,r.jsx)("button",{type:"button",onClick:()=>tk(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:[eK&&E.length>0&&(0,r.jsxs)("div",{ref:tn,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:ee("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:E.map((e,t)=>{let n=t===eJ;return(0,r.jsxs)("button",{ref:e=>{tp.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tq(e)},onMouseEnter:()=>eY(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}`)})})]}),ek&&null!==tM&&(0,r.jsxs)("div",{ref:ta,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===eI?"min(72.8vh, 598px)":`min(72.8vh, 598px, ${eI}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:W?ee("chat.loadingCommands"):ee("chat.slashCommands",{label:tW})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ee("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:10},children:W||0!==tE.length?tL.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:ee(rI[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===eS,i=rR(e,e3);return(0,r.jsxs)("button",{ref:e=>{td.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),tK(e)},onMouseEnter:()=>eC(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:ee("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:rE(e,ee)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ee("chat.noCommands")})})]}),eR&&null!==eM&&(Z=e1&&(!eQ||eQ.cwd!==H),G=1===tH.length?ee("chat.match"):ee("chat.matches",{count:tH.length}),X=eQ?.truncated&&!tF?eM.query?ee("chat.searchingAll"):ee("chat.indexTruncated"):"",(0,r.jsxs)("div",{ref:tc,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===e$?"min(48vh, 400px)":`min(48vh, 400px, ${e$}px)`},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:Z?ee("chat.loadingFiles"):ee("chat.files",{label:G,hint:X})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ee("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:4},children:Z||0!==tH.length?tH.map((e,t)=>{let n=t===ez,i=e.path.split("/").pop()??e.path,o=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tu.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),t_(e)},onMouseEnter:()=>eN(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)(O,{size:14}):q(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:tD&&!tF?ee("chat.searching"):ee("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 ${eb?"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:e9,className:"chat-input-textarea","aria-label":U?ee("chat.quoteQuestion"):void 0,value:ed,onChange:e=>{tx.current=e.target.value,ec(e.target.value),eV(!1),tP(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;tP(t.value,t.selectionStart)},onKeyDown:tY,onCompositionStart:()=>{to.current=!0},onCompositionEnd:e=>{to.current=!1,tl.current=Date.now();let t=e.currentTarget;tP(t.value,t.selectionStart)},onInput:tZ,onPaste:tG,placeholder:l&&(n||o)?ee("chat.steerPlaceholder"):l?ee("chat.agentPlaceholder"):ee("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:[eo&&t6(!0),!el&&t5(!eo,!1)]}):t3]})]}),eb&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:ew?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ee("chat.shell")," \xb7 ",ew?ee("chat.outputLocal"):ee("chat.outputModel")]}),!U&&(0,r.jsxs)("div",{style:{marginTop:8,display:eo?"grid":"flex",gridTemplateColumns:eo?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eo?"1 1 auto":"0 0 auto",minWidth:0,display:"flex",alignItems:"center",gap:2,position:et()?"relative":void 0},children:[(0,r.jsx)("button",{onClick:tw,title:ee("chat.attachImage"),"aria-expanded":et()&&eO||void 0,style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:em.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=em.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=em.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"})]})}),et()&&eO&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{"aria-hidden":"true",onClick:()=>eU(!1),style:{position:"fixed",inset:0,zIndex:99,background:"transparent"}}),(0,r.jsxs)("div",{role:"menu","aria-label":ee("chat.attachImage"),style:{position:"absolute",left:0,bottom:"calc(100% + 6px)",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,padding:4},children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{eU(!1),tb("camera")},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"8px 10px",background:"none",border:"none",borderRadius:6,color:"var(--text)",fontSize:12,cursor:"pointer",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"}),(0,r.jsx)("circle",{cx:"12",cy:"13",r:"4"})]}),ee("chat.attachFromCamera")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{eU(!1),tb("gallery")},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"8px 10px",background:"none",border:"none",borderRadius:6,color:"var(--text)",fontSize:12,cursor:"pointer",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",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"})]}),ee("chat.attachFromGallery")]})]})]}),(tX.length>0||s||u)&&h&&(0,r.jsx)(rp,{options:tX,value:s,onChange:h,disabled:l,busy:f,isAutoSelection:a})]}),!eo&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsxs)("div",{ref:tt,style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:eo?0:"auto"},children:[eo&&(0,r.jsx)("button",{type:"button",title:eg?void 0:ee("chat.moreControls"),"aria-label":ee("chat.moreControls"),"aria-expanded":eg,"aria-hidden":eg||void 0,tabIndex:eg?-1:void 0,onClick:()=>{ex(!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:eg?"default":"pointer",fontSize:12,fontWeight:500,visibility:eg?"hidden":"visible",pointerEvents:eg?"none":"auto",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{eg||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{eg||(e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)")},children:ee("chat.moreControls")}),(0,r.jsxs)("div",{style:{display:eo?eg?"flex":"none":"flex",alignItems:"center",gap:eo?1:2,...eo?{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:[S&&(0,r.jsxs)("div",{ref:te,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!l&&ef(e=>!e),disabled:l,title:l?ee("chat.currentReasoning",{level:t2}):ee("chat.changeReasoning",{level:t2}),"aria-label":ee("chat.changeReasoningLabel"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eo?"0 6px":"8px 12px",width:eo?"auto":void 0,height:32,background:eh?"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=eh?"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"})]}),(!eo||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t2})]}),eh&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",...eo?{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:rb.filter(e=>!C||"auto"===e||C.includes(e)).map(e=>{let t="auto"===e?j:!j&&t1===e,n=ee(rw[e]),i="auto"!==e&&I?I[e]:void 0,o=null!=i&&i!==e?i:e,l=null!=i&&i!==e;return(0,r.jsxs)("button",{onClick:()=>{if(ef(!1),"auto"===e){j||S("auto");return}(!t||j)&&S(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&&w&&(0,r.jsxs)("div",{ref:e7,style:{position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>!l&&ep(e=>!e),disabled:l,title:ee("chat.changeToolPreset")+`: ${t8}`,"aria-label":ee("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eo?"0 6px":"8px 12px",width:eo?"auto":void 0,height:32,background:eu?"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=eu?"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"})}),(!eo||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:t8})]}),eu&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:eo?void 0:0,left:eo?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:rf.map(e=>{let t,n=rg[e],i=(b??"default")===n;return t="chat-only"===e?ee("chat.chatOnly"):"read-only"===e?ee("chat.readOnlyTools",{count:4}):"default"===e?ee("chat.builtInTools",{count:4}):ee("chat.allBuiltInTools"),(0,r.jsxs)("button",{onClick:()=>{ep(!1),i||w(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&&g&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{onClick:m?x:g,disabled:l&&!m,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eo?"0 6px":"8px 12px",width:eo?"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?ee("chat.stopCompaction"):ee("chat.compactContext"),"aria-label":m?ee("chat.stopCompaction"):ee("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"})}),(!eo||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ee("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"})]}),(!eo||eg)&&(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:ee("chat.compact")})]})})}),l&&el&&t5(!eo||eg,!0),!eo&&l&&t6(!1),void 0!==A&&(0,r.jsx)("button",{onClick:A,title:P?ee("chat.disableSound"):ee("chat.enableSound"),"aria-label":P?ee("chat.disableSound"):ee("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"})]})}),eo&&eg&&(0,r.jsx)("button",{type:"button",title:ee("chat.collapseControls"),"aria-label":ee("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ep(!1),ef(!1),ex(!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 rH=n(88576),rO=n.n(rH);function rU({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 r_=[...tE??[],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]:[]}}],rq=[[tf.A,{throwOnError:!1,strict:!1}]];function rK(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 rV=(0,i.memo)(function({markdown:e,nodeIndex:t,assistantIndex:n,onHeadingClick:o,onAnswerClick:l}){let s=(0,i.useMemo)(()=>tS(e),[e]);return e?(0,r.jsx)("div",{className:rO().outline,children:(0,r.jsx)(th.oz,{remarkPlugins:r_,rehypePlugins:rq,components:{h1:({children:e,node:i})=>(0,r.jsx)(rU,{level:1,headingIndex:rK(i),onClick:e=>o?.(t,n,e),children:e}),h2:({children:e,node:i})=>(0,r.jsx)(rU,{level:2,headingIndex:rK(i),onClick:e=>o?.(t,n,e),children:e}),h3:({children:e,node:i})=>(0,r.jsx)(rU,{level:3,headingIndex:rK(i),onClick:e=>o?.(t,n,e),children:e}),h4:()=>null,h5:()=>null,h6:()=>null,p:({children:e})=>(0,r.jsx)("button",{type:"button",className:rO().paragraph,onClick:()=>l?.(t,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:s})}):null});function rJ({messages:e,streamingMessage:t,scrollContainer:n,messageRefs:o,onRevealHistory:l,scrollToOffset:s}){let{t:a}=(0,L.s)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(600),[m,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(null),w=(0,i.useRef)(!1),k=(0,i.useRef)(null),j=(0,i.useRef)([]),S=(0,i.useRef)({nodes:[],gap:50,fillsHeight:!1}),C=(0,i.useRef)(null),I=(0,i.useRef)(null),T=(0,i.useRef)(new Map),M=(0,i.useRef)(null),E=(0,i.useRef)(null),R=(0,i.useMemo)(()=>t?[...e,t]:e,[e,t]),$=(0,i.useRef)(R);$.current=R;let W=(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}})(u,g),[u,g]),{nodes:z,gap:N}=W;S.current=W;let P=(0,i.useCallback)(e=>{M.current={index:e,until:Date.now()+1600},f(e)},[]),A=(0,i.useCallback)((e,t)=>{let n=M.current;if(n&&Date.now()<n.until)return void f(n.index);M.current=null;let r=t.filter(e=>null!==e.targetTurn.scrollTop);if(0===r.length)return void f(null);let i=e.scrollTop+.3*e.clientHeight;f(r.reduce((e,t)=>Math.abs((t.targetTurn.scrollTop??0)-i)<Math.abs((e.targetTurn.scrollTop??0)-i)?t:e,r[0]).index)},[]),B=(0,i.useCallback)(()=>{let e=n.current;if(!e)return;let t=e.scrollHeight-e.clientHeight,r=j.current;c(t>20),A(e,r)},[n,A]),D=(0,i.useRef)(null),F=(0,i.useCallback)(()=>{D.current||(D.current=setTimeout(()=>{D.current=null;let e=n.current,t=k.current;if(!e||!t)return;let r=o.current,i=e.getBoundingClientRect(),l=[],a=0,d=null;for(let t of $.current){let n=e0(t);if(!n&&"assistant"!==t.role)continue;let o=r?.[a];if(a++,n){d=null;let n=o?.getBoundingClientRect();d={userMessage:t,assistantPreviews:[],scrollTop:n?n.top-i.top+e.scrollTop:null},l.push(d);continue}if(!d)continue;let s=function(e){if("assistant"!==e.role)return"";let{answerBlocks:t}=e6(e);return t.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n").trim()}(t);s&&d.assistantPreviews.push({markdown:s,element:o})}let u=l.map((e,t)=>({topRatio:0,targetTurn:e,index:t}));x(t.clientHeight);let h=j.current;h.length===u.length&&h.every((e,t)=>{let n=u[t];return e.index===n.index&&e.targetTurn.userMessage===n.targetTurn.userMessage&&e.targetTurn.assistantPreviews.length===n.targetTurn.assistantPreviews.length&&e.targetTurn.assistantPreviews.every((e,t)=>e.markdown===n.targetTurn.assistantPreviews[t].markdown)})||(j.current=u,p(u)),c(e.scrollHeight-e.clientHeight>20),A(e,j.current);let f=E.current,g=f?u[f.nodeIndex]:null;if(f&&g){let t=void 0===f.assistantIndex?null:g.targetTurn.assistantPreviews[f.assistantIndex],n=g.targetTurn.scrollTop;if("assistant"===f.target){let r=t?.element?.getBoundingClientRect();n=r?r.top-i.top+e.scrollTop:null}else if("heading"===f.target){let r=void 0===f.headingIndex?null:t?.element?.querySelectorAll("h1, h2, h3").item(f.headingIndex),o=r?.getBoundingClientRect();n=o?o.top-i.top+e.scrollTop:null}if(null===n)return;E.current=null,P(g.index),s(n,.3*e.clientHeight)}},150))},[P,o,n,A,s]);(0,i.useEffect)(()=>{let e=n.current;if(e)return e.addEventListener("scroll",B,{passive:!0}),()=>e.removeEventListener("scroll",B)},[n,B]),(0,i.useEffect)(()=>{let e=n.current;if(!e)return;let t=()=>{F(),B()},r=new ResizeObserver(t);return r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild),t(),()=>{r.disconnect(),D.current&&(clearTimeout(D.current),D.current=null)}},[F,n,B]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{F(),B()},50);return()=>clearTimeout(e)},[e.length,F,B]);let H=(0,i.useCallback)((e,t)=>{let r=n.current;if(!r)return;if(P(e.index),null===e.targetTurn.scrollTop){E.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})},[P,l,n]),O=(0,i.useCallback)((e,t)=>{let r=n.current;if(!r)return;let i=e.targetTurn.assistantPreviews[t]?.element;if(!i){E.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;P(e.index),r.scrollTo({top:Math.max(0,s),behavior:"smooth"})},[P,l,n]),U=(0,i.useCallback)(e=>{let{nodes:t,gap:n,fillsHeight:r}=S.current,i=k.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},[]),_=(0,i.useCallback)((e,t,r)=>{let i=n.current;if(!i)return;let o=e.targetTurn.assistantPreviews[t]?.element;if(!o){E.current={nodeIndex:e.index,target:"heading",assistantIndex:t,headingIndex:r},l();return}let a=o.querySelectorAll("h1, h2, h3").item(r);if(!a)return;let d=i.getBoundingClientRect(),c=a.getBoundingClientRect().top-d.top+i.scrollTop;P(e.index),s(c,.3*i.clientHeight)},[P,l,n,s]),q=(0,i.useCallback)((e,t,n)=>{let r=j.current[e];r&&_(r,t,n),v(!1)},[_]),K=(0,i.useCallback)((e,t)=>{let n=j.current[e];n&&O(n,t),v(!1)},[O]),V=(0,i.useCallback)(()=>{v(!0)},[]),J=(0,i.useCallback)(()=>{v(!1),b(null)},[]);(0,i.useEffect)(()=>{if(!m)return;let e=e=>{let t=C.current,n=k.current;t&&e.target instanceof Node&&t.contains(e.target)||n&&e.target instanceof Node&&n.contains(e.target)||J()};return window.addEventListener("pointerdown",e),()=>window.removeEventListener("pointerdown",e)},[m,J]);let Y=(0,i.useCallback)(e=>{if(!d)return;if(m)return void J();V(),w.current=!0;let t=e.currentTarget.getBoundingClientRect();b(Math.max(0,Math.min(1,(e.clientY-t.top)/t.height)));let n=(e,n)=>{let r=U(Math.max(0,Math.min(1,(e-t.top)/t.height)));r&&H(r,n)};n(e.clientY,"smooth");let r=e=>{w.current&&n(e.clientY,"auto")},i=()=>{w.current=!1,window.removeEventListener("mousemove",r),window.removeEventListener("mouseup",i)};window.addEventListener("mousemove",r),window.addEventListener("mouseup",i)},[U,H,V,J,m,d]),Z=null===y?null:U(y),G=Z?.index??null;if((0,i.useEffect)(()=>{if(!m||null===G)return;let e=C.current,t=T.current.get(G);if(!e||!t)return;let n=t.offsetTop-(e.clientHeight-t.offsetHeight)/2;e.scrollTop=Math.max(0,n)},[u,m,G]),!d)return null;let X=Math.max(1,(z.length>0?z[z.length-1].topRatio*g:12)-12);return(0,r.jsxs)("div",{ref:k,onMouseDown:Y,onMouseMove:e=>{I.current={x:e.clientX,y:e.clientY};let t=e.currentTarget.getBoundingClientRect();b((e.clientY-t.top)/t.height)},style:{width:24,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:X,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),z.map(e=>{let t=m&&Z?.index===e.index,n=h===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,N),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)}),m&&u.length>0&&(0,r.jsx)("div",{ref:C,className:rO().preview,"data-minimap-preview-box":"",onMouseDown:e=>e.stopPropagation(),onMouseMove:e=>{I.current={x:e.clientX,y:e.clientY},e.stopPropagation()},children:u.map(e=>{var t;let n=G===e.index;return(0,r.jsxs)("div",{ref:t=>{t?T.current.set(e.index,t):T.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:()=>{H(e,"smooth"),v(!1)},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:()=>{O(e,n),v(!1)},"aria-label":a("chatMinimap.locateAssistant"),title:a("chatMinimap.locateAssistant"),children:"A"}),(0,r.jsx)(rV,{markdown:t.markdown,nodeIndex:e.index,assistantIndex:n,onAnswerClick:K,onHeadingClick:q})]},n))]})]},e.index)})})]})}var rY=n(42790);function rZ({text:e}){let t=(0,i.useMemo)(()=>new rY.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,L.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 f=e.find(e=>e.key===c&&e.lines.length>0);return(0,r.jsxs)(r.Fragment,{children:[f&&(0,r.jsx)("div",{className:"extension-widget-panels",children:(t=e.indexOf(f),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:f.key}),(0,r.jsx)("pre",{className:"extension-widget-content",children:(0,r.jsx)(rZ,{text:f.lines.join("\n")})})]},f.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===f?.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}`,g=(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:g},e.key):(0,r.jsx)("div",{className:`extension-widget-trigger${o?" is-updating":""}`,"aria-label":`${d}: ${e.key}, ${a}`,title:`${e.key} - ${d}`,children:g},e.key)})})]})}function rX({statuses:e,widgets:t=[]}){let[n,o]=(0,i.useState)(!1);if(0===e.length&&0===t.length)return null;let l=[...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(" "),s=eJ(l),a=()=>o(e=>!e);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${n?" extension-status-expanded":""}`,"aria-label":s,title:s,tabIndex:0,onClick:a,onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),a())},children:(0,r.jsx)("span",{className:"extension-status-text",children:(0,r.jsx)(rZ,{text:l})})})]})}function rQ(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function r0(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 r1(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null,scheduleLocalNotification:function(){let e=eo();if(!e?.schedule)return null;let t=1;return async(n,r,i)=>{try{return await e.schedule({notifications:[{id:t,title:n,body:String(r.body??""),extra:{sessionUrl:i}}]}),t=t%0x7fffffff+1,!0}catch{return!1}}}()}){let n={body:e.body,...e.tag?{tag:e.tag,renotify:!0}:{}};if(t.scheduleLocalNotification)try{if(await t.scheduleLocalNotification(e.title,n,e.sessionUrl))return"local-notifications"}catch{}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 r2(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r4(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(!r2(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=r2(e.customInput)?e.customInput:null,n=t&&"string"==typeof t.property?t.property:null,r=r2(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 r8 extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}function r6(e){return e instanceof r8&&"prompt_rejected"===e.code&&!1===e.accepted}async function r5(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 r8(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}var r3=n(14755);let r9="pi-tool-preset";function r7(){try{return window.localStorage}catch{return null}}function ie(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 it(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,ie(t,n.usage)):"assistant"===n.role&&(t.assistantMessages+=1,Array.isArray(n.content)&&(t.toolCalls+=n.content.filter(e=>"toolCall"===e.type).length),ie(t,n.usage)));return t.tokens.total=t.tokens.input+t.tokens.output+t.tokens.cacheRead+t.tokens.cacheWrite,t}function ir(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 ii(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(ir).filter(Boolean)}):JSON.stringify({text:"",images:[]})}class io 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 il{constructor(e){this.options=e,this.current=null,this.retry=null,this.retryGeneration=0}close(){this.stopRetrying(),this.current&&this.discard(this.current,new io("closed"))}maintain(e){if(!this.options.shouldMaintain(e))return;let t=this.retryGeneration;this.ensureConnected(e).catch(n=>{t===this.retryGeneration&&(n instanceof io?"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 io("closed")}if(1===t.source.readyState)return;this.discard(t,new io("closed"))}}open(e){let t,n,r;this.current&&this.discard(this.current,new io("closed"));try{t=this.options.createSource(e)}catch(e){throw new io("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 io("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 io("startup_error",e));return}this.options.onEvent(t)}},t.onerror=()=>{this.fail(a,new io("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 is(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ia(e,t,n){return{distance:e-t,scrollHeight:e,firstEntryId:n}}function id(e,t,n,r=8){return e+t>=n-r}let ic={isStreaming:!1,streamingMessage:null};function iu(e,t,n){let r=e.streamingMessage;if(!r||!Number.isInteger(t)||t<0)return e;let i=[...r.content],o=n(i[t]);return o?(i[t]=o,{isStreaming:!0,streamingMessage:{...r,content:i}}):e}function ip(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"resume":return{...e,isStreaming:!0};case"snapshot":{let n=r4(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 iu(e,n.contentIndex,()=>({type:"text",text:""}));case"text_delta":return iu(e,n.contentIndex,e=>e?.type==="text"?{...e,text:e.text+n.delta}:null);case"text_end":return iu(e,n.contentIndex,e=>({...e?.type==="text"?e:{},type:"text",text:n.content}));case"thinking_start":return iu(e,n.contentIndex,()=>({type:"thinking",thinking:""}));case"thinking_delta":return iu(e,n.contentIndex,e=>e?.type==="thinking"?{...e,thinking:e.thinking+n.delta}:null);case"thinking_end":return iu(e,n.contentIndex,e=>({...e?.type==="thinking"?e:{},type:"thinking",thinking:n.content}));case"toolcall_start":return iu(e,n.contentIndex,e=>e?.type==="toolCall"?{...e,toolCallId:n.id??e.toolCallId,toolName:n.toolName??e.toolName,rawInput:""}:"string"!=typeof n.toolName?null:{type:"toolCall",toolCallId:n.id??"",toolName:n.toolName,input:{},rawInput:""});case"toolcall_delta":return iu(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 iu(e,n.contentIndex,()=>({type:"toolCall",toolCallId:n.toolCall.id,toolName:n.toolCall.name,input:n.toolCall.arguments}));default:return e}case"end":return ic;default:return e}}function ih(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function ig(e){return e&&"auto"!==e?e:null}let ix=[2e3,5e3,1e4];function im(e){return new Promise(t=>setTimeout(t,e))}function iv(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function iy(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:iv(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:iv(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=iv(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function ib(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 iw({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 ik(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function ij({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 iS({session:e,searchTarget:t,onSearchTargetHandled:o,initialScrollPosition:s,onScrollPositionChange:a,sessionRunning:d,isActivePane:c=!0,newSessionCwd:u,newSessionDraftKey:p,onAgentEnd:h,onAttentionNeeded:f,onBackgroundTasksEvent:g,onSessionCreated:x,onSessionForked:m,modelsRefreshKey:v,chatInputRef:y,onBranchDataChange:b,onSystemPromptChange:w,onSystemToolsChange:k,onSystemInfoLoaderChange:j,onSessionStatsChange:S,onSessionStatsPanelOpen:C,onContextUsageChange:I,externalSessionChange:T,onOpenFile:M,onOpenSession:E,onAskInNewChat:R,quoteSelectionEnabled:$=!1,initialPrompt:W,onInitialPromptConsumed:z,soundEnabled:P=!0,onSoundToggle:A,playDoneSound:B=()=>{},unlockAudio:D}){var F;let H,{t:O}=(0,L.s)(),U=n4(),_=e?.relation?.kind!=="subagent",q=(0,i.useRef)(B);q.current=B;let K=(0,i.useRef)(P);K.current=P;let V=(0,i.useRef)(null),J=(0,i.useCallback)(()=>{_&&K.current&&q.current(),h?.()},[_,h]),Y=(0,i.useCallback)(e=>{y?.current?.replaceMessage(e)},[y]),Z=(0,i.useRef)(t?null:s??null),[G,X]=(0,i.useState)(()=>{let e=Z.current;return e&&!e.atBottom?e:null}),[Q,ee]=(0,i.useState)(!1),{loading:et,error:en,messages:er,activeToolResults:ei,entryIds:eo,historyCursor:el,hasEarlierMessages:es,streamState:ea,agentRunning:ed,bashRunning:ec,pendingBash:eu,modelNames:ep,modelList:eh,modelError:ef,modelScopeWarnings:eg,modelThinkingLevels:ex,modelThinkingLevelMaps:em,toolPreset:ev,thinkingLevel:ey,retryInfo:eb,contextUsage:ew,forkingEntryId:ek,isCompacting:ej,compactError:eS,compactResult:eC,displayModel:eI,modelSwitching:eT,sessionStats:eM,slashCommands:eE,slashCommandsLoading:eR,queuedMessages:eL,notices:e$,extensionDialog:eW,extensionCustomUi:ez,extensionStatuses:eN,extensionWidgets:eP,respondToExtensionUi:eA,sendExtensionCustomInput:eB,setNoticePaused:eD,isAutoModelSelection:eF,isAutoThinkingSelection:eH,agentPhase:eO,isNew:eU,showScrollToBottom:eq,sessionIdRef:eK,scrollContainerRef:eV,lastUserMsgRef:eJ,promptAnchorActive:eY,handleSend:eZ,handleAbort:eG,handleFork:eX,handleNavigate:eQ,handleModelChange:e1,handleCompact:e5,handleSteer:e3,handleFollowUp:e9,handlePromptWithStreamingBehavior:te,handleAbortCompaction:tt,handleRecallQueue:tn,handleBuiltinSlashCommand:ta,handleToolPresetChange:th,handleThinkingLevelChange:tf,loadSlashCommands:tg,scrollUserMsgToTop:tx,loadContext:tm,activeLeafId:tv,scrollToBottom:ty,scrollToMessage:tb,scrollToOffset:tw,refreshFromDisk:tk}=function(e){let{session:t,newSessionCwd:r,newSessionDraftKey:o,onAgentEnd:l,onAttentionNeeded:s,onBackgroundTasksEvent:a,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,onBranchDataChange:p,onSystemPromptChange:h,onSystemToolsChange:f,onSystemInfoLoaderChange:g,onSessionStatsPanelOpen:x}=e,m=null===t&&null!==r,[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(!m),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)(null),[I,T]=(0,i.useState)([]),[M,E]=(0,i.useState)(new Map),[R,L]=(0,i.useState)([]),[$,W]=(0,i.useState)(null),[z,N]=(0,i.useState)(!1),[P,A]=(0,i.useReducer)(ip,ic),[B,D]=(0,i.useState)(!1),[F,H]=(0,i.useState)(!1),[O,U]=(0,i.useState)(null),[_,q]=(0,i.useState)({}),[K,V]=(0,i.useState)([]),[J,Y]=(0,i.useState)(null),[Z,G]=(0,i.useState)([]),[X,Q]=(0,i.useState)({}),[ee,et]=(0,i.useState)({}),[en,er]=(0,i.useState)(null),[ei,eo]=(0,i.useState)(null),[el,es]=(0,i.useState)("default"),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[ef,eg]=(0,i.useState)(null),[ex,em]=(0,i.useState)(null),[ev,ey]=(0,i.useState)(null),[eb,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(null),[eI,eT]=(0,i.useState)(null),[eM,eE]=(0,i.useState)(null),[eR,eL]=(0,i.useState)(!1),[e$,eW]=(0,i.useState)(!1),[ez,eN]=(0,i.useState)(!0),[eP,eA]=(0,i.useState)(null),[eB,eD]=(0,i.useState)(null),[eF,eH]=(0,i.useState)(null),[eO,eU]=(0,i.useState)(!1),[e_,eq]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)([]),[eJ,eY]=(0,i.useState)(!1),[eZ,eG]=(0,i.useReducer)(iy,{visible:[],pending:[]}),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(null),[e8,e6]=(0,i.useState)([]),[e5,e3]=(0,i.useState)([]),[e9,e7]=(0,i.useState)({steering:[],followUp:[]}),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(0),tr=(0,i.useRef)(!1),ti=(0,i.useRef)(t?.id??null),to=(0,i.useRef)(t?.id??null),tl=(0,i.useRef)(!1),ts=(0,i.useRef)(!1),ta=(0,i.useRef)(!1),td=(0,i.useRef)(-1),tc=(0,i.useRef)(!1),tu=(0,i.useRef)(0),tp=(0,i.useRef)(null),th=(0,i.useRef)(!!e.deferInitialScroll),tf=(0,i.useRef)(null),tg=(0,i.useRef)(!1),tx=(0,i.useRef)(!0),tm=(0,i.useRef)(0),tv=(0,i.useRef)(null),ty=(0,i.useRef)(void 0),tb=(0,i.useRef)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(null),tS=(0,i.useRef)(null),tC=(0,i.useRef)({}),tI=(0,i.useRef)(null),tT=(0,i.useRef)(0),tM=(0,i.useRef)(null),tE=(0,i.useRef)(!1),tR=(0,i.useRef)(new Map),tL=(0,i.useRef)(!0);to.current=t?.id??null,te.current||(te.current=new il({createSource:e=>new EventSource(`/api/agent/${encodeURIComponent(e)}/events`),onEvent:e=>tp.current?.(e),shouldMaintain:e=>tL.current&&ti.current===e&&(tl.current||tr.current||to.current===e),readinessTimeoutMs:6e4,reconnectDelayMs:1e3,onUnexpectedError:e=>{console.error("Failed to maintain the agent event stream:",e)}}));let t$=e.setToolPreset??es,tW=t?.id;(0,i.useLayoutEffect)(()=>{(tW||m&&!ti.current)&&t$(function(e=r7()){if(!e)return"default";try{let t=e.getItem(r9);return(0,r3.sn)(t)?t:"default"}catch{return"default"}}())},[tW,m,t$]);let tz=(0,i.useCallback)((e="smooth")=>{let t=tb.current;t&&(t.scrollTo({top:t.scrollHeight,behavior:e}),tm.current=t.scrollTop)},[]),tN=eS??eI??v?.context.model??eM??null,tP=m?en??ei:tN??(v?.context.messages.length===0?ei:null),tA=ig(v?.context.thinkingLevel&&"off"!==v.context.thinkingLevel?v.context.thinkingLevel:null),tB=m?ea??ec:ep??ef??tA??(v?.context.messages.length===0?ec:null),tD=t?.id??o??void 0,tF=(0,i.useCallback)(e=>{eT(e?.model?{provider:e.model.provider,modelId:e.model.id}:null),e?.thinkingLevel!==void 0&&eg(ig(e.thinkingLevel))},[]),tH=(0,i.useCallback)(e=>{if(!e)return;let t=e,n=new Set;for(;!n.has(t);){n.add(t);let e=tR.current.get(t);if(!e)break;t=e}return t},[]),tO=(0,i.useCallback)((t,n,r)=>{let i=n?.map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=tH(r);if(!tL.current&&!tk.current&&r===o)return;let s=e.chatInputRef?.current;if(s)s.restoreSubmission(t,i,l);else{let e,n;l&&(n=nO(t,i,(e=nB(l)??{value:"",images:[]}).value,e.images),nD(l,n))}},[o,e.chatInputRef,tH]),tU=(0,i.useMemo)(()=>{if(eX)return{...eX,totalActiveMs:v?.totalActiveMs,...ev?{contextUsage:ev}:{}};let e=v?.stats,n=function(e,t,n){let r=it(n);if(!e)return r;let i=it(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,v?.context.messages??[],I);return 0!==n.tokens.total||0!==I.length||e?{sessionFile:v?.filePath||void 0,sessionId:ti.current??t?.id??"",sessionName:t?.name,...n,totalActiveMs:v?.totalActiveMs,...ev?{contextUsage:ev}:{}}:null},[I,eX,ev,v?.context.messages,v?.filePath,v?.totalActiveMs,v?.stats,t?.id,t?.name]),t_=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&w(!0);let o=new URLSearchParams({deferThinking:"1",deferMedia:"1"});r?.force&&o.set("force","1");let l=await fetch(`/api/sessions/${encodeURIComponent(e)}?${o}`);if(404===l.status)return t&&(y(null),C(null),T([]),L([]),W(null),N(!1),j(null)),null;if(!l.ok)throw Error(`HTTP ${l.status}`);let s=await l.json();if(ti.current!==e)return null;let a=s.context.messages;if(y(s),C(s.leafId),T(a),L(s.context.entryIds??[]),W(s.context.oldestEntryId),N(s.context.hasMore),t$(void 0!==s.toolNames?(0,r3.YO)(s.toolNames):"default"),eC(e=>tE.current?e:null),eh(null),j(null),s.wrapperRebuilt&&(te.current?.close(),te.current?.maintain(e)),!n&&s.context.thinkingLevel&&"off"!==s.context.thinkingLevel&&eg(ig(s.context.thinkingLevel)),i=!0,t&&w(!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(ti.current!==e)return null;let r=n.state;return tF(r),r?(void 0!==r.contextUsage&&ey(r.contextUsage??null),void 0!==r.systemPrompt&&ew(r.systemPrompt??null),void 0!==r.extensionStatuses&&e6(r.extensionStatuses??[]),void 0!==r.extensionWidgets&&e3(r.extensionWidgets??[]),void 0!==r.queuedMessages&&e7(ih(r.queuedMessages)),void 0!==r.autoCompactionEnabled&&eN(r.autoCompactionEnabled??!0)):n.running||e7({steering:[],followUp:[]}),n}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return j(String(e)),null}finally{t&&!i&&w(!1)}},[t$,tF]),tq=(0,i.useCallback)(async e=>{!tL.current||ti.current!==e||tl.current||tc.current||e$||await t_(e,!1,!1,{force:!0})},[e$,t_]),tK=(0,i.useCallback)(async(e,t,n,r)=>{try{let i=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&i.set("leafId",t),n&&i.set("before",n),r?.tail&&i.set("tail",String(r.tail));let o=`/api/sessions/${encodeURIComponent(e)}/context?${i}`,l=await fetch(o,{signal:r?.signal});if(!l.ok)throw Error(`HTTP ${l.status}`);let s=await l.json();if(ti.current!==e||r?.signal?.aborted||!tL.current)return;return W(s.context.oldestEntryId),N(s.context.hasMore),y(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]),L(e=>[...s.context.entryIds,...e])):(T(s.context.messages),L(s.context.entryIds??[])),s.context}catch(e){r?.signal?.aborted||console.error("Failed to load context:",e)}},[]),tV=(0,i.useCallback)(async e=>{try{let t=await r5(e,{type:"get_tools"});if(!t||!tL.current||ti.current!==e)return null;let{getPresetFromTools:r}=await Promise.resolve().then(n.bind(n,14755));return t$(r(t)),f?.(t),t}catch(e){return console.error("Failed to load tools:",e),null}},[f,t$]),tJ=(0,i.useCallback)((t=0,n="(no messages)")=>{let i=ti.current;if(m&&r&&i&&!tk.current&&(tk.current=!0,o)){if(o!==i){tR.current.set(o,i);let t=e.chatInputRef?.current;t?t.rekeyDraft(o,i):nU(o,i)}d?.({id:i,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:t,firstMessage:n,transient:!0},o)}},[m,r,o,d,e.chatInputRef]),tY=(0,i.useCallback)(async()=>{if(ti.current||!m||!r)return ti.current;if(tw.current)return tw.current;let e=(async()=>{let e=tj.current,t=tS.current;e&&eE(e);let n=(0,r3.xG)(el),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 ti.current=l,o.model&&tj.current===e&&(eE(o.model),e||eo(o.model)),o.thinkingLevel&&tS.current===t&&(eg(ig(o.thinkingLevel)),t||eu(ig(o.thinkingLevel))),l})();tw.current=e;try{return await e}finally{tw.current=null}},[m,r,el]),tZ=(0,i.useCallback)(async()=>{let e=ti.current??await tY();if(!e)return;let[t]=await Promise.all([r5(e,{type:"get_state"}),tV(e)]);tL.current&&ti.current===e&&(tF(t),ew(t.systemPrompt??""))},[tY,tV,tF]),tG=(0,i.useCallback)(async()=>{let e=ti.current??await tY();if(!e)return eV([]),[];eY(!0);try{let t=await r5(e,{type:"get_commands"}),n=t?.commands??[];return eV(n),n}catch(e){return console.error("Failed to load slash commands:",e),eV([]),[]}finally{eY(!1)}},[tY]),tX=(0,i.useCallback)(()=>{tn.current+=1,tr.current=!1,tt.current&&(clearTimeout(tt.current),tt.current=null)},[]),tQ=(0,i.useCallback)(()=>{te.current?.close()},[]),t0=(0,i.useCallback)(e=>te.current.ensureConnected(e),[]),t1=(0,i.useCallback)(e=>{te.current.maintain(e)},[]);(0,i.useEffect)(()=>{let e=t?.id;if(e)return t1(e),()=>{ti.current===e&&te.current?.close()}},[t1,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||ti.current!==e||to.current!==e||(tQ(),t1(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)}},[tQ,t1,t?.id]);let t2=(0,i.useCallback)(async(e,t)=>{let n=ti.current;if(e1(t=>t?.id===e.id?null:t),n)try{await r5(n,{type:"extension_ui_response",id:e.id,...t})}catch(e){console.error("Failed to send extension UI response:",e)}},[]),t4=(0,i.useCallback)(async(e,t)=>{let n=ti.current;if(n)try{await r5(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),t8=(0,i.useCallback)(e=>{let t=e.message.trim();t&&eG({type:"add",notice:{id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info"}})},[]),t6=(0,i.useCallback)(e=>{e&&"object"==typeof e&&!0===e.reloadedFromDisk&&t8({type:"info",message:"This session was updated by another Pi process. Reloaded from disk."})},[t8]),t5=(0,i.useCallback)(t=>{switch(r0(t)&&s?.(t),t.method){case"select":case"confirm":case"input":case"editor":e1(t);break;case"notify":t8({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":e6(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":e3(e=>(function(e,t,n,r="aboveEditor"){if(void 0===n)return e.filter(e=>e.key!==t);let i={key:t,lines:n,placement:r},o=e.findIndex(e=>e.key===t);return -1===o?[...e,i]:e.map((e,t)=>t===o?i:e)})(e,t.widgetKey,t.widgetLines,t.widgetPlacement));break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":e4(e=>t.closed?e?.id===t.id?null:e:t)}},[t8,s,e.chatInputRef]),t3=(0,i.useCallback)(()=>{let e=tl.current;return tl.current=!1,D(!1),eH(null),em(null),E(new Map),A({type:"end"}),e},[]),t9=(0,i.useCallback)(e=>td.current!==e&&(td.current=e,l?.(),!0),[l]),t7=(0,i.useCallback)(e=>{if(to.current===e)return void tX();tX(),tr.current=!0;let t=tn.current,n=async()=>{if(t===tn.current&&ti.current===e&&tr.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!==tn.current||ti.current!==e||!tr.current)return;let o=i.state;if(tF(o),i.running&&o&&(o.isStreaming||o.isPromptRunning)){tr.current=!1,tt.current=null,ts.current=!!o?.isStreaming,ta.current=!!o?.isPromptRunning,tl.current=!0,D(!0),eH(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(i.running&&o?.isCompacting){eW(!0),tt.current=setTimeout(()=>void n(),600);return}tr.current=!1,tt.current=null,tQ()}catch{if(t!==tn.current||ti.current!==e||!tr.current)return;tt.current=setTimeout(()=>void n(),600)}};tt.current=setTimeout(()=>void n(),3e4)},[tX,tQ,tF]),ne=(0,i.useCallback)(async(e=ti.current,t=tT.current)=>{if(tT.current===t)try{e&&await t_(e)}finally{if(tT.current!==t)return;let n=ta.current,r=ts.current;ta.current=!1,ts.current=!1,tM.current=null;let i=t3();n?t9(t):r&&i&&l?.(),e&&t7(e)}},[t_,t9,l,t7,t3]),nt=(0,i.useCallback)(async(e,t)=>{await im(800);let n=Date.now();for(;tl.current&&Date.now()-n<2e4;){if(void 0!==t&&tT.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(tF(i),!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await ne(e,t)}}catch{}await im(600)}},[ne,tF]),nn=(0,i.useCallback)(async e=>{let t=tu.current+1;for(tu.current=t;tc.current&&tu.current===t&&ti.current===e;){await im(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(tF(r.state),r.state?.isBashRunning)continue;if(await t_(e),tu.current!==t||ti.current!==e)return;tc.current=!1,H(!1),U(null);return}catch{}}},[t_,tF]),nr=(0,i.useCallback)(async e=>{if(!tl.current||ti.current!==e)return;let t=tT.current;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)return;let r=await n.json();if(ti.current!==e||tT.current!==t)return;let i=r.state;if(tF(i),eW(i?.isCompacting??!1),eN(i?.autoCompactionEnabled??!0),e7(ih(i?.queuedMessages)),r.running&&i&&(i.isStreaming||i.isPromptRunning||i.isCompacting)){ts.current=!!i.isStreaming,ta.current=!!i.isPromptRunning;return}if(!tl.current)return;i&&(void 0!==i.contextUsage&&ey(i.contextUsage??null),void 0!==i.systemPrompt&&ew(i.systemPrompt??null),void 0!==i.extensionStatuses&&e6(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&e3(i.extensionWidgets??[])),await ne(e,t)}catch{}},[ne,tF]);(0,i.useEffect)(()=>{if(!B)return;let e=()=>{let e=ti.current;e&&nr(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)}},[B,nr]),(0,i.useEffect)(()=>{tl.current=B},[B]),tp.current=(0,i.useCallback)(e=>{switch(e.type){case"connected":A({type:"end"}),!0===e.isStreaming&&(tX(),ts.current=!0,tl.current=!0,D(!0),eH({kind:"waiting_model"}));break;case"agent_start":tX(),ts.current=!0,tl.current=!0,D(!0),eH({kind:"waiting_model"}),A({type:"start"});break;case"background_task_terminal":case"background_tasks_update":a?.(e);break;case"agent_end":if(!tl.current)break;eH(null),em(null),A({type:"end"}),ti.current&&(t_(ti.current),fetch(`/api/agent/${encodeURIComponent(ti.current)}`).then(e=>e.json()).then(e=>{tF(e.state),e.state?.contextUsage!==void 0&&ey(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&ew(e.state.systemPrompt??null),e.state?.extensionStatuses!==void 0&&e6(e.state.extensionStatuses??[]),e.state?.extensionWidgets!==void 0&&e3(e.state.extensionWidgets??[]),e7(ih(e.state?.queuedMessages))}).catch(()=>{}));break;case"agent_settled":{let e=ts.current;if(ts.current=!1,!e||ta.current)break;let t=ti.current,n=t3();eW(!1),t&&(t_(t),t7(t)),n&&l?.();break}case"prompt_done":{let e=tT.current,t=ta.current;ta.current=!1,tM.current=null;let n=t9(e);if(!t&&!n)break;let r=ti.current;r&&t_(r),!ts.current&&(t3(),r&&t7(r))}break;case"prompt_error":t8({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t8({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":if(!tl.current)break;if("message_start"===e.type){let t=e.message;if(t?.role==="user")break;t?.role==="assistant"?(A({type:"snapshot",message:t}),t.content.length>0&&eH(null)):t&&eH(null)}else{let t=e.assistantMessageEvent;t&&(A({type:"delta",event:t}),"toolcall_start"!==t.type&&"toolcall_delta"!==t.type&&eH(null))}!tg.current&&tx.current&&null===tv.current&&(tv.current=requestAnimationFrame(()=>{tv.current=null,tx.current&&tz("auto")}));break;case"message_end":{if(!tl.current)break;let t=e.message;if(t&&"user"===t.role){let e=r4(t),n=ii(e),r=tM.current;tM.current=null,T(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ii(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]})}else t&&T(e=>[...e,r4(t)]);A({type:"end"}),eH({kind:"waiting_model"});break}case"tool_execution_start":{let t=e.toolCallId,n=e.toolName;eH(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(!is(e))return null;let t=e.content;if(!Array.isArray(t))return null;let n=t.filter(e=>is(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);eH(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}),eH(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":e7({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":em({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":em(null);break;case"auto_compaction_start":case"compaction_start":eW(!0),eA(null),eD(null);break;case"auto_compaction_end":case"compaction_end":eW(!1),e.errorMessage?(eA(e.errorMessage),eD(null)):!e.aborted&&(eD(ib(e.result,e.reason??"auto")),ti.current&&t_(ti.current));break;case"extension_ui_request":t5(e);break;case"extension_ui_closed":e1(t=>t?.id===e.id?null:t)}},[t8,tX,t5,t_,t9,l,a,t7,tz,t3,tF]);let ni=(0,i.useCallback)(async(e,n)=>{let i=e.trim();if(!i&&!n?.length)return;if(tl.current||tc.current)return void tO(e,n,tD);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 ty.current?.(r,t):void tO(e,n,tD)}let l=tT.current+1;tX(),ta.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]),tM.current=ii(a),tT.current=l,tl.current=!0,D(!0),eH(o?{kind:"running_command"}:{kind:"waiting_model"}),A({type:"start"}),tg.current=!0,eU(!0);let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),c=null,u=!1;try{if(m&&r){let t=ti.current??await tw.current,n=t??await tY();if(!n)throw Error("Unable to create a session for the prompt");c=n,en&&(eE(en),t&&await r5(n,{type:"set_model",provider:en.provider,modelId:en.modelId})),await t0(n),u=!0,t6(await r5(n,{type:"prompt",message:e,...d?.length?{images:d}:{}})),tJ(1,e)}else if(t)c=t.id,await t0(t.id),u=!0,t6(await r5(t.id,{type:"prompt",message:e,...d?.length?{images:d}:{}}));else throw Error("No active session for the prompt");o&&c&&nt(c,l)}catch(t){if(console.error("Failed to send message:",t),!(!u||r6(t))&&c)return void nt(c,l);if(ta.current=!1,T(e=>{let t=e.lastIndexOf(a);return -1===t?e:[...e.slice(0,t),...e.slice(t+1)]}),t8({type:"error",message:t instanceof Error?t.message:String(t)}),tO(e,n,tD),tM.current=null,c)return void nr(c);tl.current=!1,tQ(),D(!1),eH(null),A({type:"end"})}},[m,r,en,t,tY,t0,tJ,nt,t8,t6,tX,tQ,tD,nr,tO]);ty.current=(0,i.useCallback)(async(e,n)=>{if(tl.current||tc.current)return;let r=`${n?"!!":"!"}${e}`;tc.current=!0,U({command:e,excludeFromContext:n}),H(!0);try{let i=ti.current??t?.id??await tY();if(!i)throw Error("Unable to create a session for the shell command");await r5(i,{type:"bash",command:e,excludeFromContext:n}),await t_(i),tJ(1,r)}catch(e){console.error("Failed to execute shell command:",e),t8({type:"error",message:e instanceof Error?e.message:String(e)}),tO(r,void 0,tD)}finally{tc.current=!1,U(null),H(!1)}},[t8,tD,tY,t_,tJ,tO,t]);let no=(0,i.useCallback)(async()=>{let e=ti.current;if(e){if(tc.current){try{await r5(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await r5(e,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}}},[]),nl=(0,i.useCallback)(async e=>{if(tc.current)return;let t=ti.current;if(t){ej(e);try{let{cancelled:n,newSessionId:r}=await r5(t,{type:"fork",entryId:e})??{};!n&&r&&c?.(r)}catch(e){console.error("Fork failed:",e)}finally{ej(null)}}},[c]),ns=(0,i.useCallback)(async e=>{if(tc.current)return!1;let t=ti.current;if(!t)return!1;try{let n=await r5(t,{type:"navigate_tree",targetId:e});if(n?.cancelled||ti.current!==t)return!1;return await t_(t),ti.current===t}catch(e){return console.error("Failed to navigate:",e),!1}},[t_]),na=(0,i.useCallback)(async e=>{if(tc.current)return;C(e);let t=ti.current;t&&(await tK(t,e),e&&r5(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[tK]),nd=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t};tj.current=n,er(n),eE(n),null===tS.current&&eu(ig(tC.current[`${e}/${t}`])??tI.current);let r=ti.current??await tw.current;if(!r)return;try{await r5(r,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=ti.current;if(n&&!tE.current){tE.current=!0,eC({provider:e,modelId:t}),eL(!0);try{let r=await r5(n,{type:"set_model",provider:e,modelId:t});eT({provider:r.provider,modelId:r.id}),tE.current=!1,await t_(n)}catch(e){console.error("Failed to set model:",e),tE.current=!1,eC(eS),t8({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await t_(n,!1,!0)}finally{tE.current=!1,eL(!1)}}},[t8,eS,m,t_,er]),nc=(0,i.useCallback)(async()=>{let e=ti.current;if(e&&!e$){eW(!0),eA(null),eD(null);try{let t=await r5(e,{type:"compact"});eD(ib(t,"manual")),await t_(e,!0)}catch(e){eA(e instanceof Error?e.message:String(e)),eD(null)}finally{eW(!1)}}},[e$,t_]),nu=(0,i.useCallback)(async e=>{let n,i=r??t?.cwd??"";if(!i)return;let 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||Y(t instanceof Error?t.message:String(t)),t}q(n.models),Y(n.modelError??null),G(n.modelScopeWarnings??[]),Q(n.thinkingLevels??{}),et(n.thinkingLevelMaps??{});let l=n.modelList??[];V(l);let s=n.defaultModel?l.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0;if(eo(s?{provider:s.provider,modelId:s.id}:null),tC.current=n.thinkingLevelPins??{},tI.current=ig(n.defaultThinkingLevel),m&&!ti.current){let e=s&&n.thinkingLevelPins?.[`${s.provider}/${s.id}`];null===tS.current&&eu(ig(e)??tI.current)}},[m,r,t?.cwd]),np=(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=ti.current??await tY(),l=e=>(e.handled&&(e.error?t8({type:"error",message:e.error}):"openSessionStats"!==e.action&&t8({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!o||e$)return l({handled:!0,error:"No active session to compact"});eW(!0),eA(null),eD(null);let e=await r5(o,{type:"compact",...i?{customInstructions:i}:{}});return eD(ib(e,"manual")),await t_(o,!0)&&tJ(),l({handled:!0,message:"Compacted context"})}case"auto-compact":{if(!o)return l({handled:!0,error:"No active session"});let e=await r5(o,{type:"get_state"}),t=!(e?.autoCompactionEnabled??!0);return await r5(o,{type:"set_auto_compaction",enabled:t}),eN(t),l({handled:!0,message:t?"Auto-compaction enabled":"Auto-compaction disabled"})}case"reload":if(!o)return l({handled:!0,error:"No active session to reload"});return await r5(o,{type:"reload"}),await Promise.all([t_(o,!1,!0),tV(o),tG(),nu()]),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 r5(o,{type:"set_session_name",name:i}),await t_(o)&&tJ(),l({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!o)return l({handled:!0,error:"No active session"});let e=await r5(o,{type:"get_session_stats"});return e&&eQ(e),x?.(),l({handled:!0,action:"openSessionStats"})}case"copy":{if(!o)return l({handled:!0,error:"No active session"});let e=await r5(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(tl.current||tc.current)return l({handled:!0,error:"Cannot clone while the session is running"});let e=await r5(o,{type:"clone",leafId:S});if(e?.cancelled||!e?.newSessionId)return l({handled:!0,error:"Cannot clone an empty or unsaved session"});let t=l({handled:!0,message:"Cloned current session branch"});return c?.(e.newSessionId),t}default:return{handled:!1}}}catch(e){return l({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&eW(!1)}},[S,t8,tY,e$,nu,t_,tG,tV,tJ,c,x]),nh=(0,i.useCallback)(async(e,t,n)=>{let r=ti.current;if(!r){tO(e,n,tD),t8({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{t6(await r5(r,{type:"prompt",message:e,streamingBehavior:t,...i?.length?{images:i}:{}}))}catch(t){console.error("Failed to submit streaming prompt:",t),r6(t)&&tO(e,n,tD),t8({type:"error",message:t instanceof Error?t.message:String(t)})}},[t8,t6,tD,tO]),nf=(0,i.useCallback)(async(e,t)=>{await nh(e,"steer",t)},[nh]),ng=(0,i.useCallback)(async(e,t,n)=>{await nh(e,t,n)},[nh]),nx=(0,i.useCallback)(async(e,t)=>{await nh(e,"followUp",t)},[nh]),nm=(0,i.useCallback)(async()=>{let e=ti.current;if(e)try{await r5(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),nv=(0,i.useCallback)(async()=>{let t=ti.current;if(t)try{let n=await r5(t,{type:"clear_queue"});e7({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),t8({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,t8]),ny=(0,i.useCallback)(async e=>{if("auto"===e){tS.current=null,ed(null),eh(null);return}m?(tS.current=e,ed(e)):eh(e);let t=ti.current??await tw.current;if(t)try{await r5(t,{type:"set_thinking_level",level:e}),tL.current&&ti.current===t&&(eg(e),eh(null))}catch(e){console.error("Failed to set thinking level:",e),eh(null)}},[m]),nb=(0,i.useCallback)(async e=>{let t=(0,r3.xG)(e);!function(e,t=r7()){if(t)try{t.setItem(r9,e)}catch{}}(e),t$(e);let n=ti.current??await tw.current;if(n)try{let e=await r5(n,{type:"set_tools",toolNames:t}),r=e?.sessionId??n;(r!==n||e?.recreated)&&(tX(),tQ(),ti.current=r,e?.recreated&&to.current===r&&t1(r)),eV([]),e6([]),e3([]);let[i]=await Promise.all([r5(r,{type:"get_state"}),tV(r)]);tL.current&&ti.current===r&&(ew(i.systemPrompt??""),tF(i))}catch(e){console.error("Failed to set tools:",e)}},[tX,tQ,tV,t1,t$,tF]),nw=(0,i.useCallback)((e,t=16)=>{let n=tb.current;n&&(null!==tv.current&&(cancelAnimationFrame(tv.current),tv.current=null),th.current=!0,tg.current=!1,tx.current=!1,eU(!1),n.scrollTo({top:e.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop-t,behavior:"instant"}),tm.current=n.scrollTop)},[]),nk=(0,i.useCallback)((e,t=0)=>{let n=tb.current;n&&(null!==tv.current&&(cancelAnimationFrame(tv.current),tv.current=null),th.current=!0,tg.current=!1,tx.current=!1,eU(!1),n.scrollTo({top:Math.max(0,e-t),behavior:"instant"}),tm.current=n.scrollTop)},[]),nj=(0,i.useCallback)(()=>{let e=tb.current,t=tf.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!==tv.current&&(cancelAnimationFrame(tv.current),tv.current=null),tx.current=!0,tm.current=n,e.scrollTo({top:n,behavior:"auto"})},[]),nS=(0,i.useCallback)(()=>{let e=tb.current;if(e){let{scrollTop:t,clientHeight:n,scrollHeight:r}=e,i=tl.current,o=tx.current,l=function(e,t,n,r,i,o=96){return!!id(n,r,i)||!(n<t)&&(!!(!e&&n>t&&id(n,r,i,o))||e)}(o,tm.current,t,n,r,i?96:8);tx.current=l,tm.current=t;let s=function(e,t,n,r=8){return!(n<=t)&&!id(e,t,n,r)}(t,n,r);eq(e=>e===s?e:s),!o&&l&&i?tz("auto"):l||null===tv.current||(cancelAnimationFrame(tv.current),tv.current=null)}},[tz]);(0,i.useEffect)(()=>(tL.current=!0,t&&(ti.current=t.id,t_(t.id,!0,!0,{force:!0}).then(e=>{e?.running&&(tV(t.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(ts.current=!!e.state.isStreaming,ta.current=!!e.state.isPromptRunning,tl.current=!0,D(!0),eH(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),A({type:"resume"}),!e.state.isStreaming&&e.state.isPromptRunning&&nt(t.id)),e.state?.isBashRunning&&(tc.current=!0,H(!0),nn(t.id))),e?.state&&(void 0!==e.state.isCompacting&&eW(e.state.isCompacting),void 0!==e.state.contextUsage&&ey(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&ew(e.state.systemPrompt??null),void 0!==e.state.extensionStatuses&&e6(e.state.extensionStatuses??[]),void 0!==e.state.extensionWidgets&&e3(e.state.extensionWidgets??[]),void 0!==e.state.queuedMessages&&e7(ih(e.state.queuedMessages)))})),()=>{tL.current=!1;let e=m?o:null;e&&queueMicrotask(()=>{tL.current||tk.current||nF(e)}),null!==tv.current&&(cancelAnimationFrame(tv.current),tv.current=null),tu.current+=1,tX(),tQ()}),[]),(0,i.useEffect)(()=>{h?.(eb)},[eb,h]),(0,i.useEffect)(()=>(g?.(tZ),()=>g?.(null)),[tZ,g]),(0,i.useEffect)(()=>{p&&p(v?.tree??[],S,na)},[v?.tree,S,na,p]),(0,i.useEffect)(()=>{let e=tb.current;if(e)return tm.current=e.scrollTop,e.addEventListener("scroll",nS,{passive:!0}),()=>{e.removeEventListener("scroll",nS)}},[I.length,b,nS]),(0,i.useEffect)(()=>{B||eU(!1)},[B]),(0,i.useLayoutEffect)(()=>{I.length>0&&(tg.current?(tg.current=!1,th.current=!0,nj()):th.current?!tl.current&&tx.current&&tz("auto"):(th.current=!0,tz("instant")))},[I.length,B,tz,nj]),(0,i.useEffect)(()=>{let e=new AbortController;return(async()=>{for(let t=0;;t++)try{await nu(e.signal);return}catch(n){if(e.signal.aborted||n instanceof DOMException&&"AbortError"===n.name||t>=ix.length||(await im(ix[t]),e.signal.aborted))return}})(),()=>e.abort()},[nu,u]),(0,i.useEffect)(()=>{if(!eB)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[eB]);let[nC,nI]=(0,i.useState)(null),nT=(0,i.useRef)(5e3),nM=(0,i.useRef)(null),nE=(0,i.useRef)(null);return(0,i.useEffect)(()=>{if(0===eZ.visible.length){nE.current=null;return}let e=eZ.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eG({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}let t=eZ.visible[0];if(!t||(nE.current!==t.id&&(nE.current=t.id,nT.current=5e3),eZ.visible.some(e=>e.id===nC)))return;nM.current=Date.now();let n=setTimeout(()=>{eG({type:"mark_oldest_exiting"})},nT.current);return()=>{clearTimeout(n),null!==nM.current&&(nT.current=Math.max(0,nT.current-(Date.now()-nM.current)),nM.current=null)}},[eZ.visible,nC]),(0,i.useEffect)(()=>{eQ(null)},[I.length,ev?.tokens,ev?.percent,ev?.contextWindow]),{data:v,loading:b,error:k,activeLeafId:S,messages:I,activeToolResults:M,entryIds:R,historyCursor:$,hasEarlierMessages:z,streamState:P,agentRunning:B,modelNames:_,modelList:K,modelError:J,modelScopeWarnings:Z,modelThinkingLevels:X,modelThinkingLevelMaps:ee,newSessionModel:en,toolPreset:el,thinkingLevel:tB??"auto",retryInfo:ex,contextUsage:ev,systemPrompt:eb,forkingEntryId:ek,isCompacting:e$,compactError:eP,compactResult:eB,currentModel:tN,displayModel:tP,modelSwitching:eR,sessionStats:tU,autoCompactionEnabled:ez,slashCommands:eK,slashCommandsLoading:eJ,queuedMessages:e9,notices:eZ.visible,extensionDialog:e0,extensionCustomUi:e2,extensionStatuses:e8,extensionWidgets:e5,respondToExtensionUi:t2,sendExtensionCustomInput:t4,isAutoModelSelection:m&&null===en,isAutoThinkingSelection:m&&null===ea,agentPhase:eF,isNew:m,promptAnchorActive:eO,showScrollToBottom:e_,sessionIdRef:ti,scrollContainerRef:tb,lastUserMsgRef:tf,pendingScrollToUserRef:tg,initialScrollDoneRef:th,handleSend:ni,handleAbort:no,handleFork:nl,handleNavigate:ns,handleModelChange:nd,handleCompact:nc,handleSteer:nf,handleFollowUp:nx,handlePromptWithStreamingBehavior:ng,handleAbortCompaction:nm,handleRecallQueue:nv,handleBuiltinSlashCommand:np,setNoticePaused:nI,handleToolPresetChange:nb,handleThinkingLevelChange:ny,loadTools:tV,loadSlashCommands:tG,setActiveLeafId:C,setData:y,setMessages:T,loadContext:tK,refreshFromDisk:tq,scrollToBottom:tz,scrollUserMsgToTop:nj,scrollToMessage:nw,scrollToOffset:nk,dispatch:A,setAgentRunning:D,setForkingEntryId:ej,bashRunning:F,pendingBash:O,handleAgentEventRef:tp}}({session:e,sessionRunning:d,newSessionCwd:u,newSessionDraftKey:p,onAgentEnd:J,onAttentionNeeded:f,onBackgroundTasksEvent:g,onSessionCreated:x,onSessionForked:m,modelsRefreshKey:v,chatInputRef:y,onBranchDataChange:b,onSystemPromptChange:w,onSystemToolsChange:k,onSystemInfoLoaderChange:j,onSessionStatsPanelOpen:C,deferInitialScroll:!!G}),tj=ed||ec,tS=(0,i.useRef)(null);(0,i.useEffect)(()=>{T&&tS.current!==T.key&&(tS.current=T.key,T.sessionId===e?.id&&tk(T.sessionId))},[T,e?.id,tk]);let[tC,tI]=(0,i.useState)(null),[tT,tM]=(0,i.useState)(!1),[tE,tR]=(0,i.useState)(!1),[tL,t$]=(0,i.useState)(null),tW=(0,i.useRef)(null),tz=(0,i.useRef)(null),tN=(0,i.useCallback)(()=>{tI(null),tM(!1),t$(null)},[]);(0,i.useEffect)(()=>{$||tN()},[$,tN]);let tP=(0,i.useCallback)(()=>{if(!$||tT)return;let e=window.getSelection(),t=e?.rangeCount?e.getRangeAt(0):null,n=tU.current;if(!e||e.isCollapsed||!t||!n||!n.contains(t.commonAncestorContainer))return void tI(null);let r=e.toString().trim();if(!r)return void tI(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);tI({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})},[$,tT]);(0,i.useEffect)(()=>{tT&&tC&&tz.current?.insertIfEmpty(tp(tC.text,O("chat.quoteIntro"),O("chat.quoteQuestion")))},[tT,tC,O]),(0,i.useLayoutEffect)(()=>{let e=tW.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,tT,tL]),(0,i.useEffect)(()=>{if(!tC)return;let e=e=>{tT||tW.current?.contains(e.target)||tN()},t=e=>{"Escape"===e.key&&!e.isComposing&&(e.preventDefault(),e.stopPropagation(),tE||tN())};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[tC,tT,tE,tN]);let tA=(0,i.useCallback)(()=>{tC&&(y?.current?.insertText(tp(tC.text,O("chat.quoteIntro"),O("chat.quoteQuestion"))),window.getSelection()?.removeAllRanges(),tN())},[y,tC,tN,O]),tB=(0,i.useCallback)(async t=>{let n=eK.current??e?.id;if(!tE&&t.trim()&&tC?.sourceEntryId&&n&&R){tR(!0),t$(null),D?.();try{await R(t,n,tC.sourceEntryId),tN()}catch(e){tz.current?.restoreSubmission(t),t$(e instanceof Error?e.message:String(e))}finally{tR(!1)}}},[R,tC,tE,e?.id,eK,tN,D]),tD=(0,i.useRef)(!1);(0,i.useEffect)(()=>{et||en||!W||tD.current||(tD.current=!0,z?.(),eZ(W))},[W,et,en,eZ,z]),(0,i.useEffect)(()=>{_&&eW&&V.current!==eW.id&&(V.current=eW.id,q.current())},[_,eW]),(0,i.useEffect)(()=>{l=tj?eG:null},[tj,eG]);let[tF,tH]=(0,i.useState)(50),tO=(0,i.useRef)(null),tU=(0,i.useRef)(null),t_=(0,i.useRef)(null),tq=(0,i.useRef)(!1),tK=(0,i.useRef)(!1),tV=(0,i.useRef)(G);tV.current=G;let[tJ,tY]=(0,i.useState)(null),tZ=er[eo.indexOf(tJ?.entryId??"")],tG=tZ?.role==="assistant"?tJ?.blockIndex===void 0?tZ.content.find(e=>"text"===e.type):tZ.content[tJ.blockIndex]:void 0,tX=(0,i.useRef)({entryIds:eo,historyCursor:el,hasEarlierMessages:es});tX.current={entryIds:eo,historyCursor:el,hasEarlierMessages:es},(0,i.useLayoutEffect)(()=>{let t=e?.id,n=eV.current,r=tU.current;if(t&&a&&n&&r)return()=>{if(tV.current)return;if(id(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:tX.current.historyCursor})}},[et,a,eV,e?.id]),(0,i.useEffect)(()=>{t&&X(null)},[t]),(0,i.useEffect)(()=>{let n=e?.id;if(!G||!n||et||t||tK.current)return;tK.current=!0;let r=new AbortController;return(async()=>{let e=tX.current;if(e.entryIds.includes(G.anchorEntryId)){tH(t=>Math.max(t,2*e.entryIds.length)),ee(!0);return}tq.current=!0;let t=e.historyCursor,i=e.hasEarlierMessages;try{for(;i&&t&&!r.signal.aborted;){let e=await tm(n,tv,t,{signal:r.signal});if(r.signal.aborted)return;if(!e){ty("instant"),X(null);return}if(tH(t=>t+Math.max(50,2*e.messages.length)),e.entryIds.includes(G.anchorEntryId))return void ee(!0);if(e.oldestEntryId===G.oldestEntryId)break;t=e.oldestEntryId,i=e.hasMore}r.signal.aborted||(ty("instant"),X(null))}finally{tq.current=!1}})(),()=>{r.abort(),X(null)}},[tv,tm,et,G,ty,t,e?.id]),(0,i.useLayoutEffect)(()=>{let e=tU.current;if(!G||!e||t)return;let n=Array.from(e.children).find(e=>e instanceof HTMLElement&&e.dataset.entryId===G.anchorEntryId);if(n instanceof HTMLElement){tb(n,G.anchorOffset),X(null);return}Q&&(ty("instant"),X(null))},[eo,G,Q,ty,tb,t,tF]),(0,i.useEffect)(()=>{if(!t||et)return;let e=new AbortController;return(async()=>{let n=tX.current,r=n.entryIds.includes(t.entryId);if(!r&&!tj&&n.hasEarlierMessages&&n.historyCursor&&!tq.current){tq.current=!0;let i=eV.current;i&&(t_.current=ia(i.scrollHeight,i.scrollTop,i.querySelector("[data-entry-id]")?.dataset.entryId??null));let o=await tm(t.sessionId,tv,n.historyCursor,{tail:200,signal:e.signal});tq.current=!1,r=!!o?.entryIds.includes(t.entryId)}e.signal.aborted||(r?(t_.current=null,tH(e=>Math.max(e,(tX.current.entryIds.length+200)*2)),tY(t)):o?.(t))})(),()=>e.abort()},[t,et,tv,tj,tm,o,eV]),(0,i.useLayoutEffect)(()=>{if(!tJ||tJ!==t)return;let e=`[data-entry-id="${CSS.escape(tJ.entryId)}"]`,n=eV.current?.querySelector(tZ?.role==="user"?e:`${e} [data-search-target]`);n&&(tb(n),n.animate([{backgroundColor:"var(--bg-selected)"},{backgroundColor:"transparent"}],{duration:2500})),tY(null),o?.(tJ)},[tJ,t,tZ,eV,tb,o]),(0,i.useEffect)(()=>{let t=tO.current,n=eV.current;if(!t||!n)return;let r=new IntersectionObserver(t=>{if(!t[0]?.isIntersecting||tq.current)return;let r=tX.current;if(!r.hasEarlierMessages)return;let i=r.historyCursor;if(!i)return;let o=e?.id??eK.current;o&&(tq.current=!0,t_.current=ia(n.scrollHeight,n.scrollTop,n.querySelector("[data-entry-id]")?.dataset.entryId??null),tm(o,tv,i).finally(()=>{tq.current=!1}))},{root:n,threshold:0});return r.observe(t),()=>r.disconnect()},[es,e,tv,tm,eK,eV]),(0,i.useEffect)(()=>{tH(e=>Math.max(e,er.length))},[er.length]),(0,i.useEffect)(()=>{var e,t,n;let r=t_.current;if(null==r)return;let i=eV.current;i&&(e=i.scrollHeight,t=i.querySelector("[data-entry-id]")?.dataset.entryId??null,e!==r.scrollHeight&&(null===r.firstEntryId||t!==r.firstEntryId)&&(n=i.scrollHeight,i.scrollTop=Math.max(0,n-r.distance),t_.current=null))},[tF,er.length,eV]);let tQ=eM?[eM.sessionId,eM.sessionFile??"",eM.sessionName??"",eM.userMessages,eM.assistantMessages,eM.toolCalls,eM.toolResults,eM.totalMessages,eM.tokens.input,eM.tokens.output,eM.tokens.cacheRead,eM.tokens.cacheWrite,eM.tokens.total,eM.cost??0,eM.totalActiveMs??0].join("|"):null,t0=(0,i.useRef)(eM);t0.current=eM,(0,i.useEffect)(()=>{S?.(t0.current)},[tQ,S]),(0,i.useEffect)(()=>()=>{S?.(null)},[S]);let t1=ew?`${ew.percent??"null"}|${ew.contextWindow}|${ew.tokens??"null"}`:null,t2=(0,i.useRef)(ew);t2.current=ew,(0,i.useEffect)(()=>{I?.(t2.current)},[t1,I]),(0,i.useEffect)(()=>()=>{I?.(null)},[I]);let{isDragOver:t4,handleDragEnter:t8,handleDragOver:t6,handleDragLeave:t5,handleDrop:t3}=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=>{y?.current?.addImages(e)},[y])),t9=er.filter(e=>e0(e)||"assistant"===e.role),t7=(0,i.useMemo)(()=>{let e=new Map(ei);for(let t of er)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ei,er]),ne=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=er.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}(er[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[er]),nt=(F=t9.length,(H=(0,i.useRef)([])).current=Array(F).fill(null).map((e,t)=>H.current[t]??null),H),nn=(0,i.useCallback)(()=>{tH(e=>Math.max(e,2*er.length))},[er.length]),nr=eU&&0===er.length&&!ea.isStreaming&&!tj,ni=!!ea.streamingMessage?.content.length,no=e?.cwd??u??void 0,nl=(0,i.useRef)(null),ns=(0,i.useRef)(0),na=(0,i.useRef)(null),nd=(0,i.useRef)(!1),nu=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=nl.current;if(!ed||!eY){nu.current=null,ns.current=0,nd.current=!1,e&&(e.style.height="");return}let t=eV.current,n=tU.current,r=eJ.current;if(!t||!n||!r||!e)return;let i=!1,o=()=>{var o;let l;if(i||eV.current!==t||tU.current!==n||eJ.current!==r||nl.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=!nd.current;u&&(nd.current=!0),c!==ns.current&&(ns.current=c,e.style.height=c>0?`${c}px`:"",u&&c>0&&tx())};nu.current=o,o();let l="u"<typeof ResizeObserver?null:new ResizeObserver(()=>{i||null!==na.current||(na.current=requestAnimationFrame(()=>{na.current=null,o()}))});return l?.observe(t),l?.observe(n),l?.observe(r),()=>{i=!0,nu.current===o&&(nu.current=null),l?.disconnect(),null!==na.current&&(cancelAnimationFrame(na.current),na.current=null)}},[ed,eJ,er.length,eY,eV,tx]),(0,i.useLayoutEffect)(()=>{nu.current?.()},[ea.streamingMessage]);let np=eI?ex[`${eI.provider}:${eI.modelId}`]??null:null,nh=eI?em[`${eI.provider}:${eI.modelId}`]??null:null,nf=(0,r.jsx)(rF,{ref:y,onSend:c?eZ:()=>{},onAbort:c?eG:()=>{},onSteer:c&&ed?e3:void 0,onFollowUp:c&&ed?e9:void 0,onPromptWithStreamingBehavior:c&&ed?te:void 0,isStreaming:tj,model:eI,isAutoModelSelection:eF,modelNames:ep,modelList:eh,modelError:ef,modelScopeWarnings:eg,onModelChange:e1,modelSwitching:eT,onCompact:e||eU?e5:void 0,onAbortCompaction:tt,isCompacting:ej,compactError:eS,compactResult:eC,toolPreset:ev,onToolPresetChange:e||eU?th:void 0,thinkingLevel:ey,isAutoThinkingSelection:eH,onThinkingLevelChange:e||eU?tf:void 0,availableThinkingLevels:np,thinkingLevelMap:nh,retryInfo:eb,queuedMessages:eL,inputHistory:ne,onRecallQueue:tn,slashCommands:eE,slashCommandsLoading:eR,onLoadSlashCommands:tg,onBuiltinCommand:ta,soundEnabled:P,onSoundToggle:A,onAudioUnlock:D,draftKey:e?.id??p??void 0,cwd:e?.cwd??u});return et?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:O("chat.loadingSession")}):en?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:en}):(0,r.jsxs)("div",{className:"chat-content relative flex h-full min-w-0 flex-col overflow-hidden",style:{paddingBottom:"var(--safe-area-bottom, 0px)"},onDragEnter:t8,onDragOver:t6,onDragLeave:t5,onDrop:t3,children:[t4&&(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:24*!U,zIndex:40,display:"flex",justifyContent:"flex-end",padding:"0 16px",pointerEvents:"none"},children:(0,r.jsx)(iC,{notices:e$,floating:!0,onPauseChange:eD})}),(0,r.jsxs)("div",{className:"relative flex min-h-0 min-w-0 flex-1 overflow-hidden",children:[eW&&(0,r.jsx)(iI,{request:eW,onRespond:eA},eW.id),ez&&(0,r.jsx)(iT,{request:ez,onInput:eB},ez.id),!nr&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{"data-chat-focused":c?"true":void 0,ref:eV,className:"min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",style:{visibility:G?"hidden":void 0},children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{ref:tU,onPointerUp:tP,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=er.length-1;e>=0;e--)if("user"===er[e].role){o=e;break}let l=-1;for(let e=er.length-1;e>=0;e--)if(e0(er[e])){l=e;break}let s=new Map,a=0;er.forEach((e,t)=>{(e0(e)||"assistant"===e.role)&&s.set(t,a++)});let d=(t,n={})=>{let i=n.messageOverride??er[t],l=e0(i)||"assistant"===i.role,a=s.get(t),d=n.keyPrefix??"message",c=eo[t]??t,u=!1;if("assistant"===i.role){u=!0;for(let e=t+1;e<er.length;e++){let t=er[e].role;if("user"===t)break;if("assistant"===t){u=!1;break}}u&&ea.isStreaming&&t===er.length-1&&(u=!1)}void 0!==n.showTimestamp&&(u=n.showTimestamp);let p=(0,r.jsx)(nc,{message:i,toolResults:t7,modelNames:ep,cwd:no,onOpenFile:M,onOpenSession:E,entryId:eo[t],searchBlock:eo[t]===tJ?.entryId?tG:void 0,onFork:tj||eU?void 0:eX,forking:ek===eo[t],onNavigate:tj?void 0:eQ,onEditContent:Y,showTimestamp:u,prevTimestamp:t>0?er[t-1].timestamp:void 0,sessionId:e?.id??eK.current??void 0,writtenFiles:n.writtenFiles},`${d}-view-${c}`);return l&&void 0!==a?(0,r.jsx)("div",{"data-entry-id":eo[t],ref:!1===n.attachRef?void 0:e=>{nt.current[a]=e,t===o&&(eJ.current=e)},children:p},`${d}-${c}`):p},c=[];for(let e=0;e<er.length;){let t;if(!e0(er[e])){c.push(d(e)),e+=1;continue}let n=e,i=n+1;for(;i<er.length&&!e0(er[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&&e6(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}(er,n,i);if(-1===o||(tj||ea.isStreaming)&&i===er.length&&n===l){for(let e=n;e<i;e++)c.push(d(e));e=i;continue}c.push(d(n));let a=er[o],u=e6(a),p=u.answerBlocks.length>0||e4(a)||e8(a)?ik(a,u.answerBlocks):null,h=a.content.indexOf(u.answerBlocks[0]),f=a.content.slice(0,h<0?void 0:h),g=[],x=0,m=!1;for(let e=n+1;e<=o;e++){let n=er[e];if("custom"===n.role){m||=!!(tJ&&tJ.entryId===eo[e]),g.push(d(e,{attachRef:!1,keyPrefix:"process"}));continue}if("assistant"!==n.role)continue;let r=e===o?ik(n,f,{omitUsage:!!p}):n,i=e2(r);0!==i.length&&(t??=s.get(e),x+=i.filter(e=>"toolCall"===e.type).length,m||=!!(tJ&&eo[e]===tJ.entryId&&(!tG||i.includes(tG))),g.push(d(e,{attachRef:!1,keyPrefix:"process",messageOverride:r,showTimestamp:!1})))}if(g.length>0&&c.push((0,r.jsx)("div",{ref:void 0===t?void 0:e=>{nt.current[t]=e},children:(0,r.jsx)(ij,{messageCount:g.length,toolCallCount:x,defaultExpanded:!p,reveal:m,t:O,children:g})},`process-group-${eo[n]??n}`)),p){let e=[];for(let t=n+1;t<=o;t++){let n=er[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")||tr(e)}(o.toolName)&&!ti(o.toolName))continue;let e=t?.get(o.toolCallId);if(e&&!e.isError)for(let t of ti(o.toolName)?function(e,t){let n=t?.details,r=function(e,t){let n=new Set;if(t&&"object"==typeof t&&!Array.isArray(t)){let e=t.preview;if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.files;if(Array.isArray(t))for(let e of t)!(!e||"object"!=typeof e||Array.isArray(e))&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath)}}for(let t of to(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,n),i=function(e){if(!tl(e)||!tl(e.result))return null;let t=e.result.appliedFiles;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):null}(n);if(i)return i.filter(e=>!r.has(e));if(ts(n))return[];if(n&&"object"==typeof n&&!Array.isArray(n)){let e=tu(tc(n.preview));if(e.length>0)return e}return tu(td(to(e)))}(o.input,e):[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(!t)continue;let e=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 e7(n)}(t,n);e&&(r.has(e)||(r.add(e),i.push({filePath:e})))}}return i}(e,t7,no);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(tF,0),Math.max(t=c.length,0)),{startIndex:i=Math.max(0,t-n),hasMore:i>0}),p=u>0||es;return(0,r.jsxs)(r.Fragment,{children:[p&&(0,r.jsx)("div",{ref:tO,className:"py-3 text-center text-xs text-text-muted",children:O("chat.loadEarlier")}),c.slice(u)]})})(),ea.isStreaming&&ni&&ea.streamingMessage&&(0,r.jsx)(nc,{message:ea.streamingMessage,toolResults:t7,isStreaming:!0,modelNames:ep,cwd:no,onOpenFile:M,onOpenSession:E}),ed&&!ni&&eO&&(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}(eO,O)})}),ec&&!eu&&(0,r.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,r.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:O("chat.runningCommand")})}),eu&&(0,r.jsx)(nc,{message:{role:"bashExecution",command:eu.command,output:"",excludeFromContext:eu.excludeFromContext},sessionId:e?.id??eK.current??void 0,onOpenSession:E}),(0,r.jsx)("div",{ref:nl,"aria-hidden":"true"})]})})}),U||G?null:(0,r.jsx)(rJ,{messages:er,streamingMessage:ea.streamingMessage,scrollContainer:eV,messageRefs:nt,onRevealHistory:nn,scrollToOffset:tw})]})]}),$&&tC&&(0,N.createPortal)((0,r.jsx)("div",{ref:tW,role:tT?"dialog":"toolbar","aria-label":O(tT?"chat.newQuoteChat":"chat.askSelection"),style:{position:"fixed",top:tC.top,left:tC.left,zIndex:260,display:"flex",flexWrap:"wrap",gap:3,width:tT?"min(420px, calc(100vw - 16px))":void 0,maxWidth:"calc(100vw - 16px)",maxHeight:"calc(var(--app-viewport-height, 100dvh) - 16px)",overflowY:"auto",padding:tT?12:3,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",boxShadow:"0 2px 10px rgba(0,0,0,0.12)"},children:tT?(0,r.jsxs)("fieldset",{disabled:tE,"aria-busy":tE,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:O("chat.askInNewChat")}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",title:O("i18n.close"),"aria-label":O("i18n.close"),disabled:tE,onClick:tN,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)(rF,{ref:tz,compact:!0,onSend:tB,onAbort:tN,isStreaming:!1}),tL&&(0,r.jsx)("div",{role:"alert",style:{color:"#dc2626",fontSize:12,overflowWrap:"anywhere"},children:tL})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:O("chat.askInCurrent"),"aria-label":O("chat.askInCurrent"),onPointerDown:e=>e.preventDefault(),onClick:tA,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:O("chat.askInCurrent")})]}),R&&tC.sourceEntryId&&!tj&&(0,r.jsxs)("button",{type:"button",className:"file-viewer-icon-button",title:O("chat.askInNewChat"),"aria-label":O("chat.askInNewChat"),onPointerDown:e=>e.preventDefault(),onClick:()=>{tM(!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:O("chat.askInNewChat")})]})]})}),document.body),(0,r.jsxs)("div",{className:"relative shrink-0",children:[!nr&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"100%",left:0,right:24*!U,display:"flex",justifyContent:"center",paddingBottom:10,pointerEvents:"none",zIndex:20},children:(0,r.jsx)("button",{type:"button",className:`chat-scroll-to-bottom${eq&&!G?" is-visible":""}`,title:O("chat.scrollToLatest"),"aria-label":O("chat.scrollToLatest"),onClick:()=>ty("smooth"),children:(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",children:(0,r.jsx)("path",{d:"M12 5v14M5 12l7 7 7-7"})})})}),nr&&(0,r.jsx)("div",{className:"mb-3 w-full",style:{paddingLeft:16,paddingRight:U?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:U?7:10,minWidth:0,flex:1,lineHeight:1.4,overflow:"hidden"},children:[(0,r.jsx)(e_.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)(iw,{label:e=>O("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.0.7"]})]}),(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"]})]})]})]})}),nf,(0,r.jsx)(rX,{statuses:eN,widgets:eP})]}),nr&&(0,r.jsx)("div",{className:"min-h-0 flex-1"})]})}function iC({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 iI({request:e,onRespond:t}){let{t:n}=(0,L.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 f=null!==h&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap",flexShrink:0},children:n("chat.extensionExpiresIn",{seconds:h})}),g=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:o})};return(0,r.jsx)("div",{onKeyDown:n=>{"Escape"!==n.key||n.nativeEvent.isComposing||(n.preventDefault(),n.stopPropagation(),t(e,{cancelled:!0}))},style:{position:"absolute",inset:0,zIndex:90,display:"flex",alignItems:s?"flex-start":"center",justifyContent:"center",padding:20,pointerEvents:"none"},children:s?(0,r.jsxs)("button",{type:"button",onClick:()=>a(!1),"aria-expanded":!1,style:{pointerEvents:"auto",display:"flex",alignItems:"center",gap:10,maxWidth:"min(560px, 100%)",width:"100%",padding:"10px 12px",border:"1px solid var(--border)",borderRadius: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}),f,(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",flexShrink:0},children:n("chat.extensionExpand")})]}):(0,r.jsxs)("div",{role:"dialog","aria-label":e.title,style:{pointerEvents:"auto",width:"min(560px, 100%)",maxHeight:"min(760px, 100%)",display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius: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")}),f]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>a(!0),"aria-expanded":!0,title:n("chat.extensionCollapse"),"aria-label":n("chat.extensionCollapse"),style:{display:"grid",placeItems:"center",width:28,height:28,borderRadius: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)(t8,{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)(t8,{children:n})})},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:o,placeholder:e.placeholder,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||g()},style:{width:"100%",padding:"9px 10px",borderRadius: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&&g()},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:g,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:g,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 iT({request:e,onInput:t}){let{t:n}=(0,L.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(eV,""),i=eJ(e).trimEnd();if(t.test(i))continue;let o=e,l=eG(o);("│"===l||"┃"===l)&&" "===eG(o=eZ(o,0))&&(o=eZ(o,0));let s=function(e){let t=eY(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(o),a=s>=0?eY(o)[s]?.char:void 0;("│"===a||"┃"===a)&&(o=eZ(o,s)),n.push(function(e){let t=e;for(;;){let e=eY(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&&""===eJ(n[0]).trim();)n.shift();for(;n.length>0&&""===eJ(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":" ":eX[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)(rZ,{text:d.join("\n")})})]})})}var iM=n(50640);let iE={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"},iR={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"},iL={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",mov:"video/quicktime",ogv:"video/ogg"};function i$(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}var iW=n(73620);let iz=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function iN(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 iP=["tags","categories","keywords","tag","category"];function iA({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=iP.find(t=>Array.isArray(e[t])),l=o?e[o].map(iN).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=iN(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 iB={source:"Source",preview:"Preview",diff:"Diff"},iD={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},iF={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 iH(){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 iO(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function iU(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=iO(n.startContainer),i=iO(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 i_({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,iM.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,iM.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${o}-${r}`}))})]},`source-line-${o}`)})}function iq(e,t,n,r={}){let i=V(e),o=new URLSearchParams({type:t});for(let[e,t]of(n&&o.set("sessionId",n),Object.entries(r)))void 0!==t&&o.set(e,String(t));return`/api/files/${i}?${o.toString()}`}function iK({filePath:e,sourceSessionId:t}){let{t:n}=(0,L.s)();return(0,r.jsx)("a",{href:iq(e,"download",t),download:J(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 iV(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function iJ({patch:e}){let t,{t:n}=(0,L.s)(),i=(t=t9(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%",...iD},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:iF,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 iY({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,L.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v=(0,i.useRef)(0),y=J(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),p(null),f(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(iq(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(iq(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),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}f(null),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,n,o]);let b=iq(e,"read",n,d?{v:d}:void 0),w=null!=u?iV(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:Z(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"image"}),h&&(0,r.jsxs)("span",{children:[h.w," \xd7 ",h.h]}),w&&(0,r.jsx)("span",{children:w}),(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)(iK,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:g?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,r.jsx)("img",{src:b,alt:e,onLoad:e=>{let t=e.currentTarget;f({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>x("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function iZ(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 iG({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,L.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v=(0,i.useRef)(0),y=J(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),p(null),f(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(iq(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(iq(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),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}f(null),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,n,o]);let b=iq(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:Z(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"audio"}),null!=h&&(0,r.jsx)("span",{children:iZ(h)}),null!=u&&(0,r.jsx)("span",{children:iV(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)(iK,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:b,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x("Failed to load audio"),style:{width:"100%"}},b)]})})]})}function iX({filePath:e,cwd:t,sourceSessionId:n,watchEnabled:o=!0}){let{t:l}=(0,L.s)(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v=(0,i.useRef)(0),y=J(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{c(0),p(null),f(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(iq(e,"watch",n));m.current=r,r.addEventListener("connected",()=>{let r;a(!0),r=++v.current,fetch(iq(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),f(null),x(null),c(e=>e+1)}}).catch(e=>{t&&r===v.current&&x(String(e))})}),r.addEventListener("change",e=>{v.current+=1;try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}f(null),x(null),c(e=>e+1)});let i=()=>{a(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),m.current===r&&(m.current=null)}},[e,n,o]);let b=iq(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:Z(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:y||"video"}),null!=h&&(0,r.jsx)("span",{children:iZ(h)}),null!=u&&(0,r.jsx)("span",{children:iV(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)(iK,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)",minHeight:0},children:(0,r.jsxs)("div",{style:{width:"min(960px, 100%)",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:0},children:[g&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:b,onLoadedMetadata:e=>f(e.currentTarget.duration),onError:()=>x("Failed to load video"),style:{maxWidth:"100%",maxHeight:"100%"}},b)]})})]})}function iQ({filePath:e,cwd:t,sourceSessionId:n,initialPage:o,watchEnabled:l=!0}){let{t:s}=(0,L.s)(),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(0),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),x=(0,i.useRef)(null),m=(0,i.useRef)(0),v=i$(e),y="pdf"===v,b=y&&o&&o>0?`#page=${o}`:"",w=y?`${iq(e,"read",n,c?{v:c}:void 0)}${b}`:iq(e,"preview",n,c?{v:c}:void 0);return(0,i.useEffect)(()=>{u(0),h(null),g(null),d(!1);let t=!0,r=++m.current;return fetch(iq(e,"meta",n)).then(e=>e.json()).then(e=>{t&&r===m.current&&(e.error&&g(e.error),"number"==typeof e.size&&(h(e.size),!y&&e.size>0xa00000&&g("DOCX too large for preview (>10MB)")))}).catch(e=>{t&&r===m.current&&g(String(e))}),()=>{t=!1}},[e,y,n]),(0,i.useEffect)(()=>{if(d(!1),x.current&&(x.current.close(),x.current=null),!l)return;let t=!0,r=new EventSource(iq(e,"watch",n));x.current=r,r.addEventListener("connected",()=>{let r;d(!0),r=++m.current,fetch(iq(e,"meta",n)).then(e=>e.json()).then(e=>{if(t&&r===m.current){if(e.error)return void g(e.error);if("number"==typeof e.size&&(h(e.size),!y&&e.size>0xa00000))return void g("DOCX too large for preview (>10MB)");g(null),u(e=>e+1)}}).catch(e=>{t&&r===m.current&&g(String(e))})}),r.addEventListener("change",e=>{m.current+=1;try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(h(t.size),!y&&t.size>0xa00000))return void g("DOCX too large for preview (>10MB)")}catch{}g(null),u(e=>e+1)});let i=()=>{d(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{t=!1,r.close(),x.current===r&&(x.current=null)}},[e,y,n,l]),(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:Z(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===v?"docx preview":"pdf"}),null!=p&&(0,r.jsx)("span",{children:iV(p)}),(0,r.jsx)(iK,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:s(a?"i18n.liveSync":"i18n.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:a?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a?"#4ade80":"var(--border)",display:"inline-block",boxShadow:a?"0 0 4px #4ade80":"none"}}),a?"live":"static"]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:f?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:f}):(0,r.jsx)("iframe",{src:w,sandbox:y?void 0:"allow-same-origin",title:s("i18n.previewFile",{file:J(e)}),style:{width:"100%",height:"100%",border:"none",background:y?"var(--bg)":"#eef1f5"}},w)})]})}function i0({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,initialPage:c,onStateChange:u,watchEnabled:p=!0}){let h;return null!==(iE[i$(e)]??null)?(0,r.jsx)(iY,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:p}):null!==(iR[i$(e)]??null)?(0,r.jsx)(iG,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:p}):null!==(iL[i$(e)]??null)?(0,r.jsx)(iX,{filePath:e,cwd:t,sourceSessionId:n,watchEnabled:p}):null!==("pdf"===(h=i$(e))||"docx"===h?h:null)?(0,r.jsx)(iQ,{filePath:e,cwd:t,sourceSessionId:n,initialPage:c,watchEnabled:p}):(0,r.jsx)(i1,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:o,onAtMention:l,gitRefreshKey:s,initialDisplayMode:a,initialState:d,onStateChange:u,watchEnabled:p})}function i1({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}=tG(),{t:f}=(0,L.s)(),[g,x]=(0,i.useState)(null),[m,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(!1),[j,S]=(0,i.useState)(!0),[C,I]=(0,i.useState)(!1),[T,M]=(0,i.useState)(null),E=c?.displayMode??d??"source",R=c?.wrapLines??!1,$=c?.scrollTop??0,W=c?.scrollLeft??0,[z,N]=(0,i.useState)(E),[P,A]=(0,i.useState)(R),[B,D]=(0,i.useState)(!1),F=(0,i.useRef)(null),H=(0,i.useRef)(0),O=(0,i.useRef)(0),U=(0,i.useRef)(null),_=(0,i.useRef)(!1),q=(0,i.useRef)(void 0===c&&void 0===d),K=(0,i.useRef)(!0),V=(0,i.useRef)({displayMode:E,wrapLines:R,scrollTop:$,scrollLeft:W}),J=(0,i.useRef)(u),[G,X]=(0,i.useState)(null);J.current=u;let Q=(0,i.useCallback)(e=>{V.current.displayMode=e,N(e)},[]),ee=(0,i.useCallback)(()=>{A(e=>{let t=!e;return V.current.wrapLines=t,t})},[]);(0,i.useEffect)(()=>(V.current={displayMode:E,wrapLines:R,scrollTop:$,scrollLeft:W},K.current=!0,_.current=!1,N(E),A(R),()=>{J.current?.({...V.current})}),[e,n,E,R,$,W]);let et=(0,i.useCallback)((e,t=0)=>{let r=++H.current;return fetch(iq(e,"read",n,{offset:t||void 0})).then(e=>e.json()).then(e=>r!==H.current?null:e.error?(M(e.error),null):(M(null),x(n=>t&&n?{...e,content:n.content+e.content}:e),e)).catch(e=>(r!==H.current||M(String(e)),null))},[n]),en=(0,i.useCallback)(async e=>{let n=++O.current;if(b(!0),!t){v(null),b(!1),k(!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!==O.current)return;v(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch{n===O.current&&v(null)}finally{n===O.current&&(b(!1),k(!0))}},[t]);(0,i.useEffect)(()=>{let t=!0;return S(!0),M(null),x(null),v(null),k(!1),D(!1),et(e).finally(()=>{t&&S(!1)}),()=>{t=!1}},[e,et,n]),(0,i.useEffect)(()=>{if(D(!1),F.current&&(F.current.close(),F.current=null),!p)return;let t=()=>{et(e),en(e)},r=new EventSource(iq(e,"watch",n));F.current=r,r.addEventListener("connected",()=>{D(!0),t()}),r.addEventListener("change",t);let i=()=>{D(!1)};return r.addEventListener("error",i),r.onerror=i,()=>{r.close(),F.current===r&&(F.current=null)}},[e,et,en,n,p]),(0,i.useEffect)(()=>{en(e)},[en,e,a]),(0,i.useEffect)(()=>{q.current&&!g?.truncated&&(g?.language==="markdown"||g?.language==="html")&&(q.current=!1,Q("preview"))},[g?.language,g?.truncated,Q]);let er=m?.supported===!0&&"string"==typeof m.patch,ei=er&&"deleted"===m.status;(0,i.useEffect)(()=>{w&&!er&&"diff"===z&&Q("source")},[z,w,er,Q]),(0,i.useEffect)(()=>{"diff"===E&&er&&!_.current&&(_.current=!0,Q("diff"))},[E,er,Q]);let eo=(0,i.useMemo)(()=>g?.language==="markdown"?tS(g.content):"",[g]),el=(0,i.useMemo)(()=>g?.language==="markdown"?function(e){let t=function(e){let t=iz.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,iW.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(g.content):null,[g]),es=g?.content??"",ea=(0,i.useMemo)(()=>es.split("\n"),[es]),ed=g?.language??"text",ec="html"===ed,eu="markdown"===ed,ep=!g?.truncated&&(ec||eu),eh=ei?"diff":z,ef=ea.length>1e3&&!("diff"===eh&&er)&&!("preview"===eh&&ep),eg=(0,i.useMemo)(()=>(0,r.jsx)(tW.A,{className:P?"file-source-view is-wrapped":"file-source-view",language:"text"===ed?"plaintext":ed,style:h?tz.xJ:tz.vs,showLineNumbers:!0,lineNumberStyle:{...iF},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...iD,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)(i_,{...e,wrapLines:P}),wrapLongLines:P,children:es}),[h,ed,es,P]),ex=(0,i.useMemo)(()=>ef?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:iF,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,ef,P]);(0,i.useEffect)(()=>{let e=()=>{let e=U.current;X(t=>{let n=l&&"source"===z&&e?iU(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)},[g?.content,z,l]);let em=(0,i.useCallback)(n=>{l&&n&&l(Z(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=U.current,r=n?iU(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(!K.current||j||T&&!ei||"diff"===E&&!w||"diff"===E&&er&&"diff"!==z)return;let e=U.current;e&&(e.scrollTop=V.current.scrollTop,e.scrollLeft=V.current.scrollLeft,K.current=!1)},[g?.content,z,T,w,er,ei,j,E]),j||"diff"===E&&y&&!g)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:f("i18n.loading")});if(T&&!ei)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#f87171",fontSize:13},children:T});if(!g&&!ei)return null;let ev=Y(e),ey=ei?["diff"]:["source",...ep?["preview"]:[],...er?["diff"]:[]],eb=ei?f("files.deleted"):`${ed} \xb7 ${ea.length} lines \xb7 ${iV(g.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:Z(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:eb,children:eb}),!ei&&(0,r.jsx)("span",{title:B?f("i18n.liveSync"):f("i18n.notWatching"),"aria-label":B?f("i18n.liveSync"):f("i18n.notWatching"),className:"file-viewer-live-indicator",style:{background:B?"#4ade80":"var(--border)",boxShadow:B?"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":f("i18n.fileViewMode"),children:ey.map(e=>{let t=eh===e;return(0,r.jsx)("button",{type:"button",onClick:()=>Q(e),title:"diff"===e?f("i18n.compareHead"):void 0,"aria-pressed":t,className:"file-viewer-mode-button",style:{background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-muted)"},children:iB[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?.(Z(e,t),!1)},title:G&&l?`${f("i18n.mentionSelectedLines")} (L${G.startLine}${G.startLine!==G.endLine?`-L${G.endLine}`:""})`:f("files.insertPath"),"aria-label":f("files.mention"),disabled:!s&&!l,className:"file-viewer-icon-button",children:(0,r.jsx)(iH,{})}),"source"===eh&&(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("button",{type:"button",onClick:ee,title:P?f("i18n.disableWrap"):f("i18n.enableWrap"),"aria-label":P?f("i18n.disableWrap"):f("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)(iK,{filePath:e,sourceSessionId:n})]})]}),g?.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:[iV(g.nextOffset)," / ",iV(g.size)]}),(0,r.jsx)("button",{type:"button",className:"file-viewer-mode-button",disabled:C,onClick:()=>{I(!0),et(e,g.nextOffset).finally(()=>I(!1))},children:C?f("i18n.loading"):f("i18n.loadMore")})]}),(0,r.jsx)("div",{ref:U,className:"file-viewer-content",onScroll:e=>{V.current.scrollTop=e.currentTarget.scrollTop,V.current.scrollLeft=e.currentTarget.scrollLeft},style:{flex:1,overflow:"auto",background:"var(--bg)",paddingBottom:g?.truncated?48:void 0},children:"diff"===eh&&er?(0,r.jsx)(iJ,{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:f("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)(iA,{data:el.data}),(0,r.jsx)(th.oz,{remarkPlugins:tE,rehypePlugins:tL,urlTransform:o?tk:void 0,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",o=String(t);return e?.includes("language-")||o.includes("\n")?"mermaid"===i?(0,r.jsx)(tQ,{code:o.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(t1,{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?te(e,ev,t??ev):null;return l&&o?(0,r.jsx)("a",{href:e,...i,onClick:t=>{e5(t)&&(t.preventDefault(),o(l,tn(e)??void 0))},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?te(e,ev,t??ev):null,s=l?iq(l,"read",n):e;return(0,r.jsx)("img",{src:s,alt:i??"",loading:"lazy",...o})}},children:eo})]}):ef?(0,r.jsx)("div",{className:"file-source-view is-lightweight",style:{width:P?"100%":"max-content",minWidth:"100%",minHeight:"100%",background:"var(--bg)",...iD},children:ex}):eg})]})}let i2={running:"var(--accent)",completed:"#16a34a",failed:"#dc2626",killed:"#d97706"};function i4({sessionId:e,state:t,logs:n,onRefresh:o,onFetchLogs:l,onKill:s,onClose:a,selectedTaskId:d,onSelectTask:c}){let{t:u,locale:p}=(0,L.s)(),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),m=(0,i.useRef)(null),v="ready"===t.kind?t.tasks:[];(0,i.useEffect)(()=>{d&&l(d)},[d,l]);let y=(0,i.useCallback)(async e=>{x(null);try{await s(e),f(null)}catch(e){x(e instanceof Error?e.message:String(e))}},[s]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:"var(--bg-panel)"},role:"complementary","aria-label":u("bgTasks.title"),children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:12,fontWeight:600,color:"var(--text)",flex:1},children:u("bgTasks.title")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:"ready"!==t.kind,title:u("bgTasks.refresh"),"aria-label":u("bgTasks.refresh"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,background:"none",border:"none",color:"var(--text-muted)",cursor:"ready"===t.kind?"pointer":"not-allowed",fontSize:14},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:"M21 12a9 9 0 1 1-2.64-6.36"}),(0,r.jsx)("path",{d:"M21 3v6h-6"})]})}),(0,r.jsx)("button",{type:"button",onClick:a,title:u("bgTasks.close"),"aria-label":u("bgTasks.close"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:14},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:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:["loading"===t.kind&&(0,r.jsx)("div",{style:{padding:16,color:"var(--text-dim)",fontSize:12},children:u("bgTasks.loading")}),"unavailable"===t.kind&&(0,r.jsx)("div",{style:{padding:16,color:"var(--text-dim)",fontSize:12},children:u("bgTasks.unavailable")}),"ready"===t.kind&&0===v.length&&(0,r.jsx)("div",{style:{padding:16,color:"var(--text-dim)",fontSize:12},children:u("bgTasks.empty")}),"ready"===t.kind&&v.length>0&&(0,r.jsxs)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:[(0,r.jsx)("div",{style:{maxHeight:"45%",overflowY:"auto",borderBottom:"1px solid var(--border)"},children:v.map(e=>{var t;return(0,r.jsxs)("div",{role:"button",tabIndex:0,onClick:()=>c(d===e.id?null:e.id),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),c(d===e.id?null:e.id))},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",cursor:"pointer",fontSize:12,background:d===e.id?"var(--bg-selected)":"none",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("span",{"aria-label":u(`bgTasks.status.${e.status}`),style:{width:8,height:8,borderRadius:4,flexShrink:0,background:i2[e.status]??"var(--text-dim)"}}),(0,r.jsxs)("span",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:2},children:[(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:[e.name||e.id,e.isAgent?(0,r.jsxs)("em",{style:{color:"var(--text-dim)",fontSize:10,marginLeft:4,fontStyle:"normal"},children:[" \xb7 ",u("bgTasks.agentTask")]}):null]}),(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:[function(e,t){try{return new Intl.DateTimeFormat(t,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(e))}catch{return new Date(e).toISOString()}}(e.startTime,p)," \xb7 ",function(e,t){let n=Math.max(0,Math.round(((t??Date.now())-e)/1e3));if(n<60)return`${n}s`;let r=Math.floor(n/60);return r<60?`${r}m ${n%60}s`:`${Math.floor(r/60)}h ${r%60}m`}(e.startTime,e.endTime)," \xb7 ",(t=e.bytesWritten)<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1048576).toFixed(1)} MB`,"number"==typeof e.exitCode?` \xb7 ${u("bgTasks.exitCode")} ${e.exitCode}`:""]})]}),"running"===e.status&&(h===e.id?(0,r.jsxs)("span",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),y(e.id)},style:{padding:"2px 8px",fontSize:11,background:"#dc2626",border:"none",borderRadius:6,color:"#fff",cursor:"pointer"},children:u("bgTasks.killConfirm")}),(0,r.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),f(null),x(null)},style:{padding:"2px 8px",fontSize:11,background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer"},children:u("common.cancel")})]}):(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),f(e.id),x(null)},title:u("bgTasks.kill"),"aria-label":u("bgTasks.kill"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:22,height:22,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1"})})}))]},e.id)})}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:d?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{padding:"4px 12px",fontSize:11,color:"var(--text-dim)",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",justifyContent:"space-between",gap:8},children:[(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u("bgTasks.output")}),n[d]?.truncated?(0,r.jsx)("span",{style:{flexShrink:0},children:u("bgTasks.outputTruncated")}):null]}),(0,r.jsx)("div",{ref:m,style:{flex:1,minHeight:0,overflowY:"auto",padding:"6px 12px",fontSize:11,lineHeight:1.45,fontFamily:"var(--font-mono, monospace)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:n[d]?(0,r.jsx)(rZ,{text:n[d].text}):(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:u("bgTasks.loading")})})]}):(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:u("bgTasks.selectTask")})})]}),g&&(0,r.jsx)("div",{style:{padding:"6px 12px",color:"#dc2626",fontSize:11,borderTop:"1px solid var(--border)",flexShrink:0},children:g})]}),(0,r.jsx)("span",{"data-bg-tasks-session":e??"",hidden:!0})]})}function i8({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:o}){let{t:l}=(0,L.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"})]}):q(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 i6({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 i5=["general","models","skills","agents","plugins"],i3="pi-web:settings-navigation",i9=new Set(["skills","agents","plugins"]);function i7(){try{return window.localStorage}catch{return null}}function oe(e){let t=e.getItem(i3);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 ot(e,t){return"models"===e?e:t?JSON.stringify([e,t]):null}function on(e,t=i7()){if(t)try{let n=oe(t);n.section=e,t.setItem(i3,JSON.stringify(n))}catch{}}function or(e,t,n=i7()){if(!n)return null;let r=ot(e,t);if(!r)return null;try{let e=oe(n).selections?.[r];return"string"==typeof e&&e.length>0?e:null}catch{return null}}function oi(e,t,n,r=i7()){if(!r||!t)return;let i=ot(e,n);if(i)try{let e=oe(r);e.selections={...e.selections,[i]:t},r.setItem(i3,JSON.stringify(e))}catch{}}let oo=["input","output","cacheRead","cacheWrite"];function ol(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 os(e){if(!oa(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 oa(e){return oo.some(t=>""!==e[t].trim())}function od({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 oc({children:e}){return(0,r.jsx)("div",{className:"config-split-view",children:e})}function ou({children:e}){return(0,r.jsx)("aside",{className:"config-sidebar",children:e})}function op({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-list",children:e})}function oh({children:e}){return(0,r.jsx)("div",{className:"config-sidebar-group-label",children:e})}function of({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 og({className:e,...t}){return(0,r.jsx)("span",{...t,className:["config-sidebar-text",e].filter(Boolean).join(" ")})}function ox({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-stack",e].filter(Boolean).join(" ")})}function om({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header",e].filter(Boolean).join(" ")})}function ov({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-header-info",e].filter(Boolean).join(" ")})}function oy({className:e,...t}){return(0,r.jsx)("div",{...t,className:["config-detail-actions",e].filter(Boolean).join(" ")})}function ob({children:e}){return(0,r.jsx)("div",{className:"config-detail-title",children:e})}function ow({children:e}){return(0,r.jsx)("div",{className:"config-section-title",children:e})}function ok({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 oj({children:e}){return(0,r.jsx)("div",{className:"config-empty-state",children:e})}function oS({children:e,style:t}){return(0,r.jsx)("div",{className:"config-detail",style:t,children:e})}function oC({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 oI({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 oT({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 oM({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 oE({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 oR={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 oL({id:e,size:t}){let n=oR[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 o$=["openai-codex","deepseek","openrouter","moonshotai","moonshotai-cn","minimax","minimax-cn","vercel-ai-gateway","opencode-go"],oW="pi-web:provider-usage:";function oz({providerId:e,enabled:t}){return o$.includes(e)?(0,r.jsx)(oN,{providerId:e,enabled:t}):null}function oN({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,L.s)();(0,i.useEffect)(()=>{p.current&&clearTimeout(p.current),u(!1),o(null);try{let t=localStorage.getItem(`${oW}${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(`${oW}${e}`)}catch{}}return d(null),()=>{p.current&&clearTimeout(p.current)}},[e]);let f=(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(`${oW}${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]),g=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:f,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"})]})}),g&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:h("providerUsage.updated",{time:new Date(g.capturedAt).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})})]}),!g&&!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}),g&&(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:[g.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 ":"$"}${oP(e.remaining??e.limit)}`:void 0!==e.remaining&&void 0!==e.limit?`${oP(e.remaining)} / ${oP(e.limit)}`:e.period??t}(e,h("providerUsage.available"))})]},e.id)),g.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 oP(e){return void 0===e?"-":Number.isInteger(e)?String(e):e.toFixed(2)}function oA(){let e=or("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 oB=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function oD({label:e,children:t}){return(0,r.jsx)(ok,{label:e,children:t})}let oF={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 oH({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...oF,fontFamily:i?"var(--font-mono)":"inherit"}})}function oO({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,L.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:{...oF,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 oU({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:oF})}function o_({value:e,onChange:t,options:n,required:i}){let{t:o}=(0,L.s)();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...oF,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 oq({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 oK({children:e}){return(0,r.jsx)(ow,{children:e})}function oV({name:e,provider:t,onChange:n,onRename:o,onDelete:l,onAddModels:s}){let{t:a}=(0,L.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,f]=(0,i.useState)(""),[g,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"}),f(""),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]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),I=C.filter(e=>!w.has(e.id)).map(e=>e.id),T=g.filter(e=>!w.has(e)).length,M=I.length>0&&I.every(e=>g.includes(e)),E=!M&&I.some(e=>g.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=E)},[E]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(om,{children:[(0,r.jsx)(ov,{children:(0,r.jsx)(oK,{children:a("i18n.provider")})}),(0,r.jsx)(oy,{children:(0,r.jsx)(oI,{variant:"danger",size:"small",onClick:l,children:a("i18n.delete")})})]}),(0,r.jsxs)(oD,{label:a("i18n.providerName"),children:[(0,r.jsx)(oH,{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)(oD,{label:"Base URL",children:(0,r.jsx)(oH,{value:t.baseUrl??"",onChange:e=>y("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(oD,{label:"API Key",children:[(0,r.jsx)(oO,{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)(oD,{label:"API",children:(0,r.jsx)(o_,{value:t.api??"openai-completions",onChange:e=>y("api",e),options:oB,required:!0})}),(0,r.jsxs)(oD,{label:"Headers",children:[(0,r.jsx)(oQ,{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=>f(e.target.value),placeholder:a("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":a("models.discoveryFilter"),style:{...oF,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:I.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:M,disabled:0===I.length,onChange:()=>{let e=new Set(I);x(t=>M?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...I])))},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=w.has(e.id),i=g.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(g),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(s(t),x([]))},disabled:0===T,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:T?"var(--accent)":"var(--bg-panel)",color:T?"var(--accent-contrast)":"var(--text-dim)",cursor:T?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:T?a("models.discoveryAddSelectedCount",{count:T}):a("models.discoveryAddSelected")})]})]})]})]})}let oJ=["off","minimal","low","medium","high","xhigh","max"],oY={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function oZ({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:oJ.map(e=>{let t=n[e],o=e in n?null===t?"null":"string":"omit",l="string"==typeof t?t:"",s=oY[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 oG={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function oX(e){return e.compat?.thinkingFormat==="deepseek"}function oQ({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:{...oF,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:{...oF,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 o0({providerName:e,provider:t,model:n,onChange:o,onDelete:l}){let[s,a]=(0,i.useState)({phase:"idle"}),{t:d}=(0,L.s)(),[c,u]=(0,i.useState)({phase:"idle"}),[p,h]=(0,i.useState)(!1),[f,g]=(0,i.useState)(()=>ol(n.cost)),x=(0,i.useRef)(f),[m,v]=(0,i.useState)(!1),y=(0,i.useRef)(0),b=(0,i.useRef)(null),w=(0,i.useRef)(n.cost),k=(e,t)=>o({...n,[e]:t}),j=(()=>{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=os(ol(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]),I=(()=>{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}`})(),T="error"===c.phase?c.message:I,M="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)",E=[{key:"input",label:d("models.costInput")},{key:"output",label:d("models.costOutput")},{key:"cacheRead",label:d("models.costCacheRead")},{key:"cacheWrite",label:d("models.costCacheWrite")}],R=new Set(Object.keys(n.compat??{})),$=0;oX(n)&&($+=1,R.delete("thinkingFormat"),R.delete("requiresReasoningContentOnAssistantMessages")),Object.prototype.hasOwnProperty.call(n.compat??{},"supportsDeveloperRole")&&($+=1,R.delete("supportsDeveloperRole")),$+=R.size;let W=[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=W.length?W.join(" \xb7 "):d("models.providerDefaults");return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)(om,{children:[(0,r.jsx)(ov,{children:(0,r.jsx)(oK,{children:d("i18n.model")})}),(0,r.jsxs)(oy,{children:[j&&(0,r.jsx)("span",{title:j,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:j}),(0,r.jsxs)(oI,{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)(oI,{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)(oD,{label:"ID *",children:(0,r.jsx)(oH,{value:n.id,onChange:e=>k("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(oD,{label:"Name",children:(0,r.jsx)(oH,{value:n.name??"",onChange:e=>k("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")})]}),T&&(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:8,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:M,fontSize:10},children:[(0,r.jsx)("span",{title:T,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),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)(oK,{children:d("models.capabilities")}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginTop:8},children:[(0,r.jsx)(oq,{label:d("models.reasoning"),checked:n.reasoning??!1,onChange:e=>k("reasoning",e||void 0)}),(0,r.jsx)(oq,{label:d("models.imageInput"),checked:n.input?.includes("image")??!1,onChange:e=>k("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)(oK,{children:d("models.modelSpecs")}),(0,r.jsx)("button",{type:"button",onClick:()=>{if(p)return void h(!1);w.current=n.cost;let e=ol(n.cost);x.current=e,g(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)(oD,{label:d("models.contextWindow"),children:(0,r.jsx)(oU,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>k("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(oD,{label:d("models.maxOutputTokens"),children:(0,r.jsx)(oU,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>k("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:[E.map(({key:e,label:t})=>(0,r.jsx)(oD,{label:t,children:(0,r.jsx)(oU,{value:f[e],onChange:t=>{let r,i,l;return i=os(r={...x.current,[e]:t}),l={...n},void(x.current=r,g(r),i?(l.cost={...w.current??{},...i},w.current=l.cost):delete l.cost,o(l))},placeholder:"0"})},e)),oa(f)&&!os(f)&&(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:E.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)(oD,{label:d("models.apiOverride"),children:(0,r.jsx)(o_,{value:n.api??"",onChange:e=>k("api",e||void 0),options:oB})}),(0,r.jsxs)(oD,{label:d("models.headers"),children:[(0,r.jsx)(oQ,{headers:n.headers,onChange:e=>k("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)(oK,{children:d("models.compatibility")}),(0,r.jsx)(oq,{label:d("models.deepSeekThinkingCompat"),checked:oX(n),onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...oG}};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)(oq,{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)(oK,{children:d("models.thinkingLevelMap")}),n.thinkingLevelMap&&(0,r.jsx)("button",{type:"button",onClick:()=>k("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)(oZ,{value:n.thinkingLevelMap,onChange:e=>k("thinkingLevelMap",e)})]})]})]})]})]})}function o1({provider:e,onRefresh:t}){let[n,o]=(0,i.useState)({phase:"idle"}),{t:l}=(0,L.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]),f=(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]),g="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)(om,{children:[(0,r.jsx)(ov,{children:(0,r.jsx)(oK,{children:l("i18n.subscription")})}),(0,r.jsxs)(oy,{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")})]}),g?(0,r.jsx)(oI,{size:"small",onClick:()=>{d.current?.close(),o({phase:"idle"})},children:l("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oI,{variant:"primary",size:"small",onClick:u,children:l(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&(0,r.jsx)(oI,{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:()=>f(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)(oz,{providerId:e.id,enabled:e.loggedIn})]})}function o2({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:f}=(0,L.s)();(0,i.useEffect)(()=>{o(""),u(null),h(!1)},[e.id]);let g=(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)(om,{children:[(0,r.jsx)(ov,{children:(0,r.jsx)(oK,{children:"API Key"})}),(0,r.jsxs)(oy,{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:f(e.configured?"i18n.configured":"i18n.notConfigured")})]}),e.configured&&(0,r.jsx)(oI,{variant:"danger",size:"small",onClick:x,disabled:a,children:f(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)(oO,{value:n,onChange:o,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&g()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:g,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"})}),f(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)(oz,{providerId:e.id,enabled:e.configured})]})}function o4({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:o,onAddCustom:l,onClose:s}){let[a,d]=(0,i.useState)(""),{t:c}=(0,L.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))),f=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),g=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),x=h.length+f.length+ +!!g,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:[g&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),g&&(0,r.jsxs)("button",{onClick:()=>{l(),s()},style: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*!!g,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)(oL,{id:e.id,size:28})]},e.id)),f.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"}),f.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)(oL,{id:e.id,size:28})]},e.id))]})})]})})}function o8({onClose:e,embedded:t=!1}){let{t:n}=(0,L.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,f]=(0,i.useState)(!1),[g,x]=(0,i.useState)(oA),[m,v]=(0,i.useState)([]),[y,b]=(0,i.useState)([]),[w,k]=(0,i.useState)(!1),j=(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)),j()},[j]),(0,i.useEffect)(()=>{g&&oi("models",JSON.stringify(g))},[g]);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}}))},[]),I=(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)},[]),T=(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})},[]),M=(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})},[]),E=(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}}}})},[]),R=(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})},[]),W=(0,i.useCallback)(async()=>{c(!0),p(null),f(!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}`):(f(!0),setTimeout(()=>f(!1),2e3))}catch(e){p(String(e))}finally{c(!1)}},[o]),z=Object.entries(o.providers??{}),N=m.filter(e=>e.loggedIn),P=y.filter(e=>e.configured),A=(()=>{if(!g)return null;if("oauth"===g.type){let e=m.find(e=>e.id===g.providerId);return e?(0,r.jsx)(o1,{provider:e,onRefresh:j},e.id):null}if("apikey"===g.type){let e=y.find(e=>e.id===g.providerId);return e?(0,r.jsx)(o2,{provider:e,onRefresh:j},e.id):null}if("provider"===g.type){let e=o.providers?.[g.name];return e?(0,r.jsx)(oV,{name:g.name,provider:e,onChange:e=>C(g.name,e),onRename:e=>I(g.name,e),onDelete:()=>T(g.name),onAddModels:e=>E(g.name,e)},g.name):null}let e=o.providers?.[g.providerName],t=e?.models?.[g.index];return t?(0,r.jsx)(o0,{providerName:g.providerName,provider:e,model:t,onChange:e=>R(g.providerName,g.index,e),onDelete:()=>$(g.providerName,g.index)},`${g.providerName}-${g.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)(od,{embedded:t,title:n("common.models"),subtitle:"~/.pi/agent/models.json",closeLabel:n("i18n.close"),onClose:e,children:[(0,r.jsxs)(oc,{children:[(0,r.jsxs)(ou,{children:[(0,r.jsxs)(op,{children:[N.map(e=>{let t=g?.type==="oauth"&&g.providerId===e.id;return(0,r.jsxs)(of,{active:t,onClick:()=>x({type:"oauth",providerId:e.id}),children:[(0,r.jsx)(oL,{id:e.id,size:16}),(0,r.jsx)(og,{className:"is-grow",children:e.name})]},e.id)}),P.map(e=>{let t=g?.type==="apikey"&&g.providerId===e.id;return(0,r.jsxs)(of,{active:t,onClick:()=>x({type:"apikey",providerId:e.id}),children:[(0,r.jsx)(oL,{id:e.id,size:16}),(0,r.jsx)(og,{className:"is-grow",children:e.displayName})]},e.id)}),(N.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=g?.type==="provider"&&g.name===e,o=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)(of,{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)(og,{className:"is-grow",children:e})]}),o.map((t,i)=>{let o=g?.type==="model"&&g.providerName===e&&g.index===i;return(0,r.jsxs)(of,{active:o,className:"models-sidebar-indented-item",onClick:()=>x({type:"model",providerName:e,index:i}),children:[(0,r.jsx)(og,{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)(of,{className:"models-sidebar-indented-item models-sidebar-add-item",onClick:t=>{t.stopPropagation(),M(e)},children:(0,r.jsxs)(og,{children:["+ ",n("i18n.model")]})})]},e)})]}),(0,r.jsx)(oM,{onClick:()=>k(!0),children:n("i18n.addProvider")})]}),(0,r.jsx)(oS,{children:(0,r.jsx)(ox,{className:"is-fill",children:s?null:A??(0,r.jsx)(oj,{children:n("i18n.selectProviderModel")})})})]}),(0,r.jsxs)(oC,{status:u&&(0,r.jsx)("span",{style:{color:"#f87171"},children:u}),children:[!t&&(0,r.jsx)(oI,{onClick:e,children:n("i18n.cancel")}),(0,r.jsxs)(oI,{variant:"primary",onClick:W,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")})]})]})]}),w&&(0,r.jsx)(o4,{oauthProviders:m,apiKeyProviders:y,onSelectOAuth:e=>x({type:"oauth",providerId:e}),onSelectApiKey:e=>x({type:"apikey",providerId:e}),onAddCustom:S,onClose:()=>k(!1)})]})}let o6=null;async function o5(e){if(!("serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window)||"granted"!==Notification.permission)return!1;if(o6)return o6;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 o6=null,!1}})();return o6=t,t.then(e=>{e||o6!==t||(o6=null)}),t}function o3(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function o9(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function o7(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function le(e){return e?e.slice(0,8):"unknown"}function lt({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,L.s)(),h=o9(e),f=!e.disableModelInvocation;return(0,r.jsxs)(ox,{children:[(0,r.jsxs)("div",{className:"skill-detail-heading",children:[(0,r.jsxs)(om,{children:[(0,r.jsxs)(ov,{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 o3(e)}(e.filePath)})]}),(0,r.jsx)(oy,{children:(0,r.jsx)(oT,{checked:f,loading:i,label:p(f?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),onChange:()=>n(e)})})]}),(0,r.jsxs)("div",{className:"skill-detail-status-row",children:[!f&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),o&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:o})]})]}),e.install?.skillsShUrl&&(0,r.jsx)(ok,{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)(ok,{label:"Version",children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:le(l?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)(oI,{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:le(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)(oI,{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)(ok,{label:"Name",children:(0,r.jsx)("span",{className:"skill-name-value",children:e.name})}),(0,r.jsx)(ok,{label:"Description",children:(0,r.jsx)("span",{className:"skill-description",children:e.description})})]})}function ln({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:o}){let{t:l}=(0,L.s)(),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),[m,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),f(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void f(n.error);c(n.results??[]),0===(n.results??[]).length&&f("No skills found")}catch(e){f(String(e))}finally{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:w,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(`${w}:${t}`)),o()}catch(e){v(String(e))}finally{x(null)}},[o,w,e]),I="global"===w?"~/.pi/agent/skills/":`${o3(e)}/.pi/skills/`;return(0,r.jsxs)(ox,{className:"is-full-height",children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)(ob,{children:l("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,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)(oI,{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)&&k(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:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===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:["→ ",I]})]}),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[w].has(e.package)||y.has(`${w}:${e.package}`),i=g===e.package,o=e.package.indexOf("@"),s=o>-1?e.package.slice(0,o):e.package,a=o>-1?e.package.slice(o+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:a??s}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:s}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)(oI,{size:"small",onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==g,style:{flexShrink:0,background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)"},children:n?`✓ ${l("i18n.installed")}`:i?l("i18n.installing"):l("i18n.install")})]},e.package)})}):!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 lr({cwd:e,onClose:t,embedded:n=!1}){let{t:o}=(0,L.s)(),[l,s]=(0,i.useState)([]),[a,d]=(0,i.useState)(!0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(()=>or("skills",e)),[f,g]=(0,i.useState)(new Set),[x,m]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(new Set),[S,C]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,E]=(0,i.useState)(null),[R,$]=(0,i.useState)(!0),W=(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)(()=>{w({}),E(null),W()},[e]),(0,i.useEffect)(()=>{p&&oi("skills",p,e)},[e,p]);let z=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(o7).filter(e=>!!e);if(0!==n.length){E(null),j(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}`);w(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){E(e instanceof Error?e.message:String(e))}finally{j(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||C(!1)}}},[e,l]),N=(0,i.useCallback)(async t=>{if(!t.install)return;let n=o7(t);T(n),E(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 W();let o=i.skill?.install?.versionHash;w(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){E(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,W]),P=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(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{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),A=l.find(e=>e.filePath===p)??null;return(0,r.jsxs)(od,{embedded:n,title:o("common.skills"),subtitle:o3(e),closeLabel:o("i18n.close"),onClose:t,children:[!R&&(0,r.jsx)("div",{role:"status",className:"config-trust-notice",children:o("trust.skillsNotLoaded")}),(0,r.jsxs)(oc,{children:[(0,r.jsxs)(ou,{children:[(0,r.jsx)(op,{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"===o9(e)&&!!e.install?.skillsShUrl},{label:t.project,matches:e=>"project"===o9(e)&&!e.install?.skillsShUrl},{label:`${t.global} / skills.sh`,matches:e=>"global"===o9(e)&&!!e.install?.skillsShUrl},{label:t.global,matches:e=>"global"===o9(e)&&!e.install?.skillsShUrl},{label:t.path,matches:e=>"path"===o9(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)(of,{active:i,onClick:()=>{h(e.filePath),y(!1)},children:[(0,r.jsx)(oE,{active:!l}),(0,r.jsx)(og,{className:`is-grow${l?" is-muted":""}`,children:e.name}),(n=(t=o7(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)(oh,{children:e}),[...t.filter(e=>!e.disableModelInvocation),...t.filter(e=>e.disableModelInvocation)].map(n)]},e))})()}),(0,r.jsx)(oM,{onClick:()=>y(!0),active:v,children:o("i18n.addSkill")})]}),(0,r.jsx)(oS,{children:(0,r.jsx)(ox,{className:"is-fill",children:v?(0,r.jsx)(ln,{cwd:e,projectResourcesLoaded:R,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{W()}}):a?null:A?(0,r.jsx)(lt,{skill:A,cwd:e,onToggle:P,toggling:f.has(A.filePath),saveError:x,updateStatus:o7(A)?b[o7(A)]:void 0,checkingUpdate:!!o7(A)&&k.has(o7(A)),updating:I===o7(A),updateError:M,onCheckUpdate:()=>void z(A),onUpdate:()=>void N(A)},A.filePath):(0,r.jsx)(oj,{children:o("i18n.selectSkill")})})})]}),(0,r.jsxs)(oC,{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)(oI,{onClick:t,children:o("i18n.close")}),l.some(e=>!!e.install)&&(0,r.jsx)(oI,{variant:"secondary",onClick:()=>void z(),disabled:S||null!==I,children:S?o("i18n.checking"):o("i18n.checkUpdates")})]})]})}let li={builtin:0,global:1,workspace:2,project:3},lo=["read","bash","edit","write","grep","find","ls"],ll=["","off","minimal","low","medium","high","xhigh","max"],ls={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},la={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"},ld={background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"default"};function lc(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 lu(e){return`${e.scope}:${e.name}`}function lp(e){return"global"===e||"project"===e}function lh(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lf({label:e,children:t}){return(0,r.jsx)(ok,{label:e,children:t})}function lg({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 lx({cwd:e,sessionId:t=null,onClose:n,onReloaded:o,embedded:l=!1}){let s=n4(),{t:a}=(0,L.s)(),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)([]),[h,f]=(0,i.useState)(!0),[g,x]=(0,i.useState)(null),[m,v]=(0,i.useState)(()=>or("agents",e)),[y,b]=(0,i.useState)(ls),[w,k]=(0,i.useState)("view"),[j,S]=(0,i.useState)("global"),[C,I]=(0,i.useState)(!0),[T,M]=(0,i.useState)(!1),[E,R]=(0,i.useState)(!1),[$,W]=(0,i.useState)(!1),[z,N]=(0,i.useState)(null),[P,A]=(0,i.useState)(!1),[B,D]=(0,i.useState)(10),[F,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=>lu(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=>{I(!0),N(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??or("agents",e),l=i.find(e=>lu(e)===o)??i.find(e=>"project"===e.scope)??i.find(e=>"global"===e.scope)??i[0]??null;v(l?lu(l):null),l&&(b(lc(l)),k(lp(l.scope)?"edit":"view"),lp(l.scope)&&S(l.scope))}catch(e){N(e instanceof Error?e.message:String(e))}finally{I(!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&&D(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&&oi("agents",m,e)},[e,m]),(0,i.useEffect)(()=>{let t=new AbortController;return f(!0),x(null),(async()=>{try{let n=await fetch(`/api/models?cwd=${encodeURIComponent(e)}`,{signal:t.signal}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);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||f(!1)}})(),()=>t.abort()},[e]);let Q=async()=>{M(!0),N(null),R(!1);try{let t=await fetch("/api/subagents/profiles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,scope:j,profile:y})}),n=await t.json();if(!t.ok||n.error||!n.profile)throw Error(n.error??`HTTP ${t.status}`);await X(lu(n.profile)),R(!0),setTimeout(()=>R(!1),2e3)}catch(e){N(e instanceof Error?e.message:String(e))}finally{M(!1)}},ee=async()=>{if(Z&&lp(Z.scope)&&window.confirm(a("agents.deleteConfirm",{name:Z.displayName}))){M(!0),N(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){N(e instanceof Error?e.message:String(e))}finally{M(!1)}}},et="view"!==w,en="create"===w,er=!et||T||$,ei=en?j:Z?.scope,eo=en?"global"===j?`~/.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 lh(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?{...la,...ld}:la,ec=(e,t)=>{b(n=>({...n,[e]:t}))},eu=async t=>{if(en)return void ec("enabled",t);if(Z&&lp(Z.scope)){W(!0),N(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=>lu(e)===lu(i)?i:e)),b(e=>({...e,enabled:i.enabled}))}catch(e){N(e instanceof Error?e.message:String(e))}finally{W(!1)}}},ep=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)}},eh=async e=>{D(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}`);D(n.maxConcurrent)}catch(e){q(e instanceof Error?e.message:String(e))}},ef=async()=>{if(t){Y(!0),q(null);try{await r5(t,{type:"reload"}),V(!1),o?.()}catch(e){q(e instanceof Error?e.message:String(e))}finally{Y(!1)}}};return(0,r.jsxs)(od,{embedded:l,title:a("common.agents"),subtitle:lh(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)(oI,{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:B,disabled:F||O,onChange:e=>D(Number(e.target.value)),onBlur:()=>void eh(B)})]}),(0,r.jsx)(oT,{checked:P,disabled:F||J,loading:O,label:a("agents.builtInTitle"),onChange:e=>void ep(e)})]})]}),(0,r.jsxs)(oc,{children:[(0,r.jsxs)(ou,{children:[(0,r.jsx)(op,{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)(oh,{children:a(`agents.scope.${e}`)}),t.map(e=>{let t,n,i=(t=e.name.toLowerCase(),n=li[e.scope],d.some(e=>e.name.toLowerCase()===t&&li[e.scope]>n));return(0,r.jsxs)(of,{active:m===lu(e)&&!en,onClick:()=>{v(lu(e)),b(lc(e)),k(lp(e.scope)?"edit":"view"),lp(e.scope)&&S(e.scope),N(null)},children:[(0,r.jsx)(oE,{active:e.enabled}),(0,r.jsx)(og,{className:`is-grow${e.enabled?"":" is-muted"}`,children:e.displayName}),i&&(0,r.jsx)("span",{className:"agents-overridden-label",children:a("agents.overridden")})]},lu(e))})]},e)})}),(0,r.jsx)(oM,{active:en,onClick:()=>{let e="custom-agent",t=2;for(;d.some(t=>t.name===e);)e=`custom-agent-${t++}`;v(null),b({...ls,name:e,displayName:e}),k("create"),S("global"),N(null)},children:a("agents.new")})]}),(0,r.jsx)(oS,{children:(0,r.jsx)(ox,{className:"is-fill",children:Z||en?(0,r.jsxs)(ox,{children:[(0,r.jsxs)(om,{children:[(0,r.jsxs)(ov,{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)(oy,{children:[Z&&("view"===w||"edit"===w)&&(0,r.jsx)(oI,{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({...lc(Z),name:e,displayName:a("agents.copyName",{name:Z.displayName})}),k("create"),S(lp(Z.scope)?Z.scope:"global"),N(null)},disabled:T||$,children:a("agents.duplicate")}),Z&&lp(Z.scope)&&"edit"===w&&(0,r.jsx)(oI,{variant:"danger",size:"small",onClick:()=>void ee(),disabled:T||$,children:a("agents.delete")}),(0,r.jsx)(oT,{checked:y.enabled,disabled:er,label:y.enabled?a("agents.disable"):a("agents.enable"),onChange:e=>void eu(e)})]})]}),en&&(0,r.jsx)(lf,{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:T,style:{height:28,border:"none",borderRadius:4,background:j===e?"var(--bg-selected)":"transparent",color:j===e?"var(--text)":"var(--text-muted)",cursor:T?"default":"pointer",fontSize:11,fontWeight:j===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)(lf,{label:a("agents.name"),children:en?(0,r.jsx)("input",{"aria-label":a("agents.name"),value:y.name,disabled:er,onChange:e=>ec("name",e.target.value),style:la}):(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)(lf,{label:a("agents.displayName"),children:(0,r.jsx)("input",{"aria-label":a("agents.displayName"),value:y.displayName,disabled:er,onChange:e=>ec("displayName",e.target.value),style:ed})})]}),(0,r.jsx)(lf,{label:a("agents.description"),children:(0,r.jsx)("input",{"aria-label":a("agents.description"),value:y.description,disabled:er,onChange:e=>ec("description",e.target.value),style:ed})}),(0,r.jsx)(lf,{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=>ec("systemPrompt",e.target.value),style:{...ed,height:195,minHeight:195,maxHeight:"60vh",padding:9,overflow:"auto",resize:er?"none":"vertical",lineHeight:1.5}})}),(0,r.jsx)(lf,{label:a("agents.tools"),children:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 16px"},children:lo.map(e=>(0,r.jsx)(lg,{label:e,disabled:er,checked:y.tools.includes(e),onChange:t=>ec("tools",t?[...y.tools,e]:y.tools.filter(t=>t!==e))},e))})}),(0,r.jsx)(lf,{label:a("agents.resources"),children:(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px 20px"},children:[(0,r.jsx)(lg,{label:a("agents.loadSkills"),disabled:er,checked:y.loadSkills,onChange:e=>ec("loadSkills",e)}),(0,r.jsx)(lg,{label:a("agents.loadExtensions"),disabled:er,checked:y.loadExtensions,onChange:e=>ec("loadExtensions",e)})]})}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:s?"1fr":"minmax(0, 1.5fr) minmax(120px, 0.75fr) minmax(100px, 0.5fr)",gap:12},children:[(0,r.jsx)(lf,{label:a("agents.model"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)(rp,{options:G,value:ea,onChange:(e,t)=>ec("model",`${e}/${t}`),onClear:()=>ec("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"}),g&&(0,r.jsx)("span",{style:{color:"#ef4444",fontSize:10},children:g})]})}),(0,r.jsx)(lf,{label:a("agents.thinking"),children:(0,r.jsx)("select",{"aria-label":a("agents.thinking"),value:y.thinking??"",disabled:er,onChange:e=>ec("thinking",e.target.value||void 0),style:ed,children:ll.map(e=>(0,r.jsx)("option",{value:e,children:e||a("agents.inherit")},e||"default"))})}),(0,r.jsx)(lf,{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=>ec("maxTurns",e.target.value?Number(e.target.value):void 0),style:ed})})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"10px 20px"},children:[(0,r.jsx)(lg,{label:a("agents.inheritContext"),disabled:er,checked:y.inheritContext,onChange:e=>ec("inheritContext",e)}),(0,r.jsx)(lg,{label:a("agents.background"),disabled:er,checked:y.runInBackground,onChange:e=>ec("runInBackground",e)})]})]}):(0,r.jsx)(oj,{children:a("agents.empty")})})})]}),(0,r.jsx)(oC,{status:(_||z)&&(0,r.jsx)("span",{role:"alert",style:{color:"#ef4444"},children:_||z}),children:et&&(0,r.jsxs)(oI,{variant:"primary",onClick:()=>void Q(),disabled:T||E||$||!y.name.trim(),className:E?"is-success":void 0,children:[E&&(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:E?a("i18n.saved"):T?a("agents.saving"):a("agents.save")})]})})]})}function lm(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function lv(e){let t=e.trim().match(/^\$?\s*pi\s+install\s+(\S+)\s*$/);return t?.[1]??e}function ly(e){return`${e.scope}\0${e.source}`}function lb(e){return`extension\0${e.path}`}function lw(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function lk({pkg:e}){let{t}=(0,L.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 lj({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 lS({value:e,projectResourcesLoaded:t,onChange:n}){let{t:i}=(0,L.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 lC({cwd:e,source:t,scope:n,projectResourcesLoaded:o,busy:l,actionError:s,onSourceChange:a,onScopeChange:d,onInstall:c}){let{t:u}=(0,L.s)(),p=(0,i.useRef)(null);return(0,i.useEffect)(()=>{p.current?.focus()},[]),(0,r.jsxs)(ox,{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)(ob,{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?`${lm(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsx)(ok,{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=lv(t);n!==t&&(e.preventDefault(),a(n))},onBlur:e=>a(lv(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)(lS,{value:n,projectResourcesLoaded:o,onChange:d}),(0,r.jsx)(oI,{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 lI({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:f}=(0,L.s)(),g=ly(e),x=n?.endsWith(g)??!1,m="reload"===n,v=!e.disabled,y=e.canCheckForUpdates,b=s?.state==="update-available",w=e.description?.trim();return(0,r.jsxs)(ox,{children:[(0,r.jsxs)(om,{className:"is-top-aligned",children:[(0,r.jsxs)(ov,{children:[(0,r.jsx)(lj,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:f("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:f("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)(oy,{children:[(0,r.jsx)(oI,{size:"small",variant:b?"primary":void 0,onClick:b||!y?()=>c("update",e):u,disabled:x||m||a,title:b?f("i18n.updateAvailable"):void 0,children:f(n===`update:${g}`?"i18n.updating":a?"i18n.checking":b||!y?"i18n.update":"i18n.check")}),(0,r.jsx)(oI,{size:"small",onClick:p,disabled:!l||m||x,title:f(l?"i18n.reloadSession":"i18n.openSessionToReload"),children:f(m?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)(oI,{variant:"danger",size:"small",onClick:()=>c("remove",e),disabled:x||m,children:f(n===`remove:${g}`?"i18n.removing":"i18n.remove")}),(0,r.jsx)(oT,{checked:v,loading:x||m,onChange:()=>c(e.disabled?"enable":"disable",e),label:f(e.disabled?"i18n.enablePackage":"i18n.disablePackage")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[w&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.description")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",overflowWrap:"anywhere"},children:w})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.status")}),(0,r.jsx)("div",{style:{color:lw(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.version")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsxs)("div",{className:"skill-version-row",children:[(0,r.jsx)("span",{className:"skill-version-value",children:(h=[],e.version&&h.push(f("i18n.installedVersion",{version:e.version})),e.configuredVersion&&h.push(f("i18n.configuredVersion",{version:e.configuredVersion})),h.length?h.join(" \xb7 "):f("i18n.unknown"))}),b&&(0,r.jsx)("span",{className:"skill-version-value is-update",title:s.displayName,children:f("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?f("i18n.checking"):s?.state==="up-to-date"?f("i18n.upToDate"):s?.state==="unsupported"?f("i18n.automaticChecksUnavailable"):s?.message||f("i18n.checkFailed")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??f("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:function(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}(e,f)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?lm(e.installedPath):f("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:f("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:lm(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)(ow,{children:f("i18n.resolvedResources")}),(0,r.jsx)(lk,{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 lT({extension:e}){let{t}=(0,L.s)(),n=e.enabled?"loaded":"disabled";return(0,r.jsxs)(ox,{children:[(0,r.jsx)(om,{children:(0,r.jsxs)(ov,{children:[(0,r.jsx)(lj,{scope:e.scope}),(0,r.jsx)(ob,{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:lm(e.path)})]})]})}function lM({cwd:e,sessionId:t,onClose:n,onReloaded:o,embedded:l=!1}){let{t:s}=(0,L.s)(),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(()=>or("plugins",e)),[x,m]=(0,i.useState)(!1),[v,y]=(0,i.useState)(""),[b,w]=(0,i.useState)("global"),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)(null),[I,T]=(0,i.useState)(null),[M,E]=(0,i.useState)({}),[R,$]=(0,i.useState)(new Set),[W,z]=(0,i.useState)(!1),[N,P]=(0,i.useState)(null),[A,B]=(0,i.useState)(!1),D=(0,i.useMemo)(()=>a?.packages??[],[a?.packages]),F=(0,i.useMemo)(()=>a?.standaloneExtensions??[],[a?.standaloneExtensions]),H=D.find(e=>ly(e)===f)??null,O=F.find(e=>lb(e)===f)??null,U=a?.projectResourcesLoaded??!0,_=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:D.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[D]),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),g(e=>e&&(n.packages.some(t=>ly(t)===e)||n.standaloneExtensions.some(t=>lb(t)===e))?e:n.packages[0]?ly(n.packages[0]):n.standaloneExtensions[0]?lb(n.standaloneExtensions[0]):null)}catch(e){h(e instanceof Error?e.message:String(e))}finally{u(!1)}},[e]);(0,i.useEffect)(()=>{E({}),P(null),q()},[e]),(0,i.useEffect)(()=>{f&&oi("plugins",f,e)},[e,f]);let K=(0,i.useCallback)(async t=>{let n=(t?[t]:D.filter(e=>e.canCheckForUpdates)).map(ly);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}`);E(e=>{let t={...e};for(let e of r.updates??[])t[ly(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,D]),V=(0,i.useCallback)(async()=>{B(!0),C(null),T(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),E({}),T(s("i18n.packagesUpdated")),t&&T(`${s("i18n.packagesUpdated")} ${s("agents.reloadRequired")}`)}catch(e){C(e instanceof Error?e.message:String(e))}finally{B(!1)}},[e,t,s]),J=(0,i.useCallback)(async(t,n)=>{let r=ly(n);j(`${t}:${r}`),C(null),T(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),o=await i.json();if(!i.ok||o.error)throw Error(o.error??`HTTP ${i.status}`);d(o),"remove"===t?(g(o.packages[0]?ly(o.packages[0]):o.standaloneExtensions[0]?lb(o.standaloneExtensions[0]):null),0===o.packages.length&&0===o.standaloneExtensions.length&&m(!0),T("Package removed."),E(e=>{let t={...e};return delete t[r],t})):(T({install:"Package installed.",update:"Package updated.",disable:"Package disabled.",enable:"Package enabled."}[t]),"update"===t&&E(e=>{let t={...e};return delete t[r],t}))}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(null)}},[e]),Y=(0,i.useCallback)(async()=>{let t=lv(v).trim();if(!t)return;y(t);let n=`${b}\0${t}`;j(`install:${n}`),C(null),T(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)));g(a?ly(a):n),m(!1),y(""),T("Package installed.")}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(null)}},[e,b,v]),Z=(0,i.useCallback)(async()=>{if(t){j("reload"),C(null),T(null);try{await r5(t,{type:"reload"}),o?.(),await q(),T("Session reloaded.")}catch(e){C(e instanceof Error?e.message:String(e))}finally{j(null)}}},[q,o,t]),G=k?.startsWith("install:")??!1,X=Object.values(M).filter(e=>"update-available"===e.state).length,Q=D.some(e=>e.canCheckForUpdates),ee=c||null!==k||R.size>0||A;return(0,r.jsxs)(od,{embedded:l,title:s("common.plugins"),subtitle:lm(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)(oc,{children:[(0,r.jsxs)(ou,{children:[(0,r.jsx)(op,{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===D.length&&0===F.length?(0,r.jsx)("div",{className:"config-sidebar-message is-empty",children:"No plugins configured"}):(0,r.jsxs)(r.Fragment,{children:[F.length>0&&(0,r.jsxs)("div",{className:"config-sidebar-group",children:[(0,r.jsx)(oh,{children:s("i18n.extensions")}),F.map(e=>{let t=lb(e);return(0,r.jsxs)(of,{active:!x&&f===t,title:e.path,onClick:()=>{g(t),m(!1),C(null),T(null)},children:[(0,r.jsx)(oE,{active:e.enabled}),(0,r.jsx)(og,{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)(oh,{children:e.scope}),e.packages.map(e=>{let t=ly(e),n=!x&&f===t;return(0,r.jsxs)(of,{active:n,title:e.description??e.source,onClick:()=>{g(t),m(!1),C(null),T(null)},children:[(0,r.jsx)(oE,{active:!e.disabled,color:lw(e.status)}),(0,r.jsx)(og,{className:`is-grow${e.disabled?" is-muted":""}`,children:e.source}),M[ly(e)]?.state==="update-available"&&(0,r.jsx)("span",{title:s("i18n.updateAvailable"),className:"skill-update-indicator",children:"↑"})]},t)})]},e.scope))]})}),(0,r.jsx)(oM,{active:x,onClick:()=>{m(!0),C(null),T(null)},children:s("i18n.addPlugin")})]}),(0,r.jsx)(oS,{children:(0,r.jsx)(ox,{className:"is-fill",children:x?(0,r.jsx)(lC,{cwd:e,source:v,scope:b,projectResourcesLoaded:U,busy:G,actionError:S,onSourceChange:y,onScopeChange:w,onInstall:Y}):c?null:O?(0,r.jsx)(lT,{extension:O}):H?(0,r.jsx)(lI,{pkg:H,cwd:e,busyKey:k,actionError:S,actionMessage:I,sessionId:t,updateStatus:M[ly(H)],checkingUpdate:R.has(ly(H)),updateError:N,onAction:J,onCheckUpdate:()=>void K(H),onReloadSession:Z},ly(H)):(0,r.jsx)(oj,{children:s("i18n.selectPackage")})})})]}),(0,r.jsxs)(oC,{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)(oI,{onClick:n,children:s("i18n.close")}),Q&&(0,r.jsx)(oI,{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"):W?s("i18n.checking"):X>0?`${s("i18n.updateAllPlugins")} (${X})`:s("i18n.checkUpdates")}),(0,r.jsx)(oI,{variant:"secondary",onClick:()=>void q(),disabled:ee,children:s("i18n.refresh")})]})]})}function lE({section:e,size:t=16,strokeWidth:n=1.8}){let i={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"settings-section-icon"};return"general"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("path",{d:"M20 7h-9M14 17H5"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"3"}),(0,r.jsx)("circle",{cx:"17",cy:"17",r:"3"})]}):"models"===e?(0,r.jsxs)("svg",{...i,children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("path",{d:"M9 1v3M15 1v3M9 20v3M15 20v3M20 9h3M20 15h3M1 9h3M1 15h3"})]}):"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"})]}):(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 lR({sessionId:e,onSessionReloaded:t,quoteSelectionEnabled:n,onQuoteSelectionChange:o}){let{locale:l,setLocale:s,supportedLocales:a,t:d}=(0,L.s)(),{preference:c,setThemePreference:u}=tG(),{width:p,setWidth:h,fontSize:f,setFontSize:g}=rd(),[x,m]=(0,i.useState)(null),[v,y]=(0,i.useState)(!1),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,E]=(0,i.useState)(!1),[R,$]=(0,i.useState)(!1),[W,z]=(0,i.useState)("");(0,i.useEffect)(()=>{j(nr()),fetch("/api/web-auth").then(e=>e.ok?e.json():null).then(e=>E(e?.enabled===!0)).catch(()=>{})},[]);let N=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||w(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[]);let P=async n=>{y(!0),w(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 r5(e,{type:"reload"}),t())}catch(e){w(e instanceof Error?e.message:String(e))}finally{y(!1)}},A=async()=>{if(!S){C(!0),T(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 o5(l))throw Error("unsupported or not permitted");T({kind:"ok",message:d("settings.pushRegistered")})}catch(e){T({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:tN.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)(i6,{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)(oT,{checked:k,label:d("settings.thinkingExpandedDefault"),onChange:e=>{window.localStorage.setItem(nt,String(e)),window.dispatchEvent(new Event(nn)),j(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)(oI,{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:[f,"px"]}),(0,r.jsx)(oI,{variant:"ghost",size:"small",className:"settings-chat-reset",title:d("settings.resetChatContentFontSize"),"aria-label":d("settings.resetChatContentFontSize"),disabled:14===f,onClick:()=>g(14),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5"})})})]}),(0,r.jsx)("input",{id:"settings-chat-content-font-size",type:"range",min:12,max:24,step:1,value:f,onChange:e=>g(Number(e.target.value))})]}),(0,r.jsxs)("div",{className:"settings-chat-option settings-chat-switch-option",children:[(0,r.jsx)("span",{children:d("settings.quoteSelection")}),(0,r.jsx)(oT,{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)(oT,{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")})]}),I&&(0,r.jsx)("p",{role:"status",className:"settings-general-error",style:"ok"===I.kind?{color:"var(--accent)"}:void 0,children:I.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)})})]}),M&&(0,r.jsxs)("section",{className:"settings-general-section",children:[(0,r.jsxs)(oI,{variant:"secondary",disabled:R,onClick:()=>void N(),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"})}),R?d("auth.loggingOut"):d("auth.logOut")]}),W&&(0,r.jsx)("p",{role:"alert",className:"settings-general-error",children:W})]})]})}function lL({cwd:e,sessionId:t,initialSection:n,onClose:o,onSessionReloaded:l,quoteSelectionEnabled:s,onQuoteSelectionChange:a}){let{t:d}=(0,L.s)(),[c,u]=(0,i.useState)(n),[p,h]=(0,i.useState)(()=>new Set([c])),f=[{id:"general",label:d("settings.general"),requiresProject:!1},{id:"models",label:d("common.models"),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)(()=>on(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"!==c&&"agents"!==c&&"plugins"!==c||(u("general"),h(e=>new Set(e).add("general")),on("general"))},[e,c]);let g=e=>{h(t=>new Set(t).add(e)),u(e),on(e)},x=(e,t)=>p.has(e)?(0,r.jsx)("div",{hidden:c!==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:c,onChange:e=>g(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=c===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:()=>g(t.id),children:[(0,r.jsx)(lE,{section:t.id}),(0,r.jsx)("span",{children:t.label})]},t.id)})}),(0,r.jsx)("button",{type:"button",onClick: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:[x("general",(0,r.jsx)(lR,{sessionId:t,onSessionReloaded:l,quoteSelectionEnabled:s,onQuoteSelectionChange:a})),x("models",(0,r.jsx)(o8,{embedded:!0,onClose:o})),e&&x("skills",(0,r.jsx)(lr,{embedded:!0,cwd:e,onClose:o},e)),e&&x("agents",(0,r.jsx)(lx,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e)),e&&x("plugins",(0,r.jsx)(lM,{embedded:!0,cwd:e,sessionId:t,onClose:o,onReloaded:l},e))]})]})})}function l$({cwd:e,busy:t,error:n,onCancel:i,onConfirm:o}){let{t:l}=(0,L.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 lW(e){return"message"===e.type&&"message"in e}function lz(e){let t=e,n=t.branchPreview,r=lW(t.entry)?t.entry:null,i=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&lW(t.entry)&&(r=t.entry),i+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:i,branchPreview:n,labelEntry:r??t.entry}}function lN(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 lP({node:e,activePathIds:t,depth:n,isLast:i,parentLines:o,onSelect:l}){let{node:s,skipped:a,branchPreview:d,labelEntry:c}=lz(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),f=d?d.role??null:lW(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"}}),f&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===f?"var(--accent)":"var(--text-dim)",background:"user"===f?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===f?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===f?"U":"A"}),a>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",a]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":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)(lP,{node:e,activePathIds:t,depth:n+1,isLast:a===s.children.length-1,parentLines:[...o,!i],onSelect:l},e.entry.id))]})}function lA({tree:e,activeLeafId:t,onLeafChange:n,inline:o,containerRef:l,open:s,onToggle:a,hasSession:d,compact:c,hideInlineButton:u}){let{t:p}=(0,L.s)(),[h,f]=(0,i.useState)(!1),g=void 0!==s?s:h,x=(0,i.useRef)(null),[m,v]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!g||!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()},[g,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]),w=d?lN(e)?null:p("i18n.noBranches"):p("i18n.noActiveSession"),k=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=lz(e[0]).node;return t.children.length>1?t.children:[]}(e),j=!w&&k.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:j?"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:g?"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():f(e=>!e),style:{display:u?"none":"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:g?"var(--bg-selected)":"none",border:"none",borderTop:g?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:g?"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=g?"var(--text)":"var(--text-muted)"},title:p("i18n.branches"),"aria-label":p("i18n.branches"),"aria-pressed":g,children:[S,!c&&(0,r.jsx)("span",{children:p("i18n.branches")})]}),g&&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:j?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:k.map((e,t)=>(0,r.jsx)(lP,{node:e,activePathIds:y,depth:0,isLast:t===k.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:w})})]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>f(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]}),g&&(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:j?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:k.map((e,t)=>(0,r.jsx)(lP,{node:e,activePathIds:y,depth:0,isLast:t===k.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:w??p("i18n.noBranches")})})]})}function lB({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 lD(e){if("string"==typeof e)return e;if(void 0===e)return"";try{return JSON.stringify(e)}catch{return String(e)}}function lF({children:e}){return(0,r.jsx)("div",{className:"tool-definitions-empty",children:e})}function lH({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 lD(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(lD).join(", "):void 0,defaultValue:void 0===r.default?void 0:lD(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)(lF,{children:n("tools.noTools")}):(0,r.jsx)(lF,{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)(lF,{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 lO(e){return e.name||e.firstMessage||e.id.slice(0,12)}function lU({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 l_({session:e,main:t,selected:n,running:i,onSelect:o}){let{locale:l,t:s}=(0,L.s)(),a=e.relation?.kind==="subagent"?e.relation:null,d=i?"running":a?.status??"completed",c=t?s("agentSwitcher.main"):a?.description||lO(e),u=t?lO(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)(lU,{status:d}),(0,r.jsx)("span",{children:s(`agentSwitcher.status.${d}`)})]})})]})}function lq({rootSession:e,subagents:t,selectedSessionId:n,runningSessionIds:o,onSelectSession:l}){let{t:s}=(0,L.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)(l_,{session:e,main:!0,selected:e.id===n,running:o.has(e.id),onSelect:()=>l(e)}),p.map(e=>(0,r.jsx)(l_,{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 lK=n(63606),lV=n(8422);async function lJ(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 lY({tab:e,active:t,onRestart:n,onClosed:o,onCloseError:l}){let{t:s}=(0,L.s)(),{id:a,cwd:d,restored:c}=e,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(Promise.resolve()),f=(0,i.useRef)(null),g=(0,i.useRef)({onClosed:o,onCloseError:l});g.current={onClosed:o,onCloseError:l};let[x,m]=(0,i.useState)("connecting"),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(null),[k,j]=(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,g=null,x=!1,v=!1,b=!1;m("connecting"),y(null),w(null);let j=new lV.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=j;let S=new lK.Y;j.loadAddon(S),j.open(l),j.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&&j.hasSelection())});let C=(e=e=>{s||(b=!0,j.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 lJ(`/api/terminal/${encodeURIComponent(a)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}))}).catch(t=>{r=!0,e(t)}))},{write(e){if(!r)for(let t of e.match(/[\s\S]{1,32768}/gu)??[])i&&i.data.length+t.length<=65536?i.data+=t:o(i={type:"input",data:t})},resize(e,t){i=null,o({type:"resize",cols:e,rows:t})},stop:()=>(r=!0,i=null,n)});f.current=C;let I=j.onData(e=>{!x||v||b||C.write(e)}),T=()=>{l.offsetWidth&&l.offsetHeight&&S.fit()},M=j.onResize(({cols:e,rows:t})=>{!x||v||b||C.resize(e,t)}),E=new ResizeObserver(T);E.observe(l);let R=()=>{s||v||!navigator.onLine||(g?.close(),(g=new EventSource(`/api/terminal/${encodeURIComponent(a)}/events${void 0===t?"":`?after=${t}`}`)).onmessage=e=>{let n=JSON.parse(e.data);if("output"===n.type){if(n.reset)j.reset();else if(void 0!==t&&n.offset<=t)return;j.write(n.data),t=n.offset}else v=!0,x=!1,j.options.disableStdin=!0,g?.close(),w("exit"===n.type?n.exitCode:null),m("exited")},g.onopen=()=>{x=!0,!b&&(j.options.disableStdin=!1,m("ready"),T(),C.resize(j.cols,j.rows),l.offsetWidth&&l.offsetHeight&&j.focus())},g.onerror=()=>{s||v||(x=!1,j.options.disableStdin=!0,m(g?.readyState===EventSource.CLOSED?"error":"connecting"))})};h.current=(async()=>{T(),c||k>0?await lJ(`/api/terminal/${encodeURIComponent(a)}`):await lJ("/api/terminal",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:a,cwd:d,cols:j.cols,rows:j.rows})}),R()})().catch(e=>{s||(y(e.message),m("error"))});let L=()=>{x=!1,j.options.disableStdin=!0,g?.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,g?.close(),C.stop(),E.disconnect(),I.dispose(),M.dispose(),window.removeEventListener("pagehide",L),window.removeEventListener("pageshow",$),window.removeEventListener("offline",L),window.removeEventListener("online",R),j.dispose(),p.current=null}},[a,d,c,k]),(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 f.current?.stop(),await lJ(`/api/terminal/${encodeURIComponent(a)}`,{method:"DELETE",keepalive:!0}),t||g.current.onClosed()})().catch(e=>{t||(y(e.message),m("error"),g.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:()=>j(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 lZ="pi-web:terminal-tabs";function lG(e){return{id:Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join(""),cwd:e}}function lX({id:e,label:t,running:n,hasBadge:i,focused:o,onClick:l,onClose:s}){return(0,r.jsxs)("button",{type:"button",id:e,role:"tab","aria-selected":o,onClick:l,title:t,style:{display:"flex",alignItems:"center",gap:6,width:"100%",height:30,padding:"0 10px 0 8px",flexShrink:0,border:"none",borderTop:o?"2px solid var(--accent)":"2px solid transparent",borderBottom:"1px solid var(--border)",background:o?"var(--bg-selected)":"var(--bg-panel)",color:o?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontFamily:"inherit",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",transition:"background 0.1s, color 0.1s"},children:[n&&(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"var(--accent)",flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,flex:"1 1 auto",overflow:"hidden",textOverflow:"ellipsis",textAlign:"left"},children:t}),i&&(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#f59e0b",flexShrink:0},"aria-label":"completed"}),(0,r.jsx)("span",{role:"button",tabIndex:0,"aria-label":"Close tab",onClick:e=>{e.stopPropagation(),s()},onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.stopPropagation(),e.preventDefault(),s())},style:{display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,borderRadius:4,fontSize:11,lineHeight:1,color:"var(--text-dim)",cursor:"pointer",flexShrink:0,marginLeft:2},children:"\xd7"})]})}function lQ(e){return e.sessionId===l2?`${e.label} \xb7 ${e.projectName}`:`${e.projectName} \xb7 ${e.label}`}function l0(e,t){return!Number.isFinite(e)||e<=0?1:!Number.isFinite(t)||t<=0?Number.MAX_SAFE_INTEGER:Math.max(1,Math.floor(e/t))}function l1(e,t,n,r){return e.find(e=>e.sessionId===t)?e:[...e,{sessionId:t,label:n,projectName:r,hasBadge:!1}]}let l2="__new-session__";function l4(e,t){return e.map(e=>e.sessionId===t?{...e,hasBadge:!1}:e)}let l8=(0,i.forwardRef)(function({tabs:e,focusedId:t,runningSessionIds:n,onFocusPane:o,onClosePane:l,renderPane:s},a){var d;let{t:c}=(0,L.s)(),u=(0,i.useRef)(null),p=(0,i.useRef)(new Map),h=(0,i.useRef)(null),f=(0,i.useRef)(null),[g,x]=(0,i.useState)(!1),[m,v]=(0,i.useState)(()=>window.innerWidth);(0,i.useEffect)(()=>{let e=u.current;if(!e||"u"<typeof ResizeObserver)return;let t=new ResizeObserver(()=>{v(e.clientWidth)});return t.observe(e),()=>t.disconnect()},[]);let y=(d=e.length,d<=1?m:!Number.isFinite(520)||d<=l0(m,520)?m/d:520),b=l0(m,520),w=e.length>b;(0,i.useEffect)(()=>{w||x(!1)},[w]);let k=(0,i.useCallback)(e=>{let t=u.current,n=p.current.get(e);if(!t||!n)return;let r=n.offsetLeft;t.scrollTo({left:r,behavior:"smooth"})},[]);(0,i.useImperativeHandle)(a,()=>({scrollPaneIntoView:k}),[k]);let j=(0,i.useCallback)(e=>{window.getSelection()?.toString()||o(e)},[o]),S=(0,i.useCallback)(e=>{x(!1),k(e),o(e),h.current?.focus()},[k,o]);(0,i.useEffect)(()=>{if(!g)return;let e=f.current?.querySelector("[role='menuitem']");e?.focus()},[g]);let C=(0,i.useCallback)(e=>{if("Escape"===e.key){e.preventDefault(),x(!1),h.current?.focus();return}if("ArrowDown"!==e.key&&"ArrowUp"!==e.key)return;e.preventDefault();let t=Array.from(f.current?.querySelectorAll("[role='menuitem']")??[]);if(0===t.length)return;let n=t.findIndex(e=>e===document.activeElement),r=t[(n+("ArrowDown"===e.key?1:-1)+t.length)%t.length];r?.focus()},[]);return(0,r.jsxs)("div",{style:{flex:1,height:"100%",display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden",position:"relative"},children:[(0,r.jsx)("div",{ref:u,role:"tablist","data-split-pane-area":"true",style:{flex:"1 1 0",display:"flex",flexDirection:"row",overflowX:"auto",overflowY:"hidden",minHeight:0},children:e.map(e=>(0,r.jsxs)("div",{ref:t=>{t?p.current.set(e.sessionId,t):p.current.delete(e.sessionId)},onPointerUp:()=>j(e.sessionId),style:{width:`${y}px`,flex:"none",minWidth:0,height:"100%",overflow:"hidden",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column"},children:[(0,r.jsx)(lX,{id:`pane-tab-${e.sessionId}`,label:lQ(e),running:n.has(e.sessionId),hasBadge:e.hasBadge,focused:e.sessionId===t,onClick:()=>{k(e.sessionId),o(e.sessionId)},onClose:()=>l(e.sessionId)}),(0,r.jsx)("div",{role:"tabpanel",id:`pane-panel-${e.sessionId}`,"aria-labelledby":`pane-tab-${e.sessionId}`,style:{flex:"1 1 0",minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s(e.sessionId,e.sessionId===t)})]},e.sessionId))}),w&&(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{"data-pane-overflow-backdrop":!0,onClick:()=>x(!1),style:{position:"absolute",inset:0,zIndex:55}}),(0,r.jsxs)("div",{"data-pane-overflow":!0,style:{position:"absolute",top:4,left:4,zIndex:60},children:[(0,r.jsxs)("button",{ref:h,type:"button","data-pane-overflow-trigger":!0,"aria-haspopup":"menu","aria-expanded":g,title:c("tabs.openPanes"),"aria-label":c("tabs.openPanes"),onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},style:{display:"flex",alignItems:"center",gap:4,height:22,padding:"0 7px",borderRadius:6,background:"var(--bg-panel)",border:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontFamily:"inherit",lineHeight:1},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"1.5",y:"2.5",width:"9",height:"7",rx:"1"}),(0,r.jsx)("line",{x1:"1.5",y1:"5",x2:"10.5",y2:"5"})]}),e.length]}),g&&(0,r.jsx)("div",{ref:f,role:"menu","data-pane-overflow-menu":!0,onKeyDown:C,style:{position:"absolute",top:26,left:0,minWidth:180,maxHeight:260,overflowY:"auto",display:"flex",flexDirection:"column",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,boxShadow:"0 4px 16px rgba(0,0,0,0.25)",padding:4,zIndex:60},children:e.map(e=>(0,r.jsxs)("button",{type:"button",role:"menuitem","data-pane-overflow-item":e.sessionId,onClick:()=>S(e.sessionId),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px",border:"none",borderRadius:4,background:"transparent",color:e.sessionId===t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontFamily:"inherit",textAlign:"left",whiteSpace:"nowrap"},children:[n.has(e.sessionId)&&(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"var(--accent)",flexShrink:0},"aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,flex:"1 1 auto",overflow:"hidden",textOverflow:"ellipsis"},children:lQ(e)}),e.hasBadge&&(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"#f59e0b",flexShrink:0},"aria-label":"completed"})]},e.sessionId))})]})]})]})}),l6="pi-web:split-view-enabled";function l5(){try{return"false"!==window.localStorage.getItem(l6)}catch{return!0}}function l3(e){return`parked-new:${e}`}function l9(){let e,t,n,d,c,u,p,y,b,w,k,j,S,I=(0,o.useRouter)(),T=(0,o.useSearchParams)(),[M]=(0,i.useState)(()=>{let e;return{requestedCwd:e=T.get("cwd")?.trim()||null,sessionId:e?null:T.get("session"),sidebarCollapsed:"collapsed"===T.get("sidebar")}});tG();let{locale:E,t:R}=(0,L.s)(),W=n4(),N=n8();(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")}},[]);let P=(0,i.useRef)("unrequested"),[A,B]=(0,i.useState)(l5),D=(0,i.useCallback)(e=>{B(e);try{window.localStorage.setItem(l6,e?"true":"false")}catch{}},[]),[F,H]=(0,i.useState)([]),[O,U]=(0,i.useState)(null),_=(0,i.useRef)(0),q=(0,i.useRef)(null),K=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(F.length>K.current&&F.length>0){let e=F[F.length-1].sessionId;q.current?.scrollPaneIntoView(e)}K.current=F.length},[F]),(0,i.useEffect)(()=>{"Notification"in window&&"granted"===Notification.permission&&o5(E)},[E]);let{soundEnabled:V,onSoundToggle:Y,playDoneSound:Z,unlockAudio:G,soundEnabledRef:X}=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}}(),[Q,ee]=(0,i.useState)(!1);(0,i.useEffect)(()=>{try{ee("true"===localStorage.getItem("pi-quote-selection-enabled"))}catch{}},[]);let en=(0,i.useCallback)(e=>{ee(e);try{localStorage.setItem("pi-quote-selection-enabled",String(e))}catch{}},[]),er=(0,i.useRef)(new Set),ei=(0,i.useCallback)(()=>{X.current&&Z()},[Z,X]),[el,es]=(0,i.useState)(null),[ea,ed]=(0,i.useState)(!1),[ec,eu]=(0,i.useState)(null),ep=(0,i.useRef)(null);(0,i.useEffect)(()=>{O&&O!==l2&&(ep.current=O)},[O]);let eh=(0,i.useMemo)(()=>(function({splitPaneEnabled:e,focusedPaneId:t,selectedSessionId:n,lastSessionPaneId:r,paneTabs:i}){if(!e)return n;if(t&&t!==l2)return t;let o=new Set(i.filter(e=>e.sessionId!==l2).map(e=>e.sessionId));if(r&&o.has(r))return r;let l=i.find(e=>e.sessionId!==l2);return l?l.sessionId:n})({splitPaneEnabled:A&&!W,focusedPaneId:O,selectedSessionId:el?.id??null,lastSessionPaneId:ep.current,paneTabs:F}),[A,W,O,el?.id,F]),ef=(0,i.useRef)(null);ef.current=eh;let{state:eg,logs:ex,runningCount:em,refresh:ev,applyEvent:ey,fetchLogs:eb,killTask:ew}=function(e,t){let[n,r]=(0,i.useState)({kind:"loading"}),[o,l]=(0,i.useState)({}),s=(0,i.useRef)(0),a=(0,i.useCallback)(()=>{if(!e||!t)return;let n=++s.current;r(e=>"ready"===e.kind?e:{kind:"loading"}),fetch(`/api/agent/${encodeURIComponent(e)}/bg-tasks`).then(async e=>{let t=await e.json();if(n===s.current){if(!e.ok)return void r({kind:"unavailable",error:t.error??`HTTP ${e.status}`});r({kind:"ready",tasks:(t.tasks??[]).filter(e=>"string"==typeof e?.id)})}}).catch(e=>{n===s.current&&r({kind:"unavailable",error:e instanceof Error?e.message:String(e)})})},[e,t]);(0,i.useEffect)(()=>{if(!e)return void r({kind:"unavailable",error:"no active session"});let t=s.current;return a(),()=>{s.current=t+1}},[e,a]);let d=(0,i.useCallback)(e=>{"background_tasks_update"===e.type?r({kind:"ready",tasks:e.tasks}):"background_task_terminal"===e.type&&a()},[a]),c=(0,i.useCallback)(async(t,n)=>{if(!e)return;let r=new URLSearchParams({...void 0!==n?{maxBytes:String(n)}:{}}),i=await fetch(`/api/agent/${encodeURIComponent(e)}/bg-tasks/${encodeURIComponent(t)}/logs?${r}`),o=await i.json();i.ok?l(e=>({...e,[t]:o})):l(e=>({...e,[t]:{text:o.error??`HTTP ${i.status}`,bytesRead:0,truncated:!1,tail:!0}}))},[e]),u=(0,i.useCallback)(async t=>{if(!e)return;let n=await fetch(`/api/agent/${encodeURIComponent(e)}/bg-tasks/${encodeURIComponent(t)}/kill`,{method:"POST"});if(!n.ok){let e=await n.json().catch(()=>null);throw Error(e?.error??`HTTP ${n.status}`)}a()},[e,a]),p="ready"===n.kind?n.tasks.filter(e=>"running"===e.status).length:0;return{state:n,logs:o,runningCount:p,refresh:a,applyEvent:d,fetchLogs:c,killTask:u}}(eh,ea),ek=(0,i.useCallback)((e,t)=>{var n;let r=e===ef.current;if(r&&ey(t),"background_task_terminal"!==t.type)return;let i=t.task;n=i.id,!s.has(n)&&(s.add(n),1)&&(r&&eu(i.id),rQ()&&r1({title:R("bgTasks.notification.title"),body:R("bgTasks.notification.body").replace("{name}",i.name||i.id).replace("{status}",R(`bgTasks.status.${i.status}`)),sessionUrl:`/?session=${encodeURIComponent(e)}`,tag:`pi-bg-task:${i.id}`,onClick:()=>{window.focus(),ed(!0),eu(i.id)}}))},[ey,R]),[ej,eS]=(0,i.useState)([]),eC=(0,i.useCallback)(e=>{eS(e)},[]),[eI,eT]=(0,i.useState)(null),eM=(0,i.useCallback)(e=>{eT(t=>({sessionId:e,key:(t?.key??0)+1}))},[]),eE=(0,i.useMemo)(()=>el?[...ej.filter(e=>e.id!==el.id),el]:ej,[el,ej]),eR=(0,i.useMemo)(()=>{var e;return(e=el?.id)?a(eE).find(t=>t.root.id===e||t.subagents.some(t=>t.id===e))??null:null},[el?.id,eE]),eL=!!eR?.subagents.length,[e$,eW]=(0,i.useState)(()=>new Set),ez=(0,i.useCallback)(e=>{eW(t=>t.size===e.size&&[...e].every(e=>t.has(e))?t:e)},[]),[eN,eP]=(0,i.useState)(null),[eA,eB]=(0,i.useState)("initial"),eF=(0,i.useRef)(null),[eH,eO]=(0,i.useState)(()=>M.requestedCwd?"validating":"idle"),[eU,e_]=(0,i.useState)(null),[eq,eK]=(0,i.useState)(0),[eV,eJ]=(0,i.useState)(0),eY=(0,i.useRef)(new Map),eZ=(0,i.useCallback)((e,t)=>{eY.current.set(e,t)},[]),[eG,eX]=(0,i.useState)(null),eQ=(0,i.useCallback)(e=>{eX(t=>t===e?null:t)},[]),[e0,e1]=(0,i.useState)(0),[e2,e4]=(0,i.useState)(null),[e8,e6]=(0,i.useState)(0),[e5,e3]=(0,i.useState)(null),[e9,e7]=(0,i.useState)(!1),[te,tt]=(0,i.useState)(!1),[tn,tr]=(0,i.useState)(null),[ti,to]=(0,i.useState)(()=>!M.sidebarCollapsed),[tl,ts]=(0,i.useState)(!1),[ta,td]=(0,i.useState)(null),[tc,tu]=(0,i.useState)(!1),tp=tl&&tc&&!W;(0,i.useEffect)(()=>{(!tl||W)&&tu(!1)},[tl,W]),(0,i.useEffect)(()=>{tl||td(null)},[tl]);let[th,tf]=(0,i.useState)(!1),[tg,tx]=(0,i.useState)(!1),tm=(0,i.useRef)(260),tv=(0,i.useRef)(560),ty=(0,i.useCallback)(()=>$(.42*window.innerWidth,360,640),[]),tb=(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:tl,rightPanelWidth:tv.current}),[tl]),tw=(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:ti,sidebarWidth:tm.current}),[ti]),tk=z({ariaLabel:R("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:tb,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"pi-sidebar-width",widthRef:tm}),tj=z({ariaLabel:R("layout.resizeFilePanel"),cssVariable:"--right-panel-width",defaultWidth:560,getDefaultWidth:ty,getMaxWidth:tw,growthDirection:"left",maxWidth:1200,minWidth:300,storageKey:"pi-right-panel-width",widthRef:tv}),tS=tk.reclampWidth,tC=tj.reclampWidth;(0,i.useEffect)(()=>{W&&to(!1)},[W]),(0,i.useEffect)(()=>{tx(!0)},[]),(0,i.useEffect)(()=>{tl&&(tS(),tC())},[tC,tS,tl]);let tI=(0,i.useRef)(null),tT=(0,i.useRef)(new Map),tM=(0,i.useCallback)(e=>{let t=tT.current,n=t.get(e);return n||(n={current:null},t.set(e,n)),n},[]),tE=(0,i.useCallback)(e=>{tT.current.delete(e)},[]);(0,i.useEffect)(()=>{let e=new Set(F.map(e=>e.sessionId));for(let t of tT.current.keys())e.has(t)||tT.current.delete(t)},[F]);let tR=(0,i.useCallback)(()=>A&&!W&&O?tT.current.get(O)?.current??null:tI.current,[A,W,O]),[tL,t$]=(0,i.useState)(null),tW=(0,i.useRef)(null),tz=(0,i.useRef)(null),[tN,tP]=(0,i.useState)([]),[tA,tB]=(0,i.useState)(null),tD=(0,i.useRef)(null),tF=lN(tN),tH=(0,i.useCallback)((e,t,n)=>{tP(e),tB(t),tD.current=n},[]),tO=(0,i.useCallback)(e=>{tD.current?.(e)},[]),[tU,t_]=(0,i.useState)(null),[tq,tK]=(0,i.useState)(null),[tV,tJ]=(0,i.useState)(!1),tY=(0,i.useRef)(null),tZ=(0,i.useRef)(0),tQ=(0,i.useRef)(null),t0=(0,i.useCallback)(e=>{t_(e),tJ(!1)},[]),t1=(0,i.useCallback)(e=>{tK(e)},[]),t2=(0,i.useCallback)(e=>{tZ.current+=1,tY.current=e,tJ(!1)},[]),[t4,t8]=(0,i.useState)(null),[t6,t5]=(0,i.useState)({kind:"idle"}),t3=(0,i.useRef)(null),t9=(0,i.useRef)(el?.id??null);t9.current=el?.id??null;let t7=(0,i.useCallback)(e=>{t8(e)},[]),[ne,nt]=(0,i.useState)(null),nn=(0,i.useRef)(null),nr=(0,i.useCallback)((e,t)=>{tX(t).then(()=>{nn.current&&clearTimeout(nn.current),nt(e),nn.current=setTimeout(()=>nt(null),1400)})},[]);(0,i.useEffect)(()=>()=>{nn.current&&clearTimeout(nn.current),t3.current&&clearTimeout(t3.current)},[]);let[ni,no]=(0,i.useState)(null),nl=(0,i.useCallback)(e=>{no(e)},[]),[ns,na]=(0,i.useState)(null),[nd,nc]=(0,i.useState)(null);(0,i.useEffect)(()=>{tF||na(e=>"branches"===e?null:e)},[tF]),(0,i.useEffect)(()=>{eL||na(e=>"agents"===e?null:e)},[eL]),(0,i.useEffect)(()=>{tp&&na(null)},[tp]);let nu=(0,i.useCallback)((e,t=!1)=>{W&&to(!1),na(t=>t===e?null:e),W&&N&&t&&tf(!0)},[W,N]),np=(0,i.useCallback)((e,t=!1)=>{let n=ns!==e;if(nu(e,t),!n||tV)return;let r=tY.current;if(!r)return;let i=++tZ.current;tJ(!0),r().catch(e=>{console.error("Failed to load system information:",e)}).finally(()=>{tZ.current===i&&tJ(!1)})},[ns,tV,nu]),nh=(0,i.useCallback)(()=>{W&&to(!1),tf(!1),na("session")},[W]),nf=(0,i.useCallback)(()=>{W&&(na(null),tf(!1)),to(e=>!e)},[W]),ng=(0,i.useCallback)(()=>{to(!1),na(null),tf(e=>!e)},[]),nx=(0,i.useCallback)(()=>{W&&(to(!1),na(null),tf(!1)),ts(e=>!e)},[W]),nm=(0,i.useCallback)(()=>{na(null),tu(e=>!e)},[]);(0,i.useEffect)(()=>{if(!th)return;let e=e=>{let t=tz.current;t&&e.composedPath().includes(t)||tf(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),tf(!1))};return document.addEventListener("pointerdown",e,!0),document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("pointerdown",e,!0),document.removeEventListener("keydown",t,!0)}},[th]),(0,i.useEffect)(()=>{tf(!1)},[W,N,el?.id,eA]),(0,i.useEffect)(()=>{if(!ns||!tW.current)return;let e=()=>{let e=tW.current.getBoundingClientRect();"agents"===ns?nc({top:e.bottom,left:e.left,width:Math.min(420,e.width)}):nc({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(tW.current),()=>t.disconnect()},[ns,W]);let[nv,ny]=(0,i.useState)([]),[nb,nw]=(0,i.useState)(null),nk=(0,i.useRef)(null);(0,i.useEffect)(()=>{nk.current!==nb&&(nk.current=nb,null!==nb&&td(null))},[nb]);let[nj,nS]=(0,i.useState)([]),[nC,nI]=(0,i.useState)(!1),nT=[...nv,...nj.map(e=>({id:e.id,label:J(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(lZ));nS(e.tabs),e.activeId&&(nw(e.activeId),ts(e.open))}catch{}nI(!0)},[]),(0,i.useEffect)(()=>{if(nC)try{window.sessionStorage.setItem(lZ,JSON.stringify({tabs:nj.map(({id:e,cwd:t})=>({id:e,cwd:t})),activeId:nb,open:tl}))}catch{}},[nj,nb,tl,nC]);let nM=(0,i.useCallback)((e,t,n)=>{ny(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))},[]),nE=(0,i.useCallback)((e,t)=>{tR()?.insertText(nV(e,t)),W&&(ts(!1),to(!1))},[W,tR]),nR=(0,i.useCallback)(e=>{let t=e.map(e=>nV(e,!1)).join("");t&&tR()?.insertText(t),W&&(ts(!1),to(!1))},[W,tR]),nL=(0,i.useCallback)((e,t,n)=>{let r,i,o,l;tR()?.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} `)),W&&(ts(!1),to(!1))},[W,tR]),n$=M.sessionId,[nW,nz]=(0,i.useState)(null),nN=(0,i.useRef)(null),[nP,nA]=(0,i.useState)(()=>!n$),nB=(0,i.useRef)(!1),nD=(0,i.useRef)(0),nF=(0,i.useCallback)(()=>{nD.current+=1},[]);(0,i.useEffect)(()=>{el&&function(e,t,n=f()){if(n)try{let r=g(n);r[e]=t,n.setItem(h,JSON.stringify(r))}catch{}}(el.projectKey??nN.current??m(el),el.id)},[el]),(0,i.useEffect)(()=>{let e=M.requestedCwd;if(!e)return;let t=new AbortController;return eO("validating"),e_(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async t=>{let n=await t.json().catch(()=>({}));if(!t.ok||!n.cwd)throw Error(n.error??`HTTP ${t.status}`);nB.current=!0;let r=`initial:${e}`;eB(r),eF.current=`new:${r}:${n.cwd}`,eP(n.cwd),eO("ready")}).catch(e=>{t.signal.aborted||(e_(e instanceof Error?e.message:String(e)),eO("error"))}),()=>t.abort()},[M]);let nH=(0,i.useCallback)((e,t)=>{let n=++nD.current,r=function(e,t=f()){if(!t)return null;try{let n=g(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!==nD.current)return;let o=i?.sessions.find(e=>e.id===r);if(!o){i&&x(e);return}if(m(o)!==e)return void x(e);let l=eF.current;l&&nU(l,l3(t)),eF.current=null,es(o),eJ(e=>e+1),new URLSearchParams(window.location.search).get("session")!==o.id&&I.replace(`?session=${encodeURIComponent(o.id)}`,{scroll:!1})}).catch(()=>{})},[I]),nO=(0,i.useCallback)((e,t,n)=>{nF();let r=eN??nW;if(nz(e),!e)return;let i=n??t??e,o=nN.current??(el?m(el):null);if(nN.current=i,nB.current){nB.current=!1;return}if(r===e&&o!==i||o===i&&(null!==el||r===e))return;let l=eF.current;l&&r&&nU(l,l3(r));let s="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,a=`new:${s}:${e}`;nU(l3(e),a),eB(s),eF.current=a,es(null),eP(t=>t&&t!==e?null:t),eJ(e=>e+1),tP([]),tB(null),t_(null),tK(null),tJ(!1),na(null),o!==i&&(ny([]),(!nb||nb.startsWith("file:"))&&(nw(null),ts(!1)),nH(i,e)),I.replace(window.location.pathname,{scroll:!1})},[nW,nb,nF,eN,I,el,nH]),n_=(0,i.useCallback)((e,t=!1,n,r)=>{eX(n?{sessionId:e.id,entryId:n,blockIndex:r}:null),nF();let i=eF.current,o=eN??(null===el?nW:null);i&&o&&nU(i,l3(o)),eF.current=null;let l=m(e);if(nN.current!==l&&(ny([]),(!nb||nb.startsWith("file:"))&&(nw(null),ts(!1)),na(null)),nN.current=l,!t&&el){let t=m(el)===m(e);if(el.id===e.id&&t){W&&to(!1);return}}eP(null),es(e),eJ(e=>e+1),tP([]),tB(null),tD.current=null,t_(null),tK(null),tJ(!1),nA(!0),A&&(H(t=>{let n=t.some(e=>e.sessionId===l2)?t.filter(e=>e.sessionId!==l2):t;if(n.some(t=>t.sessionId===e.id))return q.current?.scrollPaneIntoView(e.id),U(e.id),l4(n,e.id);let r=e.name||e.firstMessage||e.id.slice(0,12);return l1(n,e.id,r,v(e.projectRoot??e.cwd))}),O!==e.id&&U(e.id)),W&&!t&&to(!1),t&&(nB.current=!0),t||I.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[nW,nb,nF,I,W,eN,el,A,O]),nq=(0,i.useCallback)((e,t)=>{if(nF(),A&&!W&&F.some(e=>e.sessionId===l2)){q.current?.scrollPaneIntoView(l2),U(l2),W&&to(!1);return}let n=`new:${e}:${t}`;if(nU(l3(t),n),eF.current=n,eB(e),es(null),eP(t),eJ(e=>e+1),tP([]),tB(null),t_(null),tK(null),tJ(!1),na(null),W&&to(!1),A&&!W){let e=R("tabs.new"),n=v(t);H(t=>(t.some(e=>e.sessionId===l2)?{tabs:t,existed:!0}:{tabs:[...t,{sessionId:l2,label:e,projectName:n,hasBadge:!1}],existed:!1}).tabs),U(l2)}I.replace(window.location.pathname,{scroll:!1})},[nF,I,W,A,F,R]),nK=(0,i.useCallback)(async()=>{let e=C();if(e.length>0)return e[0].root;try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();if(t.cwd)return t.cwd}catch{}return eN??el?.cwd??nW??null},[eN,el,nW]);!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=>nq(`kb-${Date.now()}`,e),activeCwd:nW});let nJ=(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&&es(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),nY=(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}`);n_(n.info)}catch(e){console.error("[pi-web] failed to open session:",e instanceof Error?e.message:e)}},[n_]);(0,i.useEffect)(()=>{!function(e=null){if(!et())return;let t=e??("u"<typeof document?null:document);t?.documentElement.classList.add("capacitor-shell")}()},[]),(0,i.useEffect)(()=>{let e=eo();if(!e?.addListener)return;let t=!1,n=null;return e.addListener("localNotificationActionPerformed",e=>{let t=e?.notification?.extra?.sessionUrl,n=t?/[?&]session=([^&]+)/.exec(t):null,r=n?decodeURIComponent(n[1]):null;r&&nY(r)}).then(e=>{t?e.remove().catch(()=>{}):n=e}).catch(()=>{}),()=>{t=!0,n?.remove().catch(()=>{})}},[nY]);let nZ=(0,i.useCallback)((e,t)=>{if(eK(e=>e+1),eF.current===t){if(nF(),eF.current=null,eP(null),es(e),nJ(e.id),A&&!W){let t=e.name||e.firstMessage||e.id.slice(0,12),n=v(e.projectRoot??e.cwd);H(r=>r.some(e=>e.sessionId===l2)?r.map(r=>r.sessionId===l2?{sessionId:e.id,label:t,projectName:n,hasBadge:!1}:r):l1(r,e.id,t,n)),U(e.id)}I.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})}},[nF,I,nJ,A,W]),nG=(0,i.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{let i=()=>{r1({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&n_(e)}})},o=eo();o?"granted"===P.current?i():o.requestPermissions().then(e=>{P.current="denied"===e?.display?"denied":"granted","granted"===P.current&&i()}).catch(()=>{}):"Notification"in window&&("granted"===Notification.permission?(i(),o5(E)):"default"===Notification.permission&&Notification.requestPermission().then(e=>{"granted"===e&&(i(),o5(E))}))},[n_,E]),nX=(0,i.useCallback)(()=>{eK(e=>e+1),e1(e=>e+1),el&&nJ(el.id),el?.relation?.kind!=="subagent"&&rQ()&&nG({targetSession:el,title:el?.name??R("i18n.sessionComplete"),body:R("i18n.taskFinished"),tag:el?`pi-session-complete:${el.id}`:"pi-session-complete"})},[nG,nJ,el,R]),nQ=(0,i.useCallback)(e=>{var t;el?.relation?.kind!=="subagent"&&rQ()&&(t=er.current,!(!r0(e)||t.has(e.id))&&(t.add(e.id),1)&&nG({targetSession:el,title:R("i18n.attentionNeeded"),body:"custom"===e.method?R("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[nG,el,R]),n0=(0,i.useCallback)(async()=>{let e=el?.id;if(e&&"naming"!==t6.kind){t3.current&&clearTimeout(t3.current),na(null),t5({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(eK(e=>e+1),t9.current!==e)return;es(t=>t?.id===e?{...t,name:r}:t),t8(t=>t?.sessionId===e?{...t,sessionName:r}:t),t5({kind:"success"}),t3.current=setTimeout(()=>t5({kind:"idle"}),1800)}catch(t){if(t9.current!==e)return;t5({kind:"error",message:t instanceof Error?t.message:String(t)}),t3.current=setTimeout(()=>t5({kind:"idle"}),5e3)}}},[t6.kind,el?.id]);(0,i.useEffect)(()=>{t3.current&&clearTimeout(t3.current),t5({kind:"idle"})},[el?.id]);let n1=(0,i.useCallback)(()=>{e1(e=>e+1)},[]),n2=(0,i.useCallback)(e=>{nF(),eF.current=null,eK(e=>e+1),eJ(e=>e+1),eP(null),es(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),nJ(e),I.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[nF,I,nJ]),n6=(0,i.useCallback)(async(e,t,n)=>{let r=await r5(t,{type:"fork_branch",entryId:n});if(!r?.newSessionId)throw Error(R("chat.quoteForkFailed"));t$({sessionId:r.newSessionId,text:e}),n2(r.newSessionId)},[n2,R]),n5=(0,i.useCallback)(()=>{nA(!0)},[]),n3=(0,i.useCallback)(e=>{if(nF(),eK(e=>e+1),el?.id===e){let e=el.cwd,t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;eB(t),eF.current=e?`new:${t}:${e}`:null,es(null),eP(e??null),eJ(e=>e+1),tP([]),tB(null),t_(null),tK(null),tJ(!1),na(null),I.replace(window.location.pathname,{scroll:!1})}},[nF,el,I]),n9=(0,i.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,i=n?.modeHint,o=n?.page,l=`file:${e}`;ny(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,page:t.page,viewerState:t.modeHint?{displayMode:t.modeHint,wrapLines:!1,scrollTop:0,scrollLeft:0}:void 0,viewerRevision:0}];let r=!!(t.sourceSessionId&&n.sourceSessionId!==t.sourceSessionId),i=n.page!==t.page;return r||t.modeHint||i?e.map(e=>{if(e.id!==t.tabId)return e;let n={...e},o=!1;return r&&(n.sourceSessionId=t.sourceSessionId,o=!0),i&&(n.page=t.page,o=!0),t.modeHint&&(n.initialDisplayMode=t.modeHint,n.viewerState={displayMode:t.modeHint,wrapLines:e.viewerState?.wrapLines??!1,scrollTop:0,scrollLeft:0},o=!0),o&&(n.viewerRevision=(e.viewerRevision??0)+1),n}):e})(n,{fileName:t,filePath:e,modeHint:i,page:o,sourceSessionId:r,tabId:l})),nw(l),ts(!0),W&&to(!1)},[W]),n7=(0,i.useCallback)((e,t)=>{n9(e,J(e),{sourceSessionId:el?.id??null,page:t})},[n9,el?.id]),re=(0,i.useCallback)(e=>{let t=nj.find(t=>t.cwd===e),n=t??lG(e);t||nS(e=>[...e,n]),nw(n.id),ts(!0),W&&to(!1)},[nj,W]),rt=(0,i.useCallback)(e=>{nj.some(t=>t.id===e)?nS(t=>t.map(t=>t.id!==e||t.closing?t:{...t,closing:"close"})):(ny(t=>{let n=t.filter(t=>t.id!==e);return 0===n.length&&0===nj.length&&ts(!1),n}),nw(t=>{if(t!==e)return t;let n=nv.filter(t=>t.id!==e);return n.at(-1)?.id??nj.at(-1)?.id??null}))},[nv,nj]),rn=(0,i.useCallback)(()=>{el&&(td(e=>e===el.id&&tl?null:el.id),ts(!0))},[el,tl]),rr=eN??(null===el&&nW?nW:null),ri=null===el&&rr?`new:${eA}:${rr}`:null;(0,i.useLayoutEffect)(()=>{eF.current=ri},[ri]);let ro=null!==el||null!==rr,rl=el?.cwd??rr,rs=nP&&!ro,ra=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(!ra.current&&nP){if(el||rr||F.length>0||!A||W){ra.current=!0;return}ra.current=!0,nK().then(e=>{e&&nq(`entry-${Date.now()}`,e)})}},[nP,el,rr,F.length,A,W,nK,nq]),(0,i.useEffect)(()=>{if(e3(null),e7(!1),tr(null),!rl)return;let e=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(rl)}`,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e3(t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>e.abort()},[rl]);let rd=(0,i.useCallback)(async()=>{if(rl&&!te){tt(!0),tr(null);try{let e=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:rl})}),t=await e.json();if(!e.ok||t.error)throw Error(t.error??`HTTP ${e.status}`);e3(t),e7(!1),e6(e=>e+1),eJ(e=>e+1)}catch(e){tr(e instanceof Error?e.message:String(e))}finally{tt(!1)}}},[te,rl]),rc=nv.find(e=>e.id===nb)??null,ru=nW?J(nW)||nW:null,rp=ru?`${ru} - Pi Web`:"Pi Web";(0,i.useEffect)(()=>{let e=()=>{document.title!==rp&&(document.title=rp)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[rp]);let rh=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(eD,{selectedSessionId:el?.id??null,onSelectSession:n_,onNewSession:nq,initialSessionId:n$,skipInitialProjectSelection:null!==M.requestedCwd,onInitialRestoreDone:n5,refreshKey:eq,onSessionDeleted:n3,selectedCwd:el?.cwd??eN??null,onCwdChange:nO,onOpenFile:n9,onOpenTerminal:re,explorerRefreshKey:e0,onExplorerRefresh:n1,onAtMention:nE,onAtMentions:nR,onBackgroundTaskDone:ei,onRunningSessionIdsChange:ez,onSessionsChange:eC,onExternalSessionChange:eM}),(0,r.jsxs)("div",{style:{padding:"8px",flexShrink:0,display:"flex",justifyContent:"space-between",gap:4},children:[[["models",R("common.models")],["skills",R("common.skills")]].map(([e,t])=>{let n="models"!==e&&!rl;return(0,r.jsxs)("button",{type:"button",onClick:()=>e4(e),disabled:n,title:n?R("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)(lE,{section:e,size:14,strokeWidth:2}),(0,r.jsx)("span",{children:t})]},e)}),(0,r.jsxs)("button",{type:"button",onClick:()=>e4(function(e,t=i7()){if(!t)return"general";try{let n=oe(t).section;if(!("string"==typeof n&&i5.includes(n)))return"general";return i9.has(n)&&!e?"general":n}catch{return"general"}}(rl)),title:R("common.settings"),"aria-label":R("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)(lE,{section:"general",size:14,strokeWidth:2}),(0,r.jsx)("span",{children:R("common.settings")})]})]})]}),rf=e=>ro&&e5?.requiresTrust&&!e5.trusted?(0,r.jsxs)("button",{type:"button",onClick:()=>{tr(null),e7(!0)},title:R("trust.resourcesNotLoaded"),"aria-label":R("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:R("trust.resourcesNotLoaded")})]}):null,rg=e=>{let t,n,i,o,l,s;return e||ro?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>{ed(e=>!e)},title:R("bgTasks.open"),"aria-label":R("bgTasks.open"),"aria-pressed":ea,style:{display:"flex",alignItems:"center",justifyContent:"center",position:"relative",width:e?36:void 0,minWidth:e?void 0:34,height:"100%",padding:e?0:"0 10px",background:ea?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:em>0?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,flexShrink:0,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},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:"M4 5h16"}),(0,r.jsx)("path",{d:"M4 12h10"}),(0,r.jsx)("path",{d:"M4 19h6"})]}),em>0&&(0,r.jsx)("span",{"aria-label":String(em),style:{position:"absolute",top:6,right:e?6:10,minWidth:14,height:14,padding:"0 3px",borderRadius:7,background:"var(--accent)",color:"var(--bg-panel)",fontSize:9,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1},children:em>9?"9+":em})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>{rn(),e&&N&&tf(!0)},disabled:!el,title:el?R("history.full"):R("history.unsaved"),"aria-label":R("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:el?"var(--text-muted)":"var(--text-dim)",cursor:el?"pointer":"not-allowed",opacity:el?1:.45,flexShrink:0,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s, opacity 0.1s"},onMouseEnter:e=>{el&&(e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{e.currentTarget.style.color=el?"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:el?"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:R("history.label")})]}),(t=!!(el&&((t4?.userMessages??0)>0||el.messageCount>0)),n=!el||el.transient||!t||"naming"===t6.kind,i="success"===t6.kind,o="error"===t6.kind,l="naming"===t6.kind?R("title.generating"):i?R("title.updated"):o?R("title.failed"):R("title.generate"),s=!el||el.transient?R("title.unsaved"):t?o?t6.message:R("title.generateSession"):R("title.noMessages"),(0,r.jsxs)("button",{type:"button",onClick:()=>{n0(),e&&N&&tf(!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"!==t6.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"===t6.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})]})),eL&&(0,r.jsxs)("button",{type:"button",onClick:()=>nu("agents",e),title:R("agentSwitcher.title"),"aria-label":R("agentSwitcher.title"),"aria-pressed":"agents"===ns,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"===ns?"var(--bg-selected)":"none",border:"none",borderTop:"agents"===ns?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"agents"===ns?"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:R("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:eR.subagents.length})]}),tF&&(e?(0,r.jsx)("button",{type:"button",onClick:()=>nu("branches",!0),title:R("i18n.branches"),"aria-label":R("i18n.branches"),"aria-pressed":"branches"===ns,style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:"100%",padding:0,background:"branches"===ns?"var(--bg-selected)":"none",border:"none",borderTop:"branches"===ns?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",color:"branches"===ns?"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:tN.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)(lA,{tree:tN,activeLeafId:tA,onLeafChange:tO,inline:!0,containerRef:tW,open:"branches"===ns,onToggle:()=>nu("branches"),hasSession:!0})),(0,r.jsxs)("button",{ref:tQ,type:"button",onClick:()=>np("system",e),disabled:e&&!ro,title:R("system.prompt"),"aria-label":R("system.prompt"),"aria-pressed":"system"===ns,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"system"===ns?"var(--bg-selected)":"none",border:"none",borderTop:"system"===ns?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!ro?"not-allowed":"pointer",color:"system"===ns?"var(--text)":"var(--text-muted)",opacity:e&&!ro?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||ro)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="system"===ns?"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:tU?"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:R("system.label")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>np("tools",e),disabled:e&&!ro,title:R("tools.title"),"aria-label":R("tools.title"),"aria-pressed":"tools"===ns,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:e?36:void 0,height:"100%",padding:e?0:"0 12px",background:"tools"===ns?"var(--bg-selected)":"none",border:"none",borderTop:"tools"===ns?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:e&&!ro?"not-allowed":"pointer",color:"tools"===ns?"var(--text)":"var(--text-muted)",opacity:e&&!ro?.45:1,fontSize:11,whiteSpace:"nowrap",transition:"color 0.1s, background 0.1s"},onMouseEnter:t=>{(!e||ro)&&(t.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="tools"===ns?"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:tq?.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:R("tools.label")})]})]}):null},rx=e=>{if(!e&&(!ro||!t4&&!ni))return null;let t=t4?.tokens,n=t4?.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(ni?.contextWindow){let e=ni.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(ni.contextWindow)}`:`? / ${i(ni.contextWindow)}`,a=null!==e?`${e.toFixed(0)}%`:null}let d=[];if(t&&(d.push(`in: ${t.input.toLocaleString(E)}`),d.push(`out: ${t.output.toLocaleString(E)}`),d.push(`cache read: ${t.cacheRead.toLocaleString(E)}`),d.push(`cache write: ${t.cacheWrite.toLocaleString(E)}`),n>0&&d.push(`cost: $${n.toFixed(4)}`)),ni?.contextWindow){let e=ni.percent;d.push(`context: ${null!==e?e.toFixed(1)+"%":"unknown"} of ${ni.contextWindow.toLocaleString()} tokens`)}let c=d.join(" | "),u=e&&N&&th,p=!!(t&&(t.input>0||t.output>0)||o||a);return(0,r.jsx)("button",{type:"button",onClick:()=>nu("session"),disabled:!ro||u,tabIndex:u?-1:void 0,title:c||R("session.title"),"aria-label":R("session.title"),"aria-pressed":"session"===ns,"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"===ns?"var(--bg-selected)":"none",border:"none",borderTop:"session"===ns?"2px solid var(--accent)":"2px solid transparent",fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:ro?"pointer":"default",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{ro&&!u&&(e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.color="session"===ns?"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&&ro&&(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-dim)"},children:R("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]})]})})},rm=e=>{let t=e&&N&&th;return(0,r.jsx)("button",{type:"button",onClick:nx,disabled:t,tabIndex:t?-1:void 0,"aria-controls":"file-panel","aria-expanded":tl,"aria-hidden":!!t||void 0,title:tl?R("files.hidePanel"):R("files.showPanel"),"aria-label":tl?R("files.hidePanel"):R("files.showPanel"),"data-mobile-toolbar-file":e?"true":void 0,style:{marginLeft:e||t4||ni?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,visibility:t?"hidden":"visible",pointerEvents:t?"none":"auto",background:tl?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:tl?"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=tl?"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${tg?"":" sidebar-mobile-pending"}`,onClick:()=>to(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!ti,pointerEvents:ti?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)("div",{ref:tk.panelRef,id:"session-sidebar",inert:tp,className:`sidebar-container${ti?" sidebar-open":" sidebar-closed"}${tg?"":" sidebar-mobile-pending"}${tk.isResizing?" sidebar-resizing":""}`,style:{"--sidebar-width":`${tk.width}px`,background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,paddingTop:"var(--safe-area-top, 0px)",paddingBottom:"var(--safe-area-bottom, 0px)",zIndex:200},children:rh}),ti&&(0,r.jsx)("div",{...tk.separatorProps,inert:tp,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${tk.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${R("layout.resizeSidebar")}: ${R("layout.resizeHint")}`}),(0,r.jsxs)("div",{inert:tp,style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,r.jsxs)("div",{ref:tW,style:{flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",position:"relative",borderBottom:"1px solid var(--border)",height:"calc(36px + var(--safe-area-top, 0px))",paddingTop:"var(--safe-area-top, 0px)"},children:[!W&&!A&&el&&(0,r.jsx)("button",{type:"button",onClick:()=>{D(!0);let e=el.id,t=el.name||el.firstMessage||e.slice(0,12);H(n=>n.some(t=>t.sessionId===e)?n:l1(n,e,t,v(el.projectRoot??el.cwd))),U(e)},title:"Enable split view","aria-label":"Enable split view",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},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"4",width:"20",height:"16",rx:"1.5"}),(0,r.jsx)("line",{x1:"12",y1:"4",x2:"12",y2:"20"})]})}),(0,r.jsx)("button",{onClick:nf,title:ti?R("sidebar.hide"):R("sidebar.show"),"aria-label":ti?R("sidebar.hide"):R("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:ti?(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"})]})}),W&&(0,r.jsxs)("div",{ref:tz,"data-mobile-toolbar":"true",style:{position:"relative",display:"flex",alignItems:"stretch",flex:1,minWidth:0,height:"100%"},children:[N&&(0,r.jsx)("button",{type:"button",onClick:ng,title:th?R("chat.close"):R("chat.moreControls"),"aria-label":th?R("chat.close"):R("chat.moreControls"),"aria-controls":"mobile-toolbar-actions","aria-expanded":th,"data-mobile-toolbar-more":"true",style:{position:"relative",zIndex:th?21:void 0,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:th?"var(--bg-selected)":"none",border:"none",borderRight:"1px solid var(--border)",color:th?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s, background 0.12s"},children:th?(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"})]})}),!N&&rg(!0),rx(!0),rm(!0),N&&th&&(0,r.jsx)("div",{id:"mobile-toolbar-actions",role:"toolbar","aria-label":R("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:rg(!0)})]}),!W&&(0,r.jsxs)(r.Fragment,{children:[rf(!1),rg(!1),rx(!1)]}),!W&&rm(!1),W&&tF&&(0,r.jsx)(lA,{tree:tN,activeLeafId:tA,onLeafChange:tO,inline:!0,compact:!0,containerRef:tW,open:"branches"===ns,onToggle:()=>nu("branches"),hasSession:ro,hideInlineButton:!0}),ns&&nd&&(0,r.jsxs)("div",{style:{position:"fixed",top:nd.top,left:nd.left,width:nd.width,maxHeight:`calc(100dvh - ${nd.top}px)`,overflowY:"auto",zIndex:500},children:["agents"===ns&&eR&&el&&(0,r.jsx)(lq,{rootSession:eR.root,subagents:eR.subagents,selectedSessionId:el.id,runningSessionIds:e$,onSelectSession:n_}),"system"===ns&&(0,r.jsx)(lB,{loading:tV,prompt:tU,translate:R}),"tools"===ns&&(0,r.jsx)(lH,{loading:tV,tools:tq,translate:R}),"session"===ns&&(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:t4?(e=t4.totalActiveMs??0,t=[...t4.sessionName?[{label:R("session.name"),value:t4.sessionName,copyField:null}]:[],{label:R("session.file"),value:t4.sessionFile??R("session.inMemory"),copyField:"file"},{label:R("session.id"),value:t4.sessionId,copyField:"id"},...e>0?[{label:R("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=[...el?[{label:R("session.projectDir"),value:el.projectRoot??el.cwd,copyField:"projectDir"}]:[],...el?.branch?[{label:R("session.gitBranch"),value:el.branch,copyField:"gitBranch"}]:[],...el?.isWorktree?[{label:R("session.gitWorktree"),value:el.cwd,copyField:"gitWorktree"}]:[]],d=[[R("session.user"),t4.userMessages.toLocaleString(E)],[R("session.assistant"),t4.assistantMessages.toLocaleString(E)],[R("session.toolCalls"),t4.toolCalls.toLocaleString(E)],[R("session.toolResults"),t4.toolResults.toLocaleString(E)],[R("session.total"),t4.totalMessages.toLocaleString(E)]],c=[[R("session.input"),t4.tokens.input.toLocaleString(E)],[R("session.output"),t4.tokens.output.toLocaleString(E)],...t4.tokens.cacheRead>0?[[R("session.cacheRead"),t4.tokens.cacheRead.toLocaleString(E)]]:[],...t4.tokens.cacheWrite>0?[[R("session.cacheWrite"),t4.tokens.cacheWrite.toLocaleString(E)]]:[],[R("session.total"),t4.tokens.total.toLocaleString(E)]],u=ni??t4.contextUsage,y=[...t4.cost>0?[[R("session.cost"),`$${t4.cost.toFixed(4)}`]]:[],...u?.contextWindow?[[R("session.context"),`${null!==u.percent?`${u.percent.toFixed(1)}%`:"?"} / ${(p=u.contextWindow)>=1e6?`${(p/1e6).toFixed(1)}M`:p>=1e3?`${(p/1e3).toFixed(0)}k`:String(p)}`]]:[],...t4.tokens.cacheRead+t4.tokens.cacheWrite>0&&t4.tokens.cacheRead+t4.tokens.cacheWrite+t4.tokens.input>0?[[R("session.cacheHitRate"),`${(t4.tokens.cacheRead/(t4.tokens.cacheRead+t4.tokens.cacheWrite+t4.tokens.input)*100).toFixed(1)}%`]]:[]],b=(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}`))})]}),w={file:"session.copyFile",id:"session.copyId",projectDir:"session.copyProjectDir",gitBranch:"session.copyGitBranch",gitWorktree:"session.copyGitWorktree"},k=(e,t)=>{let n=ne===e;return(0,r.jsx)("button",{type:"button",title:n?R("session.copied"):R(w[e]),onClick:()=>nr(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"})]})})},j=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:R("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?k(e.copyField,e.value):null})]},`session-info:${e.label}`))})]}),S=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:R("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?k(e.copyField,e.value):null})]},`project-info:${e.label}`))})]}):null,(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:W?"1fr":"minmax(360px, 1.7fr) minmax(140px, 0.55fr) minmax(190px, 0.75fr)",gap:W?16:24,fontSize:12,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:W?16:20},children:[j,S]}),b(R("session.messages"),d),b(R("session.tokens"),[...c,...y],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:R("session.load")})})]})]}),W&&rf(!0)]}),(0,r.jsxs)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:[ro&&!W&&F.length>0?(0,r.jsx)(l8,{ref:q,tabs:F,focusedId:O,runningSessionIds:e$,onFocusPane:e=>{U(e),H(t=>l4(t,e))},onClosePane:e=>{tE(e);let t=e===l2,n=F.filter(t=>t.sessionId!==e);(H(t=>t.filter(t=>t.sessionId!==e)),t)?0===n.length?(D(!1),U(null)):O===e&&U(n[n.length-1].sessionId):n.some(e=>e.sessionId!==l2)?O===e&&U(n[n.length-1].sessionId):n.some(e=>e.sessionId===l2)?(U(l2),q.current?.scrollPaneIntoView(l2)):nK().then(e=>{e?nq(`pane-${Date.now()}`,e):(D(!1),U(null))})},renderPane:(e,t)=>{if(e===l2)return(0,r.jsx)(iS,{session:null,isActivePane:t,newSessionCwd:rr,newSessionDraftKey:ri,sessionRunning:!1,chatInputRef:tM(l2),onSessionCreated:nZ},l2);let n=e===el?.id?el:ej.find(t=>t.id===e)??null;return n?(0,r.jsx)(iS,{session:n,isActivePane:t,newSessionCwd:null,newSessionDraftKey:null,sessionRunning:e$.has(e),chatInputRef:tM(e),onSessionStatsChange:t?t7:void 0,onContextUsageChange:t?nl:void 0,onBackgroundTasksEvent:t=>ek(e,t),onAgentEnd:()=>{if(e!==O){H(t=>t.map(t=>t.sessionId===e?{...t,hasBadge:!0}:t));let t=Date.now();(function(e,t,n=500){return t-e>=n})(_.current,t)&&(_.current=t,X.current&&Z())}}},e):null}}):ro?(0,r.jsx)(iS,{session:el,searchTarget:eG?.sessionId===el?.id?eG:null,onSearchTargetHandled:eQ,initialScrollPosition:el?eY.current.get(el.id)??null:null,onScrollPositionChange:eZ,sessionRunning:!!(el&&e$.has(el.id)),newSessionCwd:rr,newSessionDraftKey:ri,onAgentEnd:nX,onAttentionNeeded:nQ,onBackgroundTasksEvent:el?e=>ek(el.id,e):void 0,onSessionCreated:nZ,onSessionForked:n2,modelsRefreshKey:e8,chatInputRef:tI,onBranchDataChange:tH,onSystemPromptChange:t0,onSystemToolsChange:t1,onSystemInfoLoaderChange:t2,onSessionStatsChange:t7,onSessionStatsPanelOpen:nh,onContextUsageChange:nl,externalSessionChange:eI,onOpenFile:n7,onOpenSession:nY,onAskInNewChat:n6,quoteSelectionEnabled:Q,initialPrompt:tL?.sessionId===el?.id?tL?.text:void 0,onInitialPromptConsumed:()=>t$(null),soundEnabled:V,onSoundToggle:Y,playDoneSound:Z,unlockAudio:G},eV):"validating"===eH?(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:R("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:M.requestedCwd})]}):"error"===eH?(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:R("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:M.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:eU})]}):rs?nW?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:R("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:R("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."}),R("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),R("workspace.addModels")]})]})]}):null,ea&&(W?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{onClick:()=>ed(!1),style:{position:"absolute",inset:0,zIndex:39,background:"rgba(0,0,0,0.35)"}}),(0,r.jsx)("div",{role:"dialog","aria-label":R("bgTasks.title"),style:{position:"absolute",left:0,right:0,bottom:0,height:"62%",zIndex:40,background:"var(--bg-panel)",borderTop:"1px solid var(--border)",boxShadow:"0 -12px 40px rgba(0,0,0,0.22)",paddingBottom:"var(--safe-area-bottom, 0px)"},children:(0,r.jsx)(i4,{sessionId:eh,state:eg,logs:ex,onRefresh:ev,onFetchLogs:eb,onKill:ew,onClose:()=>ed(!1),selectedTaskId:ec,onSelectTask:eu})})]}):(0,r.jsx)("div",{role:"complementary","aria-label":R("bgTasks.title"),style:{position:"absolute",top:0,right:0,bottom:0,width:340,zIndex:25,background:"var(--bg-panel)",borderLeft:"1px solid var(--border)",boxShadow:"-8px 0 24px rgba(0,0,0,0.10)"},children:(0,r.jsx)(i4,{sessionId:eh,state:eg,logs:ex,onRefresh:ev,onFetchLogs:eb,onKill:ew,onClose:()=>ed(!1),selectedTaskId:ec,onSelectTask:eu})}))]})]}),(0,r.jsx)("div",{"aria-hidden":"true",className:`right-panel-overlay-backdrop${tl?" is-open":""}`,onClick:()=>ts(!1)}),tl&&(0,r.jsx)("div",{...tj.separatorProps,inert:tp,"aria-controls":"file-panel",className:`panel-resize-handle right-panel-resize-handle${tj.isResizing?" is-resizing":""}`,"data-resize-handle":"right-panel",title:`${R("layout.resizeFilePanel")}: ${R("layout.resizeHint")}`}),(0,r.jsxs)("div",{ref:tj.panelRef,id:"file-panel",className:`right-panel-container${tl?" right-panel-open":" right-panel-closed"}${tp?" right-panel-full-width":""}${tj.isResizing?" right-panel-resizing":""}`,style:{"--right-panel-width":`${tj.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 + var(--safe-area-top, 0px))",paddingTop:"var(--safe-area-top, 0px)",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,r.jsx)(i8,{tabs:nT,activeTabId:nb??"",onSelectTab:nw,onCloseTab:rt})}),(0,r.jsx)("button",{type:"button",className:"file-panel-expand-button",onClick:nm,"aria-controls":"file-panel","aria-pressed":tp,title:R(tp?"files.restorePanelWidth":"files.expandPanel"),"aria-label":R(tp?"files.restorePanelWidth":"files.expandPanel"),children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:tp?"M9 3v6H3m12-6v6h6M9 21v-6H3m12 6v-6h6M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6":"M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M3 3l6 6m12-6-6 6M3 21l6-6m12 6-6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>ts(!1),"aria-controls":"file-panel","aria-expanded":tl,title:R("files.hidePanel"),"aria-label":R("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:"var(--safe-area-bottom, 0px)",display:"flex",flexDirection:"column"},children:[ta?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R("history.snapshot")}),(0,r.jsxs)("a",{href:`/api/sessions/${encodeURIComponent(ta)}/export?inline=1`,target:"_blank",rel:"noopener noreferrer",title:R("history.openInTab"),style:{fontSize:11,color:"var(--text-muted)",textDecoration:"none",flexShrink:0,display:"flex",alignItems:"center",gap:4},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),(0,r.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),R("history.openInTab")]})]}),(0,r.jsx)("iframe",{src:`/api/sessions/${encodeURIComponent(ta)}/export?inline=1`,title:R("history.full"),style:{flex:1,width:"100%",minHeight:0,border:"none",background:"var(--bg)"}})]}):rc?.filePath?(0,r.jsx)(i0,{filePath:rc.filePath,cwd:nW??void 0,sourceSessionId:rc.sourceSessionId,gitRefreshKey:e0,initialDisplayMode:rc.initialDisplayMode,initialPage:rc.page,initialState:rc.viewerState,watchEnabled:tl,onStateChange:e=>nM(rc.id,rc.viewerRevision??0,e),onMentionLines:tl?nL:void 0,onAtMention:nE,onOpenFile:(e,t)=>n9(e,J(e),{sourceSessionId:rc.sourceSessionId,page:t})},`${rc.id}:${rc.viewerRevision??0}`):nj.some(e=>e.id===nb)?null:(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:R("files.noneOpen")}),nj.map(e=>(0,r.jsx)("div",{hidden:e.id!==nb,style:{width:"100%",height:"100%"},children:(0,r.jsx)(lY,{tab:e,active:tl&&e.id===nb,onRestart:()=>nS(t=>t.map(t=>t.id===e.id?{...t,closing:"restart"}:t)),onClosed:()=>{let t,n;return t="restart"===e.closing?lG(e.cwd):null,n=nj.filter(t=>t.id!==e.id),void(nS(n=>n.flatMap(n=>n.id!==e.id?[n]:t?[t]:[])),nw(r=>r!==e.id?r:t?.id??n.at(-1)?.id??nv.at(-1)?.id??null),!t&&!n.length&&!nv.length&&ts(!1))},onCloseError:()=>nS(t=>t.map(t=>t.id===e.id?{...t,closing:void 0}:t))})},e.id))]})]})]}),e2&&(0,r.jsx)(lL,{cwd:rl,sessionId:el?.id??null,initialSection:e2,quoteSelectionEnabled:Q,onQuoteSelectionChange:en,onClose:()=>{e4(null),e6(e=>e+1)},onSessionReloaded:()=>eJ(e=>e+1)}),e9&&rl&&(0,r.jsx)(l$,{cwd:rl,busy:te,error:tn,onCancel:()=>{te||e7(!1)},onConfirm:()=>void rd()})]})}},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,14242)),Promise.resolve().then(n.bind(n,21278))},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,255,1278,8441,3794,7358],()=>e(e.s=42927)),_N_E=e.O()}]);
|