pi-app 0.8.1 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +4 -4
- package/.next/build-manifest.json +2 -2
- package/.next/prerender-manifest.json +3 -3
- package/.next/required-server-files.js +1 -1
- package/.next/required-server-files.json +1 -1
- 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/_global-error.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_index.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 +2 -2
- package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/api/skills/install/route.js +1 -1
- package/.next/server/app/api/skills/search/route.js +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +3 -3
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
- package/.next/server/app/index.segments/_full.segment.rsc +3 -3
- package/.next/server/app/index.segments/_head.segment.rsc +1 -1
- package/.next/server/app/index.segments/_index.segment.rsc +2 -2
- package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/server/app/page.js +2 -2
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/share/[token]/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +4 -4
- package/.next/server/chunks/349.js +1 -1
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/middleware-manifest.json +5 -5
- 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/{2261-1213d31c519af896.js → 2261-bdeacd38bbdf7a65.js} +1 -1
- package/.next/static/chunks/app/page-12fb7504b3b0a7a5.js +2 -0
- package/.next/static/css/bdd24a16bf93fd97.css +1 -0
- package/.next/trace +84 -84
- package/.next/trace-build +1 -1
- package/README.md +20 -3
- package/bin/pi-app.js +20 -6
- package/next.config.ts +4 -0
- package/package.json +2 -4
- package/public/Pi-LOGO.png +0 -0
- package/.next/static/chunks/app/page-84b8dd2798476830.js +0 -2
- package/.next/static/css/55427e8acf53e124.css +0 -1
- /package/.next/static/{jWlwtI3NyKCLPvodN51mW → VL7I477I2Xvb0sQR9Po90}/_buildManifest.js +0 -0
- /package/.next/static/{jWlwtI3NyKCLPvodN51mW → VL7I477I2Xvb0sQR9Po90}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{3e3:(e,t,r)=>{"use strict";r.d(t,{AppShell:()=>rG});var n=r(95155),o=r(12115),i=r(73321),s=r(82241);async function l(e,t={}){let{timeoutMs:r=8e3,...n}=t;return fetch(e,{...n,signal:AbortSignal.timeout(r)})}async function a(e=5e3){try{let t=await l("/api/health",{timeoutMs:e,cache:"no-store"});if(!t.ok)return!1;let r=await t.json().catch(()=>null);return r?.ok===!0}catch{return!1}}let d=[/^\/tmp\//,/^\/tmp$/,/^\/private\/tmp\//,/^\/private\/tmp$/,/^\/var\/folders\/[^/]+\/[^/]+\/T\//,/^\/var\/folders\/[^/]+\/[^/]+\/T$/,/^\/private\/var\/folders\/[^/]+\/[^/]+\/T\//,/^\/private\/var\/folders\/[^/]+\/[^/]+\/T$/,/^[A-Za-z]:\\Users\\[^\\]+\\AppData\\Local\\Temp\\/i,/^[A-Za-z]:\\Windows\\Temp\\/i];function c(e){return(function(e){let t=new Map;for(let r of e){if(!r.cwd)continue;let e=t.get(r.cwd);(!e||r.modified>e)&&t.set(r.cwd,r.modified)}return[...t.entries()].sort((e,t)=>t[1].localeCompare(e[1])).map(([e])=>e)})(e).filter(e=>!(e&&d.some(t=>t.test(e))))}let u="var(--text-dim)";function p({size:e=14,open:t=!1}){return t?(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:[(0,n.jsx)("path",{d:"M1 4.5A1 1 0 0 1 2 3.5H5.5L7 5h7.5v1H1V4.5Z",fill:u}),(0,n.jsx)("path",{d:"M1 6h14.5L14 13H2L1 6Z",stroke:u,strokeWidth:"1",fill:u,fillOpacity:"0.12"})]}):(0,n.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:(0,n.jsx)("path",{d:"M1 4.5A1 1 0 0 1 2 3.5H5.5L7 5H14a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4.5Z",stroke:u,strokeWidth:"1",fill:u,fillOpacity:"0.1"})})}function x({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:[(0,n.jsx)("path",{d:"M3 2h7l3 3v9H3V2Z",stroke:u,strokeWidth:"1",fill:u,fillOpacity:"0.08"}),(0,n.jsx)("path",{d:"M10 2v3h3",stroke:u,strokeWidth:"1",fill:"none",strokeLinejoin:"round"})]})}function h({label:e,size:t=14}){let r=t/14;return(0,n.jsxs)("svg",{width:t,height:t,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("text",{x:"7",y:"9.5",textAnchor:"middle",fontSize:3.4*r,fontFamily:"var(--font-mono), monospace",fontWeight:"600",fill:u,letterSpacing:"0",children:e})]})}function g({size:e=14}){return(0,n.jsx)(h,{label:"TS",size:e})}function f({size:e=14}){return(0,n.jsx)(h,{label:"TSX",size:e})}function m({size:e=14}){return(0,n.jsx)(h,{label:"JS",size:e})}function b({size:e=14}){return(0,n.jsx)(h,{label:"JSX",size:e})}function v({size:e=14}){return(0,n.jsx)(h,{label:"PY",size:e})}function y({size:e=14}){return(0,n.jsx)(h,{label:"{}",size:e})}function j({size:e=14}){return(0,n.jsx)(h,{label:"CSS",size:e})}function k({size:e=14}){return(0,n.jsx)(h,{label:"SC",size:e})}function w({size:e=14}){return(0,n.jsx)(h,{label:"HTM",size:e})}function S({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M3.5 9.5V7l1.5 1.5L6.5 7v2.5",stroke:u,strokeWidth:"0.9",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),(0,n.jsx)("path",{d:"M8 7v2.5M7 9l1 1.5 1-1.5",stroke:u,strokeWidth:"0.9",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function C({size:e=14}){return(0,n.jsx)(h,{label:"YML",size:e})}function N({size:e=14}){return(0,n.jsx)(h,{label:"TOM",size:e})}function T({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M4 7.5l2 1.5-2 1.5",stroke:u,strokeWidth:"0.95",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),(0,n.jsx)("path",{d:"M7.5 10.5h2.5",stroke:u,strokeWidth:"0.95",strokeLinecap:"round"})]})}function I({size:e=14}){return(0,n.jsx)(h,{label:"RS",size:e})}function L({size:e=14}){return(0,n.jsx)(h,{label:"GO",size:e})}function R({size:e=14}){return(0,n.jsx)(h,{label:"SQL",size:e})}function z({size:e=14}){return(0,n.jsx)(h,{label:"GQL",size:e})}function M({size:e=14}){return(0,n.jsx)(h,{label:"TF",size:e})}function E({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("rect",{x:"3.5",y:"6.5",width:"2",height:"1.5",rx:"0.3",stroke:u,strokeWidth:"0.8"}),(0,n.jsx)("rect",{x:"6",y:"6.5",width:"2",height:"1.5",rx:"0.3",stroke:u,strokeWidth:"0.8"}),(0,n.jsx)("rect",{x:"3.5",y:"8.5",width:"2",height:"1.5",rx:"0.3",stroke:u,strokeWidth:"0.8"})]})}function W({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"5.5",cy:"8.5",r:"1.5",stroke:u,strokeWidth:"0.9"}),(0,n.jsx)("path",{d:"M7 8.5h2.5M8.5 8.5v1.5",stroke:u,strokeWidth:"0.9",strokeLinecap:"round"})]})}function A({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"5",cy:"6.5",r:"1",stroke:u,strokeWidth:"0.85"}),(0,n.jsx)("circle",{cx:"9",cy:"6.5",r:"1",stroke:u,strokeWidth:"0.85"}),(0,n.jsx)("circle",{cx:"5",cy:"10",r:"1",stroke:u,strokeWidth:"0.85"}),(0,n.jsx)("path",{d:"M5 7.5V9",stroke:u,strokeWidth:"0.85",strokeLinecap:"round"}),(0,n.jsx)("path",{d:"M9 7.5v.5a2 2 0 0 1-2 2H6",stroke:u,strokeWidth:"0.85",strokeLinecap:"round",fill:"none"})]})}function P({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("rect",{x:"4.5",y:"8.5",width:"5",height:"3",rx:"0.6",stroke:u,strokeWidth:"0.9"}),(0,n.jsx)("path",{d:"M5.5 8.5V7.5a1.5 1.5 0 0 1 3 0v1",stroke:u,strokeWidth:"0.9",strokeLinecap:"round",fill:"none"})]})}function $({size:e=14}){return(0,n.jsx)(h,{label:"DOC",size:e})}function O({size:e=14}){return(0,n.jsx)(h,{label:"PDF",size:e})}function H({size:e=14}){return(0,n.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,n.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:u,strokeWidth:"0.9",fill:u,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,n.jsx)("path",{d:"M8.5 1v3h3",stroke:u,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,n.jsx)("circle",{cx:"7",cy:"8.5",r:"1.3",stroke:u,strokeWidth:"0.9"}),(0,n.jsx)("path",{d:"M7 6.5v.7M7 10.3v.7M5 8.5h.7M8.3 8.5H9M5.5 6.9l.5.5M8.5 9.6l-.5-.5M5.5 10.1l.5-.5M8.5 7.4l-.5.5",stroke:u,strokeWidth:"0.8",strokeLinecap:"round"})]})}function D(e,t=14){let r=e.toLowerCase(),o=r.split(".").pop()??"";if("dockerfile"===r||r.startsWith("dockerfile."))return(0,n.jsx)(E,{size:t});if(".env"===r||r.startsWith(".env."))return(0,n.jsx)(W,{size:t});if(".gitignore"===r||".gitattributes"===r||".gitmodules"===r)return(0,n.jsx)(A,{size:t});if("package-lock.json"===r||"yarn.lock"===r||"bun.lock"===r||"pnpm-lock.yaml"===r||"cargo.lock"===r)return(0,n.jsx)(P,{size:t});if(r.endsWith(".config.ts")||r.endsWith(".config.js")||r.endsWith(".config.mjs")||r.endsWith(".config.cjs")||[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(r))return(0,n.jsx)(H,{size:t});switch(o){case"ts":return(0,n.jsx)(g,{size:t});case"tsx":return(0,n.jsx)(f,{size:t});case"js":case"mjs":case"cjs":return(0,n.jsx)(m,{size:t});case"jsx":return(0,n.jsx)(b,{size:t});case"py":return(0,n.jsx)(v,{size:t});case"json":case"jsonl":return(0,n.jsx)(y,{size:t});case"css":case"less":return(0,n.jsx)(j,{size:t});case"scss":return(0,n.jsx)(k,{size:t});case"html":case"htm":return(0,n.jsx)(w,{size:t});case"md":case"mdx":return(0,n.jsx)(S,{size:t});case"yaml":case"yml":return(0,n.jsx)(C,{size:t});case"toml":return(0,n.jsx)(N,{size:t});case"sh":case"bash":case"zsh":case"fish":return(0,n.jsx)(T,{size:t});case"rs":return(0,n.jsx)(I,{size:t});case"go":return(0,n.jsx)(L,{size:t});case"sql":return(0,n.jsx)(R,{size:t});case"graphql":case"gql":return(0,n.jsx)(z,{size:t});case"tf":case"hcl":return(0,n.jsx)(M,{size:t});case"docx":return(0,n.jsx)($,{size:t});case"pdf":return(0,n.jsx)(O,{size:t});case"lock":return(0,n.jsx)(P,{size:t});default:return(0,n.jsx)(x,{size:t})}}var B=r(28999);async function F(e){let t=(0,B.HG)(e),r=await fetch(`/api/files/${t}?type=list`);return r.ok?((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:(0,B.e_)(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir})):[]}function U({node:e,depth:t,cwd:r,onOpenFile:i,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshKey:c}){let{t:u}=(0,s.s)(),x=a.has(e.fullPath),[h,g]=(0,o.useState)(e.children??[]),[f,m]=(0,o.useState)(e.loaded??!1),[b,v]=(0,o.useState)(!1),[y,j]=(0,o.useState)(!1),k=(0,o.useCallback)(async(t=!1)=>{if(!f||t){v(!0);try{let t=await F(e.fullPath);g(t),m(!0)}catch{}finally{v(!1)}}},[f,e.fullPath]),w=(0,o.useRef)(f);(0,o.useEffect)(()=>{w.current=f}),(0,o.useEffect)(()=>{x&&f&&k(!0)},[c]);let S=(0,o.useCallback)(()=>{if(e.isDir){let t=!x;d(e.fullPath,t),t&&!f&&k()}else i(e.fullPath,e.name)},[e.isDir,e.fullPath,e.name,f,x,k,i,d]);return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{onClick:S,onMouseEnter:()=>j(!0),onMouseLeave:()=>j(!1),style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*t,paddingRight:8,height:24,cursor:"pointer",background:y?"var(--bg-hover)":"transparent",borderRadius:4,userSelect:"none"},children:[e.isDir&&(0,n.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:x?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,n.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!e.isDir&&(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,n.jsx)(p,{size:14,open:x}):D(e.name,14)}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),b&&(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,n.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),l&&y&&(0,n.jsxs)("button",{onClick:t=>{t.stopPropagation(),l((0,B.qP)(e.fullPath,r))},title:u("fileExplorer.insertPathIntoChat"),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,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,n.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]}),u("fileExplorer.mention")]})]}),e.isDir&&x&&(0,n.jsxs)("div",{children:[h.map(e=>(0,n.jsx)(U,{node:e,depth:t+1,cwd:r,onOpenFile:i,onAtMention:l,expandedPaths:a,onToggleExpanded:d,refreshKey:c},e.fullPath)),0===h.length&&f&&(0,n.jsx)("div",{style:{paddingLeft:8+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:u("fileExplorer.empty")})]})]})}function V({cwd:e,onOpenFile:t,refreshKey:r,onAtMention:i}){let{t:l}=(0,s.s)(),[a,d]=(0,o.useState)([]),[c,u]=(0,o.useState)(!0),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(new Set),f=(0,o.useRef)(null),m=(0,o.useCallback)((e,t)=>{g(r=>{let n=new Set(r);return t?n.add(e):n.delete(e),n})},[]);return((0,o.useEffect)(()=>{let t=f.current!==e;f.current=e,t&&g(new Set),u(t),x(null),F(e).then(e=>d(e)).catch(e=>x(String(e))).finally(()=>u(!1))},[e,r]),c)?(0,n.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:l("fileExplorer.loadingFiles")}):p?(0,n.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"#f87171"},children:p}):(0,n.jsxs)("div",{style:{padding:"2px 4px"},children:[a.map(o=>(0,n.jsx)(U,{node:o,depth:0,cwd:e,onOpenFile:t,onAtMention:i,expandedPaths:h,onToggleExpanded:m,refreshKey:r},o.fullPath)),0===a.length&&(0,n.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:l("fileExplorer.noFilesFound")})]})}function _(e,t){let r=t&&e.startsWith(t)?"~"+e.slice(t.length):e,n=r.includes("/")?"/":"\\",o=r.split(n).filter(Boolean);return o.length<=2?r:"…/"+o.slice(-2).join(n)}let K="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function q(){let{t:e}=(0,s.s)(),[t,r]=(0,o.useState)(!1),[i,l]=(0,o.useState)(!1),a=(0,o.useRef)(null),d=function(e,t){let[r,n]=(0,o.useState)(e),i=(0,o.useRef)(null),s=(0,o.useRef)(0);return(0,o.useEffect)(()=>{if(!t)return void n(e);s.current=0;let r=4*e.length,o=()=>{s.current+=1;let t=Math.floor(s.current/r*e.length);n(e.split("").map((e,r)=>" "===e?" ":r<t?e:K[Math.floor(Math.random()*K.length)]).join("")),s.current<r?i.current=requestAnimationFrame(o):n(e)};return i.current=requestAnimationFrame(o),()=>{i.current&&cancelAnimationFrame(i.current)}},[e,t]),r}(t?"0.8.4p0.79.0":e("sessionSidebar.title"),i),c=(0,o.useCallback)(e=>{r(e),l(!0),setTimeout(()=>l(!1),(e?6:8)*4*(1e3/60)+100)},[]),u=(0,o.useCallback)(()=>{a.current&&clearTimeout(a.current);let e=!t;c(e),e&&(a.current=setTimeout(()=>c(!1),3e3))},[t,c]);return(0,o.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]),(0,n.jsxs)("button",{onClick:u,"aria-label":e("sessionSidebar.title"),style:{display:"inline-flex",alignItems:"center",gap:8,background:"none",border:"none",padding:0,cursor:"default",color:t?"var(--accent)":"var(--text)",minWidth:"6ch"},children:[(0,n.jsx)("img",{src:"/icon-192.png",alt:"",width:24,height:24,style:{display:"block",borderRadius:6,flexShrink:0}}),(0,n.jsx)("span",{style:{fontWeight:700,fontSize:15,letterSpacing:0,fontFamily:"var(--font-mono)"},children:d})]})}function J({selectedSessionId:e,onSelectSession:t,onNewSession:r,onOpenSettings:i,isSettingsView:a=!1,initialSessionId:d,onInitialRestoreDone:u,refreshKey:p,onSessionDeleted:x,onSessionRenamed:h,pinnedSession:g,selectedCwd:f,onCwdChange:m,onOpenFile:b,explorerRefreshKey:v,onAtMention:y}){let j,{t:k}=(0,s.s)(),[w,S]=(0,o.useState)([]),[C,N]=(0,o.useState)([]),[T,I]=(0,o.useState)(!0),[L,R]=(0,o.useState)(null),[z,M]=(0,o.useState)(null),[E,W]=(0,o.useState)(""),[A,P]=(0,o.useState)(!1),[$,O]=(0,o.useState)(!1),[H,D]=(0,o.useState)(""),[B,F]=(0,o.useState)(null),[U,K]=(0,o.useState)(!1),Y=(0,o.useRef)(null),Z=(0,o.useRef)(null),X=(0,o.useRef)(null),[Q,ee]=(0,o.useState)(null),[et,er]=(0,o.useState)(!0),[en,eo]=(0,o.useState)(0),[ei,es]=(0,o.useState)(!1),[el,ea]=(0,o.useState)(!1),ed=(0,o.useRef)(null),ec=(0,o.useRef)(null),eu=(0,o.useRef)(0),ep=(0,o.useCallback)(async(e=!1)=>{let t=++eu.current;try{e&&I(!0);let r=await l("/api/sessions",{cache:"no-store"});if(t!==eu.current)return;if(401===r.status)throw Error("auth");if(!r.ok)throw Error(`HTTP ${r.status}`);let n=await r.json();S(n.sessions),Array.isArray(n.projectCwds)&&N(n.projectCwds),R(null),e||(es(!0),ed.current&&clearTimeout(ed.current),ed.current=setTimeout(()=>es(!1),2e3))}catch(e){if(t!==eu.current)return;(e instanceof TypeError||e instanceof DOMException&&"TimeoutError"===e.name||e instanceof Error&&/failed to fetch|networkerror|load failed/i.test(e.message)?0:1)?e instanceof Error&&"auth"===e.message?R(k("remoteAccess.authRequired")):R(String(e)):R(k("sessionSidebar.serverUnavailable"))}finally{t===eu.current&&I(!1)}},[k]),ex=(0,o.useRef)(!1);(0,o.useEffect)(()=>{let e=!ex.current;ex.current=!0,ep(e)},[ep,p]),(0,o.useEffect)(()=>{void 0!==v&&eo(e=>e+1)},[v]),(0,o.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&W(e.home)}).catch(()=>{})},[]);let eh=(0,o.useRef)(!1);(0,o.useEffect)(()=>{m?.(z)},[z,m]),(0,o.useEffect)(()=>{if(!d||eh.current||T)return;let e=e=>{eh.current=!0,u?.(e)};if(null===z){if(f){M(f);let r=w.find(e=>e.id===d);if(r&&r.cwd===f){t(r,!0),e(!0);return}e(!1);return}let r=w.find(e=>e.id===d);if(r){M(r.cwd),t(r,!0),e(!0);return}e(!1);let n=C.length>0?C:c(w);n.length>0&&M(n[0]);return}let r=w.find(e=>e.id===d);if(r){t(r,!0),e(!0);return}e(!1)},[T,w,C,z,f,d,t,u]),(0,o.useEffect)(()=>{null===z&&f&&M(f)},[f,z]);let eg=(0,o.useRef)(null);(0,o.useEffect)(()=>{e&&e!==eg.current&&f&&M(f),eg.current=e},[e,f]);let ef=z??f,em=(0,o.useCallback)(async()=>{let e=H.trim();if(e&&!U){K(!0),F(null);try{let t=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)return void F(r.error??`HTTP ${t.status}`);M(r.cwd??e),O(!1),D(""),P(!1)}catch(e){F(e instanceof Error?e.message:String(e))}finally{K(!1)}}},[H,U]),eb=(0,o.useCallback)(async()=>{try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json();t.cwd&&(M(t.cwd),O(!1),D(""),F(null),P(!1))}catch{}},[]);(0,o.useEffect)(()=>{if(!A)return;let e=e=>{let t=e.target;Z.current?.contains(t)||X.current?.contains(t)||(P(!1),O(!1),D(""),F(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[A]);let ev=(0,o.useCallback)(()=>{if(!ef)return;let e="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;r?.(e,ef)},[ef,r]),ey=(0,o.useMemo)(()=>{let e=new Set(C),t=[...C];for(let r of c(w))e.has(r)||(e.add(r),t.push(r));return t},[C,w]),ej=ef?w.filter(e=>e.cwd===ef):w,ek=function(e){let t=new Map;for(let r of e)t.set(r.id,{session:r,children:[]});let r=new Map;for(let t of e)t.parentSessionId&&r.set(t.id,t.parentSessionId);let n=[];for(let e of t.values()){let o=function(e){let n=r.get(e),o=new Set;for(;n&&!o.has(n);){if(o.add(n),t.has(n))return n;n=r.get(n)}return null}(e.session.id);o?t.get(o).children.push(e):n.push(e)}let o=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>o(e.children))};return o(n),n}((0,o.useMemo)(()=>!g||ef&&g.cwd!==ef||ej.some(e=>e.id===g.id)?ej:[g,...ej],[ej,g,ef]));return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{padding:"12px 10px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10},children:[(0,n.jsx)(q,{}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsxs)("button",{onClick:ev,disabled:!ef,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,background:"var(--bg-hover)",border:"1px solid var(--border)",color:ef?"var(--text-muted)":"var(--text-dim)",cursor:ef?"pointer":"not-allowed",height:32,paddingLeft:10,paddingRight:12,borderRadius:7,fontSize:12,fontWeight:500,letterSpacing:0,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:ef?k("sessionSidebar.newSessionIn",{cwd:ef}):k("sessionSidebar.selectProjectFirst"),onMouseEnter:e=>{ef&&(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=ef?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,n.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]}),k("sessionSidebar.newSession")]}),(0,n.jsx)("button",{onClick:()=>ep(!1),style:{display:"flex",alignItems:"center",justifyContent:"center",background:ei?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${ei?"rgba(74,222,128,0.4)":"var(--border)"}`,color:ei?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{ei||(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=>{ei||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:k("sessionSidebar.refresh"),children:ei?(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]})]}),(0,n.jsxs)("div",{ref:Z,style:{position:"relative"},children:[(0,n.jsx)("button",{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ee({top:t.top,left:t.left,width:t.width,bottom:t.bottom}),P(e=>!e)},style:{width:"100%",display:"flex",alignItems:"center",padding:"6px 10px",background:ef?"var(--bg-hover)":"rgba(37,99,235,0.06)",border:ef?"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:(0,n.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:11,color:ef?"var(--text)":"var(--text-dim)"},title:ef??"",children:ef?_(ef,E):d&&!eh.current?"":k("sessionSidebar.selectProject")})}),A&&Q&&(j=Math.max(120,Math.min((window.visualViewport?.height??window.innerHeight)-Q.bottom-12,520)),(0,n.jsxs)("div",{ref:X,style:{position:"fixed",top:Q.bottom+4,left:Q.left,width:Q.width,zIndex:1e3,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden",maxHeight:j,overflowY:"auto"},children:[ey.map(e=>(0,n.jsxs)("button",{onClick:()=>{if(e!==ef){let r=function(e,t){if(!t)return null;let r=null;for(let n of e)n&&n.cwd&&n.modified&&n.cwd===t&&(!r||n.modified>r.modified||n.modified===r.modified&&n.id>r.id)&&(r=n);return r}(w,e);r&&t(r)}M(e),O(!1),D(""),F(null),P(!1)},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:e===ef?"var(--bg-selected)":"none",border:"none",borderBottom:"1px solid var(--border)",color:e===ef?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:[e===ef&&(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}),e!==ef&&(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_(e,E)})]},e)),!$&&(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),eb()},style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",borderTop:ey.length>0?"1px solid var(--border)":"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,n.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,n.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,n.jsx)("span",{children:k("sessionSidebar.useDefaultDirectory")})]}),$?(0,n.jsxs)("div",{style:{padding:"6px 8px",borderTop:ey.length>0?"none":void 0},children:[(0,n.jsx)("input",{ref:Y,value:H,onChange:e=>{D(e.target.value),F(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),em()),"Escape"===e.key&&(O(!1),D(""),F(null))},placeholder:k("sessionSidebar.customPathPlaceholder"),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"}}),B&&(0,n.jsx)("div",{style:{marginTop:5,color:"#dc2626",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:B}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,n.jsx)("button",{onClick:()=>void em(),disabled:U||!H.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",fontSize:11,fontWeight:600,cursor:U||!H.trim()?"not-allowed":"pointer",opacity:U||!H.trim()?.65:1},children:U?k("common.loading"):k("sessionSidebar.open")}),(0,n.jsx)("button",{onClick:()=>{O(!1),D(""),F(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:k("sessionSidebar.cancel")})]})]}):(0,n.jsxs)("button",{onClick:e=>{e.stopPropagation(),O(!0),F(null),setTimeout(()=>Y.current?.focus(),0)},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,n.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,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,n.jsx)("span",{children:k("sessionSidebar.customPath")})]})]}))]})]}),(0,n.jsxs)("div",{style:{flex:et&&(f||z)?"1 1 0":"1 1 auto",overflowY:"auto",padding:"0",minHeight:80},children:[T&&(0,n.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:k("sessionSidebar.loading")}),L&&(0,n.jsxs)("div",{style:{padding:"12px 14px",color:"#f87171",fontSize:12},children:[(0,n.jsx)("div",{children:L}),(0,n.jsx)("button",{type:"button",onClick:()=>void ep(!0),style:{marginTop:8,fontSize:12,textDecoration:"underline",color:"var(--text-muted)"},children:k("common.retry")})]}),!T&&!L&&0===ej.length&&(0,n.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:k("sessionSidebar.noSessionsFound")}),ek.map(r=>(0,n.jsx)(G,{node:r,selectedSessionId:e,onSelectSession:t,onRenamed:(e,t)=>{h?.(e,t),ep()},onSessionDeleted:e=>{x?.(e),ep()},depth:0},r.session.id))]}),(f||z)&&(0,n.jsxs)("div",{style:{borderTop:"1px solid var(--border)",display:"flex",flexDirection:"column",flex:et?"1 1 0":"0 0 auto",minHeight:0,overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",flexShrink:0},children:[(0,n.jsxs)("button",{onClick:()=>er(e=>!e),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,n.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:et?"rotate(90deg)":"none",transition:"transform 0.15s",flexShrink:0},children:(0,n.jsx)("polyline",{points:"3 2 7 5 3 8"})}),k("sessionSidebar.explorer")]}),(0,n.jsx)("button",{onClick:()=>{eo(e=>e+1),ea(!0),ec.current&&clearTimeout(ec.current),ec.current=setTimeout(()=>ea(!1),2e3)},title:k("sessionSidebar.refreshExplorer"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,marginRight:6,background:el?"rgba(74,222,128,0.18)":"none",border:"none",color:el?"#4ade80":"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.3s, background 0.3s"},onMouseEnter:e=>{el||(e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{el||(e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none")},children:el?(0,n.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]})})]}),et&&(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",overflowX:"hidden"},children:(0,n.jsx)(V,{cwd:f??z,onOpenFile:b??(()=>{}),refreshKey:en,onAtMention:y})})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"10px",flexShrink:0},children:(0,n.jsxs)("button",{onClick:i,style:{display:"flex",alignItems:"center",gap:8,width:"100%",height:34,padding:"0 10px",background:a?"var(--bg-selected)":"var(--bg-hover)",border:`1px solid ${a?"color-mix(in srgb, var(--accent) 35%, var(--border))":"var(--border)"}`,borderRadius:8,color:a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--text)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 35%, var(--border))")},onMouseLeave:e=>{a||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,n.jsx)("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c.36.58.92.94 1.51 1H21a2 2 0 1 1 0 4h-.09c-.59.06-1.15.43-1.51 1Z"})]}),(0,n.jsx)("span",{children:k("common.settings")})]})})]})}function G({node:e,selectedSessionId:t,onSelectSession:r,onRenamed:i,onSessionDeleted:s,depth:l}){let[a,d]=(0,o.useState)(!1),c=e.children.length>0;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{position:"relative"},children:[l>0&&(0,n.jsx)("div",{style:{position:"absolute",left:12*l+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,n.jsx)(Y,{session:e.session,isSelected:e.session.id===t,onClick:()=>r(e.session),onRenamed:i,onDeleted:e=>s?.(e),depth:l,hasChildren:c,collapsed:a,onToggleCollapse:()=>d(e=>!e)})]}),c&&!a&&(0,n.jsx)("div",{children:e.children.map(e=>(0,n.jsx)(G,{node:e,selectedSessionId:t,onSelectSession:r,onRenamed:i,onSessionDeleted:s,depth:l+1},e.session.id))})]})}function Y({session:e,isSelected:t,onClick:r,onRenamed:i,onDeleted:l,depth:a=0,hasChildren:d=!1,collapsed:c=!1,onToggleCollapse:u}){var p;let x,h,g,f,m,{t:b,locale:v}=(0,s.s)(),[y,j]=(0,o.useState)(!1),[k,w]=(0,o.useState)(!1),[S,C]=(0,o.useState)(""),[N,T]=(0,o.useState)(!1),[I,L]=(0,o.useState)(!1),R=(0,o.useRef)(null),z=e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12),M=(0,o.useCallback)(e=>{e.stopPropagation(),C(z),w(!0),setTimeout(()=>R.current?.select(),0)},[z]),E=(0,o.useCallback)(async()=>{let t=S.trim();if(w(!1),t!==z.trim())try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),i?.(e.id,t)}catch{}},[S,e.id,z,i]),W=(0,o.useCallback)(e=>{e.stopPropagation(),T(!0)},[]),A=(0,o.useCallback)(async t=>{t.stopPropagation(),T(!1),L(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),l?.(e.id)}catch{L(!1)}},[e.id,l]),P=(0,o.useCallback)(e=>{e.stopPropagation(),T(!1)},[]);return(0,n.jsx)("div",{onClick:N||k?void 0:r,onMouseEnter:()=>j(!0),onMouseLeave:()=>{j(!1)},style:{height:54,display:"flex",alignItems:"center",paddingLeft:a>0?12*a+14:14,paddingRight:8,cursor:N||k?"default":"pointer",background:N?"rgba(239,68,68,0.06)":t?"var(--bg-selected)":y?"var(--bg-hover)":"transparent",borderLeft:N?"2px solid #ef4444":t?"2px solid var(--accent)":"2px solid transparent",transition:"background 0.1s",opacity:I?.5:1,gap:6,overflow:"hidden"},children:N?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sessionSidebar.deleteSessionPrompt",{name:`${z.slice(0,22)}${z.length>22?"…":""}`})}),(0,n.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,n.jsxs)("button",{onClick:A,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"#ef4444",border:"none",borderRadius:6,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),b("sessionSidebar.delete")]}),(0,n.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:b("sessionSidebar.cancel")})]})]}):k?(0,n.jsx)("input",{ref:R,value:S,onChange:e=>C(e.target.value),onBlur:E,onKeyDown:e=>{"Enter"===e.key&&E(),"Escape"===e.key&&w(!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,n.jsxs)(n.Fragment,{children:[a>0&&(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:t?500:400,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},title:z,children:z}),(0,n.jsxs)("div",{style:{marginTop:2,display:"flex",gap:8,color:"var(--text-dim)",fontSize:11},children:[(0,n.jsx)("span",{title:new Date(e.modified).toLocaleString(v),children:(p=e.modified,x=new Date(p),g=Math.floor((h=new Date().getTime()-x.getTime())/6e4),f=Math.floor(h/36e5),m=Math.floor(h/864e5),g<1?b("sessionSidebar.justNow"):g<60?b("sessionSidebar.minutesAgo",{count:g}):f<24?b("sessionSidebar.hoursAgo",{count:f}):m<7?b("sessionSidebar.daysAgo",{count:m}):x.toLocaleDateString())}),(0,n.jsx)("span",{children:b("sessionSidebar.messagesCount",{count:e.messageCount})})]})]}),d&&(0,n.jsx)("button",{onClick:e=>{e.stopPropagation(),u?.()},title:b(c?"sessionSidebar.expandForks":"sessionSidebar.collapseForks"),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:c?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),y&&(0,n.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,n.jsx)("button",{onClick:M,title:b("sessionSidebar.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,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,n.jsx)("button",{onClick:W,title:b("sessionSidebar.delete"),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,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,n.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,n.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,n.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}var Z=r(72261);async function X(e){let t=await fetch(`/api/agent/${encodeURIComponent(e)}/export.html`);if(!t.ok)throw Error((await t.json().catch(()=>({}))).error??`Export failed (${t.status})`);return{blob:await t.blob(),filename:function(e){if(!e)return null;let t=/filename="([^"]+)"/.exec(e);return t?.[1]??null}(t.headers.get("Content-Disposition"))??"session.html"}}function Q({sessionId:e,isStreaming:t,onClose:r}){let{t:i}=(0,s.s)(),[l,a]=(0,o.useState)(null),[d,c]=(0,o.useState)(!0),[u,p]=(0,o.useState)(null),[x,h]=(0,o.useState)(!1),g=(0,o.useCallback)(async()=>{if(t){p(i("chatInput.exportHtmlStreaming")),c(!1);return}c(!0),p(null);try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/share`,{method:"POST"}),r=await t.json();if(!t.ok||!r.url)throw Error(r.error??i("shareConversation.createFailed"));a(r.url)}catch(e){a(null),p(e instanceof Error?e.message:i("shareConversation.createFailed"))}finally{c(!1)}},[t,e,i]);(0,o.useEffect)(()=>{g()},[g]);let f=async()=>{if(l)try{await navigator.clipboard.writeText(l),h(!0),setTimeout(()=>h(!1),2e3)}catch{p(i("shareConversation.copyFailed"))}};return(0,n.jsx)("div",{className:"fixed inset-0 z-[1000] flex items-center justify-center bg-black/40 p-4",onClick:r,role:"presentation",children:(0,n.jsxs)("div",{className:"w-full max-w-[480px] rounded-[10px] border border-border bg-[var(--bg-popover)] p-5 shadow-lg",onClick:e=>e.stopPropagation(),role:"dialog","aria-modal":"true","aria-labelledby":"share-conversation-title",children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"share-conversation-title",className:"m-0 text-[16px] font-semibold text-text",children:i("shareConversation.title")}),(0,n.jsx)("p",{className:"m-0 mt-1 text-[12px] leading-5 text-text-muted",children:i("shareConversation.subtitle")})]}),(0,n.jsx)("button",{type:"button",onClick:r,className:"text-[12px] text-text-muted hover:text-text",children:i("common.close")})]}),(0,n.jsxs)("div",{className:"mt-4",children:[d?(0,n.jsx)("p",{className:"m-0 text-[12px] text-text-muted",children:i("shareConversation.generating")}):l?(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsx)("input",{type:"text",readOnly:!0,value:l,className:"min-w-0 flex-1 rounded-[6px] border border-border bg-bg-panel px-3 py-2 font-mono text-[11px] text-text",onFocus:e=>e.currentTarget.select()}),(0,n.jsx)("button",{type:"button",onClick:()=>void f(),className:"shrink-0 rounded-[6px] bg-accent px-3 py-2 text-[12px] font-medium text-white hover:bg-accent-hover",children:x?i("shareConversation.copied"):i("shareConversation.copyLink")})]}):null,(0,n.jsx)("p",{className:"mb-0 mt-3 text-[11px] leading-5 text-text-dim",children:i("shareConversation.hint")})]}),u?(0,n.jsx)("p",{className:"mb-0 mt-3 text-[12px] text-red-600 dark:text-red-400",children:u}):null]})})}function ee(e,t){let r=e.slice(0,t),n=r.match(/(?:^|\s)\/([\w:.-]*)$/);return n?{query:n[1]??"",replaceStart:r.length-n[0].length+(n[0].startsWith("/")?1:n[0].indexOf("/")+1)}:null}var et=r(54357);async function er(e){if(!e.length)return[];let t=await Promise.all(e.map(async e=>({name:e.name,mimeType:e.type||"application/octet-stream",base64:await new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{let e=n.result;t(e.includes(",")?e.split(",")[1]:e)},n.onerror=()=>r(n.error??Error("read failed")),n.readAsDataURL(e)})}))),r=await fetch("/api/files/stage",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:t})});if(!r.ok)throw Error((await r.json().catch(()=>({}))).error??`HTTP ${r.status}`);let n=await r.json();return n.files?.length?n.files.map(e=>({path:e.path,label:(e.label??e.name??(0,et.PG)(e.path)).trim()||(0,et.PG)(e.path)})):(n.paths??[]).map(e=>({path:e,label:(0,et.PG)(e)}))}async function en(){let e=window.piNative?.pickFiles;if(!e)return null;let t=await e();return t?.length?t.map(e=>({path:e,label:(0,et.gp)(e)})):null}var eo=r(89974);let ei=["off","default","full"],es={off:"none",default:"default",full:"full"},el=["auto","off","minimal","low","medium","high","xhigh"],ea=(0,o.forwardRef)(function({onSend:e,onAbort:t,onSteer:r,onFollowUp:i,isStreaming:l,steerMode:a=!1,model:d,modelNames:c,modelList:u,supportsImages:p=!0,onModelChange:x,onCompact:h,onAbortCompaction:g,isCompacting:f,compactError:m,toolPreset:b,onToolPresetChange:v,showAdvancedTools:y=!1,thinkingLevel:j,onThinkingLevelChange:k,availableThinkingLevels:w,thinkingLevelMap:S,retryInfo:C,soundEnabled:N,onSoundToggle:T,sessionId:I=null,slashCommandsEnabled:L=!1,slashCommands:R=[],onOpenFile:z},M){var E;let W,A,P,{t:$}=(0,s.s)(),O=(E=m??null)?E.startsWith("branchNavigator.")?$(E):E:null,[H,D]=(0,o.useState)(""),[B,F]=(0,o.useState)(!1),[U,V]=(0,o.useState)(null),[_,K]=(0,o.useState)(!1),[q,J]=(0,o.useState)(!1),[G,Y]=(0,o.useState)([]),[Z,ea]=(0,o.useState)([]),[ed,ec]=(0,o.useState)(!1),[eu,ep]=(0,o.useState)(null),[ex,eh]=(0,o.useState)(null),eg=(0,o.useRef)(null),[ef,em]=(0,o.useState)(0),[eb,ev]=(0,o.useState)(0),[ey,ej]=(0,o.useState)(!1),[ek,ew]=(0,o.useState)(null),[eS,eC]=(0,o.useState)(!1),eN=(0,o.useRef)(null),eT=(0,o.useRef)(null),eI=(0,o.useRef)(null),eL=(0,o.useRef)(null),eR=(0,o.useRef)(null),ez=(0,o.useRef)(null),eM=(0,o.useRef)(!1),eE=(0,o.useRef)(0);(0,o.useImperativeHandle)(M,()=>({insertIfEmpty(e){let t=eN.current;(t?t.value:H).trim()||(D(e),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},insertText(e){let t=eN.current;if(!t)return void D(t=>t+(t?" ":"")+e);let r=t.selectionStart??t.value.length,n=t.selectionEnd??t.value.length,o=t.value.slice(0,r),i=t.value.slice(n),s=o.length>0&&!o.endsWith(" ")?" ":"";D(o+s+e+i),requestAnimationFrame(()=>{if(!t)return;let n=r+s.length+e.length;t.setSelectionRange(n,n),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addImages(e){eP(e)},addFiles(e){eP(e)}}));let eW=(0,o.useCallback)(async e=>{if(!p)return;let t=e.filter(e=>e.type.startsWith("image/"));if(!t.length)return;let r=await Promise.all(t.map(e=>new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{t({data:n.result.split(",")[1],mimeType:e.type,previewUrl:URL.createObjectURL(e)})},n.onerror=r,n.readAsDataURL(e)})));Y(e=>[...e,...r])},[p]),eA=(0,o.useCallback)(e=>{e.length&&ea(t=>{let r=new Set(t.map(e=>e.path)),n=[...t];for(let t of e){let e=(0,et.Qq)(t);r.has(e.path)||(r.add(e.path),n.push(e))}return n})},[]),eP=(0,o.useCallback)(async e=>{if(e.length){ep(null),ec(!0);try{let t=await er(e);eA(t)}catch(e){ep(e instanceof Error?e.message:$("chatInput.attachFileFailed"))}finally{ec(!1)}}},[eA,$]),e$=(0,o.useCallback)(async()=>{if(!l&&!ed){if(ep(null),window.piNative?.pickFiles)try{let e=await en();e?.length&&eA(e);return}catch(e){ep(e instanceof Error?e.message:$("chatInput.attachFileFailed"));return}ez.current?.click()}},[l,ed,eA,$]),eO=(0,o.useCallback)(e=>{Y(t=>{let r=[...t];return URL.revokeObjectURL(r[e].previewUrl),r.splice(e,1),r})},[]),eH=(0,o.useCallback)(()=>{Y(e=>(e.forEach(e=>URL.revokeObjectURL(e.previewUrl)),[]))},[]),eD=(0,o.useCallback)(()=>{ea([])},[]);(0,o.useEffect)(()=>{p||eH()},[p,eH]);let eB=G.length>0||Z.length>0,eF=(0,o.useCallback)(()=>{let t=H.trim();(t||eB)&&!l&&(e(t,G.length?G:void 0,Z.length?Z:void 0),D(""),eH(),eD(),eN.current&&(eN.current.style.height="auto"))},[H,eB,G,Z,l,e,eH,eD]),eU=(0,o.useCallback)(e=>{let t=H.trim();if(!t&&!eB)return;let n=G.length?G:void 0,o=Z.length?Z:void 0;"steer"===e&&r?r(t,n,o):"followup"===e&&i&&i(t,n,o),D(""),eH(),eD(),eN.current&&(eN.current.style.height="auto")},[H,eB,G,Z,r,i,eH,eD]),eV=(0,o.useMemo)(()=>L?ee(H,ef):null,[L,H,ef]),e_=(0,o.useMemo)(()=>{let e;return eV?(e=eV.query.toLowerCase())?R.filter(t=>t.name.toLowerCase().includes(e)||(t.description?.toLowerCase().includes(e)??!1)).slice(0,50):R.slice(0,50):[]},[R,eV]),eK=!!(eV&&e_.length>0);(0,o.useEffect)(()=>{ev(0)},[eV?.query]),(0,o.useEffect)(()=>()=>{null!==eg.current&&(window.clearTimeout(eg.current),eg.current=null)},[]);let eq=(0,o.useCallback)(()=>{let e=eN.current;e&&em(e.selectionStart??e.value.length)},[]),eJ=(0,o.useCallback)(e=>{let t=eN.current,r=function(e,t,r){let n=ee(e,t);if(!n)return null;let o=n.replaceStart-1,i=`/${r} `;return{text:e.slice(0,o)+i+e.slice(t),cursor:o+i.length}}(H,t?t.selectionStart??t.value.length:ef,e);r&&(D(r.text),requestAnimationFrame(()=>{let e=eN.current;e&&(e.focus(),e.setSelectionRange(r.cursor,r.cursor),em(r.cursor),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[H,ef]),eG=(0,o.useCallback)(e=>{let t=e.nativeEvent,n=Date.now()-eE.current<100,o=eM.current||t.isComposing||229===t.keyCode;if(eK){if("ArrowDown"===e.key){e.preventDefault(),ev(e=>(e+1)%e_.length);return}if("ArrowUp"===e.key){e.preventDefault(),ev(e=>(e-1+e_.length)%e_.length);return}if(("Enter"===e.key||"Tab"===e.key)&&!e.shiftKey&&!o&&!n){e.preventDefault();let t=e_[eb];t&&eJ(t.name);return}if("Escape"===e.key)return void e.preventDefault()}if("Enter"===e.key&&!e.shiftKey&&(o||n)){n&&e.preventDefault();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),a&&(r||i)?eU(r?"steer":"followup"):l&&i?eU("followup"):eF())},[eK,e_,eb,eJ,l,a,r,i,eU,eF]),eY=(0,o.useCallback)(async()=>{if(I&&!ey){if(l)return void ew($("chatInput.exportHtmlStreaming"));ej(!0),ew(null);try{let e,t,{blob:r,filename:n}=await X(I);e=URL.createObjectURL(r),(t=document.createElement("a")).href=e,t.download=n,t.click(),URL.revokeObjectURL(e)}catch(e){ew(e instanceof Error?e.message:$("chatInput.exportHtmlFailed"))}finally{ej(!1)}}},[I,ey,l,$]),eZ=(0,o.useCallback)(()=>{let e=eN.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),eX=(0,o.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>e.type.startsWith("image/"));if(t.length){if(e.preventDefault(),!p){eh($("chatInput.imagesNotSupported")),null!==eg.current&&window.clearTimeout(eg.current),eg.current=window.setTimeout(()=>{eh(null),eg.current=null},4e3);return}eW(t.map(e=>e.getAsFile()).filter(e=>null!==e))}},[eW,p,$]),eQ=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})):Object.entries(c??{}).map(([e,t])=>({provider:d?.provider??"unknown",modelId:e,name:t})),e0=[];for(let e of eQ){let t=e0.find(t=>t.provider===e.provider);t?t.options.push(e):e0.push({provider:e.provider,options:[e]})}let e1=d?eQ.find(e=>e.modelId===d.modelId&&e.provider===d.provider)?.name??d.modelId:eQ.length>0?eQ[0].name:null;return(0,o.useEffect)(()=>{let e=e=>{eT.current&&!eT.current.contains(e.target)&&eI.current&&!eI.current.contains(e.target)&&F(!1),eL.current&&!eL.current.contains(e.target)&&K(!1),eR.current&&!eR.current.contains(e.target)&&J(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,n.jsxs)("div",{style:{flexShrink:0,background:"transparent",padding:"0 16px 8px",paddingRight:52},children:[(0,n.jsx)("input",{ref:ez,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{eP(Array.from(e.target.files??[])),e.target.value=""}}),(0,n.jsxs)("div",{style:{maxWidth:820,margin:"0 auto"},children:[ek&&(0,n.jsx)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",borderRadius:6,fontSize:12,color:"rgba(220,80,80,0.95)"},children:ek}),eu&&(0,n.jsx)("div",{style:{marginBottom:8,padding:"5px 10px",background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",borderRadius:6,fontSize:12,color:"rgba(220,80,80,0.95)"},children:eu}),ex&&(0,n.jsxs)("div",{role:"status","aria-live":"polite",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.95)",display:"flex",alignItems:"center",gap:6},children:[(0,n.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,n.jsx)("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),(0,n.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,n.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),ex]}),C&&(0,n.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,n.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,n.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,n.jsx)("path",{d:"M3 3v5h5"})]}),C.errorMessage?$("chatInput.retryingWithError",{attempt:C.attempt,maxAttempts:C.maxAttempts,error:C.errorMessage}):$("chatInput.retrying",{attempt:C.attempt,maxAttempts:C.maxAttempts})]}),(Z.length>0||ed)&&(0,n.jsxs)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap",alignItems:"center"},children:[ed&&(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:$("chatInput.attachFileStaging")}),Z.map((e,t)=>(0,n.jsx)(eo.O,{name:e.label,path:e.path,variant:"input",onOpen:z?()=>z(e.path,e.label):void 0,onRemove:()=>ea(e=>e.filter((e,r)=>r!==t))},e.path))]}),G.length>0&&(0,n.jsx)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap"},children:G.map((e,t)=>(0,n.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,n.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}}),(0,n.jsx)("button",{onClick:()=>eO(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,n.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,n.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},t))}),eK&&(0,n.jsx)("div",{style:{marginBottom:6,maxHeight:200,overflow:"auto",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)"},children:e_.map((e,t)=>(0,n.jsx)("button",{type:"button",onMouseDown:t=>{t.preventDefault(),eJ(e.name)},style:{display:"flex",width:"100%",alignItems:"center",padding:"8px 12px",background:t===eb?"var(--bg-selected)":"none",border:"none",color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:(0,n.jsxs)("span",{style:{fontFamily:"var(--font-mono)"},children:["/",e.name]})},`${e.source}-${e.name}`))}),(0,n.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center",background:"var(--bg-elevated)",border:`1px solid ${a&&(r||i)?"rgba(255,149,0,0.45)":"var(--border-strong)"}`,borderRadius:18,padding:"11px 11px 11px 15px",boxShadow:"var(--shadow-composer)",backdropFilter:"var(--chrome-blur)",WebkitBackdropFilter:"var(--chrome-blur)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,n.jsx)("textarea",{ref:eN,value:H,onChange:e=>{D(e.target.value),em(e.target.selectionStart??e.target.value.length)},onKeyDown:eG,onKeyUp:eq,onClick:eq,onSelect:eq,onCompositionStart:()=>{eM.current=!0},onCompositionEnd:()=>{eM.current=!1,eE.current=Date.now()},onInput:eZ,onPaste:eX,placeholder:a&&(r||i)?$("chatInput.placeholderSteer"):l?$("chatInput.placeholderRunning"):$("chatInput.placeholderDefault"),rows:1,style:{flex:1,background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),a?(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:[r&&(0,n.jsxs)("button",{onClick:()=>eU("steer"),disabled:!H.trim()&&!eB,title:$("chatInput.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:H.trim()||eB?"rgba(234,179,8,0.12)":"none",border:"1px solid rgba(234,179,8,0.35)",borderRadius:8,color:H.trim()||eB?"rgba(180,130,0,1)":"var(--text-dim)",cursor:H.trim()||eB?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:0,transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,n.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),$("chatInput.steer")]}),i&&(0,n.jsxs)("button",{onClick:()=>eU("followup"),disabled:!H.trim()&&!eB,title:$("chatInput.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:H.trim()||eB?"rgba(129,140,248,0.12)":"none",border:"1px solid rgba(129,140,248,0.35)",borderRadius:8,color:H.trim()||eB?"rgba(99,102,241,1)":"var(--text-dim)",cursor:H.trim()||eB?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:0,transition:"background 0.12s"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,n.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,n.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),$("chatInput.followUp")]})]}):l?null:(0,n.jsxs)("button",{onClick:eF,disabled:!H.trim()&&!eB,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:H.trim()||eB?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:10,color:H.trim()||eB?"#fff":"var(--text-dim)",cursor:H.trim()||eB?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:0,boxShadow:H.trim()||eB?"0 8px 18px rgba(0,122,255,0.26)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,n.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),$("chatInput.send")]})]}),(0,n.jsxs)("div",{style:{marginTop:8,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[(0,n.jsxs)("div",{style:{flex:"0 0 auto",display:"flex",alignItems:"center",gap:2},children:[(0,n.jsx)("button",{onClick:()=>void e$(),disabled:l||ed,title:$("chatInput.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:Z.length?"var(--accent)":"var(--text-muted)",cursor:l||ed?"not-allowed":"pointer",opacity:l||ed?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||ed||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=Z.length?"var(--accent)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=Z.length?"var(--accent)":"var(--text-muted)"},children:(0,n.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),eQ.length>0&&e1&&x&&(0,n.jsxs)("div",{ref:eT,style:{position:"relative"},children:[(0,n.jsxs)("button",{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();V({top:t.top,left:t.left,width:t.width}),F(e=>!e)},disabled:l,style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",height:32,maxWidth:220,overflow:"hidden",background:B?"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=B?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e1})]}),B&&U&&(A=(W=window.visualViewport?.height??window.innerHeight)-U.top+6,P=Math.max(120,Math.min(U.top-8,.6*W)),(0,n.jsx)("div",{ref:eI,style:{position:"fixed",bottom:A,left:U.left,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 -4px 16px rgba(0,0,0,0.10)",overflow:"hidden",width:"max-content",minWidth:U.width,maxHeight:P,overflowY:"auto"},children:e0.map((e,t)=>(0,n.jsxs)("div",{children:[e0.length>1&&(0,n.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>{let t=e.modelId===d?.modelId&&e.provider===d?.provider;return(0,n.jsxs)("button",{onClick:()=>{F(!1),t||x(e.provider,e.modelId)},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,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),e.name]},`${e.provider}:${e.modelId}`)})]},e.provider))}))]})]}),(0,n.jsx)("div",{style:{flex:1}}),(0,n.jsxs)("div",{style:{flex:"0 1 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",gap:2,marginLeft:"auto",flexWrap:"wrap",maxWidth:"100%"},children:[!l&&k&&(0,n.jsxs)("div",{ref:eR,style:{position:"relative"},children:[(0,n.jsxs)("button",{onClick:()=>!l&&J(e=>!e),disabled:l,title:$("chatInput.toggleThinking"),style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:q?"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=q?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.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,n.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,n.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),(0,n.jsx)("span",{children:(()=>{let e=j??"auto";if("auto"===e||!S)return $("chatInput.thinkingLevelDefault");let t=S[e];return null!=t?t:e})()})]}),q&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",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:el.filter(e=>!w||"auto"===e||w.includes(e)).map(e=>{let t=(j??"auto")===e,r="auto"===e?$("chatInput.thinkingLevelDefault"):"off"===e?$("chatInput.thinkingLevelOff"):"minimal"===e?$("chatInput.thinkingLevelMinimal"):"low"===e?$("chatInput.thinkingLevelLow"):"medium"===e?$("chatInput.thinkingLevelMedium"):"high"===e?$("chatInput.thinkingLevelHigh"):$("chatInput.thinkingLevelMax"),o="auto"!==e&&S?S[e]:void 0,i=null!=o&&o!==e?o:e,s=null!=o&&o!==e;return(0,n.jsxs)("button",{onClick:()=>{J(!1),t||k(e)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsxs)("span",{style:{flex:1},children:[i,s&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",e,")"]})]}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:r})]},e)})})]}),!l&&v&&y&&(0,n.jsxs)("div",{ref:eL,style:{position:"relative"},children:[(0,n.jsxs)("button",{onClick:()=>!l&&K(e=>!e),disabled:l,title:$("chatInput.toggleToolPreset"),style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:_?"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=_?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.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"})}),(0,n.jsx)("span",{children:Object.entries(es).find(([,e])=>e===(b??"default"))?.[0]??$("chatInput.defaultPreset")})]}),_&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",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:120},children:ei.map(e=>{let t=es[e],r=(b??"default")===t,o="off"===e?$("chatInput.toolPresetNone"):"default"===e?$("chatInput.toolPresetDefault"):$("chatInput.toolPresetFull");return(0,n.jsxs)("button",{onClick:()=>{K(!1),r||v(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:r?"var(--bg-selected)":"none",border:"none",color:r?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:r?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{r||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{r||(e.currentTarget.style.background="none")},children:[r?(0,n.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,n.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,n.jsx)("span",{style:{width:10,flexShrink:0}}),(0,n.jsx)("span",{style:{flex:1},children:e}),(0,n.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:o})]},e)})})]}),I&&!l&&(0,n.jsx)("button",{type:"button",onClick:()=>eC(!0),title:$("shareConversation.title"),style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:12,whiteSpace:"nowrap"},children:$("shareConversation.button")}),I&&!l&&(0,n.jsx)("button",{type:"button",onClick:()=>void eY(),disabled:ey,title:$("chatInput.exportHtmlTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:"none",border:"none",borderRadius:9,color:ey?"var(--accent)":"var(--text-muted)",cursor:ey?"not-allowed":"pointer",fontSize:12,whiteSpace:"nowrap"},children:ey?$("settings.exporting"):$("chatInput.exportHtml")}),!l&&h&&(0,n.jsxs)("div",{style:{position:"relative"},children:[O&&(0,n.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,background:"#1f2937",color:"#f87171",fontSize:11,padding:"4px 8px",borderRadius:5,whiteSpace:"nowrap",pointerEvents:"none",boxShadow:"0 2px 8px rgba(0,0,0,0.2)",zIndex:50},children:O}),(0,n.jsx)("button",{onClick:f?g:h,disabled:l&&!f,style:{display:"flex",alignItems:"center",gap:5,padding:"8px 12px",height:32,background:f?"rgba(239,68,68,0.08)":"none",border:"none",borderRadius:9,color:f?"#ef4444":"var(--text-muted)",cursor:l&&!f?"not-allowed":"pointer",fontSize:12,opacity:l&&!f?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||f)&&(e.currentTarget.style.background=f?"rgba(239,68,68,0.16)":"var(--bg-hover)",e.currentTarget.style.color=f?"#ef4444":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=f?"rgba(239,68,68,0.08)":"none",e.currentTarget.style.color=f?"#ef4444":"var(--text-muted)"},title:f?$("chatInput.stopCompacting"):$("chatInput.compactContext"),children:f?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),$("chatInput.compacting")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,n.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,n.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,n.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),$("chatInput.compact")]})})]}),l&&(0,n.jsxs)("button",{onClick:t,title:$("chatInput.stopAgentTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",height:32,background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.3)",borderRadius:9,color:"#ef4444",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:0,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,n.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,n.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),$("chatInput.stop")]}),void 0!==T&&(0,n.jsx)("button",{onClick:T,title:N?$("chatInput.soundOff"):$("chatInput.soundOn"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:N?"var(--text-muted)":"var(--text-dim)",cursor:"pointer",opacity:N?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=N?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.opacity=N?"1":"0.55"},children:N?(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),(0,n.jsx)("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,n.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,n.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})})]})]})]}),eS&&I?(0,n.jsx)(Q,{sessionId:I,isStreaming:l,onClose:()=>eC(!1)}):null]})});function ed(e){return"user"===e.role?{bg:"rgba(37,99,235,0.18)",border:"rgba(37,99,235,0.7)"}:{bg:"rgba(107,114,128,0.12)",border:"rgba(107,114,128,0.5)"}}function ec({messages:e,streamingMessage:t,scrollContainer:r,messageRefs:i}){let[s,l]=(0,o.useState)(0),[a,d]=(0,o.useState)(1),[c,u]=(0,o.useState)(!1),[p,x]=(0,o.useState)([]),[h,g]=(0,o.useState)(!1),[f,m]=(0,o.useState)(null),b=(0,o.useRef)(!1),v=(0,o.useRef)(null),y=(0,o.useMemo)(()=>t?[...e,t]:e,[e,t]),j=(0,o.useRef)(y);j.current=y;let k=(0,o.useRef)(null);k.current=()=>{let e=r.current;if(!e)return;let t=e.scrollHeight,n=e.clientHeight,o=t-n;u(o>20),o<=0?(l(0),d(1)):(l(e.scrollTop/o),d(n/t));let s=i.current,a=[],c=0,p=j.current;for(let r=0;r<p.length;r++){let n=p[r];if("user"!==n.role&&"assistant"!==n.role)continue;let o=s?.[c];if(c++,("user"===n.role||"assistant"===n.role&&(n.content??[]).some(e=>"text"===e.type))&&o&&t>0){let r=o.getBoundingClientRect(),i=e.getBoundingClientRect(),s=r.top-i.top+e.scrollTop,l=r.height;a.push({topRatio:s/t,heightRatio:l/t,msg:n,index:a.length})}}x(a)};let w=(0,o.useCallback)(()=>k.current(),[]);(0,o.useEffect)(()=>{let e=r.current;if(!e)return;e.addEventListener("scroll",w,{passive:!0});let t=new ResizeObserver(w);return t.observe(e),e.firstElementChild&&t.observe(e.firstElementChild),w(),()=>{e.removeEventListener("scroll",w),t.disconnect()}},[r,w]),(0,o.useEffect)(()=>{let e=setTimeout(w,50);return()=>clearTimeout(e)},[e.length,w]);let S=(0,o.useCallback)(e=>{if(!c)return;let t=r.current;if(!t)return;let n=e=>{let r=t.scrollHeight-t.clientHeight;r<=0||(t.scrollTop=Math.max(0,Math.min(1-a,e))/(1-a)*r)};b.current=!0;let o=e.currentTarget.getBoundingClientRect(),i=(e.clientY-o.top)/o.height,l=i-s*(1-a),d=l>=0&&l<=a?l:a/2;n(i-d);let u=e=>{b.current&&n((e.clientY-o.top)/o.height-d)},p=()=>{b.current=!1,window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",p)};window.addEventListener("mousemove",u),window.addEventListener("mouseup",p)},[c,a,s,r]),C=v.current?.clientHeight??600,N=(0,o.useMemo)(()=>{if(!h||0===p.length)return[];let e=p.map(e=>Math.round(e.topRatio*C-11));for(let t=0;t<10;t++){for(let t=1;t<e.length;t++){let r=e[t-1]+22+2;e[t]<r&&(e[t]=r)}for(let t=e.length-2;t>=0;t--){let r=e[t+1]-22-2;e[t]>r&&(e[t]=r)}}for(let t=0;t<e.length;t++)e[t]=Math.max(0,Math.min(C-22,e[t]));return e},[h,p,C]);if(!c)return null;let T=s*(1-a)*100,I=100*a,L=null!==f&&p.length>0?p.reduce((e,t)=>Math.abs(t.topRatio-f)<Math.abs(p[e].topRatio-f)?t.index:e,0):null;return(0,n.jsxs)("div",{ref:v,onMouseDown:S,onMouseEnter:()=>g(!0),onMouseLeave:()=>{g(!1),m(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();m((e.clientY-t.top)/t.height)},style:{width:36,flexShrink:0,position:"relative",cursor:"default",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[(0,n.jsx)("div",{style:{position:"absolute",left:0,right:0,top:`${T}%`,height:`${I}%`,background:"rgba(100,100,100,0.1)",borderTop:"1px solid rgba(100,100,100,0.2)",borderBottom:"1px solid rgba(100,100,100,0.2)",pointerEvents:"none",zIndex:1}}),p.map(e=>{let t=ed(e.msg),r=h&&L===e.index,o="user"===e.msg.role,i=100*e.topRatio;return(0,n.jsx)("div",{style:{position:"absolute",top:`${i}%`,transform:"translateY(-50%)",left:0,right:0,height:"12px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",zIndex:2},children:(0,n.jsx)("div",{style:{width:o?8:6,height:o?8:6,borderRadius:o?2:"50%",background:t.bg,border:`1.5px solid ${t.border}`,flexShrink:0,transition:"transform 0.1s",transform:r?"scale(1.6)":"scale(1)"}})},e.index)}),(0,n.jsx)("div",{style:{position:"absolute",left:"50%",top:0,bottom:0,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),h&&p.map((e,t)=>{let r=function(e){if("user"===e.role){let t=e.content;return"string"==typeof t?t.slice(0,200):Array.isArray(t)?t.filter(e=>"text"===e.type&&e.text).map(e=>e.text).join("\n").slice(0,200):""}if("assistant"===e.role){let t=e.content??[],r=t.filter(e=>"text"===e.type).map(e=>e.text).join(" ");if(r)return r.slice(0,200);let n=t.filter(e=>"toolCall"===e.type).map(e=>e.toolName);if(n.length)return n.join(", ")}return""}(e.msg),o=ed(e.msg),i=L===e.index;return r&&0!==N.length?(0,n.jsx)("div",{style:{position:"absolute",top:N[t],right:"100%",marginRight:6,background:"var(--bg)",borderTop:`1px solid ${i?o.border:"var(--border)"}`,borderRight:`1px solid ${i?o.border:"var(--border)"}`,borderBottom:`1px solid ${i?o.border:"var(--border)"}`,borderLeft:`2px solid ${o.border}`,borderRadius:4,padding:"2px 7px",width:200,zIndex:100,pointerEvents:"none",opacity:i?1:.45,transition:"top 0.1s, opacity 0.1s"},children:(0,n.jsx)("div",{style:{fontSize:11,color:i?"var(--text)":"var(--text-muted)",lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:r})},e.index):null})]})}function eu(e){let t="timelineSummary"===e.role&&"string"==typeof e.summary?{role:"timelineSummary",kind:"branch"===e.kind?"branch":"compaction",summary:e.summary,timestamp:"number"==typeof e.timestamp?e.timestamp:void 0}:"compactionSummary"===e.role?{role:"timelineSummary",kind:"compaction",summary:String(e.summary??""),timestamp:"number"==typeof e.timestamp?e.timestamp:void 0}:"branchSummary"===e.role?{role:"timelineSummary",kind:"branch",summary:String(e.summary??""),timestamp:"number"==typeof e.timestamp?e.timestamp:void 0}:null;if(t)return t;if("assistant"!==e.role)return e;let r=e.content;if(!Array.isArray(r))return e;let n=r.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{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})??e);return{...e,content:n}}async function ep(e,t){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),n=await r.json().catch(()=>({}));if(!r.ok||n.error)throw Error(n.error??`HTTP ${r.status}`);return n.data}let ex=[],eh=["read","bash","edit","write"],eg=["bash","read","edit","write","grep","find","ls"],ef="pi-web-preferences-cache";function em(){try{let e=localStorage.getItem(ef);if(!e)return{};let t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}function eb(e){try{localStorage.setItem(ef,JSON.stringify(e))}catch{}}function ev(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function ey(){let e=window.piNative;return e?.showNotification?e:null}async function ej(e){if(!1===em().notificationsEnabled)return;let t=ey();t?t.showNotification({sessionId:e.sessionId,sessionName:e.sessionName,title:e.sessionName?.trim()||void 0,body:void 0}):await fetch("/api/notifications/agent-end",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ek(){return globalThis.__piControlCache||(globalThis.__piControlCache=new Map),globalThis.__piControlCache}function ew(e){for(let t of e.listeners)t(e.state)}function eS(e){if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function eC(e){let t=ek(),r=t.get(e);if(r)return r;let n={state:{status:"idle",data:null,error:null,fetchedAt:0},inflight:null,listeners:new Set};return t.set(e,n),n}async function eN(e,t,r){let n=async o=>{try{let r=await t();return e.state={status:"success",data:r,error:null,fetchedAt:Date.now()},e.inflight=null,ew(e),r}catch(t){if(o>0){var i;return await (i=250*(r-o+1),new Promise(e=>setTimeout(e,i))),n(o-1)}throw e.state={...e.state,status:"error",error:eS(t)},e.inflight=null,ew(e),t}};return n(r)}function eT(e){ek().delete(e)}let eI=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,eL=/[.?!;\n]/,eR=/[\s.?!;]+$/,ez=["ready when you are.","ask me anything.","let's build something cool.","explore your codebase.","draft an email.","summarize that paper.","plan your weekend.","explain it like I'm five.","pair-program with me.","fix that pesky bug.","translate to 中文.","write a haiku.","brainstorm ideas.","review my pull request.","what should we cook tonight?","ship it.","make it pretty.","rubber-duck with me."];function eM({phrases:e}){let[t,r]=(0,o.useState)(()=>Math.floor(Math.random()*e.length)),[i,s]=(0,o.useState)(""),[l,a]=(0,o.useState)(!1),[d,c]=(0,o.useState)(!0);return(0,o.useEffect)(()=>{let e=setInterval(()=>c(e=>!e),530);return()=>clearInterval(e)},[]),(0,o.useEffect)(()=>{let n,o=e[t];if(l||i!==o)if(l&&""===i)a(!1),r(t=>(t+1)%e.length);else{let e=l?o.slice(0,i.length-1):o.slice(0,i.length+1);n=setTimeout(()=>s(e),l?28:55)}else n=setTimeout(()=>a(!0),1800);return()=>clearTimeout(n)},[i,l,t,e]),(0,n.jsxs)("span",{style:{color:"var(--text-muted)",fontWeight:400},children:[i,(0,n.jsx)("span",{style:{opacity:+!!d,color:"var(--accent)",marginLeft:1},children:"▍"})]})}function eE({session:e,newSessionCwd:t,onAgentEnd:r,onSessionCreated:i,onSessionForked:l,modelsRefreshKey:a,chatInputRef:d,onBranchDataChange:c,onBranchNavigatingChange:u,onSystemPromptChange:p,onSessionStatsChange:x,onContextUsageChange:h,toolMode:g="full",onOpenModels:f,onOpenSettings:m,onOpenFile:b}){var v;let y,{t:j}=(0,s.s)(),{loading:k,error:w,messages:S,entryIds:C,streamState:N,agentRunning:T,modelNames:I,modelList:L,modelThinkingLevels:R,modelThinkingLevelMaps:z,toolPreset:M,thinkingLevel:E,retryInfo:W,contextUsage:A,forkingEntryId:P,cloning:$,isCompacting:O,compactError:H,displayModel:D,sessionStats:B,agentPhase:F,remoteAuthError:U,isNew:V,messagesEndRef:_,scrollContainerRef:K,lastUserMsgRef:q,handleSend:J,handleAbort:G,handleFork:Y,handleClone:X,handleNavigate:Q,handleModelChange:ee,handleCompact:er,handleSteer:en,handleFollowUp:eo,handleAbortCompaction:ei,handleToolPresetChange:es,handleThinkingLevelChange:el,handleAgentEventRef:ed,sessionIdRef:ef}=function(e){let{session:t,newSessionCwd:r,onAgentEnd:n,onSessionCreated:i,onSessionForked:s,modelsRefreshKey:l,onBranchDataChange:a,onBranchNavigatingChange:d,onSystemPromptChange:c,toolMode:u="full"}=e,p=null===t&&null!==r,[x,h]=(0,o.useState)(null),[g,f]=(0,o.useState)(!p),[m,b]=(0,o.useState)(null),[v,y]=(0,o.useState)(null),[j,k]=(0,o.useState)([]),[w,S]=(0,o.useState)([]),[C,N]=(0,o.useReducer)(ev,{isStreaming:!1,streamingMessage:null}),[T,I]=(0,o.useState)(!1),[L,R]=(0,o.useState)({}),[z,M]=(0,o.useState)([]),[E,W]=(0,o.useState)({}),[A,P]=(0,o.useState)({}),[$,O]=(0,o.useState)(null),[H,D]=(0,o.useState)("default"),[B,F]=(0,o.useState)("auto"),[U,V]=(0,o.useState)(null),[_,K]=(0,o.useState)(null),[q,J]=(0,o.useState)(null),[G,Y]=(0,o.useState)(null),[Z,X]=(0,o.useState)(!1),[Q,ee]=(0,o.useState)(!1),[er,en]=(0,o.useState)(null),[eo,ei]=(0,o.useState)(null),[es,el]=(0,o.useState)(!1),[ea,ed]=(0,o.useState)(null),[ec,ef]=(0,o.useState)(null),[eb,ey]=(0,o.useState)(!1),ej=(0,o.useRef)(null),ek=(0,o.useRef)(t?.id??null),ew=(0,o.useRef)(!1),eS=(0,o.useRef)(null),eC=(0,o.useRef)(!1),eN=(0,o.useRef)(null),eT=(0,o.useRef)(!1),eI=(0,o.useRef)(null),eL=(0,o.useRef)(null),eR=(0,o.useRef)(null),ez=(0,o.useRef)(null),eM=(0,o.useRef)(null),eE=e.setNewSessionModel??O,eW=e.setToolPreset??D,eA=er??x?.context.model??eo??null,eP=p?$:eA,e$=(()=>{let e={input:0,output:0,cacheRead:0,cacheWrite:0},t=0;for(let r of j){if("assistant"!==r.role)continue;let n=r.usage;n&&(e.input+=n.input??0,e.output+=n.output??0,e.cacheRead+=n.cacheRead??0,e.cacheWrite+=n.cacheWrite??0,t+=n.cost?.total??0)}return e.input+e.output+e.cacheRead+e.cacheWrite>0?{tokens:e,cost:t}:null})(),eO=(0,o.useCallback)(async(e,t=!1,r=!1,n)=>{let o=ez.current===e,i=n?.preserveMessages||o;try{t&&f(!0);let n=r?`/api/sessions/${encodeURIComponent(e)}?includeState`:`/api/sessions/${encodeURIComponent(e)}`,o=await fetch(n);if(404===o.status)return t&&(h(null),y(null),k([]),b(null)),null;if(!o.ok)throw Error(`HTTP ${o.status}`);let s=await o.json();return h(s),y(s.leafId),i||(k(s.context.messages),S(s.context.entryIds??[])),en(null),b(null),!s.agentState?.state?.thinkingLevel&&s.context.thinkingLevel&&"off"!==s.context.thinkingLevel&&F(s.context.thinkingLevel),s.agentState??null}catch(e){return b(String(e)),null}finally{f(!1)}},[]),eH=(0,o.useCallback)(async(e,t)=>{try{let r=t?`/api/sessions/${encodeURIComponent(e)}/context?leafId=${encodeURIComponent(t)}`:`/api/sessions/${encodeURIComponent(e)}/context`,n=await fetch(r);if(!n.ok)throw Error(`HTTP ${n.status}`);let o=await n.json();k(o.context.messages),S(o.context.entryIds??[])}catch(e){console.error("Failed to load context:",e)}},[]),eD=(0,o.useCallback)(async e=>{try{let t,r=await ep(e,{type:"get_tools"});r&&eW((t=r.filter(e=>e.active).map(e=>e.name).sort().join(","),""===t?"none":t===[...eh].sort().join(",")?"default":t===[...eg].sort().join(",")?"full":"default"))}catch(e){console.error("Failed to load tools:",e)}},[eW]),eB=(0,o.useCallback)(e=>{ej.current&&(ej.current.close(),ej.current=null);let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);ej.current=t,t.onmessage=e=>{try{let t=JSON.parse(e.data);eS.current?.(t)}catch{}},t.onerror=()=>{fetch(`/api/agent/${encodeURIComponent(e)}/events`,{method:"GET"}).then(r=>{if(401===r.status){ey(!0),b("remote-auth-required"),t.close(),ej.current=null;return}ej.current===t&&ew.current&&(t.close(),ej.current=null,setTimeout(()=>{ew.current&&eB(e)},1e3))}).catch(()=>{ej.current===t&&ew.current&&(t.close(),ej.current=null,setTimeout(()=>{ew.current&&eB(e)},1e3))})}},[]);(0,o.useEffect)(()=>{ew.current=T},[T]);let eF=(0,o.useRef)(null),eU=(0,o.useRef)(null);(0,o.useEffect)(()=>{let e=C.isStreaming||T||es,t=window.piNative;if(eU.current&&(clearTimeout(eU.current),eU.current=null),null===eF.current){eF.current=e;return}if(e&&!1===eF.current){t?.preventSleep?.(),eF.current=!0;return}e||!0!==eF.current||(eU.current=setTimeout(()=>{t?.allowSleep?.(),eF.current=!1,eU.current=null},500))},[C.isStreaming,T,es]),(0,o.useEffect)(()=>()=>{eU.current&&clearTimeout(eU.current),eF.current&&window.piNative?.allowSleep?.(),eF.current=null},[]);let eV=(0,o.useCallback)(()=>{I(!1),ef(null),V(null),N({type:"end"})},[]),e_=(0,o.useCallback)(async e=>{if(e&&ew.current)try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!t.ok)return void eV();let r=await t.json();r.running&&r.state?.isStreaming!==!1||eV()}catch{}},[eV]),eK=(0,o.useCallback)(e=>{e&&(eM.current&&clearTimeout(eM.current),eM.current=setTimeout(()=>{eM.current=null,e_(e)},400))},[e_]);eS.current=(0,o.useCallback)(e=>{switch(e.type){case"agent_start":I(!0),ef({kind:"waiting_model"}),N({type:"start"});break;case"agent_end":eM.current&&(clearTimeout(eM.current),eM.current=null),I(!1),ef(null),V(null),N({type:"end"}),ez.current&&ez.current===ek.current&&(ez.current=null),ek.current&&(eO(ek.current),fetch(`/api/agent/${encodeURIComponent(ek.current)}`).then(e=>e.json()).then(e=>{e.state?.contextUsage!==void 0&&K(e.state.contextUsage??null),e.state?.systemPrompt!==void 0&&J(e.state.systemPrompt??null)}).catch(()=>{})),n?.();break;case"message_start":case"message_update":{let t=e.message;if(t?.role==="user")break;t&&N({type:"update",message:eu(t)}),ef(null);break}case"message_end":{let t=e.message;t&&"user"!==t.role&&k(e=>[...e,eu(t)]),N({type:"reset"}),ef({kind:"waiting_model"}),eK(ek.current);break}case"tool_execution_start":{let t=e.toolCallId,r=e.toolName;ef(e=>{let n=e?.kind==="running_tools"?[...e.tools]:[];return n.some(e=>e.id===t)||n.push({id:t,name:r}),{kind:"running_tools",tools:n}});break}case"tool_execution_end":{let t=e.toolCallId;ef(e=>{if(e?.kind!=="running_tools")return e;let r=e.tools.filter(e=>e.id!==t);return 0===r.length?{kind:"waiting_model"}:{kind:"running_tools",tools:r}});break}case"auto_retry_start":V({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":V(null);break;case"auto_compaction_start":case"compaction_start":el(!0),ed(null);break;case"auto_compaction_end":case"compaction_end":el(!1),e.errorMessage?ed(e.errorMessage):!e.aborted&&ek.current&&eO(ek.current)}},[eO,n,eK]);let eq=(0,o.useCallback)((e,t)=>{if(e?.running&&e.state?.isStreaming){I(!0),ef(e=>e??{kind:"waiting_model"}),eB(t),eD(t);return}eV()},[eB,eD,eV]),eJ=(0,o.useCallback)(async e=>{for(let t=0;t<120;t++){try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!t.ok)return void eV();let r=await t.json();if(!r.running||r.state?.isStreaming===!1){await eO(e,!1,!0),eV();return}}catch{return}await new Promise(e=>setTimeout(e,500))}},[eO,eV]),eG=(0,o.useCallback)(async(e,n,o)=>{if(!e.trim()&&!n?.length&&!o?.length||T)return;let s=(0,et.tl)(e,o??[]),l=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),a={role:"user",content:l?.length?[...s.trim()?[{type:"text",text:s}]:[],...l]:s,timestamp:Date.now()};k(e=>[...e,a]),I(!0),ef({kind:"waiting_model"}),N({type:"start"}),eT.current=!0;let d=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{if(p&&r){$&&ei($);let e="full"===u?eg:"default"===u||"simple"===u?eh:ex,t=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:r,type:"prompt",message:s,toolNames:e,...d?.length?{images:d}:{},...$?{provider:$.provider,modelId:$.modelId}:{},..."auto"!==B?{thinkingLevel:B}:{}})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=(await t.json()).sessionId;ek.current=n,ez.current=n,eB(n),eJ(n),i?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:s})}else t&&(eB(t.id),await ep(t.id,{type:"prompt",message:s,...d?.length?{images:d}:{}}),eJ(t.id))}catch(e){console.error("Failed to send message:",e),I(!1),ef(null),N({type:"end"})}},[p,r,$,u,B,t,T,eB,i,eJ]),eY=(0,o.useCallback)(async()=>{let e=ek.current;if(e)try{await ep(e,{type:"abort"}),eJ(e)}catch(e){console.error("Failed to abort:",e)}},[eJ]),eZ=(0,o.useCallback)(async e=>{let t=ek.current;if(t){Y(e);try{let{cancelled:r,newSessionId:n}=await ep(t,{type:"fork",entryId:e})??{};!r&&n&&s?.(n)}catch(e){console.error("Fork failed:",e)}finally{Y(null)}}},[s]),eX=(0,o.useCallback)(async e=>{let t=ek.current;t&&(ep(t,{type:"navigate_tree",targetId:e,summarize:!1}).catch(()=>{}),y(e),await eH(t,e))},[eH]),eQ=(0,o.useCallback)(async e=>{y(e);let t=ek.current;if(!t)return;if(!e)return void await eH(t,null);let r=!0===em().branchSummarizeBeforeSwitch;ee(!0);try{await ep(t,{type:"navigate_tree",targetId:e,summarize:r}),await eO(t,!0)}catch(o){let r,n=o instanceof Error?o.message:String(o);console.error("Branch navigation failed:",o),b(n),ed((r=n.toLowerCase()).includes("model")&&(r.includes("no")||r.includes("not")||r.includes("select"))?"branchNavigator.errorNoModel":r.includes("abort")||r.includes("cancel")?"branchNavigator.errorCancelled":"branchNavigator.errorGeneric"),await eH(t,e)}finally{ee(!1)}},[eH,eO]),e0=x?.leafId??null,e1=(0,o.useCallback)(async()=>{let e=ek.current;if(e){X(!0);try{let t=v??e0,{cancelled:r,newSessionId:n}=await ep(e,{type:"clone",...t?{leafId:t}:{}})??{};!r&&n&&s?.(n)}catch(e){console.error("Clone failed:",e),b(e instanceof Error?e.message:String(e))}finally{X(!1)}}},[v,e0,s]),e2=(0,o.useCallback)(async(e,t)=>{if(p)return void eE({provider:e,modelId:t});let r=ek.current;if(r)try{await ep(r,{type:"set_model",provider:e,modelId:t}),en({provider:e,modelId:t}),b(null)}catch(t){let e=t instanceof Error?t.message:String(t);console.error("Failed to set model:",t),b(e)}},[p,eE]),e4=(0,o.useCallback)(async()=>{let e=ek.current;if(e&&!es){el(!0),ed(null);try{await ep(e,{type:"compact"}),await eO(e,!0)}catch(e){ed(e instanceof Error?e.message:String(e))}finally{el(!1)}}},[es,eO]),e5=(0,o.useCallback)(async(e,t,r)=>{let n=ek.current;if(!n)return;let o=(0,et.tl)(e,r??[]);k(e=>[...e,{role:"user",content:`[steer] ${o}`,timestamp:Date.now()}]);let i=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await ep(n,{type:"steer",message:o,...i?.length?{images:i}:{}})}catch(e){console.error("Failed to steer:",e)}},[]),e6=(0,o.useCallback)(async(e,t,r)=>{let n=ek.current;if(!n)return;let o=(0,et.tl)(e,r??[]);k(e=>[...e,{role:"user",content:o,timestamp:Date.now()}]);let i=t?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}));try{await ep(n,{type:"follow_up",message:o,...i?.length?{images:i}:{}})}catch(e){console.error("Failed to follow up:",e)}},[]),e3=(0,o.useCallback)(async()=>{let e=ek.current;if(e)try{await ep(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),e8=(0,o.useCallback)(async e=>{if(F(e),"auto"===e)return;let t=ek.current;if(t)try{await ep(t,{type:"set_thinking_level",level:e})}catch(e){console.error("Failed to set thinking level:",e)}},[]),e9=(0,o.useCallback)(async e=>{let t="none"===e?ex:"default"===e?eh:eg;eW(e);let r=ek.current;if(r)try{await ep(r,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[eW]),e7=(0,o.useCallback)((e="smooth")=>{eI.current?.scrollIntoView({behavior:e})},[]),te=(0,o.useCallback)(()=>{let e=eL.current,t=eN.current;if(!e||!t)return;let r=t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop;e.scrollTo({top:r-16,behavior:"smooth"})},[]);return(0,o.useEffect)(()=>{if(!t?.id)return eR.current=null,ek.current=null,()=>{ej.current?.close(),ej.current=null};let e=eR.current,r=null!==e&&e!==t.id,n=ez.current===t.id;eR.current=t.id,ek.current=t.id;let o=!1;return r&&(k([]),S([]),I(!1),ef(null),V(null),N({type:"end"}),eC.current=!1),eO(t.id,r||null===e&&!n,!0,{preserveMessages:n}).then(e=>{!o&&(eq(e,t.id),e?.state&&(void 0!==e.state.isCompacting&&el(e.state.isCompacting),void 0!==e.state.contextUsage&&K(e.state.contextUsage??null),void 0!==e.state.systemPrompt&&J(e.state.systemPrompt??null),void 0!==e.state.thinkingLevel&&F(e.state.thinkingLevel??"auto")))}),()=>{o=!0,eM.current&&(clearTimeout(eM.current),eM.current=null),ej.current?.close(),ej.current=null}},[t?.id,eO,eq]),(0,o.useEffect)(()=>{c?.(q)},[q,c]),(0,o.useEffect)(()=>{a&&a(x?.tree??[],v,eQ)},[x?.tree,v,eQ,a]),(0,o.useEffect)(()=>{d?.(Q)},[Q,d]),(0,o.useEffect)(()=>{j.length>0&&(eT.current?(eT.current=!1,eC.current=!0,te()):eC.current?ew.current||e7("smooth"):(eC.current=!0,ew.current&&j.some(e=>"user"===e.role)?te():e7("instant")))},[j.length,T,e7,te]),(0,o.useEffect)(()=>{fetch("/api/models").then(e=>e.json()).then(e=>{if(R(e.models),e.thinkingLevels&&W(e.thinkingLevels),e.thinkingLevelMaps&&P(e.thinkingLevelMaps),e.modelList&&(M(e.modelList),p&&e.modelList.length>0)){let t=e.defaultModel,r=t&&e.modelList.find(e=>e.id===t.modelId&&e.provider===t.provider);eE(r?{provider:r.provider,modelId:r.id}:{provider:e.modelList[0].provider,modelId:e.modelList[0].id})}}).catch(()=>{})},[p,l,eE]),(0,o.useEffect)(()=>{if(!ea)return;let e=setTimeout(()=>ed(null),3e3);return()=>clearTimeout(e)},[ea]),{data:x,loading:g,error:m,activeLeafId:v,messages:j,entryIds:w,streamState:C,agentRunning:T,modelNames:L,modelList:z,modelThinkingLevels:E,modelThinkingLevelMaps:A,newSessionModel:$,toolPreset:H,thinkingLevel:B,retryInfo:U,contextUsage:_,systemPrompt:q,forkingEntryId:G,cloning:Z,branchNavigating:Q,isCompacting:es,compactError:ea,currentModel:eA,displayModel:eP,sessionStats:e$,agentPhase:ec,remoteAuthError:eb,isNew:p,sessionIdRef:ek,eventSourceRef:ej,messagesEndRef:eI,scrollContainerRef:eL,lastUserMsgRef:eN,pendingScrollToUserRef:eT,initialScrollDoneRef:eC,handleSend:eG,handleAbort:eY,handleFork:eZ,handleClone:e1,handleNavigate:eX,handleModelChange:e2,handleCompact:e4,handleSteer:e5,handleFollowUp:e6,handleAbortCompaction:e3,handleToolPresetChange:e9,handleThinkingLevelChange:e8,loadTools:eD,setActiveLeafId:y,setData:h,setMessages:k,dispatch:N,setAgentRunning:I,setForkingEntryId:Y,handleAgentEventRef:eS}}({session:e,newSessionCwd:t,onAgentEnd:r,onSessionCreated:i,onSessionForked:l,modelsRefreshKey:a,onBranchDataChange:c,onBranchNavigatingChange:u,onSystemPromptChange:p,toolMode:g}),{soundEnabled:eb,onSoundToggle:ek,playDoneSound:ew}=function(){let[e,t]=(0,o.useState)(()=>{let e=localStorage.getItem("pi-sound-enabled");return null===e||"true"===e}),r=(0,o.useRef)(e);return(0,o.useEffect)(()=>{r.current=e},[e]),{soundEnabled:e,onSoundToggle:(0,o.useCallback)(()=>{t(e=>{let t=!e;return localStorage.setItem("pi-sound-enabled",String(t)),t})},[]),playDoneSound:(0,o.useCallback)(()=>{if(r.current)try{let e=new AudioContext,t=e.currentTime;[523.25,659.25].forEach((r,n)=>{let o=e.createOscillator(),i=e.createGain();o.connect(i),i.connect(e.destination),o.type="sine",o.frequency.value=r;let s=t+.18*n;i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.18,s+.02),i.gain.exponentialRampToValueAtTime(.001,s+.45),o.start(s),o.stop(s+.45)}),setTimeout(()=>e.close(),1200)}catch{}},[]),soundEnabledRef:r}}(),eS=(0,o.useRef)(ew);eS.current=ew;let eC=(0,o.useRef)(eb);eC.current=eb;let eN=(0,o.useRef)(e);eN.current=e;let eW=ed.current;(0,o.useEffect)(()=>{ed.current=e=>{if("agent_end"===e.type){eC.current&&eS.current();let e=ef.current;if(e&&ey()){let t=eN.current?.name??e;ej({sessionId:e,sessionName:t}).catch(()=>{})}if(e){let t=eX.current;fetch(`/api/product-sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({lastResultSummary:t,status:"completed"})}).then(e=>{e.ok?eT("workbench:history:recent"):console.warn(`[ChatWindow] metadata update failed: ${e.status}`)}).catch(e=>{console.warn("[ChatWindow] metadata update error:",e)})}}eW?.(e)}},[eW,ed,ef]);let eA=B?`${B.tokens.input}|${B.tokens.output}|${B.tokens.cacheRead}|${B.tokens.cacheWrite}|${B.cost??0}`:null,eP=(0,o.useRef)(B);eP.current=B,(0,o.useEffect)(()=>{x?.(eP.current)},[eA,x]),(0,o.useEffect)(()=>()=>{x?.(null)},[x]);let e$=A?`${A.percent??"null"}|${A.contextWindow}|${A.tokens??"null"}`:null,eO=(0,o.useRef)(A);eO.current=A,(0,o.useEffect)(()=>{h?.(eO.current)},[e$,h]),(0,o.useEffect)(()=>()=>{h?.(null)},[h]);let eH=(()=>{if(!D)return!0;let e=L.find(e=>e.provider===D.provider&&e.id===D.modelId);return!e||(e.input?.includes("image")??!1)})(),{isDragOver:eD,handleDragEnter:eB,handleDragOver:eF,handleDragLeave:eU,handleDrop:eV}=function(e){let[t,r]=(0,o.useState)(!1),n=(0,o.useRef)(0),i=(0,o.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&(e.preventDefault(),n.current+=1,r(!0))},[]),s=(0,o.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>e.type.startsWith("image/"))&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:i,handleDragOver:s,handleDragLeave:(0,o.useCallback)(()=>{n.current-=1,n.current<=0&&(n.current=0,r(!1))},[]),handleDrop:(0,o.useCallback)(t=>{t.preventDefault(),n.current=0,r(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,o.useCallback)(e=>{d?.current?.addFiles(e)},[d])),e_=(v=S.filter(e=>"user"===e.role||"assistant"===e.role).length,(y=(0,o.useRef)([])).current=Array(v).fill(null).map((e,t)=>y.current[t]??null),y),eK=V&&0===S.length&&!N.isStreaming&&!T,eq=D?R[`${D.provider}:${D.modelId}`]??null:null,eJ=D?z[`${D.provider}:${D.modelId}`]??null:null,eG=e?.cwd??t??void 0,eY=(()=>{for(let e=S.length-1;e>=0;e--){let t=S[e];if("assistant"===t.role)return t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n").trim()}return""})(),eZ=(0,o.useMemo)(()=>(function(e,t=120){if(!e)return"";let r=function(e,t={}){var r;let n;if(null==e)return"";let o=t.maxChars??16e3,i=t.keep??"head",s=(r=(e.length<=o?e:"tail"===i?e.slice(e.length-o):e.slice(0,o)).replace(eI,"").split("\n").map(e=>e.length>2e3?`${e.slice(0,2e3)}…`:e).join("\n"),n=RegExp("(?:\\n\\s*){3,}","g"),r.replace(n,"\n".repeat(2)));return"ellipsis"===t.onTruncate&&s.length>0&&e.length>o?`${s}…`:"marker"===t.onTruncate&&e.length>o?`${s}
|
|
2
|
+
[truncated ${e.length-o} chars]`:s.trim()}(e,{maxChars:240,onTruncate:"none"});if(!r)return"";let n=r.match(eL),o=(n&&void 0!==n.index?r.slice(0,n.index):r).replace(eR,"");return o?o.length<=t?o:t<=1?o.slice(0,t)+"…":`${o.slice(0,t-1).trimEnd()}…`:""})(eY,120),[eY]),eX=(0,o.useRef)(eZ);eX.current=eZ;let[eQ,e0]=(0,o.useState)([]),e1=e?.id??ef.current??null;(0,o.useEffect)(()=>{V&&t?fetch(`/api/skills?cwd=${encodeURIComponent(t)}`).then(e=>e.json()).then(e=>{e0((e.skills??[]).map(e=>({name:`skill:${e.name}`,description:e.description,source:"skill"})))}).catch(()=>e0([])):e1?fetch(`/api/agent/${encodeURIComponent(e1)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_commands"})}).then(e=>e.json()).then(e=>{e0(e.data?.commands??[])}).catch(()=>e0([])):e0([])},[e1,!0,a,V,t]);let e2=T&&(N.isStreaming||F?.kind==="running_tools"||null!=W),e4=(0,n.jsx)(ea,{ref:d,onSend:J,onAbort:G,onSteer:T?en:void 0,onFollowUp:T?eo:void 0,isStreaming:T,steerMode:e2,model:D,modelNames:I,modelList:L,supportsImages:eH,onModelChange:ee,onCompact:e||V?er:void 0,onAbortCompaction:ei,isCompacting:O,compactError:H,toolPreset:M,onToolPresetChange:e||V?es:void 0,toolMode:g,showAdvancedTools:!0,thinkingLevel:E,onThinkingLevelChange:e||V?el:void 0,availableThinkingLevels:eq,thinkingLevelMap:eJ,retryInfo:W,soundEnabled:eb,onSoundToggle:ek,onClone:e&&!V?X:void 0,cloning:$,sessionId:e1,slashCommandsEnabled:!0,slashCommands:eQ,onOpenSettings:m,onOpenFile:b});return k?(0,n.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:"Loading session..."}):w?(0,n.jsxs)("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-center",children:[(0,n.jsx)("div",{className:"text-red-400",children:U?j("remoteAccess.authRequired"):w}),U&&(0,n.jsx)("div",{className:"max-w-md text-[12px] leading-5 text-text-muted",children:j("remoteAccess.pairingHint")})]}):(0,n.jsxs)("div",{className:"relative flex h-full flex-col overflow-hidden",onDragEnter:eB,onDragOver:eF,onDragLeave:eU,onDrop:eV,children:[0===L.length&&(0,n.jsx)("div",{className:"shrink-0 border-b border-border bg-bg-panel px-4 py-3",children:(0,n.jsxs)("div",{className:"mx-auto flex max-w-[820px] flex-wrap items-center justify-between gap-3",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"text-[13px] font-semibold text-text",children:j("accounts.needAccountTitle")}),(0,n.jsx)("p",{className:"mt-1 text-[12px] leading-5 text-text-muted",children:j("accounts.needAccountDescription")})]}),f&&(0,n.jsx)("button",{type:"button",onClick:f,className:"rounded-[7px] bg-accent px-3 py-2 text-[12px] font-semibold text-white hover:bg-accent-hover",children:j("accounts.configureModels")})]})}),eD&&(0,n.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,n.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,n.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,n.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,n.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,n.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,n.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,n.jsxs)("g",{stroke:"rgba(37,99,235,0.45)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,n.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,n.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,n.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,n.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,n.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,n.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,n.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),eK?(0,n.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto px-4 py-8",children:(0,n.jsxs)("div",{className:"w-full max-w-[820px]",children:[(0,n.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0,flex:1,lineHeight:1.4},children:[(0,n.jsx)("span",{style:{fontSize:28,fontWeight:700,letterSpacing:0,color:"var(--text)"},children:"π"}),(0,n.jsx)("span",{style:{fontSize:22,color:"var(--text)",fontWeight:700,letterSpacing:0},children:"Pi-Agent"}),(0,n.jsx)("span",{style:{fontSize:14,minWidth:0,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:(0,n.jsx)(eM,{phrases:ez})})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.8.4"]})]}),(0,n.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["pi ",(0,n.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.79.0"]})]})]})]}),e4]})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"relative flex flex-1 overflow-hidden",children:[(0,n.jsx)("div",{ref:K,className:"flex-1 overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,n.jsxs)("div",{className:"mx-auto max-w-[820px] px-4",children:[(()=>{let e=new Map;for(let t of S)"toolResult"===t.role&&e.set(t.toolCallId,t);let t=-1;for(let e=S.length-1;e>=0;e--)if("user"===S[e].role){t=e;break}let r=0;return S.map((o,i)=>{let s="user"===o.role&&i>0&&"assistant"===S[i-1].role?C[i-1]:void 0,l="user"===o.role||"assistant"===o.role,a=l?r++:-1,c=!1;if("assistant"===o.role){c=!0;for(let e=i+1;e<S.length;e++){let t=S[e].role;if("user"===t)break;if("assistant"===t){c=!1;break}}c&&N.isStreaming&&i===S.length-1&&(c=!1)}let u=(0,n.jsx)(Z.D,{message:o,toolResults:e,modelNames:I,entryId:C[i],onFork:T||V||0===i&&"user"===o.role?void 0:Y,forking:P===C[i],onNavigate:T?void 0:Q,prevAssistantEntryId:T?void 0:s,onEditContent:e=>d?.current?.insertIfEmpty(e),onOpenFile:b,cwd:eG,showTimestamp:c,prevTimestamp:i>0?S[i-1].timestamp:void 0},i);return l?(0,n.jsx)("div",{ref:e=>{e_.current[a]=e,i===t&&(q.current=e)},children:u},i):u})})(),N.isStreaming&&N.streamingMessage&&(0,n.jsx)(Z.D,{message:N.streamingMessage,isStreaming:!0,modelNames:I,onOpenFile:b,cwd:eG}),T&&!N.streamingMessage&&(0,n.jsx)("div",{className:"py-2 text-[13px] text-text-muted",children:(0,n.jsx)("span",{className:"animate-[pulse_1.5s_infinite]",children:function(e){if(e?.kind==="running_tools"){let t=e.tools.map(e=>e.name);return 0===t.length?"Running tool...":1===t.length?`Running ${t[0]}...`:t.length<=3?`Running ${t.join(", ")}...`:`Running ${t.slice(0,2).join(", ")} (+${t.length-2})...`}return e?.kind==="waiting_model"?"Waiting for model...":"Thinking..."}(F)})}),T&&(0,n.jsx)("div",{style:{height:K.current?K.current.clientHeight:"80vh"}}),(0,n.jsx)("div",{ref:_})]})}),(0,n.jsx)(ec,{messages:S,streamingMessage:N.streamingMessage,scrollContainer:K,messageRefs:e_})]}),(0,n.jsx)("div",{className:"relative",children:e4})]})]})}var eW=r(16764),eA=r(7644),eP=r(63143),e$=r(84678),eO=r(96793);let eH=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"]),eD=new Set(["mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","webm"]),eB=new Set(["doc","docx","xls","xlsx","ppt","pptx"]);function eF(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function eU(e,t){let r=eF((0,B.WP)(e));return r||(t?.trim()?eF(t.trim()):"")}function eV(e,t){let r=eU(e,t);if(eH.has(r))return"image";if(eD.has(r))return"audio";if("pdf"===r||t&&"pdf"===(0,et.HK)(t))return"pdf";if(eB.has(r))return"system";if(t){let e=(0,et.HK)(t);if("word"===e||"excel"===e||"ppt"===eF(t)||"pptx"===eF(t))return"system"}return"text"}function e_(){return!!window.piNative?.openPath}async function eK(e){let t=window.piNative?.openPath;return!!t&&(await t(e),!0)}function eq(e){let t=(0,B.WP)(e).replace(/\.[^.]+$/,"")||"preview";return`${t}.png`}async function eJ(e){var t;let r,n,o,{width:i,height:s,scale:l,outputWidth:a,outputHeight:d}=function(e,t,r=1){let n=Math.ceil(Math.max(e,1)),o=Math.ceil(Math.max(t,1)),i=Math.max(Math.min(Math.min(Math.max(r||1,1),2),16e3/n,16e3/o),Number.EPSILON);return{width:n,height:o,scale:i,outputWidth:Math.max(1,Math.ceil(n*i)),outputHeight:Math.max(1,Math.ceil(o*i))}}(Math.ceil(Math.max((r=e.getBoundingClientRect()).width,e.scrollWidth,1)),Math.ceil(Math.max(r.height,e.scrollHeight,1)),window.devicePixelRatio||1),c=((n=document.createElement("div")).innerHTML=e.innerHTML,!function e(t,r){if(r instanceof HTMLElement||r instanceof SVGElement){let e=window.getComputedStyle(t);for(let t of e)r.style.setProperty(t,e.getPropertyValue(t),e.getPropertyPriority(t))}let n=Array.from(t.children),o=Array.from(r.children);n.forEach((t,r)=>{let n=o[r];n&&e(t,n)})}(e,n),n);c.style.width=`${i}px`,c.style.minHeight=`${s}px`,c.style.boxSizing="border-box",c.style.background=(o=window.getComputedStyle(e).backgroundColor)&&"transparent"!==o&&"rgba(0, 0, 0, 0)"!==o?o:"#fff";let u=document.createElement("div");u.setAttribute("xmlns","http://www.w3.org/1999/xhtml"),u.style.width=`${i}px`,u.style.minHeight=`${s}px`,u.style.background=c.style.background,u.appendChild(c);let p=new XMLSerializer().serializeToString(u),x=`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${d}" viewBox="0 0 ${a} ${d}"><foreignObject width="${i}" height="${s}" transform="scale(${l})">${p}</foreignObject></svg>`,h=await (t=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(x)}`,new Promise((e,r)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>r(Error("Failed to render preview image")),n.src=t})),g=document.createElement("canvas");g.width=a,g.height=d;let f=g.getContext("2d");if(!f)throw Error("Canvas is not available");return f.drawImage(h,0,0,a,d),await new Promise((e,t)=>{g.toBlob(r=>{r?e(r):t(Error("Failed to create preview image"))},"image/png")})}async function eG(e){let t=navigator.clipboard;if(!t?.write||"u"<typeof ClipboardItem)throw Error("Image clipboard is not supported in this browser");await t.write([new ClipboardItem({"image/png":e})])}function eY(e,t){let r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(r),0)}async function eZ(e){return await new Promise((t,r)=>{let n=new FileReader;n.onload=()=>{"string"==typeof n.result?t(n.result):r(Error("FileReader returned non-string result"))},n.onerror=()=>r(n.error??Error("FileReader failed")),n.readAsDataURL(e)})}async function eX(e,t){let r=window.piNative?.copyImage;if(r){let t=await eZ(e);await r(t);return}try{await eG(e)}catch{eY(e,t)}}async function eQ(e,t){let r=window.piNative?.saveImage;if(r){let n=await eZ(e);await r(n,t);return}eY(e,t)}function e0({title:e,filePath:t,badge:r,actions:o}){let{t:i}=(0,s.s)(),l=e_();return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"4px 12px 4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},title:t,children:e}),r&&(0,n.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:r}),o,l&&(0,n.jsx)("button",{type:"button",onClick:()=>void eK(t),title:t,style:{flexShrink:0,padding:"4px 10px",fontSize:11,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer",fontWeight:500},children:i("fileViewer.openExternally")})]})}function e1(e){if(e)for(;e.firstChild;)e.removeChild(e.firstChild)}async function e2(e,t){let r=(0,B.HG)(e),n=t?`&sessionId=${encodeURIComponent(t)}`:"",o=await fetch(`/api/files/${r}?type=read${n}`,{credentials:"same-origin"}),i=o.headers.get("content-type")??"";if(!o.ok){if(i.includes("application/json"))throw Error((await o.json()).error??`HTTP ${o.status}`);throw Error(`HTTP ${o.status}`)}if(i.includes("application/json"))throw Error((await o.json()).error??"Not a PDF");return o.arrayBuffer()}function e4({filePath:e,cwd:t,displayLabel:i,sessionId:l}){let{t:a}=(0,s.s)(),d=(0,o.useRef)(null),[c,u]=(0,o.useState)(!0),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(0),f=i?.trim()||(0,et.PG)(e)||(0,B.qP)(e,t),m=h>0?`${a("fileViewer.pdf")} \xb7 ${h}`:a("fileViewer.pdf");return(0,o.useEffect)(()=>{let t=!1,n=null,o=d.current;return e1(o),u(!0),x(null),g(0),(async()=>{try{let o=await Promise.all([r.e(2084),r.e(2619)]).then(r.bind(r,66898));o.GlobalWorkerOptions.workerSrc="/pdf.worker.min.mjs";let i=await e2(e,l);if(t)return;let s=o.getDocument({data:i}),a=await s.promise;if(t)return void a.destroy();n=()=>void a.destroy(),t||g(a.numPages);let c=d.current;if(!c||t||(e1(c),0===c.clientWidth&&await new Promise(e=>requestAnimationFrame(()=>e())),t))return;let u=c.clientWidth>0?c.clientWidth-32:720;for(let e=1;e<=a.numPages;e++){if(t)return;let r=await a.getPage(e),n=r.getViewport({scale:1}),o=u/n.width,i=r.getViewport({scale:Math.min(Math.max(o,.5),2.5)}),s=document.createElement("canvas");s.width=Math.floor(i.width),s.height=Math.floor(i.height),s.style.display="block",s.style.maxWidth="100%",s.style.height="auto",s.style.margin="0 auto 16px",s.style.boxShadow="0 2px 8px rgba(0,0,0,0.12)";let l=s.getContext("2d");if(!l)continue;if(await r.render({canvasContext:l,viewport:i}).promise,t)return;let d=document.createElement("div");d.style.display="flex",d.style.justifyContent="center",d.appendChild(s),c.appendChild(d)}}catch(e){t||x(e instanceof Error?e.message:String(e))}finally{t||u(!1)}})(),()=>{t=!0,n?.(),e1(o)}},[e,l]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(e0,{title:f,filePath:e,badge:m}),(0,n.jsxs)("div",{style:{flex:1,overflow:"hidden",position:"relative",background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{ref:d,style:{height:"100%",overflow:"auto",padding:16,visibility:c||p?"hidden":"visible"}}),c&&(0,n.jsx)("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13,background:"var(--bg-panel)"},children:a("fileViewer.loading")}),!c&&p&&(0,n.jsx)("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:24,textAlign:"center",color:"var(--text-muted)",fontSize:13,background:"var(--bg-panel)"},children:(0,n.jsx)("p",{style:{margin:0,color:"#f87171"},children:p})})]})]})}function e5(e){return e?`&sessionId=${encodeURIComponent(e)}`:""}function e6(e){return(0,B.WP)(e).toLowerCase().split(".").pop()??""}function e3({filePath:e,label:t="Download",sessionId:r}){let o=(0,B.HG)(e);return(0,n.jsx)("a",{href:`/api/files/${o}?type=read${e5(r)}`,download:(0,B.WP)(e),style:{color:"var(--text-muted)",textDecoration:"none",border:"1px solid var(--border)",borderRadius:5,padding:"2px 8px",fontSize:11,lineHeight:1.4,background:"var(--bg-hover)",flexShrink:0},children:t})}function e8(e=!1){return{flexShrink:0,padding:"4px 10px",fontSize:11,borderRadius:6,border:"1px solid var(--border)",background:e?"var(--bg-selected)":"var(--bg-hover)",color:"var(--text)",cursor:"pointer",fontWeight:500}}function e9({getTarget:e,filePath:t}){let{t:r}=(0,s.s)(),[i,l]=(0,o.useState)(null),[a,d]=(0,o.useState)(null),c=(0,o.useCallback)(async()=>{let t=e();if(!t)throw Error("Preview is not ready");return eJ(t)},[e]),u=(0,o.useCallback)(()=>{l("copy"),d(null),c().then(async e=>{try{await eX(e,eq(t)),d("copied")}catch{eY(e,eq(t)),d("fallbackSaved")}setTimeout(()=>d(null),1500)}).catch(()=>d("error")).finally(()=>l(null))},[c,t]),p=(0,o.useCallback)(()=>{l("save"),d(null),c().then(async e=>{try{await eQ(e,eq(t)),d("saved")}catch{eY(e,eq(t)),d("fallbackSaved")}setTimeout(()=>d(null),1500)}).catch(()=>d("error")).finally(()=>l(null))},[c,t]);return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:["error"===a&&(0,n.jsx)("span",{style:{color:"#f87171",fontSize:11},children:r("fileViewer.imageExportFailed")}),"fallbackSaved"===a&&(0,n.jsx)("span",{style:{color:"var(--text-muted)",fontSize:11},children:r("fileViewer.savedInstead")}),(0,n.jsx)("button",{type:"button",onClick:u,disabled:null!==i,title:r("fileViewer.copyAsImage"),style:{...e8("copied"===a),opacity:i?.65:1,cursor:i?"not-allowed":"pointer"},children:r("copy"===i?"fileViewer.exportingImage":"copied"===a?"fileViewer.copiedImage":"fallbackSaved"===a?"fileViewer.savedImage":"fileViewer.copyAsImageShort")}),(0,n.jsx)("button",{type:"button",onClick:p,disabled:null!==i,title:r("fileViewer.saveAsImage"),style:{...e8("saved"===a),opacity:i?.65:1,cursor:i?"not-allowed":"pointer"},children:r("save"===i?"fileViewer.exportingImage":"saved"===a?"fileViewer.savedImage":"fileViewer.saveAsImageShort")})]})}function e7(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function te({oldContent:e,newContent:t}){let{t:r}=(0,s.s)(),o=function(e,t){let r=e.length,n=t.length,o=r+n,i=Array(2*o+1).fill(0),s=[];for(let l=0;l<=o;l++){s.push([...i]);for(let a=-l;a<=l;a+=2){let d,c=(d=a===-l||a!==l&&i[a-1+o]<i[a+1+o]?i[a+1+o]:i[a-1+o]+1)-a;for(;d<r&&c<n&&e[d]===t[c];)d++,c++;if(i[a+o]=d,d>=r&&c>=n){let i=[],a=r,d=n;for(let r=l;r>0;r--){let n,l=s[r-1],c=a-d;n=c===-r||c!==r&&l[c-1+o]<l[c+1+o]?c+1:c-1;let u=l[n+o],p=u-n;for(;a>u&&d>p;)a--,d--,i.unshift({type:"unchanged",text:e[a],lineNo:a+1});r>0&&(a>u?(a--,i.unshift({type:"removed",text:e[a],lineNo:a+1})):(d--,i.unshift({type:"added",text:t[d],lineNo:d+1})))}for(;a>0&&d>0;)a--,d--,i.unshift({type:"unchanged",text:e[a],lineNo:a+1});return i}}}return[...e.map((e,t)=>({type:"removed",text:e,lineNo:t+1})),...t.map((e,t)=>({type:"added",text:e,lineNo:t+1}))]}(e.split("\n"),t.split("\n"));if(!o.some(e=>"unchanged"!==e.type))return(0,n.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:r("fileViewer.noChanges")});let i=new Set(o.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),l=new Set;for(let e of i)for(let t=Math.max(0,e-3);t<=Math.min(o.length-1,e+3);t++)l.add(t);let a=[],d=0;for(;d<o.length;)if(l.has(d)){let e=[];for(;d<o.length&&l.has(d);)e.push(o[d]),d++;a.push({hidden:!1,lines:e})}else{let e=0;for(;d<o.length&&!l.has(d);)e++,d++;a.push({hidden:!0,count:e})}let c=[],u=1;for(let e of o)"removed"===e.type?c.push(0):c.push(u++);let p=0;return(0,n.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},children:a.map((e,t)=>{if(e.hidden){let o=(0,n.jsx)("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:r("fileViewer.unchangedLines",{count:e.count})},t);return p+=e.count,o}let o=e.lines.map((e,t)=>{let r=c[p+t],o="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",s="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,n.jsxs)("div",{style:{display:"flex",background:o,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,n.jsx)("span",{style:{minWidth:44,padding:"0 8px 0 16px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",fontSize:11,lineHeight:1.6,borderRight:"1px solid var(--border)",background:"var(--bg-panel)",flexShrink:0},children:"removed"===e.type?e.lineNo:r||""}),(0,n.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:s,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,n.jsx)("span",{style:{flex:1,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)",overflowX:"auto"},children:e.text||"\xa0"})]},t)});return p+=e.lines.length,(0,n.jsx)("div",{children:o},t)})})}function tt({filePath:e,cwd:t,sessionId:r}){let{t:i}=(0,s.s)(),[l,a]=(0,o.useState)(!1),[d,c]=(0,o.useState)(0),[u,p]=(0,o.useState)(null),[x,h]=(0,o.useState)(null),[g,f]=(0,o.useState)(null),m=(0,o.useRef)(null),b=(0,B.WP)(e).toLowerCase().split(".").pop()??"";(0,o.useEffect)(()=>{c(0),p(null),h(null),f(null),a(!1),m.current&&(m.current.close(),m.current=null);let t=(0,B.HG)(e),n=new EventSource(`/api/files/${t}?type=watch${e5(r)}`);return m.current=n,n.addEventListener("connected",()=>a(!0)),n.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}c(e=>e+1)}),n.addEventListener("error",()=>a(!1)),n.onerror=()=>a(!1),()=>{n.close(),m.current=null}},[e,r]);let v=(0,B.HG)(e),y=`/api/files/${v}?type=read${d?`&v=${d}`:""}${e5(r)}`,j=null!=u?e7(u):null;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:(0,B.qP)(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:b||i("fileViewer.image")}),x&&(0,n.jsxs)("span",{children:[x.w," \xd7 ",x.h]}),j&&(0,n.jsx)("span",{children:j}),(0,n.jsxs)("span",{title:l?i("fileViewer.liveSyncActive"):i("fileViewer.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?i("fileViewer.live"):i("fileViewer.static")]})]}),(0,n.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,n.jsx)("div",{style:{color:"#f87171",fontSize:13},children:g}):(0,n.jsx)("img",{src:y,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>f(i("fileViewer.failedToLoadImage")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function tr({filePath:e,cwd:t,sessionId:r}){let{t:i}=(0,s.s)(),[l,a]=(0,o.useState)(!1),[d,c]=(0,o.useState)(0),[u,p]=(0,o.useState)(null),[x,h]=(0,o.useState)(null),[g,f]=(0,o.useState)(null),m=(0,o.useRef)(null),b=(0,B.WP)(e).toLowerCase().split(".").pop()??"";(0,o.useEffect)(()=>{c(0),p(null),h(null),f(null),a(!1),m.current&&(m.current.close(),m.current=null);let t=(0,B.HG)(e),n=new EventSource(`/api/files/${t}?type=watch${e5(r)}`);return m.current=n,n.addEventListener("connected",()=>a(!0)),n.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&p(t.size)}catch{}h(null),f(null),c(e=>e+1)}),n.addEventListener("error",()=>a(!1)),n.onerror=()=>a(!1),()=>{n.close(),m.current=null}},[e,r]);let v=(0,B.HG)(e),y=`/api/files/${v}?type=read${d?`&v=${d}`:""}${e5(r)}`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:(0,B.qP)(e,t)}),(0,n.jsx)("span",{style:{marginLeft:"auto"},children:b||i("fileViewer.audio")}),null!=x&&(0,n.jsx)("span",{children:function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),r=Math.floor(t/60);return`${r}:${String(t%60).padStart(2,"0")}`}(x)}),null!=u&&(0,n.jsx)("span",{children:e7(u)}),(0,n.jsxs)("span",{title:l?i("fileViewer.liveSyncActive"):i("fileViewer.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:l?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"#4ade80":"var(--border)",display:"inline-block",boxShadow:l?"0 0 4px #4ade80":"none"}}),l?i("fileViewer.live"):i("fileViewer.static")]})]}),(0,n.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,n.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[g&&(0,n.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:g}),(0,n.jsx)("audio",{controls:!0,preload:"metadata",src:y,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>f(i("fileViewer.failedToLoadAudio")),style:{width:"100%"}},y)]})})]})}function tn({filePath:e,cwd:t,displayLabel:r}){let o,{t:i}=(0,s.s)(),l=r?.trim()||(0,B.qP)(e,t),a="ppt"===(o=eU(e,r))||"pptx"===o?"fileViewer.officePptHint":"xls"===o||"xlsx"===o?"fileViewer.officeExcelHint":"doc"===o||"docx"===o?"fileViewer.officeWordHint":"fileViewer.officeBinaryHint",d=e_();return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(e0,{title:l,filePath:e}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:24,textAlign:"center",color:"var(--text-muted)",fontSize:13,background:"var(--bg-panel)"},children:[d&&(0,n.jsx)("p",{style:{margin:0,maxWidth:360,color:"var(--text)"},children:i("fileViewer.systemOpenedExternally")}),(0,n.jsx)("p",{style:{margin:0,maxWidth:360},children:i(a)}),d&&(0,n.jsx)("button",{type:"button",onClick:()=>void eK(e),style:{padding:"6px 14px",fontSize:12,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer"},children:i("fileViewer.openExternally")})]})]})}function to({filePath:e,cwd:t,displayLabel:r,sessionId:i}){let[s,l]=(0,o.useState)(!1),[a,d]=(0,o.useState)(0),[c,u]=(0,o.useState)(null),[p,x]=(0,o.useState)(null),h=(0,o.useRef)(null),g=e6(r?.trim()||e),f=(0,B.HG)(e),m=`/api/files/${f}?type=preview${a?`&v=${a}`:""}${e5(i)}`,b=r?.trim()||(0,et.PG)(e)||(0,B.qP)(e,t);return(0,o.useEffect)(()=>{d(0),u(null),x(null),l(!1),h.current&&(h.current.close(),h.current=null),fetch(`/api/files/${f}?type=meta${e5(i)}`).then(e=>e.json()).then(e=>{e.error&&x(e.error),"number"==typeof e.size&&(u(e.size),e.size>0xa00000&&x("DOCX too large for preview (>10MB)"))}).catch(e=>x(String(e)));let e=new EventSource(`/api/files/${f}?type=watch${e5(i)}`);return h.current=e,e.addEventListener("connected",()=>l(!0)),e.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),t.size>0xa00000))return void x("DOCX too large for preview (>10MB)")}catch{}x(null),d(e=>e+1)}),e.addEventListener("error",()=>l(!1)),e.onerror=()=>l(!1),()=>{e.close(),h.current=null}},[f,i]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(e0,{title:b,filePath:e,badge:g||"docx"}),(0,n.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:[null!=c&&(0,n.jsx)("span",{children:e7(c)}),(0,n.jsx)(e3,{filePath:e,sessionId:i}),(0,n.jsxs)("span",{title:s?"Live sync active":"Not watching",style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:4,color:s?"#4ade80":"var(--text-dim)",flexShrink:0},children:[(0,n.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,n.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,n.jsx)("iframe",{src:m,sandbox:"",title:`Preview ${b}`,style:{width:"100%",height:"100%",border:"none",background:"#eef1f5"}},m)})]})}function ti({filePath:e,cwd:t,displayLabel:r,sessionId:o}){if("docx"===e6(r?.trim()||e))return(0,n.jsx)(to,{filePath:e,cwd:t,displayLabel:r,sessionId:o});switch(eV(e,r)){case"image":return(0,n.jsx)(tt,{filePath:e,cwd:t,sessionId:o});case"audio":return(0,n.jsx)(tr,{filePath:e,cwd:t,sessionId:o});case"pdf":return(0,n.jsx)(e4,{filePath:e,cwd:t,displayLabel:r,sessionId:o});case"system":return(0,n.jsx)(tn,{filePath:e,cwd:t,displayLabel:r});default:return(0,n.jsx)(ts,{filePath:e,cwd:t,displayLabel:r,sessionId:o})}}function ts({filePath:e,cwd:t,displayLabel:r,sessionId:i}){let{isDark:l}=(0,eO.D)(),{t:a}=(0,s.s)(),[d,c]=(0,o.useState)(null),[u,p]=(0,o.useState)(null),[x,h]=(0,o.useState)(!0),[g,f]=(0,o.useState)(null),[m,b]=(0,o.useState)(!1),[v,y]=(0,o.useState)("source"),[j,k]=(0,o.useState)(!1),[w,S]=(0,o.useState)(!1),[C,N]=(0,o.useState)(0),T=(0,o.useRef)(null),I=(0,o.useRef)(null),L=(0,o.useRef)(null),R=(0,o.useCallback)((e,t=!1)=>{let r=(0,B.HG)(e);return fetch(`/api/files/${r}?type=read${e5(i)}`).then(e=>e.json()).then(e=>e.error?(f(e.error),null):(t?(c(t=>(t&&p(t.content),e)),N(e=>e+1)):c(e),e)).catch(e=>(f(String(e)),null))},[i]);if((0,o.useEffect)(()=>{h(!0),f(null),c(null),p(null),b(!1),y("source"),k(!1),N(0),S(!1),T.current&&(T.current.close(),T.current=null),R(e).then(e=>{(e?.language==="markdown"||e?.language==="html")&&b(!0)}).finally(()=>h(!1));let t=(0,B.HG)(e),r=new EventSource(`/api/files/${t}?type=watch${e5(i)}`);return T.current=r,r.addEventListener("connected",()=>{S(!0)}),r.addEventListener("change",()=>{R(e,!0)}),r.addEventListener("error",()=>{S(!1)}),r.onerror=()=>{S(!1)},()=>{r.close(),T.current=null}},[e,R,i]),x)return(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:a("fileViewer.loading")});if(g){let o=r?.trim()||(0,et.PG)(e)||(0,B.qP)(e,t);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.jsx)(e0,{title:o,filePath:e}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:24,color:"#f87171",fontSize:13},children:[(0,n.jsx)("p",{style:{margin:0},children:g}),e_()&&(0,n.jsx)("button",{type:"button",onClick:()=>void eK(e),style:{padding:"6px 14px",fontSize:12,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer"},children:a("fileViewer.openExternally")})]})]})}if(!d)return null;let z="html"===d.language,M="markdown"===d.language,E=d.content.split("\n"),W=null!==u&&u!==d.content,A=r?.trim()||(0,et.PG)(e)||(0,B.qP)(e,t),P="source"===v&&m&&(M||z);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,n.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,n.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},title:e,children:A}),(0,n.jsx)("span",{style:{flexShrink:0},children:d.language}),"source"===v&&(0,n.jsxs)("span",{children:[E.length," lines"]}),(0,n.jsx)("span",{children:e7(d.size)}),(0,n.jsxs)("span",{title:a(w?"fileViewer.liveSyncActive":"fileViewer.notWatching"),style:{display:"flex",alignItems:"center",gap:4,color:w?"#4ade80":"var(--text-dim)"},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:w?"#4ade80":"var(--border)",display:"inline-block",boxShadow:w?"0 0 4px #4ade80":"none"}}),a(w?"fileViewer.live":"fileViewer.static")]}),W&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>y("source"),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:"source"===v?"var(--bg-selected)":"var(--bg-hover)",color:"source"===v?"var(--text)":"var(--text-muted)",fontWeight:"source"===v?600:400},children:a("fileViewer.source")}),(0,n.jsxs)("button",{onClick:()=>y("diff"),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:"diff"===v?"var(--bg-selected)":"var(--bg-hover)",color:"diff"===v?"var(--text)":"var(--text-muted)",fontWeight:"diff"===v?600:400},children:[a("fileViewer.diff")," ",C>0&&(0,n.jsxs)("span",{style:{color:"#4ade80",marginLeft:2},children:["+",C]})]})]}),"source"===v&&!m&&(0,n.jsx)("button",{onClick:()=>k(e=>!e),title:a(j?"fileViewer.disableWordWrap":"fileViewer.enableWordWrap"),style:{padding:"2px 8px",fontSize:11,cursor:"pointer",background:j?"var(--bg-selected)":"var(--bg-hover)",color:j?"var(--text)":"var(--text-muted)",border:"1px solid var(--border)",borderRadius:5,fontWeight:j?600:400},children:a("fileViewer.wrap")}),z&&"source"===v&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>b(!1),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:m?"var(--bg-hover)":"var(--bg-selected)",color:m?"var(--text-muted)":"var(--text)",fontWeight:m?400:600},children:a("fileViewer.code")}),(0,n.jsx)("button",{onClick:()=>b(!0),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:m?"var(--bg-selected)":"var(--bg-hover)",color:m?"var(--text)":"var(--text-muted)",fontWeight:m?600:400},children:a("fileViewer.preview")})]}),M&&"source"===v&&(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,n.jsx)("button",{onClick:()=>b(!0),style:{padding:"2px 8px",fontSize:11,border:"none",cursor:"pointer",background:m?"var(--bg-selected)":"var(--bg-hover)",color:m?"var(--text)":"var(--text-muted)",fontWeight:m?600:400},children:a("fileViewer.preview")}),(0,n.jsx)("button",{onClick:()=>b(!1),style:{padding:"2px 8px",fontSize:11,border:"none",borderLeft:"1px solid var(--border)",cursor:"pointer",background:m?"var(--bg-hover)":"var(--bg-selected)",color:m?"var(--text-muted)":"var(--text)",fontWeight:m?400:600},children:a("fileViewer.raw")})]}),P&&(0,n.jsx)(e9,{getTarget:()=>M?I.current:z?L.current?.contentDocument?.body??null:null,filePath:e}),e_()&&(0,n.jsx)("button",{type:"button",onClick:()=>void eK(e),title:e,style:{flexShrink:0,padding:"4px 10px",fontSize:11,borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer",fontWeight:500},children:a("fileViewer.openExternally")})]}),(0,n.jsx)("div",{style:{flex:1,minHeight:0,overflow:"auto",background:"var(--bg)",display:"flex",flexDirection:"column"},children:"diff"===v&&W?(0,n.jsx)(te,{oldContent:u,newContent:d.content,language:d.language}):z&&m?(0,n.jsx)("iframe",{ref:L,srcDoc:d.content,sandbox:"allow-scripts allow-same-origin",style:{flex:1,width:"100%",minHeight:320,border:"none",background:"#fff"},title:a("fileViewer.htmlPreview")}):M&&m?(0,n.jsx)("div",{ref:I,className:"markdown-body markdown-file-preview",style:{padding:"24px 32px",maxWidth:800,color:"var(--text)"},children:(0,n.jsx)(eP.oz,{remarkPlugins:[e$.A],children:d.content})}):(0,n.jsx)(eW.A,{language:"text"===d.language?"plaintext":d.language,style:l?eA.xJ:eA.vs,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",minWidth:"3em",paddingRight:"1em"},customStyle:{margin:0,padding:"12px 0",background:"var(--bg)",fontSize:13,lineHeight:1.6,fontFamily:"var(--font-mono)",minHeight:"100%"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},wrapLongLines:j,children:d.content})})]})}function tl({tabs:e,activeTabId:t,onSelectTab:r,onCloseTab:i}){let{t:l}=(0,s.s)(),[a,d]=(0,o.useState)(null);return(0,n.jsx)("div",{style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let o=e.id===t;return(0,n.jsxs)("div",{onClick:()=>r(e.id),style:{display:"flex",alignItems:"center",gap:6,height:36,paddingLeft:12,paddingRight:6,borderRight:"1px solid var(--border)",background:o?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:o?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,n.jsx)("span",{style:{flexShrink:0,opacity:o?1:.7,display:"flex",alignItems:"center"},children:D(e.label,13)}),(0,n.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:o?500:400},title:e.filePath,children:e.label}),(0,n.jsx)("button",{onClick:t=>{t.stopPropagation(),i(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:16,height:16,background:a===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:3,color:a===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:l("tabBar.close"),children:(0,n.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,n.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}var ta=r(67381),td=r(64433),tc=r(70350),tu=r(88195),tp=r(9312),tx=r(87275),th=r(22008),tg=r(95476),tf=r(35029),tm=r(14489),tb=r(78728),tv=r(19872),ty=r(7751),tj=r(92526),tk=r(48238),tw=r(57794),tS=r(41098),tC=r(84604),tN=r(15315),tT=r(74278),tI=r(55457),tL=r(71437),tR=r(29167),tz=r(97283),tM=r(34166),tE=r(33889),tW=r(85486),tA=r(74068),tP=r(83546),t$=r(83709);let tO=["input","output","cacheRead","cacheWrite"];function tH(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tD(e){if(!("number"!=typeof e||Number.isNaN(e)))return e}function tB(e){if(!e)return;let t=tO.map(t=>tD(e[t]));if(t.some(e=>void 0!==e))return{input:t[0]??0,output:t[1]??0,cacheRead:t[2]??0,cacheWrite:t[3]??0}}function tF(e){let t={id:"string"==typeof e.id?e.id.trim():""};"string"==typeof e.name&&e.name.trim()&&(t.name=e.name.trim()),"string"==typeof e.api&&e.api.trim()&&(t.api=e.api.trim()),"string"==typeof e.baseUrl&&e.baseUrl.trim()&&(t.baseUrl=e.baseUrl.trim()),!0===e.reasoning&&(t.reasoning=!0),tH(e.thinkingLevelMap)&&(t.thinkingLevelMap=e.thinkingLevelMap),Array.isArray(e.input)&&e.input.length>0&&(t.input=e.input.filter(e=>"text"===e||"image"===e));let r=tD(e.contextWindow);void 0!==r&&r>0&&(t.contextWindow=r);let n=tD(e.maxTokens);void 0!==n&&n>0&&(t.maxTokens=n);let o=tB(tH(e.cost)?e.cost:void 0);if(o&&(t.cost=o),tH(e.compat)&&Object.keys(e.compat).length>0&&(t.compat=e.compat),tH(e.headers)&&Object.keys(e.headers).length>0){let r={};for(let[t,n]of Object.entries(e.headers))"string"==typeof n&&n.length>0&&(r[t]=n);Object.keys(r).length>0&&(t.headers=r)}return t}function tU(e){let t=e.trim().toLowerCase();return!(!t||/(^|-)image(-|$)/.test(t)||/(^|-)video(-|$)/.test(t)||/^dall-e/.test(t)||/^gpt-image/.test(t)||/^imagen-/.test(t)||/^flux-/.test(t))}let tV={anthropic:{Icon:ta.A,hasColor:!1},openai:{Icon:td.A,hasColor:!1},"openai-codex":{Icon:td.A,hasColor:!1},google:{Icon:tc.A,hasColor:!0},"google-vertex":{Icon:tc.A,hasColor:!0},"ant-ling":{Icon:tE.A,hasColor:!0},deepseek:{Icon:tu.A,hasColor:!0},groq:{Icon:tp.A,hasColor:!1},mistral:{Icon:tx.A,hasColor:!0},moonshotai:{Icon:th.A,hasColor:!1},"moonshotai-cn":{Icon:th.A,hasColor:!1},moonshot:{Icon:th.A,hasColor:!1},minimax:{Icon:tg.A,hasColor:!0},"minimax-cn":{Icon:tg.A,hasColor:!0},fireworks:{Icon:tf.A,hasColor:!0},huggingface:{Icon:tm.A,hasColor:!0},cerebras:{Icon:tb.A,hasColor:!0},openrouter:{Icon:tv.A,hasColor:!1},xai:{Icon:ty.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:tj.A,hasColor:!0},"cloudflare-workers-ai":{Icon:tj.A,hasColor:!0},"vercel-ai-gateway":{Icon:tk.A,hasColor:!1},"github-copilot":{Icon:tw.A,hasColor:!1},"amazon-bedrock":{Icon:tS.A,hasColor:!0},"azure-openai-responses":{Icon:tC.A,hasColor:!0},"kimi-coding":{Icon:tN.A,hasColor:!0},nvidia:{Icon:tW.A,hasColor:!0},opencode:{Icon:tA.A,hasColor:!1},"opencode-go":{Icon:tA.A,hasColor:!1},qwen:{Icon:tT.A,hasColor:!0},xiaomi:{Icon:tP.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:tP.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:tP.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:tP.A,hasColor:!1},zai:{Icon:t$.A,hasColor:!1},"zai-coding-cn":{Icon:t$.A,hasColor:!1},zhipu:{Icon:tI.A,hasColor:!0},cohere:{Icon:tL.A,hasColor:!0},perplexity:{Icon:tR.A,hasColor:!0},together:{Icon:tz.A,hasColor:!0},grok:{Icon:tM.A,hasColor:!1}},t_=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function tK({label:e,children:t}){return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,n.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let tq={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 tJ({value:e,onChange:t,placeholder:r,mono:o}){return(0,n.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:r,style:{...tq,fontFamily:o?"var(--font-mono)":"inherit"}})}function tG({value:e,onChange:t,placeholder:r,mono:i,onKeyDown:l,autoComplete:a="off",spellCheck:d=!1,style:c}){let{t:u}=(0,s.s)(),[p,x]=(0,o.useState)(!1);return(0,o.useEffect)(()=>{e||x(!1)},[e]),(0,n.jsxs)("div",{style:{position:"relative",width:"100%",...c},children:[(0,n.jsx)("input",{type:p?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:r,style:{...tq,paddingRight:34,fontFamily:i?"var(--font-mono)":"inherit"},autoComplete:a,spellCheck:d}),(0,n.jsx)("button",{type:"button",onClick:()=>x(e=>!e),"aria-label":u(p?"modelsConfig.hideApiKey":"modelsConfig.showApiKey"),title:u(p?"modelsConfig.hideApiKey":"modelsConfig.showApiKey"),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:p?(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.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,n.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,n.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,n.jsx)("path",{d:"M1 1l22 22"})]}):(0,n.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,n.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function tY({value:e,onChange:t,onBlur:r,placeholder:o}){return(0,n.jsx)("input",{type:"text",inputMode:"decimal",value:e,onChange:e=>t(e.target.value),onBlur:r,placeholder:o,style:tq})}function tZ({value:e,onChange:t,placeholder:r}){return(0,n.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:r,style:tq})}function tX({value:e,onChange:t,options:r,required:o}){let{t:i}=(0,s.s)();return(0,n.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...tq,color:e?"var(--text)":"var(--text-dim)"},children:[!o&&(0,n.jsx)("option",{value:"",children:i("modelsConfig.inheritNone")}),r.map(e=>(0,n.jsx)("option",{value:e,children:e},e))]})}function tQ({label:e,checked:t,onChange:r}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:t,onChange:e=>r(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function t0({children:e}){return(0,n.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function t1({name:e,provider:t,onChange:r,onRename:i,onDelete:l}){let{t:a}=(0,s.s)(),[d,c]=(0,o.useState)(e);(0,o.useEffect)(()=>c(e),[e]);let u=(e,n)=>r({...t,[e]:n});return(0,o.useEffect)(()=>{t.api||r({...t,api:"openai-completions"})},[t.api]),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(t0,{children:a("modelsConfig.provider")}),(0,n.jsx)("button",{onClick:l,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:a("common.delete")})]}),(0,n.jsxs)(tK,{label:a("modelsConfig.providerName"),children:[(0,n.jsx)(tJ,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,n.jsx)("button",{onClick:()=>i(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:a("sessionSidebar.rename")})]}),(0,n.jsx)(tK,{label:a("modelsConfig.baseUrl"),children:(0,n.jsx)(tJ,{value:t.baseUrl??"",onChange:e=>u("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,n.jsxs)(tK,{label:a("modelsConfig.apiKey"),children:[(0,n.jsx)(tG,{value:t.apiKey??"",onChange:e=>u("apiKey",e||void 0),placeholder:a("modelsConfig.apiKeyPlaceholder"),mono:!0}),(0,n.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:a("modelsConfig.apiKeyHint")})]}),(0,n.jsx)(tK,{label:a("modelsConfig.api"),children:(0,n.jsx)(tX,{value:t.api??"openai-completions",onChange:e=>u("api",e),options:t_,required:!0})})]})}let t2=["off","minimal","low","medium","high","xhigh"],t4={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c"};function t5({value:e,onChange:t}){let r=e??{},o=(e,n)=>{let o={...r};"omit"===n?delete o[e]:o[e]=n,t(Object.keys(o).length?o:void 0)};return(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:t2.map(e=>{let t=r[e],i=e in r?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=t4[e],a={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--accent)",color:"#fff",fontWeight:600};return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,n.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===i?.3:1}}),(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===i?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===i?"line-through":"none"},children:e})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,n.jsx)("button",{onClick:()=>o(e,"omit"),style:{...a,..."omit"===i?d:{}},children:"Default"}),(0,n.jsx)("button",{onClick:()=>o(e,null),style:{...a,borderLeft:"1px solid var(--border)",..."null"===i?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,n.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===i?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,n.jsx)("button",{onClick:()=>o(e,s||e),style:{...a,..."string"===i?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,n.jsx)("input",{value:s,onChange:t=>o(e,t.target.value),onFocus:()=>{"string"!==i&&o(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===i?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===i?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let t6={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function t3({providerName:e,provider:t,model:r,onChange:i,onDelete:l}){let{t:a}=(0,s.s)(),[d,c]=(0,o.useState)({phase:"idle"}),[u,p]=(0,o.useState)({}),x=(e,t)=>i({...r,[e]:t});(0,o.useEffect)(()=>{p({})},[e,r.id]);let h=(e,t)=>{let n={...r.cost??{}},o=function(e){let t=e.trim();if(!t||"."===t||"-"===t||t.endsWith(".")||"-."===t)return;let r=parseFloat(t);return Number.isNaN(r)?void 0:r}(t);void 0===o?delete n[e]:n[e]=o,i({...r,cost:tB(n)})},g=(0,o.useMemo)(()=>{if("idle"===d.phase)return null;if("testing"===d.phase)return a("modelsConfig.testingModelConnection");let e=[void 0!==d.latencyMs?`${d.latencyMs}ms`:null,void 0!==d.status?`HTTP ${d.status}`:null].filter(Boolean);return"success"===d.phase?[a("modelsConfig.connected"),...e,d.responseText||null].filter(Boolean).join(" \xb7 "):[a("common.failed"),...e,d.message].filter(Boolean).join(" \xb7 ")},[d,a]),f=tU(r.id),m=r.id.trim()&&r.id!==r.id.toLowerCase()?a("modelsConfig.modelIdCaseHint",{suggestedId:r.id.toLowerCase()}):null;(0,o.useEffect)(()=>{c({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,r.id,r.api]);let b=(0,o.useCallback)(async()=>{if(r.id.trim()&&"testing"!==d.phase&&tU(r.id)){c({phase:"testing"});try{let n=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:r})}),o=await n.json();if(!n.ok||!o.ok){let e=!1;o.disableReasoning&&r.reasoning&&(i({...r,reasoning:void 0,thinkingLevelMap:void 0}),e=!0),c({phase:"error",message:o.error??`HTTP ${n.status}`,latencyMs:o.latencyMs,status:o.status,reasoningDisabled:e});return}c({phase:"success",latencyMs:o.latencyMs,status:o.status,responseText:o.responseText})}catch(e){c({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[r,t,e,d.phase,i]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(t0,{children:a("modelsConfig.model")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[!f&&r.id.trim()&&(0,n.jsx)("span",{title:a("modelsConfig.chatTestNotSupported"),style:{maxWidth:280,height:24,padding:"0 8px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:a("modelsConfig.chatTestNotSupportedShort")}),g&&(0,n.jsx)("span",{title:g,style:{maxWidth:280,height:24,padding:"0 8px",border:`1px solid ${"error"===d.phase?"#fecaca":"success"===d.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===d.phase?"#fee2e2":"success"===d.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:g}),(0,n.jsxs)("button",{onClick:b,disabled:!r.id.trim()||"testing"===d.phase||!f,title:f?a("modelsConfig.testModelConnection"):a("modelsConfig.chatTestNotSupported"),style:{height:24,padding:"0 8px",background:"success"===d.phase?"#16a34a":"none",border:`1px solid ${"success"===d.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===d.phase?"#fff":r.id.trim()&&"testing"!==d.phase&&f?"var(--text-muted)":"var(--text-dim)",cursor:r.id.trim()&&"testing"!==d.phase&&f?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===d.phase&&(0,n.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===d.phase?a("modelsConfig.testing"):"success"===d.phase?a("modelsConfig.ok"):a("modelsConfig.test")]}),(0,n.jsx)("button",{onClick:l,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:a("common.remove")})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(tK,{label:a("modelsConfig.idRequired"),children:(0,n.jsx)(tJ,{value:r.id,onChange:e=>x("id",e),placeholder:"model-id",mono:!0})}),(0,n.jsx)(tK,{label:a("modelsConfig.name"),children:(0,n.jsx)(tJ,{value:r.name??"",onChange:e=>x("name",e||void 0),placeholder:"Display name"})})]}),m&&(0,n.jsx)("div",{style:{marginTop:-8,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:m}),!f&&r.id.trim()&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.5,padding:"8px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)"},children:a("modelsConfig.chatTestNotSupported")}),(0,n.jsx)(tK,{label:a("modelsConfig.apiOverride"),children:(0,n.jsx)(tX,{value:r.api??"",onChange:e=>x("api",e||void 0),options:t_})}),(0,n.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,n.jsx)(tQ,{label:a("modelsConfig.reasoningThinking"),checked:r.reasoning??!1,onChange:e=>x("reasoning",e||void 0)}),(0,n.jsx)(tQ,{label:a("modelsConfig.imageInput"),checked:r.input?.includes("image")??!1,onChange:e=>x("input",e?["text","image"]:void 0)})]}),"error"===d.phase&&d.reasoningDisabled&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.5,padding:"8px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)"},children:a("modelsConfig.reasoningNotSupportedHint")}),r.reasoning&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tQ,{label:a("modelsConfig.deepSeekThinkingCompat"),checked:r.compat?.thinkingFormat==="deepseek",onChange:e=>i(function(e,t){if(t)return{...e,compat:{...e.compat??{},...t6}};if(!e.compat)return e;let r={...e.compat};return delete r.thinkingFormat,delete r.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(r).length?r:void 0}}(r,e))}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,n.jsx)(t0,{children:a("modelsConfig.thinkingLevelMap")}),r.thinkingLevelMap&&(0,n.jsx)("button",{onClick:()=>x("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:a("modelsConfig.clearAll")})]}),(0,n.jsx)(t5,{value:r.thinkingLevelMap,onChange:e=>x("thinkingLevelMap",e)})]})]}),(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,n.jsx)(tK,{label:a("modelsConfig.contextWindowTokens"),children:(0,n.jsx)(tZ,{value:void 0!==r.contextWindow?String(r.contextWindow):"",onChange:e=>x("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,n.jsx)(tK,{label:a("modelsConfig.maxOutputTokens"),children:(0,n.jsx)(tZ,{value:void 0!==r.maxTokens?String(r.maxTokens):"",onChange:e=>x("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(t0,{children:a("modelsConfig.costPerMillionTokens")}),(0,n.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,n.jsx)(tK,{label:e,children:(0,n.jsx)(tY,{value:void 0!==u[e]?u[e]:r.cost?.[e]!==void 0?String(r.cost[e]):"",onChange:t=>((e,t)=>{(""===t||/^-?\d*(\.\d*)?$/.test(t))&&(p(r=>({...r,[e]:t})),""!==t&&(t.endsWith(".")||"-"===t||"-."===t)||h(e,t))})(e,t),onBlur:()=>{let t;void 0!==(t=u[e])&&(h(e,t),p(t=>{let r={...t};return delete r[e],r}))},placeholder:"0"})},e))})]})]})}function t8({provider:e,onRefresh:t}){let{t:r}=(0,s.s)(),[i,l]=(0,o.useState)({phase:"idle"}),[a,d]=(0,o.useState)(""),c=(0,o.useRef)(null),u=(0,o.useRef)(null);(0,o.useEffect)(()=>{("auth"===i.phase||"prompt"===i.phase)&&setTimeout(()=>u.current?.focus(),50)},[i.phase]),(0,o.useEffect)(()=>{l({phase:"idle"}),d(""),c.current?.close(),c.current=null},[e.id]),(0,o.useEffect)(()=>()=>{c.current?.close()},[]);let p=(0,o.useCallback)(()=>{c.current?.close(),l({phase:"connecting"}),d("");let n=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);c.current=n,n.onmessage=e=>{let r=JSON.parse(e.data);"auth"===r.type?(l({phase:"auth",url:r.url,instructions:r.instructions??null,token:r.token}),window.open(r.url,"_blank","noopener,noreferrer")):"device_code"===r.type?(l({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?l({phase:"prompt",message:r.message,placeholder:r.placeholder??null,token:r.token}):"select_request"===r.type?l({phase:"select",message:r.message,options:r.options??[],token:r.token}):"progress"===r.type?l({phase:"progress",message:r.message}):"success"===r.type?(n.close(),l({phase:"success"}),t()):"error"===r.type?(n.close(),l({phase:"error",message:r.message})):"cancelled"===r.type&&(n.close(),l({phase:"idle"}))},n.onerror=()=>{n.close(),l(e=>"success"===e.phase?e:{phase:"error",message:r("modelsConfig.connectionLost")})}},[e.id,t,r]),x=(0,o.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),l({phase:"idle"}),t()},[e.id,t]),h=(0,o.useCallback)(async(t,n)=>{if(n.trim()){l({phase:"progress",message:r("modelsConfig.verifying")});try{let o=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n.trim()})});if(!o.ok){let e=await o.json().catch(()=>({}));l({phase:"error",message:e.error??r("modelsConfig.serverError",{status:o.status})});return}d("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:r("modelsConfig.networkError")})}}},[e.id,r]),g=(0,o.useCallback)(async(t,n)=>{l({phase:"progress",message:r("modelsConfig.continuing")});try{let o=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})});if(!o.ok){let e=await o.json().catch(()=>({}));l({phase:"error",message:e.error??r("modelsConfig.serverError",{status:o.status})})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:r("modelsConfig.networkError")})}},[e.id,r]),f="connecting"===i.phase||"progress"===i.phase||"auth"===i.phase||"device_code"===i.phase||"prompt"===i.phase||"select"===i.phase;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(t0,{children:r("modelsConfig.subscription")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:e.loggedIn?r("modelsConfig.connectedState"):r("modelsConfig.notConnectedState")})]})]}),(0,n.jsxs)("div",{style:{minHeight:48},children:["idle"===i.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?r("modelsConfig.alreadyConnected"):r("modelsConfig.connectAccount",{provider:e.name})}),"connecting"===i.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:r("modelsConfig.openingBrowser")}),"select"===i.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:i.message}),(0,n.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:i.options.map(e=>(0,n.jsx)("button",{onClick:()=>g(i.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"===i.phase||"prompt"===i.phase)&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===i.phase?r("modelsConfig.browserCompleteHint"):i.message}),"auth"===i.phase&&(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[r("modelsConfig.openLoginPageHint")," ",(0,n.jsx)("a",{href:i.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:r("common.open")}),"."]}),(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)("input",{ref:u,value:a,onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(i.token,a)},placeholder:"auth"===i.phase?r("modelsConfig.callbackPlaceholder"):i.placeholder??r("modelsConfig.enterValuePlaceholder"),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,n.jsx)("button",{onClick:()=>h(i.token,a),disabled:!a.trim(),style:{padding:"6px 12px",background:a.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:a.trim()?"#fff":"var(--text-dim)",cursor:a.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:r("modelsConfig.submit")})]})]}),"device_code"===i.phase&&(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:r("modelsConfig.verificationPageHint")}),(0,n.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:i.userCode}),(0,n.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,n.jsx)("a",{href:i.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:i.verificationUri}),i.expiresInSeconds?` ${r("modelsConfig.expiresInMinutes",{count:Math.ceil(i.expiresInSeconds/60)})}`:""]})]}),"progress"===i.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:i.message}),"success"===i.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:r("modelsConfig.connectedSuccessfully")}),"error"===i.phase&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:i.message})]}),(0,n.jsx)("div",{style:{display:"flex",gap:8},children:f?(0,n.jsx)("button",{onClick:()=>{c.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:r("common.cancel")}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{onClick:p,style:{padding:"5px 14px",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:e.loggedIn?r("modelsConfig.reLogin"):r("modelsConfig.login")}),e.loggedIn&&(0,n.jsx)("button",{onClick:x,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:r("modelsConfig.disconnect")})]})})]})}function t9({provider:e,onRefresh:t}){let{t:r}=(0,s.s)(),[i,l]=(0,o.useState)(""),[a,d]=(0,o.useState)(!1),[c,u]=(0,o.useState)(!1),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(!1);(0,o.useEffect)(()=>{l(""),x(null),g(!1)},[e.id]);let f=(0,o.useCallback)(async()=>{if(i.trim()){d(!0),x(null),g(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:i.trim()})}),n=await r.json();!r.ok||n.error?x(n.error??`HTTP ${r.status}`):(l(""),g(!0),setTimeout(()=>g(!1),2e3),t())}catch(e){x(String(e))}finally{d(!1)}}},[i,e.id,t]),m=(0,o.useCallback)(async()=>{u(!0),x(null);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),n=await r.json();!r.ok||n.error?x(n.error??`HTTP ${r.status}`):t()}catch(e){x(String(e))}finally{u(!1)}},[e.id,t]);return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,n.jsx)(t0,{children:r("modelsConfig.apiKeyShort")}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,n.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,n.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:r(e.configured?"modelsConfig.configured":"modelsConfig.notConnectedState")})]})]}),(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?r("modelsConfig.apiKeyStored"):r("modelsConfig.enterApiKey",{provider:e.displayName,count:e.modelCount})}),(0,n.jsx)(tK,{label:r("modelsConfig.apiKeyShort"),children:(0,n.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,n.jsx)(tG,{value:i,onChange:l,onKeyDown:e=>{"Enter"===e.key&&i.trim()&&f()},placeholder:r(e.configured?"modelsConfig.enterNewKeyPlaceholder":"modelsConfig.apiKeyMaskedPlaceholder"),style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,n.jsxs)("button",{onClick:f,disabled:a||!i.trim()||h,style:{padding:"6px 12px",background:h?"#16a34a":i.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:i.trim()||h?"#fff":"var(--text-dim)",cursor:a||!i.trim()||h?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[h&&(0,n.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),r(h?"modelsConfig.saved":a?"modelsConfig.saving":"common.save")]})]})}),p&&(0,n.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:p}),e.configured&&(0,n.jsx)("button",{onClick:m,disabled:c,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:c?"not-allowed":"pointer",fontSize:12},children:r(c?"modelsConfig.removing":"modelsConfig.disconnect")})]})}function t7({id:e,size:t}){let r=tV[e];return r?r.hasColor?(0,n.jsx)(r.Icon,{size:t}):(0,n.jsx)(r.Icon,{size:t,style:{color:"var(--text-muted)"}}):null}function re({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:r,onSelectApiKey:i,onAddCustom:l,onClose:a}){let{t:d}=(0,s.s)(),[c,u]=(0,o.useState)(""),p=(0,o.useRef)(null);(0,o.useEffect)(()=>{setTimeout(()=>p.current?.focus(),30)},[]);let x=c.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!x||e.name.toLowerCase().includes(x))),g=t.filter(e=>!e.configured&&(!x||e.displayName.toLowerCase().includes(x)||e.id.toLowerCase().includes(x))),f=!x||"custom".includes(x)||"openai-compatible".includes(x)||"anthropic-compatible".includes(x),m=h.length+g.length+ +!!f,b={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,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&a()},children:(0,n.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,n.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,n.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,n.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,n.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,n.jsx)("input",{ref:p,value:c,onChange:e=>u(e.target.value),onKeyDown:e=>{"Escape"===e.key&&a()},placeholder:d("modelsConfig.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===m?(0,n.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:d("modelsConfig.noProvidersMatch")}):(0,n.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("modelsConfig.customGroup")}),f&&(0,n.jsxs)("button",{onClick:()=>{l(),a()},style:b,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,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d("modelsConfig.openAiCompatible")}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("modelsConfig.customEndpointFormat")})]}),(0,n.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,n.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,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,n.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:d("modelsConfig.subscriptions")}),h.map(e=>(0,n.jsxs)("button",{onClick:()=>{r(e.id),a()},style:b,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,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("modelsConfig.oauth")})]}),(0,n.jsx)(t7,{id:e.id,size:28})]},e.id)),g.length>0&&(0,n.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:d("modelsConfig.apiKeyShort")}),g.map(e=>(0,n.jsxs)("button",{onClick:()=>{i(e.id),a()},style:b,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,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,n.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:d("modelsConfig.modelsCount",{count:e.modelCount})})]}),(0,n.jsx)(t7,{id:e.id,size:28})]},e.id))]})})]})})}function rt({onClose:e,onModelsChanged:t}){let{t:r}=(0,s.s)(),[i,l]=(0,o.useState)({providers:{}}),[a,d]=(0,o.useState)(!0),[c,u]=(0,o.useState)(!1),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(!1),[f,m]=(0,o.useState)(null),[b,v]=(0,o.useState)([]),[y,j]=(0,o.useState)([]),[k,w]=(0,o.useState)(!1),[S,C]=(0,o.useState)([]),[N,T]=(0,o.useState)(null),[I,L]=(0,o.useState)(!0),[R,z]=(0,o.useState)(!1),[M,E]=(0,o.useState)(null),W=(0,o.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>v(e.providers)).catch(()=>{})},[]),A=(0,o.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>j(e.providers)).catch(()=>{})},[]),P=(0,o.useCallback)(()=>{L(!0),fetch("/api/models").then(e=>e.json()).then(e=>{C(e.modelList??[]),T(e.defaultModel??null)}).catch(()=>{}).finally(()=>L(!1))},[]),$=(0,o.useCallback)(async e=>{let[r,n]=e.split("::");if(r&&n){z(!0),E(null);try{let e=await fetch("/api/settings/default-model",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:r,modelId:n})}),o=await e.json().catch(()=>({}));if(!e.ok)throw Error(o.error??`HTTP ${e.status}`);T({provider:r,modelId:n}),t?.()}catch(e){E(e instanceof Error?e.message:String(e))}finally{z(!1)}}},[t]);(0,o.useEffect)(()=>{P()},[P]),(0,o.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{let t=e.providers?e:{...e,providers:{}};l(t);let r=Object.keys(t.providers??{});r.length>0&&m({type:"provider",name:r[0]})}).catch(()=>l({providers:{}})).finally(()=>d(!1)),W(),A()},[W,A]);let O=(0,o.useCallback)(()=>{let e="new-provider",t=1;for(;i.providers?.[e];)e=`new-provider-${t++}`;l(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),m({type:"provider",name:e})},[i.providers]),H=(0,o.useCallback)((e,t)=>{l(r=>({...r,providers:{...r.providers??{},[e]:t}}))},[]),D=(0,o.useCallback)((e,t)=>{l(r=>{let n=Object.entries(r.providers??{}),o=n.findIndex(([t])=>t===e);return -1===o?r:(n[o]=[t,n[o][1]],{...r,providers:Object.fromEntries(n)})}),m(r=>r?"provider"===r.type&&r.name===e?{type:"provider",name:t}:"model"===r.type&&r.providerName===e?{...r,providerName:t}:r:r)},[]),B=(0,o.useCallback)(e=>{l(t=>{let r={...t.providers??{}};return delete r[e],{...t,providers:r}}),l(e=>{let t=Object.keys(e.providers??{});return m(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),F=(0,o.useCallback)(e=>{l(t=>{let r=t.providers?.[e]??{},n=[...r.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...r,models:n}}}}),l(t=>{let r=(t.providers?.[e]?.models?.length??1)-1;return m({type:"model",providerName:e,index:r}),t})},[]),U=(0,o.useCallback)((e,t,r)=>{l(n=>{let o=n.providers?.[e]??{},i=[...o.models??[]];return i[t]=r,{...n,providers:{...n.providers??{},[e]:{...o,models:i}}}})},[]),V=(0,o.useCallback)((e,t)=>{l(r=>{let n=r.providers?.[e]??{},o=[...n.models??[]];return o.splice(t,1),{...r,providers:{...r.providers??{},[e]:{...n,models:o.length?o:void 0}}}}),m({type:"provider",name:e})},[]),_=(0,o.useCallback)(async()=>{u(!0),x(null),g(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(function(e){if(!tH(e)||!tH(e.providers))return{providers:{}};let t={};for(let[r,n]of Object.entries(e.providers))r.trim()&&tH(n)&&(t[r]=function(e){let t={};if("string"==typeof e.name&&e.name.trim()&&(t.name=e.name.trim()),"string"==typeof e.baseUrl&&e.baseUrl.trim()&&(t.baseUrl=e.baseUrl.trim()),"string"==typeof e.apiKey&&e.apiKey.trim()&&(t.apiKey=e.apiKey.trim()),"string"==typeof e.api&&e.api.trim()&&(t.api=e.api.trim()),!0===e.authHeader&&(t.authHeader=!0),tH(e.headers)&&Object.keys(e.headers).length>0){let r={};for(let[t,n]of Object.entries(e.headers))"string"==typeof n&&n.length>0&&(r[t]=n);Object.keys(r).length>0&&(t.headers=r)}return tH(e.compat)&&Object.keys(e.compat).length>0&&(t.compat=e.compat),Array.isArray(e.models)&&(t.models=e.models.filter(tH).map(tF).filter(e=>e.id.length>0),0===t.models.length&&delete t.models),tH(e.modelOverrides)&&Object.keys(e.modelOverrides).length>0&&(t.modelOverrides=e.modelOverrides),t}(n));return{providers:t}}(i))}),t=await e.json();!e.ok||t.error?x(t.error??`HTTP ${e.status}`):(g(!0),setTimeout(()=>g(!1),2e3))}catch(e){x(String(e))}finally{u(!1)}},[i]),K=Object.entries(i.providers??{}),q=b.filter(e=>e.loggedIn),J=y.filter(e=>e.configured),G=(()=>{if(!f)return null;if("oauth"===f.type){let e=b.find(e=>e.id===f.providerId);return e?(0,n.jsx)(t8,{provider:e,onRefresh:W},e.id):null}if("apikey"===f.type){let e=y.find(e=>e.id===f.providerId);return e?(0,n.jsx)(t9,{provider:e,onRefresh:A},e.id):null}if("provider"===f.type){let e=i.providers?.[f.name];return e?(0,n.jsx)(t1,{name:f.name,provider:e,onChange:e=>H(f.name,e),onRename:e=>D(f.name,e),onDelete:()=>B(f.name)},f.name):null}let e=i.providers?.[f.providerName],t=e?.models?.[f.index];return t?(0,n.jsx)(t3,{providerName:f.providerName,provider:e,model:t,onChange:e=>U(f.providerName,f.index,e),onDelete:()=>V(f.providerName,f.index)},`${f.providerName}-${f.index}`):null})();return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:t=>{t.target===t.currentTarget&&e()},children:(0,n.jsxs)("div",{style:{width:860,height:"78vh",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:r("modelsConfig.models")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.pi/agent/models.json"})]}),(0,n.jsx)("button",{onClick:e,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:r("modelsConfig.defaultModel")}),(0,n.jsx)("p",{style:{margin:"4px 0 8px",fontSize:11,lineHeight:1.45,color:"var(--text-muted)"},children:r("modelsConfig.defaultModelDescription")}),(0,n.jsxs)("select",{disabled:I||0===S.length||R,value:N?`${N.provider}::${N.modelId}`:"",onChange:e=>void $(e.target.value),style:{width:"100%",padding:"8px 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",fontSize:12},children:[(0,n.jsx)("option",{value:"",children:r("modelsConfig.selectDefaultModel")}),S.map(e=>(0,n.jsxs)("option",{value:`${e.provider}::${e.id}`,children:[e.name," (",e.provider,")"]},`${e.provider}:${e.id}`))]}),(0,n.jsx)("p",{style:{margin:"6px 0 0",fontSize:11,lineHeight:1.45,color:"var(--text-dim)"},children:r("modelsConfig.perSessionModelHint")}),M&&(0,n.jsx)("p",{style:{margin:"6px 0 0",fontSize:11,color:"#f87171"},children:M})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden",minHeight:0},children:[(0,n.jsxs)("div",{style:{width:210,borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[q.map(e=>{let t=f?.type==="oauth"&&f.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>m({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(t7,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),J.map(e=>{let t=f?.type==="apikey"&&f.providerId===e.id;return(0,n.jsxs)("div",{onClick:()=>m({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)(t7,{id:e.id,size:16}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(q.length>0||J.length>0)&&K.length>0&&(0,n.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),a?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:r("common.loading")}):K.map(([e,t])=>{let o=f?.type==="provider"&&f.name===e,i=t.models??[];return(0,n.jsxs)("div",{style:{marginBottom:2},children:[(0,n.jsxs)("div",{onClick:()=>m({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:o?"var(--bg-selected)":"none"},onMouseEnter:e=>{o||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{o||(e.currentTarget.style.background="none")},children:[(0,n.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,n.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,n.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,n.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,n.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,n.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,n.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,n.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,n.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,n.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,n.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:o?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,o)=>{let i=f?.type==="model"&&f.providerName===e&&f.index===o;return(0,n.jsxs)("div",{onClick:()=>m({type:"model",providerName:e,index:o}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||r("modelsConfig.newModel")}),t.reasoning&&(0,n.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"})]},o)}),(0,n.jsx)("div",{onClick:t=>{t.stopPropagation(),F(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,n.jsx)("span",{style:{fontSize:11},children:r("modelsConfig.addModel")})})]},e)})]}),(0,n.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,n.jsx)("button",{onClick:()=>w(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:r("modelsConfig.addProvider")})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:a?null:G??(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:r("modelsConfig.selectProviderOrModel")})})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[p&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:p}),(0,n.jsx)("button",{onClick:e,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:r("common.cancel")}),(0,n.jsxs)("button",{onClick:_,disabled:c||h,style:{position:"relative",padding:"6px 16px",minWidth:92,background:h?"#16a34a":c?"var(--bg-panel)":"var(--accent)",border:"none",borderRadius:6,color:h?"#fff":c?"var(--text-muted)":"#fff",cursor:c||h?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:h?"saved-pop 0.45s ease":void 0},children:[h&&(0,n.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,n.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,n.jsx)("span",{children:h?r("modelsConfig.saved"):c?r("modelsConfig.saving"):r("common.save")})]})]})]})}),k&&(0,n.jsx)(re,{oauthProviders:b,apiKeyProviders:y,onSelectOAuth:e=>m({type:"oauth",providerId:e}),onSelectApiKey:e=>m({type:"apikey",providerId:e}),onAddCustom:O,onClose:()=>w(!1)})]})}function rr(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function rn(e){let t=e.sourceInfo?.source,r=e.sourceInfo?.scope;return"user"===r||"user"===t?"global":"project"===r||"project"===t?"project":"path"}function ro({enabled:e,loading:t,onToggle:r}){let{t:o}=(0,s.s)();return(0,n.jsx)("button",{onClick:r,disabled:t,title:o(e?"skillsConfig.visibleInPrompt":"skillsConfig.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,n.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function ri({skill:e,cwd:t,onToggle:r,toggling:o,saveError:i}){let{t:l}=(0,s.s)(),a=rn(e),d=!e.disableModelInvocation;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,n.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===a?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===a?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:a}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===a&&e.startsWith(t)){let r=e.slice(t.length).replace(/^[/\\]/,"");return`./${r}`}return rr(e)}(e.filePath)}),(0,n.jsx)(ro,{enabled:d,loading:o,onToggle:()=>r(e)}),i&&(0,n.jsx)("span",{style:{fontSize:12,color:"#f87171",flexShrink:0},children:i})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:l("skillsConfig.name")}),(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:l("skillsConfig.description")}),(0,n.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function rs({cwd:e,onInstalled:t}){let{t:r}=(0,s.s)(),[i,l]=(0,o.useState)(""),[a,d]=(0,o.useState)([]),[c,u]=(0,o.useState)(!1),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(null),[f,m]=(0,o.useState)(null),[b,v]=(0,o.useState)(new Set),[y,j]=(0,o.useState)("global"),k=(0,o.useRef)(null);(0,o.useEffect)(()=>{k.current?.focus()},[]);let w=(0,o.useCallback)(async e=>{if(e.trim()){u(!0),x(null),d([]);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 x(n.error);d(n.results??[]),0===(n.results??[]).length&&x(r("skillsConfig.noSkillsFound"))}catch(e){x(String(e))}finally{u(!1)}}},[r]),S=(0,o.useCallback)(async r=>{g(r),m(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:r,scope:y,cwd:e})}),o=await n.json();if(!n.ok||o.error)return void m(o.error??`HTTP ${n.status}`);v(e=>new Set(e).add(r)),t()}catch(e){m(String(e))}finally{g(null)}},[t,y,e]),C="global"===y?"~/.pi/agent/skills/":`${rr(e)}/.pi/agent/skills/`;return(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,n.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,n.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:r("skillsConfig.addSkill")}),(0,n.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,n.jsx)("input",{ref:k,value:i,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key&&w(i)},placeholder:r("skillsConfig.searchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,n.jsx)("button",{onClick:()=>w(i),disabled:c||!i.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--accent)",color:"#fff",cursor:c||!i.trim()?"not-allowed":"pointer",opacity:c||!i.trim()?.5:1,flexShrink:0},children:c?r("skillsConfig.searching"):r("skillsConfig.search")})]}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,n.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,n.jsx)("button",{onClick:()=>j(e),style:{padding:"3px 10px",border:"none",cursor:"pointer",background:y===e?"var(--bg-selected)":"none",color:y===e?"var(--text)":"var(--text-dim)",fontWeight:y===e?600:400,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,n.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",C]})]}),p&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:p}),f&&(0,n.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:f})]}),a.length>0?(0,n.jsx)("div",{style:{flex:1,overflowY:"auto"},children:a.map(e=>{let t=b.has(e.package),o=h===e.package,i=e.package.indexOf("@"),s=i>-1?e.package.slice(0,i):e.package,l=i>-1?e.package.slice(i+1):null;return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,n.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,n.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:l??s}),(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,n.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:s}),(0,n.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,n.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,n.jsx)("button",{onClick:()=>!t&&!o&&S(e.package),disabled:t||o||null!==h,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:t||o||null!==h?"not-allowed":"pointer",background:t?"rgba(34,197,94,0.1)":"none",color:t?"#16a34a":o?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:t?`✓ ${r("skillsConfig.installed")}`:o?r("skillsConfig.installing"):r("skillsConfig.install")})]},e.package)})}):!p&&!c&&(0,n.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:[r("skillsConfig.search")," ",(0,n.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ",r("skillsConfig.discoverAndInstall")]})]})}function rl({cwd:e,onClose:t}){let{t:r}=(0,s.s)(),[i,l]=(0,o.useState)([]),[a,d]=(0,o.useState)(!0),[c,u]=(0,o.useState)(null),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(new Set),[f,m]=(0,o.useState)(null),[b,v]=(0,o.useState)(!1),y=(0,o.useCallback)(()=>{d(!0),u(null),fetch(`/api/skills?cwd=${encodeURIComponent(e)}`).then(e=>e.json()).then(e=>{if(e.error)return void u(e.error);let t=e.skills??[];l(t),t.length>0&&!p&&x(t[0].filePath)}).catch(e=>u(String(e))).finally(()=>d(!1))},[e,p]);(0,o.useEffect)(()=>{y()},[e]);let j=(0,o.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),m(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),n=await r.json();if(!r.ok||n.error)return void m(n.error??`HTTP ${r.status}`);l(r=>r.map(r=>r.filePath===e.filePath?{...r,disableModelInvocation:t}:r))}catch(e){m(String(e))}finally{g(t=>{let r=new Set(t);return r.delete(e.filePath),r})}},[]),k=i.find(e=>e.filePath===p)??null;return(0,n.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsxs)("div",{style:{width:860,height:"78vh",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,n.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:r("skillsConfig.skills")}),(0,n.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:rr(e)})]}),(0,n.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[(0,n.jsxs)("div",{style:{width:210,borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:a?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:r("skillsConfig.loading")}):c?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:c}):0===i.length?(0,n.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:r("skillsConfig.noSkillsFound")}):(()=>{let e=[];for(let t of["project","global","path"]){let r=i.filter(e=>rn(e)===t);r.length>0&&e.push({label:t,skills:r})}return e.map(({label:e,skills:t})=>(0,n.jsxs)("div",{style:{marginBottom:6},children:[(0,n.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:"project"===e?r("skillsConfig.project"):"global"===e?r("skillsConfig.global"):r("skillsConfig.path")}),t.map(e=>{let t=!b&&p===e.filePath,r=e.disableModelInvocation;return(0,n.jsxs)("div",{onClick:()=>{x(e.filePath),v(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,n.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:r?"var(--border)":"var(--accent)",boxShadow:r?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,n.jsx)("span",{style:{fontSize:12,fontWeight:t?600:400,color:r?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.filePath)})]},e))})()}),(0,n.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsxs)("div",{onClick:()=>v(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,n.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,n.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),r("skillsConfig.addSkill")]})})]}),(0,n.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,n.jsx)(rs,{cwd:e,onInstalled:()=>{y()}}):a?null:k?(0,n.jsx)(ri,{skill:k,cwd:e,onToggle:j,toggling:h.has(k.filePath),saveError:f},k.filePath):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:r("skillsConfig.selectSkill")})})]}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,n.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:r("skillsConfig.close")})})]})})}function ra(e){let t=e,r=0;for(;1===t.children.length;)t=t.children[0],r++;return{node:t,skipped:r}}function rd(e){for(let t of e)if(t.children.length>1||rd(t.children))return!0;return!1}function rc({leafId:e,isActive:t,label:r,onSelect:o}){return(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>o(e),children:[(0,n.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:t?"var(--accent)":"var(--border)",border:t?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),(0,n.jsx)("span",{style:{fontSize:11,color:t?"var(--text)":"var(--text-muted)",fontWeight:t?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:r})]})}function ru({node:e,activePathIds:t,depth:r,isLast:o,parentLines:i,onSelect:l}){let{t:a}=(0,s.s)(),{node:d,skipped:c}=ra(e),u=t.has(d.entry.id),p=t.has(e.entry.id)||t.has(d.entry.id),x=function(e,t){if("message"===e.type&&"message"in e){let r=e.message,n=r.content,o="";if("string"==typeof n?o=n:Array.isArray(n)&&(o=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),o.length>40&&(o=`${o.slice(0,40)}…`),o)return o;if("assistant"===r.role)return t}return e.type}(d.entry,a("branchNavigator.assistantFallback")),h="message"===d.entry.type&&"message"in d.entry?d.entry.message.role:null;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>l(d.entry.id),children:[i.map((e,t)=>(0,n.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,n.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,n.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,n.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:o?"50%":0,width:1,background:"var(--border)"}}),(0,n.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,n.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"}}),h&&(0,n.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===h?"var(--accent)":"var(--text-dim)",background:"user"===h?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===h?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===h?"U":"A"}),c>0&&(0,n.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",c]}),(0,n.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:x})]}),d.children.map((e,s)=>(0,n.jsx)(ru,{node:e,activePathIds:t,depth:r+1,isLast:s===d.children.length-1,parentLines:[...i,!o],onSelect:l},e.entry.id))]})}function rp({checked:e,onChange:t,disabled:r,t:o}){return(0,n.jsxs)("label",{style:{display:"flex",alignItems:"flex-start",gap:8,marginTop:8,paddingTop:8,borderTop:"1px solid var(--border)",cursor:r?"not-allowed":"pointer",opacity:r?.6:1,fontSize:11,color:"var(--text-muted)"},children:[(0,n.jsx)("input",{type:"checkbox",checked:e,disabled:r,onChange:e=>t(e.target.checked),style:{marginTop:2}}),(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{style:{display:"block",color:"var(--text)",fontWeight:500},children:o("branchNavigator.summarizeBeforeSwitch")}),(0,n.jsx)("span",{style:{display:"block",marginTop:2,lineHeight:1.4},children:o("branchNavigator.summarizeBeforeSwitchHint")})]})]})}function rx({tree:e,activePathIds:t,forkNode:r,showMainBranch:o,mainLeafId:i,onSelect:s,summarizeBeforeSwitch:l,onSummarizeBeforeSwitchChange:a,branchNavigating:d,t:c}){let u=null;return(o&&i?u=(0,n.jsx)(rc,{leafId:i,isActive:t.has(i),label:c("branchNavigator.mainBranch"),onSelect:s}):r?u=(0,n.jsx)(n.Fragment,{children:r.children.map((e,o)=>(0,n.jsx)(ru,{node:e,activePathIds:t,depth:0,isLast:o===r.children.length-1,parentLines:[],onSelect:s},e.entry.id))}):0===e.length&&(u=(0,n.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:c("branchNavigator.noBranches")})),u)?(0,n.jsxs)("div",{style:{opacity:d?.65:1,pointerEvents:d?"none":void 0},children:[u,d&&(0,n.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:8},children:c("branchNavigator.switching")}),(0,n.jsx)(rp,{checked:l,onChange:a,disabled:d,t:c})]}):null}function rh({tree:e,activeLeafId:t,onLeafChange:r,gitBranch:i,branchNavigating:l=!1,inline:a,containerRef:d,open:c,onToggle:u,hasSession:p}){let{t:x}=(0,s.s)(),[h,g]=(0,o.useState)(!1),[f,m]=(0,o.useState)(!1);(0,o.useEffect)(()=>{fetch("/api/preferences").then(e=>e.json()).then(e=>{g(e.preferences?.branchSummarizeBeforeSwitch===!0),e.preferences&&eb(e.preferences)}).catch(()=>{})},[]);let b=(0,o.useCallback)(e=>{g(e),fetch("/api/preferences",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({branchSummarizeBeforeSwitch:e})}).then(e=>e.json()).then(e=>{e.preferences&&eb(e.preferences)}).catch(()=>{})},[]),v=void 0!==c?c:f,y=(0,o.useRef)(null),[j,k]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!v||!a)return;let e=d?.current??y.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();k({top:t.bottom,left:t.left,width:t.width})};t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[v,a,d]);let w=(0,o.useMemo)(()=>t?new Set(function e(r,n){for(let o of r){let r=[...n,o.entry.id];if(o.entry.id===t)return r;let i=e(o.children,r);if(i)return i}return null}(e,[])??[]):new Set,[e,t]),S=(0,o.useCallback)(e=>{l||r(e)},[r,l]),C=(0,o.useMemo)(()=>(function(e){if(0===e.length)return null;let{node:t}=ra(e[0]);return t.children.length>1?t:null})(e),[e]),N=e.length>0&&!rd(e),T=t??function(e){if(0===e.length)return null;let t=e[0];for(;1===t.children.length;)t=t.children[0];return t.children.length,t.entry.id}(e),I=N||null!==C,L=i??x("branchNavigator.branches"),R=p?0===e.length?x("branchNavigator.noBranches"):null:x("branchNavigator.noActiveSession"),z=(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:I?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,n.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,n.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,n.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),M=(0,n.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:v?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),E=v?"var(--bg-popover)":"var(--bg-elevated)";return a?(0,n.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,n.jsxs)("button",{ref:y,onClick:()=>u?u():m(e=>!e),style:{display:"flex",alignItems:"center",gap:6,height:"100%",boxSizing:"border-box",padding:"0 12px",background:E,border:"none",borderTop:v?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:v?"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=v?"var(--text)":"var(--text-muted)"},children:[z,(0,n.jsx)("span",{children:L}),M]}),v&&j&&(0,n.jsx)("div",{style:{position:"fixed",top:j.top,left:j.left,width:j.width,background:"var(--bg-popover)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",boxShadow:"var(--shadow-popover)",zIndex:500},children:I?(0,n.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:(0,n.jsx)(rx,{tree:e,activePathIds:w,forkNode:C,showMainBranch:N,mainLeafId:T,onSelect:S,summarizeBeforeSwitch:h,onSummarizeBeforeSwitchChange:b,branchNavigating:l,t:x})}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:R})})]}):(0,n.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,n.jsxs)("button",{onClick:()=>m(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:[z,(0,n.jsx)("span",{style:{color:"var(--text-muted)"},children:x("branchNavigator.branches")}),M]}),v&&(0,n.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:I?(0,n.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:(0,n.jsx)(rx,{tree:e,activePathIds:w,forkNode:C,showMainBranch:N,mainLeafId:T,onSelect:S,summarizeBeforeSwitch:h,onSummarizeBeforeSwitchChange:b,branchNavigating:l,t:x})}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:R??x("branchNavigator.noBranches")})})]})}let rg={active:"border-[color-mix(in_srgb,var(--accent)_55%,var(--border))] text-accent",completed:"border-[color-mix(in_srgb,#22c55e_55%,var(--border))] text-[#15803d] dark:text-[#4ade80]",draft:"border-border text-text-dim"};function rf(e,t){try{return new Date(e).toLocaleString(t)}catch{return e}}function rm({item:e,onClose:t,onOpenChat:r}){let{t:i,locale:l}=(0,s.s)(),a={active:i("workbenchHistoryDetail.active"),completed:i("workbenchHistoryDetail.completed"),draft:i("workbenchHistoryDetail.draft")};return(0,o.useEffect)(()=>{let e=e=>{"Escape"===e.key&&t()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[t]),(0,n.jsx)("div",{className:"fixed inset-0 z-[600] flex items-center justify-center bg-[rgba(0,0,0,0.36)] px-4 py-8 backdrop-blur-[2px]",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":i("workbenchHistoryDetail.historyDetails"),className:"flex max-h-[80vh] w-full max-w-[640px] flex-col overflow-hidden rounded-[12px] border border-border bg-bg-popover",style:{boxShadow:"var(--shadow-popover)"},children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-3 border-b border-border px-5 py-4",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"truncate text-[12px] text-text-dim",title:e.cwd,children:e.cwd}),(0,n.jsx)("h2",{className:"mt-1.5 truncate text-[18px] font-semibold leading-snug text-text",title:e.title,children:e.title}),(0,n.jsxs)("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-dim",children:[(0,n.jsx)("span",{className:`rounded-[6px] border bg-bg-subtle px-2 py-0.5 font-medium ${rg[e.status]}`,children:a[e.status]}),(0,n.jsx)("span",{children:"\xb7"}),(0,n.jsx)("span",{children:1===e.messageCount?i("workbenchHistoryDetail.messagesCountOne",{count:e.messageCount}):i("workbenchHistoryDetail.messagesCountOther",{count:e.messageCount})})]})]}),(0,n.jsx)("button",{onClick:t,"aria-label":i("workbenchHistoryDetail.closeDetails"),className:"h-7 w-7 shrink-0 rounded-[6px] border border-border bg-bg-subtle text-[14px] text-text-muted hover:bg-bg-hover hover:text-text",children:"\xd7"})]}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[e.summary?(0,n.jsxs)("div",{className:"mb-4",children:[(0,n.jsx)("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-dim",children:i("workbenchHistoryDetail.latestResultSummary")}),(0,n.jsx)("div",{className:"whitespace-pre-wrap rounded-[8px] border border-border bg-bg-subtle px-3 py-2.5 text-[13px] leading-6 text-text",style:{fontFamily:"var(--font-mono)"},children:e.summary})]}):(0,n.jsx)("div",{className:"mb-4 text-[12px] text-text-dim",children:i("workbenchHistoryDetail.noSummary")}),e.firstMessage&&(0,n.jsxs)("div",{className:"mb-4",children:[(0,n.jsx)("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-dim",children:i("workbenchHistoryDetail.firstMessage")}),(0,n.jsx)("div",{className:"whitespace-pre-wrap rounded-[8px] border border-border bg-bg-subtle px-3 py-2.5 text-[13px] leading-6 text-text-muted",children:e.firstMessage})]}),(0,n.jsxs)("div",{className:"grid grid-cols-2 gap-3 text-[12px]",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-dim",children:i("workbenchHistoryDetail.started")}),(0,n.jsx)("div",{className:"text-text-muted",children:rf(e.startedAt,l)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-dim",children:i("workbenchHistoryDetail.lastUpdated")}),(0,n.jsx)("div",{className:"text-text-muted",children:rf(e.updatedAt,l)})]}),(0,n.jsxs)("div",{className:"col-span-2",children:[(0,n.jsx)("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-dim",children:i("workbenchHistoryDetail.workingDirectory")}),(0,n.jsx)("div",{className:"truncate font-mono text-[12px] text-text-muted",title:e.cwd,children:e.cwd})]}),(0,n.jsxs)("div",{className:"col-span-2",children:[(0,n.jsx)("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-text-dim",children:i("workbenchHistoryDetail.sessionFile")}),(0,n.jsx)("div",{className:"truncate font-mono text-[12px] text-text-muted",title:e.path,children:e.path})]})]})]}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 border-t border-border bg-bg-panel px-5 py-3",children:[(0,n.jsx)("button",{onClick:t,className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover hover:text-text",children:i("workbenchHistoryDetail.close")}),(0,n.jsx)("button",{onClick:()=>r(e),className:"h-8 rounded-[7px] border border-transparent bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-hover",children:i("workbenchHistoryDetail.openChat")})]})]})})}let rb=async()=>{let e=await l("/api/history",{cache:"no-store"}),t=await e.json();if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);if(t.error)throw Error(t.error);return t.history??[]};function rv({onStartChat:e,onOpenHistory:t,startingChat:r,startChatError:i,sessionRestoreNotice:l}){let{t:a,locale:d}=(0,s.s)(),[c,u]=(0,o.useState)(!1),[p,x]=(0,o.useState)(null),h=function(e,t,r={}){let n=(0,o.useRef)(null);n.current||(n.current=eC(e));let[i,s]=(0,o.useState)(n.current.state),l=(0,o.useCallback)((n=!1)=>!1===r.enabled?Promise.resolve(null):(function(e,t,r={}){let n=eC(e),o=r.staleMs??15e3,i=r.retries??0,s=Date.now();return"success"===n.state.status&&s-n.state.fetchedAt<o&&!r.force?Promise.resolve(n.state.data):(n.inflight||(n.state={...n.state,status:"loading",error:null},ew(n),n.inflight=eN(n,t,i)),n.inflight)})(e,t,{staleMs:r.staleMs,retries:r.retries,force:n}).catch(t=>("u">typeof console&&console.warn(`[useCachedResource:${e}]`,eS(t)),null)),[e,t,r.enabled,r.staleMs,r.retries]);(0,o.useEffect)(()=>{let e=n.current,t=e=>s(e);return e.listeners.add(t),s(e.state),("idle"===e.state.status||"error"===e.state.status)&&l(),()=>{e.listeners.delete(t)}},[e,l]);let a=(0,o.useCallback)(()=>l(!0),[l]);return{...i,refresh:a}}("workbench:history:recent",rb,{staleMs:15e3,retries:1}),g=(0,o.useMemo)(()=>h.data??[],[h.data]),f=(0,o.useMemo)(()=>c?g:g.slice(0,5),[g,c]),m=e=>{eT("workbench:history:recent"),t(e)};return(0,n.jsxs)("div",{className:"h-full overflow-y-auto",children:[(0,n.jsxs)("div",{className:"mx-auto flex w-full max-w-[1180px] flex-col gap-5 px-5 py-5",children:[(0,n.jsx)("div",{className:"border-b border-border pb-4",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:a("workbenchHome.enterpriseWorkbench")}),(0,n.jsx)("h1",{className:"m-0 mt-1 text-[24px] font-semibold leading-tight tracking-[0] text-text",children:a("workbenchHome.title")}),(0,n.jsx)("p",{className:"m-0 mt-2 max-w-[640px] text-[13px] leading-6 text-text-muted",children:a("workbenchHome.description")})]})}),l?(0,n.jsx)("p",{className:"m-0 max-w-[640px] text-[13px] text-amber-700 dark:text-amber-400",children:l}):null,i?(0,n.jsx)("p",{className:"m-0 max-w-[640px] text-[13px] text-red-600 dark:text-red-400",children:a("workbenchHome.startChatError",{error:i})}):null,(0,n.jsx)("button",{type:"button",onClick:e,disabled:r,className:"flex w-full max-w-[320px] items-center justify-center rounded-[8px] bg-accent px-4 py-3 text-[14px] font-semibold text-white hover:bg-accent-hover disabled:opacity-60",children:r?a("workbenchHome.startingChat"):a("workbenchHome.newChat")}),(0,n.jsxs)("section",{className:"mt-2",children:[(0,n.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-3",children:[(0,n.jsx)("h2",{className:"m-0 text-[14px] font-semibold text-text",children:a("workbenchHome.myWork")}),(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("span",{className:"text-[11px] text-text-dim",children:a("workbenchHome.recentWorkDescription")}),g.length>5?(0,n.jsx)("button",{type:"button",onClick:()=>u(e=>!e),className:"text-[11px] font-medium text-accent hover:underline",children:c?a("workbenchHome.showLessHistory"):a("workbenchHome.viewAllHistory")}):null]})]}),(0,n.jsxs)("div",{className:"overflow-hidden rounded-[8px] border border-border bg-bg-panel",children:["loading"===h.status&&0===g.length?(0,n.jsx)("div",{className:"p-4 text-[13px] text-text-muted",children:a("workbenchHistory.loadingHistory")}):null,"loading"!==h.status&&0===g.length?(0,n.jsx)("div",{className:"p-4 text-[13px] text-text-muted",children:h.error?a("workbenchHome.recentWorkError",{error:h.error}):a("workbenchHome.noRecentWork")}):null,f.map(e=>c?(0,n.jsxs)("div",{className:"group grid w-full grid-cols-[minmax(0,1fr)_150px_96px_auto] items-center gap-3 border-b border-border px-4 py-3 last:border-b-0 hover:bg-bg-hover max-[720px]:grid-cols-[minmax(0,1fr)_auto]",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>m(e),className:"min-w-0 text-left",children:[(0,n.jsx)("div",{className:"truncate text-[13px] font-semibold text-text",children:e.title}),(0,n.jsx)("div",{className:"mt-1 truncate text-[12px] text-text-muted",children:e.summary})]}),(0,n.jsx)("div",{className:"truncate text-[12px] text-text-muted max-[720px]:hidden",children:e.cwd}),(0,n.jsx)("div",{className:"text-[11px] text-text-dim max-[720px]:hidden",children:new Date(e.updatedAt).toLocaleString(d)}),(0,n.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),x(e)},className:"h-7 shrink-0 rounded-[6px] border border-border bg-bg-subtle px-2.5 text-[11px] font-medium text-text-muted opacity-0 transition-opacity hover:bg-bg-hover hover:text-text group-hover:opacity-100 focus-visible:opacity-100",title:a("workbenchHistory.showDetails"),"aria-label":a("workbenchHistory.showDetails"),children:a("workbenchHistory.details")})]},e.sessionId):(0,n.jsxs)("button",{type:"button",onClick:()=>m(e),className:"flex w-full items-center gap-3 border-b border-border px-4 py-3 text-left last:border-b-0 hover:bg-bg-hover",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"truncate text-[13px] font-medium text-text",children:e.title}),(0,n.jsx)("div",{className:"mt-1 truncate text-[12px] text-text-muted",children:e.summary})]}),(0,n.jsx)("div",{className:"shrink-0 text-[11px] text-text-dim",children:new Date(e.updatedAt).toLocaleDateString(d)})]},e.sessionId))]})]})]}),p?(0,n.jsx)(rm,{item:p,onClose:()=>x(null),onOpenChat:e=>{x(null),m(e)}}):null]})}function ry(e){return encodeURIComponent(e)}function rj(e){if(!e)return"terminal %";let t=e.split("/").filter(Boolean),r=t.at(-1)??e,n="Users"===t[0]&&t[1]?t[1]:"user";return`${n}@localhost ${r} %`}function rk({lines:e,prompt:t,children:r}){let i=(0,o.useRef)(null),[s,l]=(0,o.useState)(!0);return(0,o.useEffect)(()=>{let e=i.current;e&&s&&(e.scrollTop=e.scrollHeight)},[e,s,r]),(0,n.jsxs)("div",{ref:i,className:"terminal-output",onScroll:()=>{let e=i.current;l(e.scrollHeight-e.scrollTop-e.clientHeight<30)},children:[e.map((e,r)=>(0,n.jsx)(rw,{line:e,prompt:t},r)),r,!s&&(0,n.jsx)("button",{className:"jump-to-bottom",onClick:()=>{l(!0);let e=i.current;e&&(e.scrollTop=e.scrollHeight)},children:"↓ jump to bottom"})]})}function rw({line:e,prompt:t}){switch(e.kind){case"command":return(0,n.jsxs)("div",{className:"line-cmd terminal-command-line",children:[(0,n.jsx)("span",{className:"terminal-prompt",children:t}),(0,n.jsxs)("span",{className:"terminal-command-text",children:[" ",e.text]})]});case"output":return(0,n.jsx)("div",{className:`line-out line-${e.stream}`,children:e.text});case"exit":return null;case"error":return(0,n.jsxs)("div",{className:"line-err",children:["⚠ ",e.text]});case"info":return(0,n.jsxs)("div",{className:"line-info",children:["\xb7 ",e.text]});case"truncated":return(0,n.jsxs)("div",{className:"line-info",children:["… ",e.droppedBytes," bytes truncated …"]})}}let rS=(0,o.memo)(function({history:e,onSubmit:t,disabled:r,open:i=!0,prompt:s}){let[l,a]=(0,o.useState)(""),[d,c]=(0,o.useState)(-1),u=(0,o.useRef)(null),p=(0,o.useRef)({disabled:!0,open:!1});(0,o.useEffect)(()=>{let e=p.current;p.current={disabled:r,open:i},i&&!r&&(!e.open||e.disabled)&&requestAnimationFrame(()=>u.current?.focus())},[r,i]);let x=async()=>{let e=l.trim();if(e){a(""),c(-1);try{await t(e)}catch{}}};return(0,n.jsxs)("div",{className:"terminal-input-line",onMouseDown:()=>u.current?.focus(),children:[(0,n.jsx)("span",{className:"terminal-prompt",children:s}),(0,n.jsx)("span",{className:"terminal-input-spacer",children:" "}),(0,n.jsx)("input",{ref:u,className:"terminal-input-field",type:"text",value:l,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!r)if("Enter"!==t.key||t.shiftKey){if("ArrowUp"===t.key){if(t.preventDefault(),0===e.length)return;let r=-1===d?e.length-1:d-1;if(r<0)return;c(r),a(e[r])}else if("ArrowDown"===t.key){if(t.preventDefault(),-1===d)return;let r=d+1;r>=e.length?(c(-1),a("")):(c(r),a(e[r]))}}else t.preventDefault(),x()},disabled:r,"aria-label":"Terminal command",placeholder:r?"running…":"",spellCheck:!1,autoComplete:"off"})]})});function rC({cwd:e,open:t,height:r,onClose:i,onHeightChange:s}){var l;let a,d=function(e,t){let[r,n]=(0,o.useState)([]),[i,s]=(0,o.useState)([]),[l,a]=(0,o.useState)(null),[d,c]=(0,o.useState)(()=>rj(e)),[u,p]=(0,o.useState)(!1),[x,h]=(0,o.useState)(null),g=(0,o.useRef)(null),f=(0,o.useRef)(e);f.current=e,(0,o.useEffect)(()=>{if(!t||!e){g.current?.close(),g.current=null,n([]),s([]),a(null),c(rj(e)),p(!1),h(null);return}p(!0),h(null),fetch(`/api/terminal/state/${ry(e)}`).then(e=>{if(!e.ok)throw Error(`state ${e.status}`);return e.json()}).then(t=>{f.current===e&&(c(t.prompt??rj(e)),n(t.buffer),s(t.history),a(t.running))}).catch(t=>{f.current===e&&h(t.message)}).finally(()=>{f.current===e&&p(!1)});let r=new EventSource(`/api/terminal/stream/${ry(e)}`);return g.current=r,r.onmessage=t=>{let r;if(f.current===e){try{r=JSON.parse(t.data)}catch{return}"replay"===r.type?n(r.lines):"line"===r.type?n(e=>[...e,r.line]):"state"===r.type?a(r.running):"prompt"===r.type&&c(r.text)}},r.onerror=()=>{f.current===e&&h("stream disconnected (reconnecting…)")},()=>{r.close(),g.current=null}},[e,t]);let m=(0,o.useCallback)(async(t,r)=>{if(!e)return;let n=await fetch(`/api/terminal/run/${ry(e)}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({command:t,keepRunning:r})});if(!n.ok&&202!==n.status)throw Error((await n.json().catch(()=>({}))).error??`run ${n.status}`)},[e]);return{lines:r,history:i,running:l,prompt:d,isLoading:u,error:x,submit:m,stop:(0,o.useCallback)(async()=>{if(!e)return;let t=await fetch(`/api/terminal/stop/${ry(e)}`,{method:"POST"});if(!t.ok)throw Error((await t.json().catch(()=>({}))).error??`stop ${t.status}`)},[e]),clear:(0,o.useCallback)(async()=>{n([])},[])}}(e,t),[c,u]=(0,o.useState)(!1),[p,x]=(0,o.useState)(()=>Date.now()),[h,g]=(0,o.useState)(!1),f=(0,o.useRef)(0),m=(0,o.useRef)(r);(0,o.useEffect)(()=>{if(!d.running)return;let e=setInterval(()=>x(Date.now()),1e3);return()=>clearInterval(e)},[d.running]);let b=(0,o.useCallback)(e=>{u(!0),f.current=e.clientY,m.current=r,e.target.setPointerCapture(e.pointerId)},[r]),v=(0,o.useCallback)(e=>{if(!c)return;let t=f.current-e.clientY;s(Math.max(.24,Math.min(.8,(m.current*window.innerHeight+t)/window.innerHeight)))},[c,s]),y=(0,o.useCallback)(e=>{u(!1),e.target.releasePointerCapture(e.pointerId)},[]),j=d.running?Math.floor((p-d.running.startedAt)/1e3):null,k=d.submit,w=(0,o.useCallback)(e=>{g(!1),k(e,h)},[h,k]),S=(0,o.useCallback)(()=>{i()},[i]);return(0,n.jsxs)("div",{className:"terminal-panel","data-open":t?"true":"false",style:{display:t?"flex":"none",height:`${100*r}vh`},children:[(0,n.jsx)("div",{className:"terminal-resize-handle",onPointerDown:b,onPointerMove:v,onPointerUp:y,"aria-label":"Resize terminal"}),(0,n.jsxs)("div",{className:"terminal-status-bar",children:[(0,n.jsxs)("span",{className:"terminal-status-cwd",title:e,children:["Terminal \xb7 ",(a=(l=e).split("/").filter(Boolean)).length<=2?l:"…/"+a.slice(-2).join("/")]}),d.running&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("span",{className:"terminal-status-pid",children:["PID ",d.running.pid]}),(0,n.jsxs)("span",{className:"terminal-status-elapsed",children:["running ",function(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m${e%60}s`;let r=Math.floor(t/60);return`${r}h${t%60}m`}(j)]}),d.running.isKeepRunning&&(0,n.jsx)("button",{className:"terminal-status-stop",onClick:()=>{d.stop()},children:"Stop"})]}),d.error&&(0,n.jsx)("span",{className:"terminal-status-error",children:d.error}),(0,n.jsx)("span",{className:"terminal-status-spacer"}),(0,n.jsxs)("label",{className:"terminal-keep-running-toggle",title:"Run command as a long-running process that can be stopped",children:[(0,n.jsx)("input",{type:"checkbox",checked:h,onChange:e=>g(e.target.checked),disabled:!!d.running&&!d.running.isKeepRunning}),"keep"]}),(0,n.jsx)("button",{className:"terminal-status-close",onClick:S,"aria-label":"Close terminal",children:"Close"})]}),(0,n.jsx)(rk,{lines:d.lines,prompt:d.prompt,children:(0,n.jsx)(rS,{history:d.history,disabled:!!d.running&&!d.running.isKeepRunning,open:t,prompt:d.prompt,onSubmit:w})})]})}var rN=r(768);async function rT(){if(!("serviceWorker"in navigator))return null;try{return await navigator.serviceWorker.register("/sw.js")}catch{return null}}async function rI(e){let t=await rT();if(!t||"granted"!==await Notification.requestPermission())return null;let r=await t.pushManager.getSubscription();return r||t.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){let t="=".repeat((4-e.length%4)%4),r=(e+t).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(r),o=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)o[e]=n.charCodeAt(e);return o}(e).buffer})}async function rL(){if(!("serviceWorker"in navigator))return null;let e=await navigator.serviceWorker.getRegistration();return e?e.pushManager.getSubscription():null}async function rR(){let e=await rL();return!e||e.unsubscribe()}function rz(e){let t=e.toJSON(),r=t.keys?.p256dh,n=t.keys?.auth;if(!t.endpoint||!r||!n)throw Error("Invalid push subscription");return{endpoint:t.endpoint,keys:{p256dh:r,auth:n}}}function rM(){let{t:e}=(0,s.s)(),[t,r]=(0,o.useState)(null),[i,l]=(0,o.useState)(!1),[a,d]=(0,o.useState)(!1),[c,u]=(0,o.useState)(null),[p,x]=(0,o.useState)(!0),h=(0,o.useCallback)(async()=>{let e=await fetch("/api/push");e.ok&&(r((await e.json()).push??null),l(!!await rL()))},[]);(0,o.useEffect)(()=>{let e="serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;x(e),e&&(rT(),h())},[h]);let g=async()=>{d(!0),u(null);try{let e=await fetch("/api/push"),t=await e.json(),r=t.push?.publicKey;if(!r)throw Error("Push is not configured on the server");let n=await rI(r);if(!n)throw Error("Notification permission denied");let o=rz(n),i=await fetch("/api/push",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"subscribe",subscription:o})});if(!i.ok){let e=await i.json();throw Error(e.error??"Subscribe failed")}await h()}catch(e){u(e instanceof Error?e.message:String(e))}finally{d(!1)}},f=async()=>{d(!0),u(null);try{let e=await rL();if(e){let t=rz(e);await fetch("/api/push",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"unsubscribe",subscription:{endpoint:t.endpoint}})}),await rR()}await h()}catch(e){u(e instanceof Error?e.message:String(e))}finally{d(!1)}};return p?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("div",{className:"text-[12px] leading-5 text-text-muted",children:e("remoteAccess.pushDescription")}),c&&(0,n.jsx)("div",{className:"text-[12px] text-text-muted",children:c}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("button",{onClick:()=>void g(),disabled:a||i,className:"h-8 rounded-[7px] bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-hover disabled:opacity-50",children:e(a?"remoteAccess.pushEnabling":"remoteAccess.pushEnable")}),(0,n.jsx)("button",{onClick:()=>void f(),disabled:a||!i,className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover hover:text-text disabled:opacity-50",children:e("remoteAccess.pushDisable")})]}),t&&(0,n.jsx)("div",{className:"text-[11px] text-text-dim",children:e("remoteAccess.pushServerCount",{count:t.subscriptionCount})})]}):(0,n.jsx)("div",{className:"text-[12px] text-text-muted",children:e("remoteAccess.pushUnsupported")})}var rE=r(5772);function rW(){return(0,n.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,n.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,n.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}function rA({open:e,onClose:t,pairingUrl:r,qrDataUrl:o,loading:i,error:l,copyState:a,onCopy:d}){let{t:c}=(0,s.s)();return e?(0,n.jsx)("div",{className:"fixed inset-0 z-[600] flex items-center justify-center bg-[rgba(0,0,0,0.36)] px-4 py-8 backdrop-blur-[2px]",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,n.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":c("remoteAccess.pairingTitle"),className:"w-full max-w-[640px] overflow-hidden rounded-[12px] border border-border bg-bg-popover",style:{boxShadow:"var(--shadow-popover)"},children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3 border-b border-border px-5 py-4",children:[(0,n.jsx)("h2",{className:"m-0 text-[16px] font-semibold text-text",children:c("remoteAccess.pairingTitle")}),(0,n.jsx)("button",{type:"button",onClick:t,"aria-label":c("common.close"),className:"h-7 w-7 shrink-0 rounded-[6px] border border-border bg-bg-subtle text-[14px] leading-none text-text-muted hover:bg-bg-hover hover:text-text",children:"\xd7"})]}),(0,n.jsx)("div",{className:"px-5 py-5",children:i&&!o?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center gap-3 py-16 text-[13px] text-text-muted",children:[(0,n.jsx)("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-border border-t-accent"}),c("remoteAccess.generatingPairing")]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"m-0 text-center text-[13px] leading-5 text-text-muted",children:c("remoteAccess.pairingModalHint")}),l&&(0,n.jsx)("div",{className:"mt-4 rounded-[6px] border border-border bg-bg-subtle px-3 py-2 text-center text-[12px] text-text-muted",children:l}),(0,n.jsx)("div",{className:"mt-5 flex justify-center",children:(0,n.jsx)("div",{className:"flex h-[320px] w-[320px] items-center justify-center rounded-[12px] border border-border bg-white p-3",children:o?(0,n.jsx)(rE.default,{src:o,alt:c("remoteAccess.qrAlt"),width:280,height:280,unoptimized:!0,className:"h-full w-full object-contain"}):(0,n.jsx)("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-border border-t-accent"})})}),r&&(0,n.jsxs)("div",{className:"mt-5 flex gap-2",children:[(0,n.jsx)("input",{readOnly:!0,value:r,"aria-label":c("remoteAccess.copyPairingLink"),className:"min-w-0 flex-1 rounded-[8px] border border-border bg-bg-subtle px-3 py-2 font-mono text-[11px] text-text-muted outline-none"}),(0,n.jsxs)("button",{type:"button",onClick:d,className:"flex h-[34px] shrink-0 items-center gap-1.5 rounded-[8px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text hover:bg-bg-hover",children:[(0,n.jsx)(rW,{}),c("copied"===a?"common.copied":"failed"===a?"common.failed":"common.copy")]})]})]})})]})}):null}function rP(){return(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0 text-text-dim",children:(0,n.jsx)("path",{d:"m9 18 6-6-6-6"})})}function r$(){let{t:e}=(0,s.s)(),[t,r]=(0,o.useState)(null),[i,l]=(0,o.useState)([]),[a,d]=(0,o.useState)(!0),[c,u]=(0,o.useState)(null),[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(null),[f,m]=(0,o.useState)(null),[b,v]=(0,o.useState)(null),[y,j]=(0,o.useState)(""),[k,w]=(0,o.useState)(!1),[S,C]=(0,o.useState)("idle"),[N,T]=(0,o.useState)("idle"),[I,L]=(0,o.useState)(!1),[R,z]=(0,o.useState)([]),[M,E]=(0,o.useState)(null),[W,A]=(0,o.useState)(null),[P,$]=(0,o.useState)(0),O=window.location.port||"30141",H="npm run relay:client -- '<offer-url>'",D={tailscale:`tailscale funnel ${O}`,cloudflared:"npm run tunnel:cloudflare",cloudflaredDirect:`cloudflared tunnel --url http://127.0.0.1:${O}`},B=(0,o.useCallback)(async()=>{d(!0),x(null);try{let e=await fetch("/api/remote"),t=await e.json();if(!e.ok)throw Error(t.error??"Failed to load remote settings");r(t.status??null),l(t.sessions??[]),j((t.status?.allowedHostnames??[]).join("\n")),w(!!t.status?.readOnly)}catch(e){x(e instanceof Error?e.message:String(e))}finally{d(!1)}},[]);(0,o.useEffect)(()=>{B()},[B]);let F=(0,o.useCallback)(async()=>{E(null);try{let t=await fetch("/api/remote/audit?limit=50"),r=await t.json();if(!t.ok)throw Error(r.error??e("remoteAccess.auditLoadError"));z(r.events??[])}catch(e){E(e instanceof Error?e.message:String(e))}},[e]);(0,o.useEffect)(()=>{t?.enabled&&F()},[t?.enabled,F]);let U=async e=>{u(String(e.action??"request")),x(null);try{let t=await fetch("/api/remote",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(!t.ok)throw Error(n.error??"Remote action failed");return r(n.status??null),l(n.sessions??i),n.masterToken&&g(n.masterToken),n.offer&&(m(n.offer.pairingUrl),v(await rN.toDataURL(n.offer.pairingUrl,{margin:1,width:480}))),n.relayOfferUrl&&A(n.relayOfferUrl),F(),n}catch(e){return x(e instanceof Error?e.message:String(e)),null}finally{u(null)}},V=async()=>{let e=y.split(/\r?\n|,/).map(e=>e.trim()).filter(Boolean),t=await U({action:"enable",allowedHostnames:e,readOnly:k});t?.status?.enabled&&_()},_=()=>{L(!0),T("idle"),U({action:"create-pairing"})},K=async()=>{if(f)try{await navigator.clipboard.writeText(f),T("copied"),window.setTimeout(()=>T("idle"),1400)}catch{T("failed")}},q=async e=>{try{await navigator.clipboard.writeText(e),C("copied"),window.setTimeout(()=>C("idle"),1400)}catch{C("failed")}};return(0,n.jsxs)("section",{className:"mt-6",children:[(0,n.jsxs)("div",{className:"mb-2",children:[(0,n.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:e("remoteAccess.sectionLabel")}),(0,n.jsx)("h2",{className:"m-0 mt-1 text-[15px] font-semibold text-text",children:e("remoteAccess.title")}),(0,n.jsx)("p",{className:"mt-2 max-w-[720px] text-[12px] leading-5 text-text-muted",children:e("remoteAccess.description")})]}),(0,n.jsxs)("div",{className:"overflow-hidden rounded-[8px] border border-border bg-bg-panel",children:[a&&!t&&(0,n.jsx)("div",{className:"p-4 text-[13px] text-text-muted",children:e("remoteAccess.loading")}),p&&!I&&(0,n.jsx)("div",{className:"border-b border-border px-4 py-3 text-[13px] text-text-muted",children:p}),t&&!t.enabled&&(0,n.jsxs)("div",{className:"p-4",children:[(0,n.jsx)("div",{className:"text-[13px] text-text-muted",children:e("remoteAccess.disabled")}),0===P&&(0,n.jsxs)("div",{className:"mt-4 space-y-2",children:[(0,n.jsx)("div",{className:"text-[13px] font-medium text-text",children:e("remoteAccess.wizardPurposeTitle")}),(0,n.jsx)("p",{className:"m-0 text-[12px] leading-5 text-text-muted",children:e("remoteAccess.wizardPurposeBody")}),(0,n.jsx)("button",{type:"button",onClick:()=>$(1),className:"mt-3 h-8 rounded-[7px] bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-hover",children:e("remoteAccess.wizardNext")})]}),1===P&&(0,n.jsxs)("div",{className:"mt-4 space-y-2",children:[(0,n.jsx)("div",{className:"text-[13px] font-medium text-text",children:e("remoteAccess.wizardRiskTitle")}),(0,n.jsx)("p",{className:"m-0 text-[12px] leading-5 text-text-muted",children:e("remoteAccess.wizardRiskBody")}),(0,n.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:()=>$(0),className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover",children:e("common.back")}),(0,n.jsx)("button",{type:"button",onClick:()=>$(2),className:"h-8 rounded-[7px] bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-hover",children:e("remoteAccess.wizardNext")})]})]}),2===P&&(0,n.jsxs)("div",{className:"mt-4 space-y-3",children:[(0,n.jsxs)("label",{className:"flex items-center gap-2 text-[12px] text-text-muted",children:[(0,n.jsx)("input",{type:"checkbox",checked:k,onChange:e=>w(e.target.checked)}),e("remoteAccess.readOnly")]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:()=>$(1),className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover",children:e("common.back")}),(0,n.jsx)("button",{onClick:()=>void V(),disabled:null!==c,className:"h-8 rounded-[7px] bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-hover disabled:opacity-50",children:"enable"===c?e("remoteAccess.enabling"):e("remoteAccess.wizardEnable")})]})]})]}),t?.enabled&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"divide-y divide-border",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[(0,n.jsx)("div",{className:"text-[13px] font-medium text-text",children:e("remoteAccess.enabled")}),(0,n.jsx)("button",{onClick:()=>{g(null),m(null),v(null),L(!1),$(0),U({action:"disable"})},disabled:null!==c,className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover hover:text-text disabled:opacity-50",children:"disable"===c?e("remoteAccess.disabling"):e("remoteAccess.disable")})]}),(0,n.jsxs)("button",{type:"button",onClick:_,disabled:null!==c,className:"flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-bg-hover disabled:opacity-50",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"text-[13px] font-medium text-text",children:e("remoteAccess.pairingTitle")}),(0,n.jsx)("div",{className:"mt-0.5 text-[11px] leading-5 text-text-dim",children:e("remoteAccess.pairingRowHint")})]}),(0,n.jsx)(rP,{})]}),i.length>0&&(0,n.jsxs)("div",{className:"px-4 py-3",children:[(0,n.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-2",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.pairedDevices")}),(0,n.jsx)("button",{onClick:()=>{U({action:"revoke-all-sessions"})},disabled:null!==c,className:"text-[11px] text-text-muted hover:text-text",children:e("remoteAccess.revokeAll")})]}),(0,n.jsx)("div",{className:"divide-y divide-border rounded-[7px] border border-border",children:i.map(t=>(0,n.jsxs)("div",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"truncate text-[12px] text-text",children:t.label||t.userAgent}),(0,n.jsx)("div",{className:"text-[11px] text-text-dim",children:new Date(t.lastSeenAt).toLocaleString()})]}),(0,n.jsx)("button",{onClick:()=>{U({action:"revoke-session",sessionId:t.id})},disabled:null!==c,className:"h-7 shrink-0 rounded-[6px] border border-border px-2 text-[11px] text-text-muted hover:bg-bg-hover",children:e("remoteAccess.revoke")})]},t.id))})]})]}),(0,n.jsxs)("details",{className:"group border-t border-border",children:[(0,n.jsx)("summary",{className:"cursor-pointer list-none px-4 py-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover hover:text-text [&::-webkit-details-marker]:hidden",children:(0,n.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[e("remoteAccess.developerSection"),(0,n.jsx)("span",{className:"transition-transform group-open:rotate-90",children:(0,n.jsx)(rP,{})})]})}),(0,n.jsxs)("div",{className:"space-y-4 border-t border-border px-4 py-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"text-[12px] font-medium text-text",children:e("remoteAccess.allowedHostnames")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] text-text-dim",children:e("remoteAccess.allowedHostnamesHint")}),(0,n.jsx)("textarea",{value:y,onChange:e=>j(e.target.value),rows:3,placeholder:e("remoteAccess.allowedHostnamesPlaceholder"),className:"mt-2 w-full rounded-[7px] border border-border bg-bg-subtle px-3 py-2 font-mono text-[11px] text-text outline-none focus:border-accent"})]}),(0,n.jsxs)("label",{className:"flex items-center gap-2 text-[12px] text-text-muted",children:[(0,n.jsx)("input",{type:"checkbox",checked:k,onChange:e=>w(e.target.checked)}),e("remoteAccess.readOnly")]}),(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)("button",{onClick:()=>{U({action:"update-settings",allowedHostnames:y.split(/\r?\n|,/).map(e=>e.trim()).filter(Boolean),readOnly:k})},disabled:null!==c,className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover hover:text-text disabled:opacity-50",children:e("remoteAccess.saveSettings")}),(0,n.jsx)("button",{onClick:()=>{U({action:"rotate-token"})},disabled:null!==c,className:"h-8 rounded-[7px] border border-border bg-bg-elevated px-3 text-[12px] font-medium text-text-muted hover:bg-bg-hover hover:text-text disabled:opacity-50",children:"rotate-token"===c?e("remoteAccess.rotatingToken"):e("remoteAccess.rotateToken")})]}),h&&(0,n.jsxs)("div",{className:"rounded-[7px] border border-border bg-bg-subtle p-3",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.masterTokenTitle")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] leading-5 text-text-muted",children:e("remoteAccess.masterTokenHint")}),(0,n.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"break-all rounded-[6px] bg-bg-panel px-2 py-1 font-mono text-[11px] text-text",children:h}),(0,n.jsx)("button",{onClick:()=>q(h),className:"h-7 rounded-[6px] border border-border px-2 text-[11px] text-text-muted hover:bg-bg-hover",children:"copied"===S?e("common.copied"):"failed"===S?e("common.failed"):e("common.copy")})]})]}),(0,n.jsxs)("div",{className:"grid gap-4 lg:grid-cols-2",children:[(0,n.jsxs)("div",{className:"rounded-[7px] border border-border bg-bg-subtle p-4",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.tunnelTitle")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] leading-5 text-text-muted",children:e("remoteAccess.tunnelDescription")}),(0,n.jsx)("div",{className:"mt-3 space-y-3",children:[["remoteAccess.tunnelTailscale",D.tailscale],["remoteAccess.tunnelCloudflared",D.cloudflared]].map(([t,r])=>(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-[11px] font-medium text-text",children:e(t)}),(0,n.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"break-all rounded-[6px] bg-bg-panel px-2 py-1 font-mono text-[11px] text-text",children:r}),(0,n.jsx)("button",{onClick:()=>q(r),className:"h-7 rounded-[6px] border border-border px-2 text-[11px] text-text-muted hover:bg-bg-hover",children:e("common.copy")})]})]},t))})]}),(0,n.jsxs)("div",{className:"rounded-[7px] border border-border bg-bg-subtle p-4",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.pushTitle")}),(0,n.jsx)(rM,{})]})]}),(0,n.jsxs)("div",{className:"grid gap-4 lg:grid-cols-2",children:[(0,n.jsxs)("div",{className:"rounded-[7px] border border-border bg-bg-subtle p-4",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.relayE2eeTitle")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] leading-5 text-text-muted",children:e("remoteAccess.relayE2eeDescription")}),(0,n.jsx)("button",{onClick:()=>{U({action:"create-relay-offer"})},disabled:null!==c,className:"mt-3 h-8 rounded-[7px] bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-hover disabled:opacity-50",children:"create-relay-offer"===c?e("remoteAccess.relayGeneratingOffer"):e("remoteAccess.relayGenerateOffer")}),W&&(0,n.jsxs)("div",{className:"mt-3 rounded-[7px] border border-border bg-bg-panel p-3",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.relayOfferTitle")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] text-text-muted",children:e("remoteAccess.relayOfferHint")}),(0,n.jsx)("code",{className:"mt-2 block break-all rounded-[6px] bg-bg-subtle px-2 py-1 font-mono text-[11px] text-text",children:W}),(0,n.jsx)("button",{onClick:()=>q(W),className:"mt-2 h-7 rounded-[6px] border border-border px-2 text-[11px] text-text-muted hover:bg-bg-hover",children:e("common.copy")})]}),(0,n.jsx)("div",{className:"mt-3 space-y-3",children:[["remoteAccess.relayServerCmd","npm run relay:server"],["remoteAccess.relayHostCmd","npm run relay:host"],["remoteAccess.relayClientCmd",W?H.replace("<offer-url>",W):H]].map(([t,r])=>(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"text-[11px] font-medium text-text",children:e(t)}),(0,n.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[(0,n.jsx)("code",{className:"break-all rounded-[6px] bg-bg-panel px-2 py-1 font-mono text-[11px] text-text",children:r}),(0,n.jsx)("button",{onClick:()=>q(r),className:"h-7 rounded-[6px] border border-border px-2 text-[11px] text-text-muted hover:bg-bg-hover",children:e("common.copy")})]})]},t))})]}),(0,n.jsxs)("div",{className:"rounded-[7px] border border-border bg-bg-subtle p-4",children:[(0,n.jsx)("div",{className:"text-[12px] font-semibold text-text",children:e("remoteAccess.auditTitle")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] leading-5 text-text-muted",children:e("remoteAccess.auditDescription")}),M&&(0,n.jsx)("div",{className:"mt-2 text-[11px] text-text-muted",children:M}),(0,n.jsx)("div",{className:"mt-3 max-h-[280px] overflow-y-auto rounded-[7px] border border-border",children:0===R.length?(0,n.jsx)("div",{className:"px-3 py-4 text-[12px] text-text-muted",children:e("remoteAccess.auditEmpty")}):R.map(e=>(0,n.jsxs)("div",{className:"border-b border-border px-3 py-2 last:border-b-0",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-[11px]",children:[(0,n.jsx)("span",{className:"font-mono text-text-dim",children:new Date(e.ts).toLocaleString()}),(0,n.jsx)("span",{className:"rounded-[4px] bg-bg-panel px-1.5 py-0.5 font-mono text-[10px] text-text",children:e.type})]}),(e.reason||e.detail||e.path)&&(0,n.jsx)("div",{className:"mt-1 text-[11px] text-text-muted",children:[e.method,e.path,e.reason,e.detail].filter(Boolean).join(" \xb7 ")})]},`${e.ts}-${e.type}-${e.path??""}`))})]})]})]})]})]})]}),(0,n.jsx)(rA,{open:I,onClose:()=>{L(!1)},pairingUrl:f,qrDataUrl:b,loading:"create-pairing"===c,error:I?p:null,copyState:N,onCopy:()=>void K()})]})}function rO({days:e,labels:t}){if(0===e.length)return(0,n.jsx)("p",{className:"m-0 text-[12px] text-text-muted",children:t.empty});let r=Math.max(1,...e.flatMap(e=>[e.started,e.completed,e.active]));return(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap gap-4 text-[11px] text-text-muted",children:[(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"mr-1 inline-block h-2 w-2 rounded-sm bg-accent"}),t.started]}),(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"mr-1 inline-block h-2 w-2 rounded-sm bg-emerald-500/80"}),t.completed]}),(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"mr-1 inline-block h-2 w-2 rounded-sm bg-amber-500/80"}),t.active]})]}),(0,n.jsx)("div",{className:"flex items-end gap-2",style:{minHeight:120},children:e.map(e=>(0,n.jsxs)("div",{className:"flex min-w-0 flex-1 flex-col items-center gap-1",children:[(0,n.jsxs)("div",{className:"flex w-full items-end justify-center gap-0.5",style:{height:96},children:[(0,n.jsx)("div",{className:"w-2 rounded-t-sm bg-accent",style:{height:`${e.started/r*100}%`,minHeight:4*(e.started>0)},title:`${t.started}: ${e.started}`}),(0,n.jsx)("div",{className:"w-2 rounded-t-sm bg-emerald-500/80",style:{height:`${e.completed/r*100}%`,minHeight:4*(e.completed>0)},title:`${t.completed}: ${e.completed}`}),(0,n.jsx)("div",{className:"w-2 rounded-t-sm bg-amber-500/80",style:{height:`${e.active/r*100}%`,minHeight:4*(e.active>0)},title:`${t.active}: ${e.active}`})]}),(0,n.jsx)("span",{className:"text-[10px] text-text-dim",children:e.date.slice(5)})]},e.date))})]})}function rH(){let{t:e}=(0,s.s)(),[t,r]=(0,o.useState)(!0),[i,l]=(0,o.useState)(null),[a,d]=(0,o.useState)([]),[c,u]=(0,o.useState)([]),p=(0,o.useCallback)(async()=>{r(!0),l(null);try{let e=await fetch("/api/extensions",{cache:"no-store"}),t=await e.json();if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);d(t.extensions??[]),u(t.errors??[])}catch(e){l(e instanceof Error?e.message:String(e)),d([]),u([])}finally{r(!1)}},[]);return(0,o.useEffect)(()=>{p()},[p]),(0,n.jsxs)("section",{className:"mt-6",children:[(0,n.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-3",children:[(0,n.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:e("extensionsSettings.title")}),(0,n.jsx)("button",{type:"button",onClick:()=>void p(),className:"text-[12px] text-accent hover:underline",children:e("common.retry")})]}),(0,n.jsxs)("div",{className:"rounded-[8px] border border-border bg-bg-panel px-4 py-4",children:[(0,n.jsx)("p",{className:"m-0 text-[12px] leading-5 text-text-muted",children:e("extensionsSettings.description")}),t?(0,n.jsx)("p",{className:"mb-0 mt-3 text-[12px] text-text-muted",children:e("common.loading")}):i?(0,n.jsx)("p",{className:"mb-0 mt-3 text-[12px] text-red-600 dark:text-red-400",children:i}):0===a.length?(0,n.jsx)("p",{className:"mb-0 mt-3 text-[12px] text-text-muted",children:e("extensionsSettings.empty")}):(0,n.jsx)("ul",{className:"m-0 mt-3 list-none space-y-3 p-0",children:a.map(t=>(0,n.jsxs)("li",{className:"rounded-[6px] border border-border bg-bg-elevated px-3 py-3",children:[(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,n.jsx)("span",{className:"text-[13px] font-medium text-text",children:t.displayName}),(0,n.jsx)("span",{className:"rounded-[4px] bg-bg-hover px-1.5 py-0.5 text-[10px] uppercase text-text-dim",children:t.enabled?e("extensionsSettings.enabled"):e("extensionsSettings.disabled")}),(0,n.jsxs)("span",{className:"text-[10px] text-text-dim",children:[t.source,t.scope?` \xb7 ${t.scope}`:""]})]}),(0,n.jsx)("div",{className:"mt-1 font-mono text-[11px] text-text-muted break-all",children:t.path}),t.commands.length>0?(0,n.jsxs)("div",{className:"mt-2 text-[11px] text-text-muted",children:[e("extensionsSettings.commands"),": ",t.commands.map(e=>`/${e.name}`).join(", ")]}):null,t.loadError?(0,n.jsx)("div",{className:"mt-2 text-[11px] text-red-600 dark:text-red-400",children:t.loadError}):null]},t.resolvedPath))}),c.length>0?(0,n.jsx)("div",{className:"mt-3 text-[11px] text-red-600 dark:text-red-400",children:c.map(e=>(0,n.jsxs)("div",{children:[e.path,": ",e.error]},e.path))}):null,(0,n.jsxs)("p",{className:"mb-0 mt-4 text-[11px] leading-5 text-text-dim",children:[e("extensionsSettings.restartHint")," ",(0,n.jsx)("a",{href:"https://github.com/earendil-works/pi-mono/blob/main/packages/coding-agent/docs/extensions.md",target:"_blank",rel:"noreferrer",className:"text-accent hover:underline",children:e("extensionsSettings.docsLink")})]})]})]})}function rD(){let{t:e}=(0,s.s)(),t=(0,o.useRef)(null),[r,i]=(0,o.useState)(null),[l,a]=(0,o.useState)(null),[d,c]=(0,o.useState)(null),[u,p]=(0,o.useState)(null),[x,h]=(0,o.useState)(null),g=async()=>{i("export"),a(null),h(null);try{let t=await fetch("/api/scene-overrides/export");if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`Export failed (${t.status})`)}let r=await t.blob(),n=URL.createObjectURL(r),o=document.createElement("a");o.href=n,o.download="scenes.pi-scene-pack.json",o.click(),URL.revokeObjectURL(n),h(e("scenePack.exportSuccess"))}catch(e){a(e instanceof Error?e.message:String(e))}finally{i(null)}},f=async e=>{i("import"),a(null),h(null),c(null),p(null);try{let t=await e.text(),r=JSON.parse(t),n=await fetch("/api/scene-overrides/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pack:r,preview:!0})}),o=await n.json();if(!n.ok)throw Error(o.error??`Import preview failed (${n.status})`);c(o.changes??[]),p(r)}catch(e){a(e instanceof Error?e.message:String(e))}finally{i(null)}},m=async()=>{if(u){i("import"),a(null),h(null);try{let t=await fetch("/api/scene-overrides/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pack:u,apply:!0})}),r=await t.json();if(!t.ok)throw Error(r.error??`Import failed (${t.status})`);c(null),p(null),h(e("scenePack.importApplied",{count:r.applied??0}))}catch(e){a(e instanceof Error?e.message:String(e))}finally{i(null)}}};return(0,n.jsxs)("section",{className:"mt-6",children:[(0,n.jsx)("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:e("scenePack.title")}),(0,n.jsxs)("div",{className:"rounded-[8px] border border-border bg-bg-panel px-4 py-4",children:[(0,n.jsx)("p",{className:"m-0 text-[12px] leading-5 text-text-muted",children:e("scenePack.description")}),(0,n.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:()=>void g(),disabled:null!==r,className:"rounded-[6px] border border-border bg-bg-elevated px-3 py-2 text-[12px] font-medium text-text hover:bg-bg-hover disabled:opacity-50",children:"export"===r?e("scenePack.exporting"):e("scenePack.export")}),(0,n.jsx)("button",{type:"button",onClick:()=>t.current?.click(),disabled:null!==r,className:"rounded-[6px] border border-border bg-bg-elevated px-3 py-2 text-[12px] font-medium text-text hover:bg-bg-hover disabled:opacity-50",children:"import"===r?e("scenePack.importing"):e("scenePack.import")}),(0,n.jsx)("input",{ref:t,type:"file",accept:"application/json,.json,.pi-scene-pack.json",className:"hidden",onChange:e=>{let t=e.target.files?.[0];e.target.value="",t&&f(t)}})]}),d&&d.length>0?(0,n.jsxs)("div",{className:"mt-4 rounded-[6px] border border-border bg-bg-elevated p-3",children:[(0,n.jsx)("div",{className:"text-[12px] font-medium text-text",children:e("scenePack.previewTitle")}),(0,n.jsx)("ul",{className:"m-0 mt-2 list-none space-y-1 p-0 text-[11px] text-text-muted",children:d.map(t=>(0,n.jsxs)("li",{children:[t.sceneId,": ",e(`scenePack.action.${t.action}`)," (",t.fields.join(", "),")"]},t.sceneId))}),(0,n.jsxs)("div",{className:"mt-3 flex gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:()=>void m(),disabled:null!==r,className:"rounded-[6px] bg-accent px-3 py-1.5 text-[12px] font-medium text-white hover:bg-accent-hover disabled:opacity-50",children:e("scenePack.confirmImport")}),(0,n.jsx)("button",{type:"button",onClick:()=>{c(null),p(null)},className:"rounded-[6px] border border-border px-3 py-1.5 text-[12px] text-text-muted hover:bg-bg-hover",children:e("common.cancel")})]})]}):null,l?(0,n.jsx)("p",{className:"mb-0 mt-3 text-[12px] text-red-600 dark:text-red-400",children:l}):null,x?(0,n.jsx)("p",{className:"mb-0 mt-3 text-[12px] text-emerald-700 dark:text-emerald-400",children:x}):null]})]})}function rB({initialKeepAwakeAlways:e=!1}){let{t}=(0,s.s)(),[r,i]=(0,o.useState)(e),[l,a]=(0,o.useState)(!1),[d,c]=(0,o.useState)("none"),[u,p]=(0,o.useState)(!1),x=(0,o.useCallback)(async()=>{let e=window.piNative;if(!e?.getPowerState)return void p(!1);p(!0);try{let t=await e.getPowerState();t&&"string"==typeof t.mode&&c(t.mode)}catch{}},[]);(0,o.useEffect)(()=>{(async()=>{try{let e=await fetch("/api/preferences",{cache:"no-store"});if(!e.ok)return;let t=await e.json(),r=!!t.preferences?.keepAwakeAlways;i(r),window.piNative?.setKeepAwakeAlways?.(r)}catch{}finally{x()}})()},[x]);let h=(0,o.useCallback)(async e=>{i(e),a(!0);try{window.piNative?.setKeepAwakeAlways?.(e),await fetch("/api/preferences",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({keepAwakeAlways:e})})}catch{}finally{a(!1),x()}},[x]),g=t(u?"alwaysOn"===d?"workbenchSettings.powerStatusAlwaysOn":"autoTask"===d?"workbenchSettings.powerStatusAuto":"workbenchSettings.powerStatusReleased":"workbenchSettings.powerStatusBrowserOnly"),f="none"===d?"var(--text-muted)":"var(--accent)";return(0,n.jsxs)("section",{className:"mt-6",children:[(0,n.jsx)("div",{className:"mb-2",children:(0,n.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:t("workbenchSettings.powerTitle")})}),(0,n.jsxs)("div",{className:"rounded-[8px] border border-border bg-bg-panel px-4 py-4 text-[12px] leading-6 text-text-muted",children:[(0,n.jsx)("p",{className:"m-0",children:t("workbenchSettings.powerDescription")}),(0,n.jsxs)("label",{className:"mt-3 flex cursor-pointer items-start gap-3",style:{cursor:l?"wait":"pointer"},children:[(0,n.jsx)("input",{type:"checkbox",checked:r,disabled:l,onChange:e=>void h(e.target.checked),className:"mt-[2px] h-4 w-4 cursor-pointer"}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("div",{className:"text-[12px] font-medium text-text",children:t("workbenchSettings.powerAlwaysOnLabel")}),(0,n.jsx)("div",{className:"mt-1 text-[11px] text-text-muted",children:t("workbenchSettings.powerAlwaysOnHint")})]})]}),(0,n.jsxs)("div",{className:"mt-3 flex items-center gap-2 border-t pt-3",style:{borderColor:"var(--border)"},children:[(0,n.jsx)("span",{"aria-hidden":!0,style:{display:"inline-block",width:8,height:8,borderRadius:999,background:f,flexShrink:0}}),(0,n.jsxs)("span",{className:"text-[11px]",style:{color:"var(--text-muted)"},children:[t("workbenchSettings.powerStatusLabel")," ",(0,n.jsx)("span",{className:"font-mono",style:{color:f},children:g})]})]})]})]})}function rF({onOpenModels:e,onOpenSkills:t,skillsDisabled:r}){let{locale:i,setLocale:l,t:a}=(0,s.s)(),[d,c]=(0,o.useState)(null),[u,p]=(0,o.useState)(!0);return(0,o.useEffect)(()=>{p(!0),fetch("/api/usage?days=7").then(e=>e.json()).then(e=>{c(e.timeline?.days??[])}).catch(()=>c([])).finally(()=>p(!1))},[]),(0,n.jsx)("div",{className:"h-full overflow-y-auto",children:(0,n.jsxs)("div",{className:"mx-auto w-full max-w-[960px] px-5 py-5",children:[(0,n.jsxs)("div",{className:"mb-4 border-b border-border pb-4",children:[(0,n.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:a("workbenchSettings.platform")}),(0,n.jsx)("h1",{className:"m-0 mt-1 text-[22px] font-semibold tracking-[0] text-text",children:a("workbenchSettings.settings")})]}),(0,n.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[(0,n.jsxs)("div",{className:"rounded-[8px] border border-border bg-bg-panel p-4 text-left",children:[(0,n.jsx)("div",{className:"text-[14px] font-semibold text-text",children:a("workbenchSettings.language")}),(0,n.jsx)("div",{className:"mt-2 text-[12px] leading-5 text-text-muted",children:a("workbenchSettings.languageDescription")}),(0,n.jsx)("div",{className:"mt-3 inline-flex rounded-[8px] border border-border bg-bg-elevated p-1",children:[["en",a("workbenchSettings.english")],["zh-CN",a("workbenchSettings.simplifiedChinese")]].map(([e,t])=>(0,n.jsx)("button",{onClick:()=>l(e),className:`h-8 rounded-[6px] px-3 text-[12px] font-medium transition ${i===e?"bg-accent text-white":"text-text-muted hover:bg-bg-hover hover:text-text"}`,children:t},e))})]}),(0,n.jsxs)("button",{onClick:e,className:"rounded-[8px] border border-border bg-bg-panel p-4 text-left hover:bg-bg-hover",children:[(0,n.jsx)("div",{className:"text-[14px] font-semibold text-text",children:a("workbenchSettings.models")}),(0,n.jsx)("div",{className:"mt-2 text-[12px] leading-5 text-text-muted",children:a("workbenchSettings.modelsDescription")})]}),(0,n.jsxs)("button",{onClick:t,disabled:r,className:"rounded-[8px] border border-border bg-bg-panel p-4 text-left hover:bg-bg-hover disabled:cursor-not-allowed disabled:opacity-45",children:[(0,n.jsx)("div",{className:"text-[14px] font-semibold text-text",children:a("workbenchSettings.skills")}),(0,n.jsx)("div",{className:"mt-2 text-[12px] leading-5 text-text-muted",children:a("workbenchSettings.skillsDescription")})]})]}),(0,n.jsxs)("section",{className:"mt-6",children:[(0,n.jsx)("div",{className:"mb-2",children:(0,n.jsx)("div",{className:"text-[11px] font-semibold uppercase tracking-[0] text-text-dim",children:a("settings.activityTitle")})}),(0,n.jsxs)("div",{className:"rounded-[8px] border border-border bg-bg-panel px-4 py-4",children:[(0,n.jsx)("p",{className:"m-0 text-[12px] leading-5 text-text-muted",children:a("settings.activityDescription")}),(0,n.jsx)("div",{className:"mt-4",children:u?(0,n.jsx)("p",{className:"m-0 text-[12px] text-text-muted",children:a("settings.activityLoading")}):(0,n.jsx)(rO,{days:d??[],labels:{started:a("settings.activityStarted"),completed:a("settings.activityCompleted"),active:a("settings.activityActive"),empty:a("settings.activityEmpty")}})})]})]}),(0,n.jsx)(rH,{}),(0,n.jsx)(rD,{}),(0,n.jsx)(rB,{}),(0,n.jsx)(r$,{})]})})}function rU(){let e=(0,i.useSearchParams)(),t=(0,i.useRouter)(),{t:r}=(0,s.s)(),[l,a]=(0,o.useState)(null),[d,c]=(0,o.useState)(null);return((0,o.useEffect)(()=>{let n=e.get("pair");if(!n)return;let o=!1;return(async()=>{a(r("remoteAccess.pairingInProgress")),c(null);try{let e=await fetch("/api/remote/pair",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n})}),i=await e.json();if(!e.ok)throw Error(i.error??"Pairing failed");if(o)return;a(r("remoteAccess.pairingSuccess")),window.dispatchEvent(new CustomEvent("pi-web-pairing-success"));let s=new URL(window.location.href);s.searchParams.delete("pair"),t.replace(`${s.pathname}${s.search}${s.hash}`)}catch(e){if(o)return;c(e instanceof Error?e.message:String(e)),a(null)}})(),()=>{o=!0}},[t,e,r]),l||d)?(0,n.jsxs)("div",{className:"border-b border-border bg-bg-panel px-4 py-2 text-[12px]",children:[l&&(0,n.jsx)("span",{className:"text-text",children:l}),d&&(0,n.jsx)("span",{className:"text-text-muted",children:d})]}):null}function rV(){let{t:e}=(0,s.s)(),[t,r]=(0,o.useState)(null);return((0,o.useEffect)(()=>{fetch("/api/remote/client").then(e=>e.json()).then(r).catch(()=>r(null))},[]),t?.remoteEnabled&&t.authenticated&&t.readOnly&&!t.loopback)?(0,n.jsx)("div",{className:"border-b border-border bg-bg-panel px-4 py-2 text-center text-[12px] text-text-muted",children:e("remoteAccess.readOnlyBanner")}):null}function r_(){let{t:e}=(0,s.s)(),[t,r]=(0,o.useState)(null),i=(0,o.useCallback)(async()=>{r(await a())},[]);return((0,o.useEffect)(()=>{i();let e=()=>void i();window.addEventListener("focus",e);let t=window.setInterval(()=>void i(),15e3);return()=>{window.removeEventListener("focus",e),window.clearInterval(t)}},[i]),!1!==t)?null:(0,n.jsxs)("div",{className:"border-b border-[color-mix(in_srgb,#ef4444_40%,var(--border))] bg-[color-mix(in_srgb,#ef4444_8%,var(--bg-panel))] px-4 py-2 text-center text-[12px] text-text",children:[e("common.serverUnavailable")," ",(0,n.jsx)("button",{type:"button",onClick:()=>void i(),className:"underline hover:text-text-muted",children:e("common.retry")})]})}function rK(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function rq({sessionStats:e,contextUsage:t,paddingRight:r=48}){let{t:i,locale:l}=(0,s.s)(),[a,d]=(0,o.useState)(!1);if(!e&&!t)return null;let c=e?.tokens,u=e?.cost??0,p=u>0?`$${u.toFixed(4)}`:"—",x=null;if(t?.contextWindow){let e=t.percent,r=null!==e?`${e.toFixed(1)}%`:i("common.unknown");x=i("appShell.tooltipContext",{used:r,total:t.contextWindow.toLocaleString(l)})}let h=[];return c&&c.input>0&&h.push(`↑${rK(c.input)}`),c&&c.output>0&&h.push(`↓${rK(c.output)}`),u>0&&h.push(u>=.01?`$${u.toFixed(2)}`:"<$0.01"),(0,n.jsxs)("div",{style:{marginLeft:"auto",position:"relative",display:"flex",alignItems:"center",height:"100%",paddingRight:r,flexShrink:0,minWidth:0},onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children:[(0,n.jsxs)("button",{type:"button","aria-label":i("appShell.sessionReport"),style:{display:"flex",alignItems:"center",gap:6,height:28,padding:"0 10px",border:"none",borderRadius:6,background:a?"var(--bg-hover)":"transparent",color:a?"var(--text)":"var(--text-muted)",cursor:"default",fontSize:11,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap",flexShrink:0},children:[(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[(0,n.jsx)("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),(0,n.jsx)("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),(0,n.jsx)("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]}),h.length>0?(0,n.jsx)("span",{children:h.join(" \xb7 ")}):(0,n.jsx)("span",{children:i("appShell.sessionReport")})]}),a&&(0,n.jsxs)("div",{role:"tooltip",style:{position:"absolute",top:"100%",right:0,marginTop:4,zIndex:600,minWidth:220,padding:"10px 12px",borderRadius:8,border:"1px solid var(--border)",background:"var(--bg-popover)",boxShadow:"var(--shadow-popover)",fontSize:12,lineHeight:1.5,color:"var(--text)"},children:[(0,n.jsx)("div",{style:{fontWeight:600,marginBottom:8,color:"var(--text)"},children:i("appShell.sessionReport")}),c&&(0,n.jsxs)("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",gap:"4px 12px"},children:[(0,n.jsx)("dt",{style:{margin:0,color:"var(--text-dim)"},children:i("settings.inputTokens")}),(0,n.jsx)("dd",{style:{margin:0,textAlign:"right",fontVariantNumeric:"tabular-nums"},children:c.input.toLocaleString(l)}),(0,n.jsx)("dt",{style:{margin:0,color:"var(--text-dim)"},children:i("settings.outputTokens")}),(0,n.jsx)("dd",{style:{margin:0,textAlign:"right",fontVariantNumeric:"tabular-nums"},children:c.output.toLocaleString(l)}),c.cacheRead>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{style:{margin:0,color:"var(--text-dim)"},children:i("appShell.reportCacheRead")}),(0,n.jsx)("dd",{style:{margin:0,textAlign:"right",fontVariantNumeric:"tabular-nums"},children:c.cacheRead.toLocaleString(l)})]}),c.cacheWrite>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{style:{margin:0,color:"var(--text-dim)"},children:i("appShell.reportCacheWrite")}),(0,n.jsx)("dd",{style:{margin:0,textAlign:"right",fontVariantNumeric:"tabular-nums"},children:c.cacheWrite.toLocaleString(l)})]}),(0,n.jsx)("dt",{style:{margin:0,color:"var(--text-dim)"},children:i("settings.estimatedCost")}),(0,n.jsx)("dd",{style:{margin:0,textAlign:"right",fontVariantNumeric:"tabular-nums"},children:p})]}),x&&(0,n.jsx)("div",{style:{marginTop:8*!!c,paddingTop:8*!!c,borderTop:c?"1px solid var(--border)":void 0,color:"var(--text-muted)"},children:x}),!c&&!x&&(0,n.jsx)("div",{style:{color:"var(--text-muted)"},children:i("appShell.sessionReportEmpty")})]})]})}async function rJ(e){let t=await fetch(`/api/sessions/${encodeURIComponent(e)}`);return t.ok?(await t.json()).info??null:null}function rG(){let e=(0,i.useRouter)(),t=(0,i.useSearchParams)(),{isDark:r,toggleTheme:l}=(0,eO.D)(),{t:a}=(0,s.s)(),[d,c]=(0,o.useState)(null),u=(0,o.useRef)(d);u.current=d;let[p,x]=(0,o.useState)(null),[h,g]=(0,o.useState)(0),[f,m]=(0,o.useState)(0),[b,v]=(0,o.useState)(0),[y,j]=(0,o.useState)(!1),[k,w]=(0,o.useState)(0),[S,C]=(0,o.useState)(!1),[N,T]=(0,o.useState)(!0),[I,L]=(0,o.useState)(!1),[R,z]=(0,o.useState)(.4),M=(0,o.useMemo)(()=>d?.cwd??null,[d]),E=(0,o.useRef)(null),W=(0,o.useRef)(null),[A,P]=(0,o.useState)("home"),[$,O]=(0,o.useState)(null),[H,D]=(0,o.useState)("full"),[B,F]=(0,o.useState)(!1),[U,V]=(0,o.useState)(null),[_,K]=(0,o.useState)(null),[q,G]=(0,o.useState)([]),[Y,Z]=(0,o.useState)(null),X=(0,o.useRef)(null),[Q,ee]=(0,o.useState)(!1),et=(0,o.useCallback)((e,t,r)=>{G(e),Z(t),X.current=r},[]),er=(0,o.useCallback)(e=>{X.current?.(e)},[]),[en,eo]=(0,o.useState)(null),ei=(0,o.useRef)(null),es=(0,o.useCallback)(e=>{eo(e)},[]),[el,ea]=(0,o.useState)(null),ed=(0,o.useCallback)(e=>{ea(e)},[]),[ec,eu]=(0,o.useState)(null),ep=(0,o.useCallback)(e=>{eu(e)},[]),[ex,eh]=(0,o.useState)(null),[eg,ef]=(0,o.useState)(null),em=(0,o.useCallback)(e=>{eh(t=>t===e?null:e)},[]);(0,o.useEffect)(()=>{if(!ex||!W.current)return;let e=()=>{let e=W.current.getBoundingClientRect();ef({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);return t.observe(W.current),()=>t.disconnect()},[ex]),(0,o.useEffect)(()=>{let e=()=>{window.innerWidth<=640&&T(!1)};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,o.useEffect)(()=>{let e=()=>g(e=>e+1);return window.addEventListener("pi-web-pairing-success",e),()=>window.removeEventListener("pi-web-pairing-success",e)},[]);let[ev,ey]=(0,o.useState)([]),[ej,ek]=(0,o.useState)(null),[ew,eS]=(0,o.useState)(!1),eC=(0,o.useCallback)(e=>{E.current?.insertText("`"+e+"`")},[]),[eN]=(0,o.useState)(()=>t.get("session")),[eT,eI]=(0,o.useState)(null),[eL,eR]=(0,o.useState)(null),[ez,eM]=(0,o.useState)(()=>!t.get("session")),eW=(0,o.useRef)(!1);(0,o.useEffect)(()=>{fetch("/api/preferences").then(e=>e.json()).then(e=>{e.preferences&&eb(e.preferences),e.preferences?.defaultWorkspaceCwd&&(O(e.preferences.defaultWorkspaceCwd),eI(e.preferences.defaultWorkspaceCwd)),e.preferences?.toolMode&&D(e.preferences.toolMode)}).catch(()=>{})},[]);let eA=(0,o.useCallback)(async()=>{let e=eT??d?.cwd??p??$;if(e)return e;let t=await fetch("/api/default-cwd",{method:"POST"}),r=await t.json();if(!t.ok||!r.cwd)throw Error(r.error??"Unable to create default workspace");return eI(r.cwd),r.cwd},[eT,p,$,d?.cwd]),eP=(0,o.useCallback)(()=>{G([]),Z(null),eo(null),eh(null)},[]);(0,o.useEffect)(()=>{let e=eT??d?.cwd;e?fetch(`/api/git-branch?cwd=${encodeURIComponent(e)}`).then(e=>e.json()).then(e=>eR(e.branch)).catch(()=>eR(null)):eR(null)},[eT,d?.cwd]),(0,o.useEffect)(()=>{eL||rd(q)||eh(e=>"branches"===e?null:e)},[eL,q]);let e$=(0,o.useCallback)(t=>{if(eI(t),t&&!eW.current){if(c(e=>e&&e.cwd!==t?null:e),x(e=>e&&e!==t?null:e),u.current&&u.current.cwd===t)return void g(e=>e+1);P("home"),m(e=>e+1),g(e=>e+1),eP(),e.replace("/",{scroll:!1})}},[eP,e]),eH=(0,o.useCallback)((t,r=!1)=>{x(null),c(t),P("chat"),m(e=>e+1),eo(null),eM(!0),r&&(eW.current=!0,setTimeout(()=>{eW.current=!1},0)),r||e.replace(`?session=${encodeURIComponent(t.id)}`,{scroll:!1})},[e]),eD=(0,o.useCallback)((t,r)=>{c(null),x(r),P("chat"),m(e=>e+1),eP(),e.replace("/",{scroll:!1})},[eP,e]),eB=(0,o.useCallback)(async()=>{F(!0),V(null);try{let t=await eA();c(null),x(t),P("chat"),m(e=>e+1),eP(),e.replace("/",{scroll:!1})}catch(t){let e=t instanceof Error?t.message:String(t);V("Unable to create default workspace"===e?a("appShell.createDefaultWorkspaceError"):e)}finally{F(!1)}},[eA,a,eP,e]),eF=(0,o.useRef)(new Set),eU=(0,o.useCallback)(t=>{x(null),c(t),g(e=>e+1),e.replace(`?session=${encodeURIComponent(t.id)}`,{scroll:!1});let r=setTimeout(()=>{eF.current.delete(r),g(e=>e+1)},600);eF.current.add(r)},[e]);(0,o.useEffect)(()=>{let e=eF.current;return()=>{for(let t of e)clearTimeout(t);e.clear()}},[]);let eq=(0,o.useCallback)(()=>{g(e=>e+1),v(e=>e+1)},[]),eJ=(0,o.useCallback)((e,t)=>{g(e=>e+1),c(r=>r?.id===e?{...r,name:t}:r)},[]),eG=(0,o.useCallback)(async t=>{g(e=>e+1),m(e=>e+1),x(null),P("chat");let r=await rJ(t);r?c(r):c(e=>({...e??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:t})),e.replace(`?session=${encodeURIComponent(t)}`,{scroll:!1})},[e]),eY=(0,o.useCallback)(t=>{eM(!0),t||(e.replace("/",{scroll:!1}),K(a("appShell.sessionNotFound")))},[e,a]),eZ=(0,o.useCallback)(t=>{if(g(e=>e+1),d?.id===t){let t=d.cwd;c(null),x(t??null),P("chat"),m(e=>e+1),eP(),e.replace("/",{scroll:!1})}},[eP,d,e]),eX=(0,o.useCallback)(()=>{V(null),K(null),c(null),x(null),P("home"),m(e=>e+1),eP(),e.replace("/",{scroll:!1})},[eP,e]),eQ=(0,o.useCallback)(()=>{c(null),x(null),P("settings"),m(e=>e+1),eP(),e.replace("/",{scroll:!1})},[eP,e]),e0=(0,o.useCallback)(()=>{j(!0)},[]),e1=(0,o.useCallback)(t=>{x(null),c({id:t.sessionId,path:t.path,cwd:t.cwd,created:t.startedAt,modified:t.updatedAt,messageCount:t.messageCount,firstMessage:t.firstMessage,productTitle:t.title,productStatus:t.status,lastResultSummary:t.summary}),P("chat"),m(e=>e+1),eP(),e.replace(`?session=${encodeURIComponent(t.sessionId)}`,{scroll:!1})},[eP,e]),e2=(0,o.useCallback)((e,t)=>{"system"===eV(e,t)&&e_()&&eK(e);let r=`file:${e}`;ey(n=>n.find(e=>e.id===r)?n:[...n,{id:r,label:t,filePath:e}]),ek(r),eS(!0)},[]),e4=(0,o.useCallback)(e=>{ey(t=>{let r=t.filter(t=>t.id!==e);return 0===r.length&&eS(!1),r}),ek(t=>{if(t!==e)return t;let r=ev.filter(t=>t.id!==e);return r.length>0?r[r.length-1].id:null})},[ev]),e5=p??("chat"===A&&null===d&&eT?eT:null),e6=null!==d||null!==e5,e3=!!eN&&!ez,e8=ez&&!e6,e9=!eT&&!d?.cwd&&!p,e7=ev.find(e=>e.id===ej)??null,te="var(--bg-elevated)",tt=!!eL||rd(q),tr="home"===A&&!e6;(0,o.useEffect)(()=>{"accounts"===t.get("view")&&(c(null),x(null),P("settings"),m(e=>e+1),eP(),j(!0),e.replace("/?view=settings",{scroll:!1}))},[eP,e,t]);let tn=(0,n.jsx)(n.Fragment,{children:(0,n.jsx)(J,{selectedSessionId:d?.id??null,onSelectSession:eH,onNewSession:eD,onOpenSettings:eQ,isSettingsView:"settings"===A,initialSessionId:eN,onInitialRestoreDone:eY,refreshKey:h,onSessionDeleted:eZ,onSessionRenamed:eJ,pinnedSession:d,selectedCwd:d?.cwd??p??eT??null,onCwdChange:e$,onOpenFile:e2,explorerRefreshKey:b,onAtMention:eC})});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(rU,{}),(0,n.jsx)(rV,{}),(0,n.jsx)(r_,{}),(0,n.jsxs)("div",{style:{display:"flex",height:"100dvh",overflow:"hidden",background:"linear-gradient(180deg, var(--bg) 0%, color-mix(in srgb, var(--bg) 88%, var(--bg-elevated)) 100%)"},children:[(0,n.jsx)("div",{className:"sidebar-overlay-backdrop",onClick:()=>T(!1),style:{position:"fixed",inset:0,zIndex:199,background:"rgba(0,0,0,0.4)",opacity:+!!N,pointerEvents:N?"auto":"none",transition:"opacity 0.25s ease"}}),(0,n.jsx)("div",{className:`sidebar-container${N?" sidebar-open":" sidebar-closed"}`,style:{background:"var(--bg-panel)",borderRight:"1px solid var(--border)",backdropFilter:"var(--chrome-blur)",WebkitBackdropFilter:"var(--chrome-blur)",display:"flex",flexDirection:"column",flexShrink:0,zIndex:200},children:tn}),(0,n.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:[(0,n.jsxs)("div",{ref:W,style:{display:"flex",alignItems:"center",flexShrink:0,borderBottom:"1px solid var(--border-strong)",height:38,background:te},children:[(0,n.jsx)("button",{onClick:()=>T(e=>!e),title:N?a("appShell.hideSidebar"):a("appShell.showSidebar"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:38,height:38,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:N?(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,n.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,n.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,n.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,n.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,n.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),(0,n.jsx)("button",{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();l({x:t.left+t.width/2,y:t.top+t.height/2})},title:r?a("appShell.switchToLightMode"):a("appShell.switchToDarkMode"),"aria-label":r?a("appShell.switchToLightMode"):a("appShell.switchToDarkMode"),"aria-pressed":r,style:{display:"flex",alignItems:"center",justifyContent:"center",width:38,height:38,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:r?(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("circle",{cx:"12",cy:"12",r:"5"}),(0,n.jsx)("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),(0,n.jsx)("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),(0,n.jsx)("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),(0,n.jsx)("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),(0,n.jsx)("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),(0,n.jsx)("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),(0,n.jsx)("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),(0,n.jsx)("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]}):(0,n.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}),(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",height:"100%",borderRight:"1px solid var(--border)"},children:(0,n.jsx)("button",{type:"button",onClick:eX,style:{height:"100%",padding:"0 12px",border:"none",borderTop:tr?"2px solid var(--accent)":"2px solid transparent",background:tr?"var(--bg-popover)":te,color:tr?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500},children:a("appShell.home")})}),e6&&(0,n.jsxs)("div",{className:"chat-branch-tools",style:{display:"flex",alignItems:"stretch",height:"100%"},children:[tt?(0,n.jsx)(rh,{tree:q,activeLeafId:Y,onLeafChange:er,gitBranch:eL,branchNavigating:Q,inline:!0,containerRef:W,open:"branches"===ex,onToggle:()=>em("branches"),hasSession:!0}):null,(0,n.jsxs)("button",{ref:ei,onClick:()=>em("system"),style:{display:"flex",alignItems:"center",gap:6,height:"100%",boxSizing:"border-box",padding:"0 12px",background:"system"===ex?"var(--bg-popover)":te,border:"none",borderTop:"system"===ex?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:"system"===ex?"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="system"===ex?"var(--text)":"var(--text-muted)"},children:[(0,n.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:en?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,n.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,n.jsx)("polyline",{points:"14 2 14 8 20 8"}),(0,n.jsx)("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),(0,n.jsx)("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]}),(0,n.jsx)("span",{children:a("appShell.system")}),(0,n.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:"system"===ex?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,n.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]})]}),(0,n.jsx)("button",{onClick:()=>L(e=>!e),disabled:!M,title:M?I?"Close terminal":"Open terminal":"Open a session first",style:{display:"flex",alignItems:"center",justifyContent:"center",height:38,padding:"0 10px",flexShrink:0,marginLeft:"auto",background:"none",border:"none",borderLeft:"1px solid var(--border)",color:I?"var(--text)":"#000",cursor:M?"pointer":"not-allowed",font:"inherit",fontSize:13,fontWeight:700,opacity:M?1:.4,transition:"color 0.12s, opacity 0.12s"},onMouseEnter:e=>{M&&(e.currentTarget.style.color="#000")},onMouseLeave:e=>{e.currentTarget.style.color=I?"var(--text)":"#000"},children:">_"}),e6&&(0,n.jsx)(rq,{sessionStats:el,contextUsage:ec,paddingRight:ew?12:48}),ex&&eg&&(0,n.jsx)("div",{style:{position:"fixed",top:eg.top,left:eg.left,width:eg.width,zIndex:500},children:"system"===ex&&(0,n.jsx)("div",{style:{background:"var(--bg-popover)",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)",boxShadow:"var(--shadow-popover)"},children:en?(0,n.jsx)("div",{style:{maxHeight:"min(600px, 75vh)",overflowY:"auto",padding:"12px 16px",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",fontFamily:"var(--font-mono)"},children:en}):""===en?(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:a("appShell.systemPromptEmpty")}):(0,n.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:a("appShell.systemPromptLoadHint")})})})]}),(0,n.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative"},children:e6?(0,n.jsx)(eE,{session:d,newSessionCwd:e5,onAgentEnd:eq,onSessionCreated:eU,onSessionForked:eG,modelsRefreshKey:k,chatInputRef:E,onBranchDataChange:et,onBranchNavigatingChange:ee,onSystemPromptChange:es,onSessionStatsChange:ed,onContextUsageChange:ep,toolMode:H,onOpenModels:e0,onOpenSettings:eQ,onOpenFile:e2},f):e8?"settings"===A?(0,n.jsx)(rF,{onOpenModels:e0,onOpenSkills:()=>C(!0),skillsDisabled:e9}):(0,n.jsx)(rv,{onStartChat:()=>{eB()},onOpenHistory:e1,startingChat:B,startChatError:U,sessionRestoreNotice:_}):e3?(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:a("appShell.restoringSession")}):null}),M&&(0,n.jsx)(rC,{cwd:M,open:I,height:R,onClose:()=>L(!1),onHeightChange:z},M)]}),(0,n.jsxs)("div",{className:`right-panel-container${ew?" right-panel-open":" right-panel-closed"}`,style:{display:"flex",flexDirection:"column",borderLeft:"1px solid var(--border)",background:"var(--bg-elevated)"},children:[(0,n.jsx)("div",{style:{display:"flex",alignItems:"center",flexShrink:0,background:te,borderBottom:"1px solid var(--border-strong)",height:38},children:(0,n.jsx)("div",{style:{flex:1,overflow:"hidden"},children:(0,n.jsx)(tl,{tabs:ev,activeTabId:ej??"",onSelectTab:ek,onCloseTab:e4})})}),(0,n.jsx)("div",{style:{flex:1,overflow:"hidden"},children:e7?.filePath?(0,n.jsx)(ti,{filePath:e7.filePath,displayLabel:e7.label,cwd:eT??void 0,sessionId:d?.id}):(0,n.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:12},children:a("appShell.noFileOpen")})})]})]}),(0,n.jsx)("button",{onClick:()=>eS(e=>!e),title:ew?a("appShell.hideFilePanel"):a("appShell.showFilePanel"),style:{position:"fixed",top:0,right:0,zIndex:300,display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:te,border:"none",borderLeft:"1px solid var(--border-strong)",borderBottom:"1px solid var(--border-strong)",color:ew?"var(--text)":"var(--text-muted)",cursor:"pointer",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=ew?"var(--text)":"var(--text-muted)"},children:(0,n.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,n.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,n.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})}),y&&(0,n.jsx)(rt,{onClose:()=>{j(!1),w(e=>e+1)},onModelsChanged:()=>w(e=>e+1)}),S&&(eT??d?.cwd??p)&&(0,n.jsx)(rl,{cwd:eT??d?.cwd??p,onClose:()=>C(!1)})]})}},55808:(e,t,r)=>{Promise.resolve().then(r.bind(r,3e3))}},e=>{e.O(0,[5803,1326,4605,2241,2261,8441,3794,7358],()=>e(e.s=55808)),_N_E=e.O()}]);
|