@henlii/pidance 0.2.40 → 0.2.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +12 -12
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.json +1 -1
  6. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/server/app/_global-error.html +1 -1
  8. package/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/server/app/_not-found.html +1 -1
  14. package/.next/server/app/_not-found.rsc +1 -1
  15. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  16. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  17. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  18. package/.next/server/app/api/about/route.js +1 -1
  19. package/.next/server/app/index.html +1 -1
  20. package/.next/server/app/index.rsc +3 -3
  21. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  22. package/.next/server/app/index.segments/_full.segment.rsc +3 -3
  23. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  24. package/.next/server/app/page.js +2 -2
  25. package/.next/server/app/page_client-reference-manifest.js +1 -1
  26. package/.next/server/app-paths-manifest.json +12 -12
  27. package/.next/server/chunks/5274.js +1 -1
  28. package/.next/server/middleware-build-manifest.js +1 -1
  29. package/.next/server/pages/404.html +1 -1
  30. package/.next/server/pages/500.html +1 -1
  31. package/.next/server/server-reference-manifest.json +1 -1
  32. package/.next/static/chunks/app/page-24032ecb0162638f.js +24 -0
  33. package/README.en.md +1 -1
  34. package/README.md +1 -1
  35. package/package.json +1 -1
  36. package/.next/static/chunks/app/page-03ce7a25f33f4d70.js +0 -24
  37. /package/.next/static/{qrH41YQOkbPr0RvEZs8IZ → OLUuuQTRgyV-qLJoY9ONN}/_buildManifest.js +0 -0
  38. /package/.next/static/{qrH41YQOkbPr0RvEZs8IZ → OLUuuQTRgyV-qLJoY9ONN}/_ssgManifest.js +0 -0
@@ -1,24 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{15427:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>p_});var r=n(95155),i=n(12115),o=n(73321);let l=null;var s=n(47650);function a(e,t){if(!t)return e;let n=e.replaceAll("\\","/"),r=t.replaceAll("\\","/").replace(/\/$/,"");return n===r?"~":n.startsWith(`${r}/`)?`~${n.slice(r.length)}`:e}function d(e){let t=e.replaceAll("\\","/").replace(/\/+$/,""),n=t.lastIndexOf("/");return(n>=0?t.slice(n+1):t)||e}let c={status:"idle",error:null,cwd:null,projectRoot:null};function u(e){return null===e.cwd?{...e,cwd:null,projectRoot:null}:{...e,projectRoot:e.cwd}}function p(e,t){return e.status===t.status&&e.error===t.error&&e.cwd===t.cwd&&e.projectRoot===t.projectRoot}function h(e){let t=e.filter(e=>!e.subagent),n=new Map;for(let e of t)n.set(e.id,{session:e,relation:null,children:[]});let r=new Map,i=e=>{let t=new Set([e]),n=r.get(e)?.parentId;for(;n;){if(t.has(n))return!0;t.add(n),n=r.get(n)?.parentId}return!1},o=[];for(let e of n.values()){let t=r.get(e.session.id),l=t?n.get(t.parentId):void 0;if(!t||!l||i(e.session.id)){o.push(e);continue}e.relation=t.relation,l.children.push(e)}let l=(e,t)=>t.session.modified.localeCompare(e.session.modified),s=(e,t)=>{if(t)e.sort(l);else{let t=e.filter(e=>"subagent"===e.relation).sort((e,t)=>(e.session.subagent?.runIndex??0)-(t.session.subagent?.runIndex??0)),n=e.filter(e=>"subagent"!==e.relation).sort(l);e.splice(0,e.length,...t,...n)}for(let t of e)s(t.children,!1)};return s(o,!0),o}function f(e,t){if(!t)return e;let n=[];for(let r of e){let e=f(r.children,t);((function(e,t){let n;return!t||(n=[e.name??"",e.firstMessage,e.id],e.subagent&&(n.push(e.subagent.agent??"",e.subagent.runId),n.push(`run ${e.subagent.runIndex}`,`run-${e.subagent.runIndex}`,String(e.subagent.runIndex))),n.join("\n").toLowerCase()).includes(t)})(r.session,t)||e.length>0)&&n.push({...r,children:e})}return n}function g(e,t){let n=(e,r)=>{for(let i of e){if(i.session.id===t)return r;let e=n(i.children,[...r,i.session.id]);if(e)return e}return null};return n(e,[])??[]}function m(e){return e?e instanceof Set?e:new Set(e):new Set}let x=new Set(["projectRoots","pinnedSessionIds","ungroupedSessionIds","collapsedProjectRoots"]),v="__ungrouped__",y=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function b(e,t){if(t?.[e.root])return t[e.root];let n=e.root.replaceAll("\\","/").replace(/\/+$/,""),r=n.lastIndexOf("/");return(r>=0?n.slice(r+1):n)||e.root}function w(e,t){if(0===t.size)return[];let n=[];for(let r of e){let e=w(r.children,t);(t.has(r.session.id)||e.length>0)&&n.push({...r,children:e})}return n}let k=1600/1920;function j(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(1600,Math.max(1e3,Math.round(e))):1600}function S(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?k:Math.min(1,Math.max(.2,e))}function C(e){let t=S(e.ratio),n=e.availableWidth;return!Number.isFinite(n)||n<=0?1600:j(n*t)}let _="--pidance-chat-column-width",I=`min(var(${_}, 1100px), 100%)`,R="min(320px, 45vh)",T="min(240px, 32vh)",E={padding:"0 10px 8px",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",overflowWrap:"anywhere"};function M(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(520,Math.max(240,Math.round(e))):300}function A(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(720,Math.max(320,Math.round(e))):400}function L(e){return"number"==typeof e&&Number.isFinite(e)?Math.min(960,Math.max(320,Math.round(e))):560}function z(e){if(null===e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){let e=n.trim();if(!e||null===r||"object"!=typeof r||Array.isArray(r))continue;let i=Array.isArray(r.expanded)?r.expanded.filter(e=>"string"==typeof e):[],o="number"==typeof r.scrollTop&&Number.isFinite(r.scrollTop)&&r.scrollTop>0?Math.round(r.scrollTop):0;t[e]={expanded:i,scrollTop:o}}return t}let W={displayMode:"standard",collapsedProjectRoots:[],projectAliases:{},projectRoots:[],projectRootsMigrated:!1,sidebarWidth:300,rightPanelOpen:!1,rightPanelWidth:400,changesPanelOpen:!0,changesPanelWidth:560,chatColumnWidthRatio:k,showRecentSessions:!0,pinnedSessionIds:[],ungroupedSessionIds:[],fileExplorerState:{},projectSort:"recent",projectOrder:[]},$="pidance:sidebar-preferences";function P(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function F(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e){if("string"!=typeof r)continue;let e=r.trim();!e||t.has(e)||(t.add(e),n.push(e))}return n.length>1e3?n.slice(-1e3):n}function H(e){return null===e||"object"!=typeof e?{...W,projectAliases:{},collapsedProjectRoots:[]}:{displayMode:"compact"===e.displayMode||"standard"===e.displayMode?e.displayMode:W.displayMode,collapsedProjectRoots:P(e.collapsedProjectRoots),projectAliases:function(e){if(null===e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){if("string"!=typeof r)continue;let e=n.trim(),i=r.trim();e&&i&&(t[e]=i)}return t}(e.projectAliases),...function(e){if(void 0!==e.projectRoots)return{projectRoots:N(P(e.projectRoots)),projectRootsMigrated:!1};let t=D({added:e.addedProjectRoots,closed:e.closedProjectRoots,hasProjectRoots:!1});return t?{projectRoots:t.projectRoots,projectRootsMigrated:!0}:{projectRoots:[],projectRootsMigrated:!1}}(e),sidebarWidth:M(e.sidebarWidth),rightPanelOpen:!0===e.rightPanelOpen,rightPanelWidth:A(e.rightPanelWidth),changesPanelOpen:!1!==e.changesPanelOpen,chatColumnWidthRatio:S(e.chatColumnWidthRatio),changesPanelWidth:L(e.changesPanelWidth),showRecentSessions:!1!==e.showRecentSessions,pinnedSessionIds:P(e.pinnedSessionIds),ungroupedSessionIds:F(e.ungroupedSessionIds),fileExplorerState:z(e.fileExplorerState),projectSort:B(e.projectSort),projectOrder:P(e.projectOrder)}}function D(e){if(e.hasProjectRoots||void 0===e.added&&void 0===e.closed)return null;let t=new Set(P(e.closed));return{projectRoots:N(P(e.added).filter(e=>!t.has(e)))}}function N(e){let t=[],n=new Set;for(let r of e){let e=r.trim();!e||n.has(e)||(n.add(e),t.push(e))}return t}function B(e){return"az"===e||"za"===e||"fixed"===e||"recent"===e?e:W.projectSort}function O(e){return JSON.stringify({displayMode:e.displayMode,collapsedProjectRoots:e.collapsedProjectRoots,projectAliases:e.projectAliases,projectRoots:e.projectRoots,sidebarWidth:M(e.sidebarWidth),rightPanelOpen:!0===e.rightPanelOpen,rightPanelWidth:A(e.rightPanelWidth),changesPanelOpen:!1!==e.changesPanelOpen,changesPanelWidth:L(e.changesPanelWidth),chatColumnWidthRatio:S(e.chatColumnWidthRatio),showRecentSessions:!1!==e.showRecentSessions,pinnedSessionIds:P(e.pinnedSessionIds),ungroupedSessionIds:F(e.ungroupedSessionIds),fileExplorerState:z(e.fileExplorerState),projectSort:B(e.projectSort),projectOrder:P(e.projectOrder)})}function U(e){try{let t=e.getItem($);if(null===t)return H(null);try{return H(JSON.parse(t))}catch{return H(null)}}catch{return H(null)}}function q(){return U(window.localStorage)}function K(e){try{window.localStorage.setItem($,O(e))}catch{}}function J(e){return{displayMode:e.displayMode,collapsedProjectRoots:e.collapsedProjectRoots,projectRoots:e.projectRoots,showRecentSessions:e.showRecentSessions,pinnedSessionIds:e.pinnedSessionIds,projectSort:e.projectSort,projectOrder:e.projectOrder,ungroupedSessionIds:e.ungroupedSessionIds}}function V(e){var t,n=window.localStorage;try{let r=U(n);n.setItem($,O({...r,rightPanelOpen:void 0===e.open?r.rightPanelOpen:(t=e.open,!0===t),rightPanelWidth:void 0===e.width?r.rightPanelWidth:A(e.width)}))}catch{}}function Y(e){var t,n=window.localStorage;try{let r=U(n);n.setItem($,O({...r,changesPanelOpen:void 0===e.open?r.changesPanelOpen:(t=e.open,!1!==t),changesPanelWidth:void 0===e.width?r.changesPanelWidth:L(e.width)}))}catch{}}function X(e,t){var n=window.localStorage;try{let r=U(n),i=z(r.fileExplorerState);e.trim()&&(i[e]={expanded:z({[e]:t})[e]?.expanded??[],scrollTop:Math.max(0,Math.round(Number.isFinite(t.scrollTop)?t.scrollTop:0))}),n.setItem($,O({...r,fileExplorerState:i}))}catch{}}let G="pidance.streamingEnterDefault",Z="followUp";function Q(e){return"steer"===e?"steer":"followUp"}function ee(){var e=window.localStorage;try{let t=e.getItem(G);if(null===t)return Z;try{return Q(JSON.parse(t))}catch{return Q(t)}}catch{return Z}}function et(e){var t=window.localStorage;try{t.setItem(G,JSON.stringify(Q(e)))}catch{}}let en="pidance.autoUpdateCheck";function er(e){return!1!==e&&0!==e&&"0"!==e&&"false"!==e}function ei(){var e=window.localStorage;try{let t=e.getItem(en);if(null===t)return!0;try{return er(JSON.parse(t))}catch{return er(t)}}catch{return!0}}function eo(e){var t=window.localStorage;try{t.setItem(en,JSON.stringify(er(e)))}catch{}}let el="pidance.editorTakeover",es="pidance:editor-takeover-changed";function ea(e){return!1!==e&&0!==e&&"0"!==e&&"false"!==e}function ed(){var e=window.localStorage;try{let t=e.getItem(el);if(null===t)return!0;try{return ea(JSON.parse(t))}catch{return ea(t)}}catch{return!0}}var ec=n(72634);let eu="pidance.sessionList.v1";function ep(){try{let e=window.localStorage.getItem(eu);if(!e)return null;let t=JSON.parse(e);if(!Array.isArray(t.sessions))return null;return t.sessions}catch{return null}}function eh(e){try{let t=[...e].sort((e,t)=>e.modified<t.modified?1:e.modified>t.modified?-1:0).slice(0,50);window.localStorage.setItem(eu,JSON.stringify({sessions:t}))}catch{}}let ef=["openAtLogin","minimizeToTray","notificationsEnabled"];function eg(e){let t=e&&"object"==typeof e&&!Array.isArray(e)?e:{},n={openAtLogin:!1,minimizeToTray:!1,notificationsEnabled:!1};for(let e of ef)!0===t[e]&&(n[e]=!0);return n}function em(){let[e]=(0,i.useState)(()=>(function(e=globalThis){if(!e||"object"!=typeof e)return null;let t=e.pidanceDesktop;return t&&"object"==typeof t?"function"!=typeof t.getSettings||"function"!=typeof t.setSetting||"function"!=typeof t.notify||"function"!=typeof t.onOpenSettings?null:t:null})());return e}let ex=new Set(["running","queued","paused"]),ev={...{runningChildIds:new Set,bySessionId:new Map},stale:!1,updatedAt:null},ey=ev,eb=new Set,ew=null,ek=!1;function ej(e){for(let t of(ey=e,eb))t()}async function eS(){if(!ek){ek=!0;try{let e=await fetch("/api/subagent-runs?limit=50");if(!e.ok)return void ej({...ey,stale:!0});let t=await e.json();ej({...function(e){let t=new Set,n=new Map;for(let r of e??[]){if(!r||"object"!=typeof r)continue;let e=ex.has(r.state);for(let i of r.steps??[]){let o=i?.sessionId;o&&(e&&t.add(o),n.has(o)||n.set(o,{runId:r.id,mode:r.mode,active:e,step:i}))}}return{runningChildIds:t,bySessionId:n}}(t.runs),stale:!1,updatedAt:Date.now()})}catch{ej({...ey,stale:!0})}finally{ek=!1}}}function eC(){document.hidden||eS()}function e_(e){return eb.add(e),1===eb.size&&(eS(),ew=setInterval(()=>{document.hidden||eS()},3e4),document.addEventListener("visibilitychange",eC)),()=>{eb.delete(e),0===eb.size&&(ew&&clearInterval(ew),ew=null,document.removeEventListener("visibilitychange",eC))}}function eI(){return ey}function eR(){return ev}function eT(){return(0,i.useSyncExternalStore)(e_,eI,eR)}function eE(){return{scheduled:!1,inFlight:!1,rerun:!1}}function eM(e){let t=e.coalesceMs??200,n=e.setTimer??((e,t)=>setTimeout(e,t)),r=e.clearTimer??(e=>clearTimeout(e)),i=eE(),o=null,l=!1,s=t=>{l||(null!==o&&r(o),o=n(()=>{let t;if(o=null,!l){i={...i,scheduled:!1,inFlight:!0};try{t=e.perform()}catch{t=Promise.resolve()}Promise.resolve(t).catch(()=>void 0).then(()=>{var e;let t,n=(t=(e=i).rerun,{state:{...e,inFlight:!1,rerun:!1},rerun:t});i=n.state,n.rerun&&!l&&s(0)})}},t))};return{notify(){var e;if(l)return;let n=(e=i).inFlight?{state:{...e,rerun:!0},note:"deferred"}:e.scheduled?{state:e,note:"coalesced"}:{state:{...e,scheduled:!0},note:"schedule"};i=n.state,"schedule"===n.note&&s(t)},snapshot:()=>i,dispose(){l=!0,null!==o&&r(o),o=null,i=eE()}}}var eA=n(69892);function eL(e,t){let n=e[t];return"number"!=typeof n||!Number.isFinite(n)||n<5?5:Math.floor(n)}function ez(e,t){let n=eL(e,t);return{...e,[t]:n+5}}function eW(e,t){if(!(t in e))return e;let n={...e};return delete n[t],n}function e$(e,t,n){if(n)return e;let r=Math.max(0,Math.floor(t));return r>=e.length?e:e.slice(0,r)}function eP(e,t){let n=t.modified.localeCompare(e.modified);if(0!==n)return n;let r=t.created.localeCompare(e.created);return 0!==r?r:e.id.localeCompare(t.id)}function eF(e,t){return e===t&&e>0}function eH(e,t,n){let r=Math.max(0,Math.floor(t));return"fewer"===n?Math.min(5,r):Math.min((Number.isFinite(e)?Math.max(0,Math.floor(e)):5)+5,r)}let eD=(0,i.createContext)(null);function eN({children:e,initial:t}){let n=(0,i.useRef)(null);return n.current||(n.current=function(e={}){let t=u({...c,...e.identity}),n=new Set,r=t,i=()=>n.forEach(e=>e());return{getIdentitySnapshot:()=>r,subscribeIdentity:e=>(n.add(e),()=>n.delete(e)),setIdentity:e=>{let n=void 0!==e.cwd?{...e,projectRoot:e.cwd}:e,o=u({...t,...n});p(t,o)||(r=t=o,i())},reset:()=>{let e=!p(t,c);r=t=c,e&&i()}}}(t)),(0,r.jsx)(eD.Provider,{value:n.current,children:e})}function eB(){let e=(0,i.useContext)(eD);if(!e)throw Error("useProjectIdentity/useProjectActions 必须在 ProjectProvider 内使用");return e}function eO(){let e=eB();return(0,i.useSyncExternalStore)(e.subscribeIdentity,e.getIdentitySnapshot,e.getIdentitySnapshot)}var eU=n(99780),eq=n(61995);function eK(e,t){let n=new Date(e),r=new Date().getTime()-n.getTime(),i=Math.floor(r/6e4),o=Math.floor(r/36e5),l=Math.floor(r/864e5);return i<1?t("sidebar_justNow"):i<60?t("sidebar_minutesAgo",{count:i}):o<24?t("sidebar_hoursAgo",{count:o}):l<7?t("sidebar_daysAgo",{count:l}):n.toLocaleDateString()}function eJ({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function eV({open:e,children:t,style:n}){let[o,l]=(0,i.useState)(e),[s,a]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(l(!0),a(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>a(!0))})):(a(!1),n=setTimeout(()=>l(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),o)?(0,r.jsx)("div",{style:{...n,opacity:+!!s,transform:s?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let eY="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function eX(){let[e,t]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),l=(0,i.useRef)(null),s=function(e,t){let[n,r]=(0,i.useState)(e),o=(0,i.useRef)(null),l=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);l.current=0;let n=4*e.length,i=()=>{l.current+=1;let t=Math.floor(l.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:eY[Math.floor(Math.random()*eY.length)]).join("")),l.current<n?o.current=requestAnimationFrame(i):r(e)};return o.current=requestAnimationFrame(i),()=>{o.current&&cancelAnimationFrame(o.current)}},[e,t]),n}(e?"0.2.40pexternal":"Pidance",n),a=(0,i.useCallback)(e=>{t(e),o(!0),setTimeout(()=>o(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{l.current&&clearTimeout(l.current);let t=!e;a(t),t&&(l.current=setTimeout(()=>a(!1),3e3))},[e,a]);return(0,i.useEffect)(()=>()=>{l.current&&clearTimeout(l.current)},[]),(0,r.jsx)("button",{onClick:d,style:{background:"none",border:"none",padding:0,cursor:"default",fontWeight:700,fontSize:15,letterSpacing:"-0.01em",color:e?"var(--accent)":"var(--text)",fontFamily:"var(--font-mono)",minWidth:"6ch"},children:s})}function eG({label:e,onClick:t,disabled:n=!1,active:i=!1,danger:o=!1,done:l=!1,hoverReveal:s=!1,expanded:a,pressed:d,haspopup:c,buttonRef:u,children:p}){let h=["sidebar-icon-btn"];return i&&h.push("sidebar-icon-btn--active"),o&&h.push("sidebar-icon-btn--danger"),l&&h.push("sidebar-icon-btn--done"),s&&h.push("sidebar-icon-btn--hover"),(0,r.jsx)("button",{type:"button",ref:u,onClick:t,disabled:n,"data-tooltip":e,"aria-label":e,"aria-expanded":a,"aria-pressed":d,"aria-haspopup":c,className:h.join(" "),children:p})}function eZ(e){return{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.75,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0}}let eQ=({size:e=18})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),(0,r.jsx)("path",{d:"M12 10v6"}),(0,r.jsx)("path",{d:"M9 13h6"})]}),e0=({size:e=14})=>(0,r.jsx)("svg",{...eZ(e),children:(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}),e1=({size:e=14})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),e2=({size:e=13})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z"})]}),e4=({size:e=18})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),(0,r.jsx)("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]}),e6=({size:e=18})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}),(0,r.jsx)("path",{d:"M12 7v6"}),(0,r.jsx)("path",{d:"M9 10h6"})]}),e5=({size:e=18})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("path",{d:"m21 21-4.3-4.3"})]}),e8=({size:e=18})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("line",{x1:"21",x2:"14",y1:"4",y2:"4"}),(0,r.jsx)("line",{x1:"10",x2:"3",y1:"4",y2:"4"}),(0,r.jsx)("line",{x1:"21",x2:"12",y1:"12",y2:"12"}),(0,r.jsx)("line",{x1:"8",x2:"3",y1:"12",y2:"12"}),(0,r.jsx)("line",{x1:"21",x2:"16",y1:"20",y2:"20"}),(0,r.jsx)("line",{x1:"12",x2:"3",y1:"20",y2:"20"}),(0,r.jsx)("line",{x1:"14",x2:"14",y1:"2",y2:"6"}),(0,r.jsx)("line",{x1:"8",x2:"8",y1:"10",y2:"14"}),(0,r.jsx)("line",{x1:"16",x2:"16",y1:"18",y2:"22"})]}),e3=({size:e=14})=>(0,r.jsx)("svg",{...eZ(e),children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),e9=({size:e=14})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}),e7=({size:e=13})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),te=({size:e=13})=>(0,r.jsx)("svg",{...eZ(e),children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),tt=({size:e=10})=>(0,r.jsxs)("svg",{...eZ(e),children:[(0,r.jsx)("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),(0,r.jsx)("polyline",{points:"2 17 12 22 22 17"}),(0,r.jsx)("polyline",{points:"2 12 12 17 22 12"})]}),tn=({size:e=14})=>(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"5",r:"1.7"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1.7"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"1.7"})]});function tr({collapsed:e,label:t,left:n,onClick:i}){return(0,r.jsx)("button",{type:"button",onClick:e=>{i(e),e.currentTarget.blur()},"data-tooltip":t,"aria-label":t,className:"sidebar-indent-indicator",style:{display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",left:n,top:"50%",width:16,height:20,padding:0,flexShrink:0,zIndex:1,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",transform:`translateY(-50%)${e?" rotate(-90deg)":""}`,transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})})}function ti({primary:e=!1,danger:t=!1,disabled:n=!1,onClick:i,children:o}){let l=e||t;return(0,r.jsx)("button",{type:"button",onClick:i,disabled:n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,height:30,padding:"0 14px",flexShrink:0,background:t?"var(--status-danger)":e?"var(--accent)":"var(--bg)",border:l?"none":"1px solid var(--border)",borderRadius:7,color:l?"#fff":"var(--text-muted)",cursor:n?"not-allowed":"pointer",fontSize:12,fontWeight:l?600:500,opacity:n?.55:1,whiteSpace:"nowrap"},children:o})}function to({label:e,checked:t,onClick:n}){return(0,r.jsxs)("button",{type:"button",onClick:n,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"7px 10px",background:"var(--bg-elevated)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11.5},children:[t?(0,r.jsx)("span",{style:{color:"var(--accent)",display:"flex",flexShrink:0},children:(0,r.jsx)(e3,{size:11})}):(0,r.jsx)("span",{style:{width:11,flexShrink:0}}),e]})}function tl({icon:e,label:t,onClick:n}){return(0,r.jsxs)("button",{type:"button",role:"menuitem",onClick:n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:"var(--bg-elevated)",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12,whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-elevated)",e.currentTarget.style.color="var(--text-muted)"},onFocus:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onBlur:e=>{e.currentTarget.style.background="var(--bg-elevated)",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("span",{style:{display:"flex",flexShrink:0,color:"var(--text-dim)"},"aria-hidden":"true",children:e}),t]})}function ts({groupKey:e,total:t,visibleCount:n,searchActive:i,onShowMore:o,onShowFewer:l}){let{t:s}=(0,eU.s9)(),a=!i&&t>Math.max(0,Math.floor(n)),d=!i&&Math.floor(n)>5;return a||d?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"2px 8px 5px 28px"},children:[a&&(0,r.jsxs)("button",{type:"button",className:"sidebar-pagination-btn",onClick:()=>o(e),children:[s("sidebar_showMore"),(0,r.jsxs)("span",{"aria-hidden":"true",children:["+",5]})]}),d&&(0,r.jsx)("button",{type:"button",className:"sidebar-pagination-btn",onClick:()=>l(e),children:s("sidebar_showFewer")})]}):null}function ta({size:e=14}){let{t}=(0,eU.s9)();return(0,r.jsx)("span",{title:t("sidebar_running"),"aria-label":t("sidebar_running"),style:{width:e,height:e,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--status-running)"},children:(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"block",width:e-4,height:e-4,borderRadius:"50%",border:"2px solid currentColor",borderTopColor:"transparent",background:"transparent",boxSizing:"border-box",animation:"sidebar-running-spin 1s linear infinite"}})})}function td({size:e=14}){let{t}=(0,eU.s9)();return(0,r.jsx)("span",{title:t("sidebar_waiting"),"aria-label":t("sidebar_waiting"),style:{width:e,height:e,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--status-waiting)"},children:(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"block",width:6,height:6,borderRadius:"50%",background:"currentColor"}})})}function tc({startedAt:e,now:t,running:n}){let{t:i}=(0,eU.s9)();return n?(0,r.jsx)("span",{title:i("sidebar_running"),style:{display:"inline-flex",alignItems:"center",flexShrink:0,color:"var(--status-running)",fontSize:10,fontVariantNumeric:"tabular-nums",whiteSpace:"nowrap"},children:(0,r.jsx)("span",{children:void 0!==e?function(e,t){let n,r,{hours:i,minutes:o,seconds:l}=(r=Math.floor((n=Math.max(0,Math.floor(e/1e3)))/3600),{hours:r,minutes:Math.floor(n%3600/60),seconds:n%60});return i>0?t("sidebar_runningHoursMinutes",{h:i,m:o}):o>0?t("sidebar_runningMinutesSeconds",{m:o,s:l}):t("sidebar_runningSeconds",{s:l})}(Math.max(0,t-e),i):i("sidebar_running")})}):null}function tu({size:e=14}){let{t}=(0,eU.s9)();return(0,r.jsx)("span",{title:t("sidebar_activity"),"aria-label":t("sidebar_activity"),style:{width:e,height:e,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--status-unread)"},children:(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"block",width:6,height:6,borderRadius:"50%",background:"currentColor"}})})}let tp=(0,i.createContext)({startedAt:new Map,now:Date.now()}),th=(0,i.createContext)(new Set),tf=0,tg=null,tm=[];function tx(e){return tm.length>0&&tm[tm.length-1]===e}let tv=i.useLayoutEffect;function ty(){let e={top:0,left:0,width:Number.isFinite(window.innerWidth)?Math.max(0,window.innerWidth):0,height:Number.isFinite(window.innerHeight)?Math.max(0,window.innerHeight):0},t=window.visualViewport;if(!t)return e;let n=Number.isFinite(t.width)?Math.max(0,t.width):0,r=Number.isFinite(t.height)?Math.max(0,t.height):0;return n<=0||r<=0?e:{top:Number.isFinite(t.offsetTop)?Math.max(0,t.offsetTop):0,left:Number.isFinite(t.offsetLeft)?Math.max(0,t.offsetLeft):0,width:n,height:r}}function tb(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0)}function tw({open:e,onClose:t,title:n,description:o,children:l,actions:a,width:d=560,height:c,zIndex:u=1e3,closeOnBackdrop:p=!0,closeOnEsc:h=!0,initialFocusRef:f,headerActions:g,contentPadding:m="14px 18px",closeLabel:x="Close"}){let v=(0,i.useRef)(null),y=(0,i.useId)(),b=(0,i.useId)(),w=(0,i.useRef)(null);null===w.current&&(w.current=Symbol("ViewportDialog")),(0,i.useEffect)(()=>{if(e){var t;let e;return t=w.current,tm.push(t),e=!1,()=>{if(e)return;e=!0;let n=tm.lastIndexOf(t);n>=0&&tm.splice(n,1)}}},[e]),(0,i.useEffect)(()=>{var t,n;if(!e)return;let r=document.activeElement,i=v.current,o=(t=f?.current,n=i?tb(i):[],t??n[0]??i);return o?.focus({preventScroll:!0}),()=>{var e,t;let n=(e=r instanceof HTMLElement?r:null,t=e=>document.contains(e),null!==e&&t(e)?e:null);n?.focus({preventScroll:!0})}},[e,f]),(0,i.useEffect)(()=>{if(e){var t;let e;return t=document.body,0===tf&&(tg=t.style.overflow,t.style.overflow="hidden"),tf+=1,e=!1,()=>{e||(e=!0,0==(tf-=1)&&(t.style.overflow=tg??"",tg=null))}}},[e]),(0,i.useEffect)(()=>{if(!e)return;let n=w.current,r=e=>{let r=function(e){if(!e.isTop)return{stopPropagation:!1,preventDefault:!1,close:!1};let t="Escape"===e.key&&e.closeOnEsc&&!e.defaultPrevented;return{stopPropagation:!0,preventDefault:t,close:t}}({key:e.key,defaultPrevented:e.defaultPrevented,closeOnEsc:h,isTop:tx(n)});r.stopPropagation&&(e.stopPropagation(),r.preventDefault&&e.preventDefault(),r.close&&t())};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,h,t]),(0,i.useEffect)(()=>{if(!e)return;let t=w.current,n=e=>{if(!tx(t))return;let n=v.current;!n||!(e.target instanceof Node)||n.contains(e.target)||(tb(n)[0]??n).focus({preventScroll:!0})};return document.addEventListener("focusin",n),()=>document.removeEventListener("focusin",n)},[e]);let[k,j]=(0,i.useState)(null),S=(0,i.useRef)(0),C=(0,i.useCallback)(()=>{let e=ty();j(t=>t&&t.top===e.top&&t.left===e.left&&t.width===e.width&&t.height===e.height?t:e)},[]);if(tv(()=>{if(!e)return void j(null);C();let t=()=>{S.current||(S.current=requestAnimationFrame(()=>{S.current=0,C()}))};window.addEventListener("resize",t);let n=window.visualViewport;return n?.addEventListener("resize",t),n?.addEventListener("scroll",t),()=>{window.removeEventListener("resize",t),n?.removeEventListener("resize",t),n?.removeEventListener("scroll",t),S.current&&(cancelAnimationFrame(S.current),S.current=0)}},[e,C]),!e||"u"<typeof document)return null;let _="number"==typeof d?`${d}px`:d,I=k??ty(),R=function(e,t=16){return{maxWidth:Math.max(0,e.width-2*t),maxHeight:Math.max(0,e.height-2*t)}}(I),T="number"==typeof d?Math.min(d,R.maxWidth):`min(${_}, ${R.maxWidth}px)`,E=void 0===c?void 0:"number"==typeof c?Math.min(c,R.maxHeight):`min(${c}, ${R.maxHeight}px)`;return(0,s.createPortal)((0,r.jsx)("div",{onMouseDown:e=>{p&&e.target===e.currentTarget&&t()},style:{position:"fixed",top:I.top,left:I.left,width:I.width,height:I.height,zIndex:u,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,overscrollBehavior:"contain"},children:(0,r.jsxs)("div",{ref:v,role:"dialog","aria-modal":"true","data-pidance-modal":"true","aria-labelledby":y,"aria-describedby":o?b:void 0,tabIndex:-1,onKeyDown:e=>{if("Tab"!==e.key)return;let t=v.current;if(!t)return;let n=function(e){let{focusable:t,active:n,shiftKey:r,panel:i,contains:o}=e;if(0===t.length)return{handled:!0,target:i};let l=t[0],s=t[t.length-1],a=null!==n&&o(n);if(r){if(n===l||!a)return{handled:!0,target:s}}else if(n===s||!a)return{handled:!0,target:l};return{handled:!1}}({focusable:tb(t),active:document.activeElement,shiftKey:e.shiftKey,panel:t,contains:e=>t.contains(e)});n.handled&&(e.preventDefault(),n.target.focus({preventScroll:!0}))},style:{width:"100%",maxWidth:T,maxHeight:R.maxHeight,...void 0!==E?{height:E,minHeight:0}:{},display:"flex",flexDirection:"column",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden",outline:"none"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{id:y,style:{fontSize:15,fontWeight:700,color:"var(--text)",minWidth:0,flex:1},children:n}),g,(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":x,style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",minWidth:32,minHeight:32,padding:"2px 6px",background:"none",border:"none",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color="var(--text-muted)"},children:"\xd7"})]}),o&&(0,r.jsx)("div",{id:b,style:{padding:"10px 18px",borderBottom:"1px solid var(--border)",fontSize:13,lineHeight:1.55,color:"var(--text-muted)",flexShrink:0},children:o}),l&&(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:m},children:l}),a&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:a})]})}),document.body)}let tk={readOnly:!1,canPrompt:!0,canFork:!0,canCompact:!0,canChangeModel:!0,canChangeThinking:!0,canChangeTools:!0,canRename:!0,canAutoName:!0,canDelete:!0,canConnectEvents:!0,canSendSessionCommands:!0},tj={readOnly:!0,canPrompt:!1,canFork:!1,canCompact:!1,canChangeModel:!1,canChangeThinking:!1,canChangeTools:!1,canRename:!1,canAutoName:!1,canDelete:!1,canConnectEvents:!1,canSendSessionCommands:!1};function tS(e){return e?.readOnly===!0?tj:tk}function tC(e){let t=()=>{try{let t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.top="-1000px",t.style.opacity="0",document.body.appendChild(t),t.select(),t.setSelectionRange(0,t.value.length);let n=document.execCommand("copy");return document.body.removeChild(t),n?Promise.resolve():Promise.reject(Error('document.execCommand("copy") returned false'))}catch(e){return Promise.reject(e instanceof Error?e:Error("clipboard unavailable"))}},n="u"<typeof navigator?void 0:navigator.clipboard;if(!n?.writeText)return t();try{return n.writeText(e).catch(t)}catch(e){return t().catch(()=>Promise.reject(e))}}function t_(e){return`/api/sessions/${encodeURIComponent(e)}/export`}function tI(e,t,n=2){return!!e&&!!t&&(Math.abs(e.top-t.top)>=n||Math.abs(e.right-t.right)>=n)}function tR({open:e,onOpenChange:t,projectName:n,onEdit:o,onClose:l}){let{t:a}=(0,eU.s9)(),d=(0,i.useRef)(null),c=(0,i.useRef)(null),u=(0,i.useRef)(null),[p,h]=(0,i.useState)(null),f=(0,i.useRef)(null),g=(0,i.useCallback)(e=>{t(!1),e&&c.current?.focus()},[t]),m=(0,i.useCallback)(()=>{if(e)return void g(!0);let n=c.current?.getBoundingClientRect();n&&(f.current={top:n.top,bottom:n.bottom,right:n.right},h({top:n.bottom+4,right:Math.max(8,window.innerWidth-n.right)})),t(!0)},[e,g,t]);return(0,i.useEffect)(()=>{if(!e||!f.current)return;let t=requestAnimationFrame(()=>{let e=u.current,t=f.current;if(!e||!t)return;let n=e.offsetHeight;t.bottom+4+n<=window.innerHeight||h(e=>e?{...e,top:Math.max(8,t.top-n-4)}:e)});return()=>cancelAnimationFrame(t)},[e]),(0,i.useEffect)(()=>{if(!e)return;let n=e=>{!d.current||d.current.contains(e.target)||u.current?.contains(e.target)||t(!1)},r=()=>{let e=c.current?.getBoundingClientRect();tI(f.current,e?{top:e.top,right:e.right}:null)&&t(!1)};return document.addEventListener("mousedown",n),window.addEventListener("scroll",r,!0),window.addEventListener("resize",r),()=>{document.removeEventListener("mousedown",n),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r)}},[e,t]),(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>{u.current?.querySelector("[role='menuitem']")?.focus()});return()=>cancelAnimationFrame(t)},[e]),(0,r.jsxs)("div",{ref:d,style:{position:"relative",flexShrink:0,display:"flex"},onClick:e=>e.stopPropagation(),onKeyDown:t=>{"Escape"===t.key&&e&&(t.stopPropagation(),t.preventDefault(),g(!0))},children:[(0,r.jsx)(eG,{label:a("sidebar_projectMenuLabel",{project:n}),active:e,expanded:e,haspopup:"menu",hoverReveal:!0,buttonRef:c,onClick:e=>{e.stopPropagation(),m()},children:(0,r.jsx)(tn,{size:14})}),e&&(0,s.createPortal)((0,r.jsx)(eV,{open:e,style:{position:"fixed",top:p?.top??0,right:p?.right??0,zIndex:600,background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-float)",overflow:"hidden",minWidth:148},children:(0,r.jsxs)("div",{ref:u,role:"menu","aria-label":a("sidebar_projectMenuLabel",{project:n}),children:[(0,r.jsx)(tl,{icon:(0,r.jsx)(te,{size:13}),label:a("sidebar_editProject"),onClick:()=>{g(!0),o()}}),(0,r.jsx)(tl,{icon:(0,r.jsx)(e9,{size:13}),label:a("sidebar_closeProject"),onClick:()=>{g(!0),l()}})]})}),document.body)]})}function tT({session:e,title:t,canRename:n,canDelete:o,canArchive:l,archiveDisabledReason:a,isPinned:d,onTogglePin:c,onRename:u,onDelete:p,onArchive:h}){var f;let g,{t:m}=(0,eU.s9)(),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(null),j=(0,i.useRef)(null),S=m("sidebar_sessionMenuLabel",{session:t}),C=(0,i.useCallback)((e=!1)=>{v(!1),e&&k.current?.focus()},[]);(0,i.useEffect)(()=>{if(!x||!w.current)return;let e=requestAnimationFrame(()=>{let e=j.current,t=w.current;if(!e||!t)return;let n=e.offsetHeight;t.bottom+4+n<=window.innerHeight||b(e=>e?{...e,top:Math.max(8,t.top-n-4)}:e)});return()=>cancelAnimationFrame(e)},[x]),(0,i.useEffect)(()=>{if(!x)return;let e=e=>{let t=e.target;j.current?.contains(t)||k.current?.contains(t)||C()},t=()=>{let e=k.current?.getBoundingClientRect();tI(w.current,e?{top:e.top,right:e.right}:null)&&C()};document.addEventListener("mousedown",e),window.addEventListener("resize",t),window.addEventListener("scroll",t,!0);let n=requestAnimationFrame(()=>j.current?.querySelector("[role='menuitem']")?.focus());return()=>{cancelAnimationFrame(n),document.removeEventListener("mousedown",e),window.removeEventListener("resize",t),window.removeEventListener("scroll",t,!0)}},[C,x]);let _={display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:32,padding:"6px 11px",boxSizing:"border-box",background:"var(--bg-elevated)",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",textDecoration:"none",fontSize:12,whiteSpace:"nowrap"},I={onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-elevated)",e.currentTarget.style.color="var(--text-muted)"}},R=e=>(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"flex",color:"var(--text-dim)"},children:e});return(0,r.jsxs)("div",{style:{display:"flex",flexShrink:0},onClick:e=>e.stopPropagation(),onKeyDown:e=>{"Escape"===e.key&&x&&(e.preventDefault(),C(!0))},children:[(0,r.jsx)(eG,{label:S,active:x,expanded:x,haspopup:"menu",hoverReveal:!0,buttonRef:k,onClick:e=>{e.stopPropagation(),(()=>{if(x)return C();let e=k.current?.getBoundingClientRect();e&&(w.current={top:e.top,bottom:e.bottom,right:e.right},b({top:e.bottom+4,right:Math.max(8,window.innerWidth-e.right)})),v(!0)})()},children:(0,r.jsx)(tn,{size:14})}),x&&y&&(0,s.createPortal)((0,r.jsxs)("div",{ref:j,role:"menu","aria-label":S,style:{position:"fixed",top:y.top,right:y.right,zIndex:600,minWidth:190,padding:4,background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-float)"},children:[n&&(0,r.jsxs)("button",{type:"button",role:"menuitem",style:_,...I,onClick:()=>{C(),u()},children:[R((0,r.jsx)(te,{size:13})),m("sidebar_renameSession")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:_,...I,onClick:()=>{C(),tC(e.id)},children:[R((0,r.jsxs)("svg",{...eZ(13),children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})),m("sidebar_copySessionId")]}),!e.subagent&&c&&(0,r.jsxs)("button",{type:"button",role:"menuitem",style:_,...I,onClick:()=>{C(),c()},children:[R((0,r.jsx)(e2,{size:13})),m(d?"sidebar_unpinSession":"sidebar_pinSession")]}),(l||null!==a)&&(0,r.jsxs)("button",{type:"button",role:"menuitem",disabled:!l,title:l?void 0:a??void 0,style:{..._,opacity:l?1:.45,cursor:l?"pointer":"not-allowed"},onClick:()=>{l&&(C(),h())},children:[R((0,r.jsx)(e4,{size:13})),m("sidebar_archiveSession")]}),"string"==typeof e?.id&&e.id.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("a",{role:"menuitem",href:t_(e.id),download:!0,style:_,...I,onClick:()=>C(),children:[R((0,r.jsxs)("svg",{...eZ(13),children:[(0,r.jsx)("path",{d:"M12 3v12"}),(0,r.jsx)("path",{d:"m7 10 5 5 5-5"}),(0,r.jsx)("path",{d:"M5 21h14"})]})),m("sidebar_exportSessionHtml")]}),(0,r.jsxs)("a",{role:"menuitem",href:(f=e.id,g=new URLSearchParams({format:"jsonl"}),`${t_(f)}?${g.toString()}`),download:!0,style:_,...I,onClick:()=>C(),children:[R((0,r.jsxs)("svg",{...eZ(13),children:[(0,r.jsx)("path",{d:"M8 3H7a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2 2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1"}),(0,r.jsx)("path",{d:"M16 21h1a2 2 0 0 0 2-2v-4a2 2 0 0 1 2-2 2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"})]})),m("sidebar_exportSessionJsonl")]})]}),o&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{height:1,margin:"4px 6px",background:"var(--border)"}}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:{..._,color:"var(--status-danger)"},onClick:()=>{C(),p()},children:[R((0,r.jsx)(e7,{size:13})),m("sidebar_deleteSession")]})]})]}),document.body)]})}function tE({project:e,displayMode:t,projectAliases:n,selectedSessionId:i,runningSessionIds:o,subagentRunningIds:l,unreadSessionIds:s,collapsedProjectRoots:a,collapsedSessionIds:c,searchActive:u,onToggleProject:p,onNewSession:h,onSelectSession:f,menuOpen:g,onMenuOpenChange:m,onEditProject:x,onCloseProject:v,onRenamed:y,onSessionDeleted:b,onToggleCollapse:w,groupVisibleCounts:k,onShowMore:j,onShowFewer:S,actionError:C,onSessionArchive:_,isSessionPinned:I,onTogglePin:R,onProjectDrop:T}){var E;let{t:M}=(0,eU.s9)(),A=(E=e.root,!u&&a.has(E)),L=e.tree.length>0,z=n[e.root]??d(e.root),W=M(A?"sidebar_expandProjectNamed":"sidebar_collapseProjectNamed",{project:z});return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{className:"sidebar-row","data-sidebar-depth":0,role:"button",tabIndex:0,"aria-expanded":!A,"aria-label":W,draggable:!!T,onDragStart:t=>{T&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/pidance-project",e.root),t.dataTransfer.setData("text/plain",e.root))},onDragOver:e=>{T&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},onDrop:t=>{if(!T)return;t.preventDefault(),t.stopPropagation();let n=t.dataTransfer.getData("text/pidance-project")||t.dataTransfer.getData("text/plain");n&&T(n,e.root)},onClick:()=>p(e.root),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},onKeyDown:t=>{t.target===t.currentTarget&&("Enter"===t.key||" "===t.key)&&(t.preventDefault(),p(e.root))},title:e.root,style:{display:"flex",alignItems:"center",gap:6,height:32,margin:"1px 6px",position:"relative",paddingLeft:32,paddingRight:8,borderRadius:6,cursor:"pointer",background:"transparent",color:"var(--text-muted)"},children:[(0,r.jsx)(tr,{collapsed:A,label:W,left:6,onClick:t=>{t.stopPropagation(),p(e.root)}}),(0,r.jsx)("span",{"aria-hidden":"true",className:"sidebar-indicator-icon",style:{position:"absolute",left:6,top:"50%",display:"flex",width:20,height:20,alignItems:"center",justifyContent:"center",transform:"translateY(-50%)",color:"var(--text-dim)"},children:(0,r.jsx)(e0,{size:13})}),(0,r.jsx)(eJ,{text:z,style:{flex:1,fontSize:12.5,fontWeight:600,fontFamily:"var(--font-mono)"}}),(0,r.jsx)(eG,{label:M("sidebar_newSessionIn",{project:z}),hoverReveal:!0,onClick:t=>{t.stopPropagation(),h(e.root)},children:(0,r.jsx)(e6,{size:14})}),(0,r.jsx)(tR,{open:g,onOpenChange:m,projectName:z,onEdit:x,onClose:v})]}),C&&(0,r.jsx)("div",{role:"alert",style:{padding:"3px 10px 6px 31px",color:"var(--status-danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:C}),!A&&(0,r.jsxs)("div",{children:[e$(e.tree,eL(k,e.root),u).map(e=>(0,r.jsx)(tM,{node:e,selectedSessionId:i,runningSessionIds:o,subagentRunningIds:l,unreadSessionIds:s,onSelectSession:f,onRenamed:y,onSessionDeleted:b,onSessionArchive:_,isSessionPinned:I,onTogglePin:R,depth:0,collapsedSessionIds:c,searchActive:u,onToggleCollapse:w,displayMode:t},e.session.id)),(0,r.jsx)(ts,{groupKey:e.root,total:e.tree.length,visibleCount:eL(k,e.root),searchActive:u,onShowMore:j,onShowFewer:S}),!L&&(0,r.jsx)("div",{style:{padding:"2px 10px 6px 31px",color:"var(--text-dim)",fontSize:11},children:M("sidebar_noSessionsYet")})]})]})}function tM({node:e,selectedSessionId:t,runningSessionIds:n,subagentRunningIds:i,unreadSessionIds:o,onSelectSession:l,onRenamed:s,onSessionDeleted:a,onSessionArchive:d,isSessionPinned:c,onTogglePin:u,depth:p,collapsedSessionIds:h,searchActive:f,onToggleCollapse:g,displayMode:m}){var x;let v=e.children.length>0,y=(x=e.session.id,!f&&h.has(x));return(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{"data-session-id":e.session.id,style:{position:"relative"},children:(0,r.jsx)(tA,{session:e.session,relation:e.relation,isSelected:e.session.id===t,isRunning:n.has(e.session.id)||i.has(e.session.id),isUnread:!e.session.subagent&&o.has(e.session.id),onClick:()=>l(e.session),onRenamed:s,onDeleted:e=>a?.(e),onArchive:e=>d?.(e),isPinned:c?.(e.session.id),onTogglePin:()=>u?.(e.session.id),depth:p,hasChildren:v,collapsed:y,onToggleCollapse:()=>g(e.session.id),displayMode:m})}),v&&!y&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(tM,{node:e,selectedSessionId:t,runningSessionIds:n,subagentRunningIds:i,unreadSessionIds:o,onSelectSession:l,onRenamed:s,onSessionDeleted:a,onSessionArchive:d,isSessionPinned:c,onTogglePin:u,depth:p+1,collapsedSessionIds:h,searchActive:f,onToggleCollapse:g,displayMode:m},e.session.id))})]})}function tA({session:e,relation:t=null,isSelected:n,isRunning:o,isUnread:l,onClick:s,onRenamed:a,onDeleted:d,onArchive:c,isPinned:u,onTogglePin:p,depth:h=0,hasChildren:f=!1,collapsed:g=!1,onToggleCollapse:m,displayMode:x}){let{t:v}=(0,eU.s9)(),[y,b]=(0,i.useState)(!1),[w,k]=(0,i.useState)(!1),[j,S]=(0,i.useState)(""),[C,_]=(0,i.useState)(!1),[I,R]=(0,i.useState)(!1),T=(0,i.useRef)(null),E=(0,i.useContext)(th),M=!!e.id&&E.has(e.id),A=tS(e),L=!0===o,z=!L&&!1===tS(e).readOnly,W=z?null:v(L?"archive_rowDisabledRunning":"archive_rowDisabledReadOnly"),$=(0,i.useContext)(tp),P=e.id?$.startedAt.get(e.id):void 0,F=!0===o&&!(f&&g),H=e.firstMessage.trim(),D=e.subagent&&(!H||"(no messages)"===H)?`${e.subagent.agent?`${e.subagent.agent} \xb7 `:""}${v("sidebar_runCount",{count:e.subagent.runIndex})}`:"",N="(no messages)"===H?v("sidebar_noMessages"):e.firstMessage,B=e.name||D||N.slice(0,50)||e.id.slice(0,12),O=(0,i.useCallback)(()=>{A.canRename&&(S(B),k(!0),setTimeout(()=>T.current?.select(),0))},[B,A.canRename]),U=(0,i.useCallback)(async()=>{if(!A.canRename)return void k(!1);let t=j.trim();if(k(!1),t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),a?.()}catch{}},[j,e.id,e.name,a,A.canRename]),q=(0,i.useCallback)(()=>{A.canDelete&&_(!0)},[A.canDelete]),K=(0,i.useCallback)(async()=>{if(!A.canDelete)return void _(!1);_(!1),R(!0);try{if(!(await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"})).ok)return void R(!1);d?.(e.id)}catch{R(!1)}},[e.id,d,A.canDelete]),J=(0,i.useCallback)(()=>{_(!1)},[]),V="compact"===x,Y=V?30:40;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"sidebar-row","data-sidebar-depth":h,onClick:w?void 0:s,onMouseEnter:()=>b(!0),onMouseLeave:()=>{b(!1)},style:{height:Y,display:"flex",alignItems:"center",width:"calc(100% - 12px)",margin:"1px 6px",position:"relative",paddingLeft:32+14*h,paddingRight:8,borderRadius:6,cursor:w?"default":"pointer",background:n?"var(--bg-selected)":y?"var(--bg-hover)":"transparent",borderLeft:n?"2px solid var(--accent)":"2px solid transparent",transition:"background 0.15s ease, color 0.15s ease",opacity:I?.5:1,gap:6,overflow:"hidden"},children:w?(0,r.jsx)("input",{ref:T,value:j,onChange:e=>S(e.target.value),onBlur:U,onKeyDown:e=>{"Enter"===e.key&&U(),"Escape"===e.key&&k(!1)},autoFocus:!0,"aria-label":v("sidebar_renameSession"),style:{flex:1,fontSize:V?11:12,padding:"0 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:V?20:28}}):(0,r.jsxs)(r.Fragment,{children:[f?(0,r.jsx)("button",{type:"button",className:"sidebar-chevron-btn sidebar-indent-indicator sidebar-chevron-always",onClick:e=>{e.stopPropagation(),m?.()},"data-tooltip":v(g?"sidebar_expandChild":"sidebar_collapseChild"),"aria-label":v(g?"sidebar_expandChild":"sidebar_collapseChild"),style:{display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",left:6+14*h,top:"50%",width:20,height:20,padding:0,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",transform:`translateY(-50%)${g?" rotate(-90deg)":""}`,transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}):(0,r.jsx)("span",{className:"sidebar-indent-placeholder","aria-hidden":"true",style:{position:"absolute",left:6+14*h,top:"50%",width:20,height:20,transform:"translateY(-50%)"}}),o&&!M&&(0,r.jsx)("span",{"aria-hidden":"true",style:{position:"absolute",left:6+14*h,top:"50%",display:"flex",width:20,height:20,alignItems:"center",justifyContent:"center",transform:"translateY(-50%)",pointerEvents:"none"},children:(0,r.jsx)(ta,{size:18})}),(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,minWidth:0,fontSize:V?11.5:12,fontWeight:400,lineHeight:1.4,color:n?"var(--accent-hover)":"var(--text)"},title:B,children:[M?(0,r.jsx)(td,{size:10}):!o&&l&&(0,r.jsx)(tu,{size:10}),!M&&F&&V&&(0,r.jsx)(tc,{startedAt:P,now:$.now,running:!0}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:B}),V&&e.subagent&&(0,r.jsx)("span",{title:`${v("sidebar_subagentReadOnly")}${e.subagent.agent?` \xb7 ${e.subagent.agent}`:""} \xb7 ${v("sidebar_runCount",{count:e.subagent.runIndex})}`,style:{display:"inline-flex",alignItems:"center",flexShrink:0,padding:"0 5px",border:"1px solid color-mix(in srgb, var(--status-success) 42%, var(--border))",borderRadius:999,color:"var(--status-success)",fontSize:9,lineHeight:1.55},children:v("sidebar_subagentBadge")})]}),!V&&(0,r.jsxs)("div",{style:{marginTop:1,display:"flex",alignItems:"center",gap:8,color:"var(--text-dim)",fontSize:10.5,minWidth:0},children:[!M&&F&&(0,r.jsx)(tc,{startedAt:P,now:$.now,running:!0}),(0,r.jsx)("span",{title:e.modified,children:eK(e.modified,v)}),(0,r.jsx)("span",{children:v("sidebar_messagesCount",{count:e.messageCount})}),e.subagent&&(0,r.jsxs)("span",{title:`${v("sidebar_subagentReadOnly")}${e.subagent.agent?` \xb7 ${e.subagent.agent}`:""} \xb7 ${v("sidebar_runCount",{count:e.subagent.runIndex})}`,style:{display:"flex",alignItems:"center",gap:4,color:"var(--text-muted)",minWidth:0,overflow:"hidden"},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:9,padding:"0 5px",borderRadius:999,border:"1px solid color-mix(in srgb, var(--status-success) 42%, var(--border))",color:"var(--status-success)",lineHeight:1.55},children:v("sidebar_subagentBadge")}),(0,r.jsxs)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"var(--font-mono)",fontSize:10},children:[e.subagent.agent?`${e.subagent.agent} \xb7 `:"",v("sidebar_runCount",{count:e.subagent.runIndex})]})]})]})]}),(0,r.jsx)(tT,{session:e,title:B,canRename:A.canRename,canDelete:A.canDelete,canArchive:z,archiveDisabledReason:W,isPinned:u,onTogglePin:p,onRename:O,onDelete:q,onArchive:()=>c?.(e.id)})]})}),(0,r.jsx)(tw,{open:C,onClose:J,title:v("sidebar_deleteSession"),description:v("sidebar_deleteConfirm",{name:B}),width:400,closeLabel:v("dialog_close"),actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ti,{disabled:I,onClick:J,children:v("sidebar_cancel")}),(0,r.jsx)(ti,{danger:!0,disabled:I,onClick:()=>void K(),children:v("sidebar_deleteSession")})]})})]})}function tL(e){return"string"==typeof e?.name&&"string"==typeof e?.path}let tz={ok:!1,path:null,parentPath:null,entries:[],git:null};async function tW(e,t=fetch){try{var n;let r=await t(`/api/cwd/browse?path=${encodeURIComponent(e)}`);if(!r.ok)return tz;let i=await r.json().catch(()=>null);if(!i||"object"!=typeof i)return tz;return{ok:!0,path:"string"==typeof i.path&&i.path?i.path:e,parentPath:"string"==typeof i.parentPath?i.parentPath:null,entries:Array.isArray(i.entries)?i.entries.filter(tL):[],git:(n=i.git,"boolean"==typeof n?.isRepo)?i.git:null}}catch{return tz}}async function t$(e,t=fetch){try{let n=await t("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})}),r=await n.json().catch(()=>({}));if(!n.ok||r.error){if("NOT_FOUND"===r.code)return{kind:"notFound",cwd:r.cwd??e};return{kind:"error",message:r.error??`HTTP ${n.status}`}}return{kind:"ok",cwd:r.cwd??e}}catch(e){return{kind:"error",message:e instanceof Error?e.message:String(e)}}}async function tP(e,t=fetch){try{let n=await t("/api/cwd/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e})}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)return{ok:!1,message:r.error??`HTTP ${n.status}`};return{ok:!0,cwd:r.cwd??e}}catch(e){return{ok:!1,message:e instanceof Error?e.message:String(e)}}}function tF({open:e,onClose:t,onAdded:n}){let{t:o}=(0,eU.s9)(),l=(0,i.useRef)(null),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(!1),[j,S]=(0,i.useState)(null),[C,_]=(0,i.useState)(null),[I,R]=(0,i.useState)(null),T=(0,i.useRef)(0),E=(0,i.useRef)(null),M=(0,i.useRef)(null),A=(0,i.useCallback)(()=>{T.current+=1,null!==E.current&&(window.clearTimeout(E.current),E.current=null)},[]),L=(0,i.useCallback)(()=>{A(),a(""),c(null),p(!1),f(null),m(null),v([]),b(null),k(!1),S(null),_(null),R(null),M.current=null},[A]);(0,i.useEffect)(()=>()=>A(),[A]);let z=(0,i.useCallback)(async(e,t=!1)=>{let n=++T.current;p(!0);let r=await tW(e);if(n===T.current){if(r.ok){let n=r.path??e;t&&(M.current=n,a(n)),f(n),m(r.parentPath),v(r.entries),b(r.git),k(!1)}else f(null),m(null),v([]),b(null),k(!0);p(!1)}},[]);(0,i.useEffect)(()=>{e?z("",!0):L()},[e,L,z]),(0,i.useEffect)(()=>{if(!e)return;let t=s.trim();if(t){if(null!==M.current&&M.current===t){M.current=null;return}A(),E.current=window.setTimeout(()=>{E.current=null,z(t)},250)}},[e,s,z,A]);let W=(0,i.useCallback)(e=>{A(),z(e,!0)},[z,A]),$=(0,i.useCallback)(()=>{t()},[t]),P=(0,i.useCallback)(async()=>{let e=s.trim();if(e&&null===I){R("validate"),c(null);try{let t=await t$(e);if("notFound"===t.kind){_(null),S(t.cwd);return}if("error"===t.kind)return void c(t.message);n(t.cwd)}finally{R(null)}}},[s,I,n]),F=(0,i.useCallback)(async()=>{if(j&&null===I){R("create"),_(null);try{let e=await tP(j);if(!e.ok)return void _(e.message);S(null),n(e.cwd)}finally{R(null)}}},[j,I,n]);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(tw,{open:e,onClose:$,title:o("sidebar_addProjectDialog"),width:440,closeLabel:o("dialog_close"),initialFocusRef:l,actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ti,{onClick:$,children:o("sidebar_cancel")}),(0,r.jsx)(ti,{primary:!0,disabled:null!==I||!s.trim(),onClick:()=>void P(),children:o("validate"===I?"sidebar_validating":"sidebar_add")})]}),children:(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:"add-project-path",style:{display:"block",fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:6},children:o("sidebar_projectPath")}),(0,r.jsx)("input",{id:"add-project-path",ref:l,value:s,onChange:e=>{a(e.target.value),c(null),M.current=null},onKeyDown:e=>{"Escape"===e.key&&null===I&&(e.preventDefault(),$())},placeholder:"/path/to/project","aria-label":o("sidebar_projectPath"),autoComplete:"off",spellCheck:!1,style:{width:"100%",height:32,fontSize:12,fontFamily:"var(--font-mono)",padding:"0 10px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-panel)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{marginTop:10},children:[u&&!h&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:o("sidebar_browseLoading")}),!u&&w&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:o("sidebar_browseMissing")}),!w&&y&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,marginBottom:6,color:y.isRepo?"var(--text-muted)":"var(--text-dim)"},children:y.isRepo?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{style:{color:"var(--accent)",fontWeight:600},children:o("sidebar_browseGitRepo")}),y.branch&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:10.5},children:y.branch})]}):(0,r.jsx)("span",{children:o("sidebar_browseNotGit")})}),h&&(0,r.jsxs)("div",{style:{maxHeight:150,overflowY:"auto",overflowX:"hidden",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",padding:4},children:[g&&(0,r.jsx)("button",{type:"button",disabled:u,onClick:()=>W(g),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"4px 8px",border:"none",background:"transparent",color:"var(--text-muted)",fontSize:12,cursor:"pointer",borderRadius:5,fontFamily:"var(--font-mono)"},onMouseEnter:e=>e.currentTarget.style.background="var(--bg-hover)",onMouseLeave:e=>e.currentTarget.style.background="transparent",children:".."}),0===x.length?(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"var(--text-dim)"},children:o("sidebar_browseEmpty")}):x.map(e=>(0,r.jsxs)("button",{type:"button",disabled:u,onClick:()=>W(e.path),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"4px 8px",border:"none",background:"transparent",color:"var(--text)",fontSize:12,cursor:"pointer",borderRadius:5,textAlign:"left",fontFamily:"var(--font-mono)"},onMouseEnter:e=>e.currentTarget.style.background="var(--bg-hover)",onMouseLeave:e=>e.currentTarget.style.background="transparent",children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10.5},children:"▸"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path))]})]}),d&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,color:"var(--status-danger)",fontSize:12,lineHeight:1.45,overflowWrap:"anywhere"},children:d})]})}),(0,r.jsxs)(tw,{open:null!==j,onClose:()=>{S(null),_(null)},title:o("sidebar_createPathTitle"),width:400,zIndex:1100,closeLabel:o("dialog_close"),actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ti,{onClick:()=>{S(null),_(null)},children:o("sidebar_cancel")}),(0,r.jsx)(ti,{primary:!0,disabled:null!==I,onClick:()=>void F(),children:o("create"===I?"sidebar_creatingPath":"sidebar_createPathAction")})]}),children:[(0,r.jsx)("div",{style:{fontSize:12.5,color:"var(--text)",lineHeight:1.5,overflowWrap:"anywhere"},children:o("sidebar_createPathPrompt",{path:j??""})}),j&&(0,r.jsx)("div",{style:{marginTop:6,fontSize:11.5,fontFamily:"var(--font-mono)",color:"var(--text-muted)",overflowWrap:"anywhere"},children:j}),C&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,color:"var(--status-danger)",fontSize:12,lineHeight:1.45,overflowWrap:"anywhere"},children:C})]})]})}function tH({cwd:e,tab:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(""),[w,k]=(0,i.useState)(""),j=(0,i.useCallback)(async()=>{c(!0),f(null);try{let t=await fetch(`/api/project-assets?cwd=${encodeURIComponent(e)}`,{cache:"no-store"});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`HTTP ${t.status}`)}let n=await t.json();l(n.rulesContent??""),a(Array.isArray(n.skills)?n.skills:[])}catch(e){f(e instanceof Error?e.message:String(e))}finally{c(!1)}},[e]);(0,i.useEffect)(()=>{j()},[j]);let S=(0,i.useCallback)(async t=>{let n=await fetch("/api/project-assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,...t})});if(!n.ok)throw Error((await n.json().catch(()=>({}))).error??`HTTP ${n.status}`);return!0},[e]),C=(0,i.useCallback)(async()=>{if(null!==o){p(!0),f(null),m(!1);try{await S({kind:"rules",content:o}),m(!0),window.setTimeout(()=>m(!1),2e3)}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}}},[o,S]),_=(0,i.useCallback)(async()=>{let e=w.trim();if(e){p(!0),f(null);try{await S({kind:"skill",action:"create",name:e}),k(""),await j()}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}}},[w,S,j]),I=(0,i.useCallback)(async e=>{p(!0),f(null);try{await S({kind:"skill",action:"update",name:e,content:y}),v(null),await j()}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}},[y,S,j]),R=(0,i.useCallback)(async e=>{p(!0),f(null);try{await S({kind:"skill",action:"toggle",name:e.name,enabled:!e.enabled}),await j()}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}},[S,j]),T=(0,i.useCallback)(async e=>{p(!0),f(null);try{await S({kind:"skill",action:"delete",name:e}),await j()}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(!1)}},[S,j]),E={width:"100%",minHeight:200,padding:"10px 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:12,lineHeight:1.55,outline:"none",fontFamily:"var(--font-mono)",whiteSpace:"pre",overflow:"auto",boxSizing:"border-box",resize:"vertical"};return d?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("common_loading")}):(0,r.jsxs)("div",{children:[h&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)",marginBottom:10,whiteSpace:"pre-wrap"},children:h}),"rules"===t?(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:8,fontFamily:"var(--font-mono)"},children:[e,"/AGENTS.md"]}),(0,r.jsx)("textarea",{value:o??"",onChange:e=>l(e.target.value),spellCheck:!1,"aria-label":n("projectAssets_rules"),style:E}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginTop:10},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void C(),disabled:u||null===o,style:{minHeight:30,padding:"0 14px",borderRadius:7,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",cursor:u||null===o?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:u||null===o?.6:1},children:u?n("common_saving"):n("common_save")}),g&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--accent)"},children:n("common_saved")})]})]}):(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:12},children:[(0,r.jsx)("input",{type:"text",value:w,onChange:e=>k(e.target.value),placeholder:n("projectAssets_newSkillName"),"aria-label":n("projectAssets_newSkillName"),style:{flex:1,height:30,padding:"0 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}}),(0,r.jsx)("button",{type:"button",onClick:()=>void _(),disabled:u||!w.trim(),style:{minHeight:30,padding:"0 12px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",cursor:u||!w.trim()?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:u||!w.trim()?.6:1},children:n("projectAssets_addSkill")})]}),s?.length===0?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n("projectAssets_noSkills")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:(s??[]).map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsxs)("label",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-muted)",cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:e.enabled,onChange:()=>void R(e),disabled:u}),n("projectAssets_enabled")]}),(0,r.jsx)("button",{type:"button",onClick:()=>{v(e.name),b(e.content)},style:{fontSize:11,color:"var(--accent)",cursor:"pointer",background:"none",border:"none"},children:n("projectAssets_edit")}),(0,r.jsx)("button",{type:"button",onClick:()=>void T(e.name),disabled:u,style:{fontSize:11,color:"var(--status-danger)",cursor:u?"not-allowed":"pointer",background:"none",border:"none"},children:n("common_remove")})]}),x===e.name&&(0,r.jsxs)("div",{style:{padding:8},children:[(0,r.jsx)("textarea",{value:y,onChange:e=>b(e.target.value),spellCheck:!1,"aria-label":`${e.name} SKILL.md`,style:E}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginTop:8},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void I(e.name),disabled:u,style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",cursor:u?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:u?.6:1},children:u?n("common_saving"):n("common_save")}),(0,r.jsx)("button",{type:"button",onClick:()=>v(null),style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("common_cancel")})]})]})]},e.name))})]})]})}function tD({projectRoot:e,initialName:t,onClose:n,onSaveName:o}){let{t:l}=(0,eU.s9)(),s=(0,i.useRef)(null),[a,d]=(0,i.useState)("name"),[c,u]=(0,i.useState)(t);return(0,i.useEffect)(()=>{null!==e&&(d("name"),u(t))},[e,t]),(0,r.jsxs)(tw,{open:null!==e,onClose:n,title:l("sidebar_editProject"),width:720,height:620,closeLabel:l("dialog_close"),description:e?l("sidebar_editProjectDescription",{path:e}):void 0,children:[(0,r.jsx)("div",{style:{display:"flex",gap:8,marginBottom:14,flexWrap:"wrap"},children:[["name",l("sidebar_projectName")],["rules",l("sidebar_projectRules")],["skills",l("sidebar_projectSkills")]].map(([e,t])=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e),style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:a===e?"var(--bg-selected)":"var(--bg-panel)",color:a===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:a===e?600:400},"aria-current":a===e?"page":void 0,children:t},e))}),"name"===a?(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=c.trim();t&&o(t)},children:[(0,r.jsx)("label",{htmlFor:"edit-project-name",style:{display:"block",fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:6},children:l("sidebar_projectName")}),(0,r.jsx)("input",{id:"edit-project-name",ref:s,value:c,onChange:e=>u(e.target.value),placeholder:l("sidebar_projectName"),"aria-label":l("sidebar_projectName"),"aria-invalid":!c.trim(),autoComplete:"off",spellCheck:!1,style:{width:"100%",height:32,fontSize:12.5,padding:"0 10px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-panel)",color:"var(--text)",boxSizing:"border-box"}}),!c.trim()&&(0,r.jsx)("div",{style:{marginTop:6,fontSize:11.5,color:"var(--status-danger)"},children:l("sidebar_projectNameRequired")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginTop:14},children:[(0,r.jsx)("button",{type:"submit",disabled:!c.trim(),style:{minHeight:30,padding:"0 14px",borderRadius:7,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",cursor:c.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,opacity:c.trim()?1:.6},children:l("sidebar_save")}),(0,r.jsx)("button",{type:"button",onClick:n,style:{minHeight:30,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:l("sidebar_cancel")})]})]}):e&&(0,r.jsx)(tH,{cwd:e,tab:"skills"===a?"skills":"rules"})]})}async function tN(e,t,n){try{let r=await n(e,t),i=await r.json().catch(()=>({}));return{ok:r.ok,status:r.status,error:i.error}}catch(e){return{ok:!1,status:0,error:e instanceof Error?e.message:String(e)}}}function tB(e){if(!e.archivedAt)return-1/0;let t=Date.parse(e.archivedAt);return Number.isNaN(t)?-1/0:t}function tO(e,t=60){let n=e.name?.trim()||e.firstMessage.trim()||e.id;return n.length<=t?n:`${n.slice(0,t)}…`}function tU(e){return e.ok?"other":409===e.status?"running":403===e.status?"readOnly":0===e.status?"network":"other"}function tq({sessions:e,count:t,homeDir:n,loading:o,onRefresh:l,onBack:s}){let{t:d}=(0,eU.s9)(),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({sessionId:null}),[f,g]=(0,i.useState)(null);(0,i.useEffect)(()=>{l()},[l]);let m=(0,i.useCallback)(e=>{let t=tU(e);return"running"===t?d("archive_runningConflict"):"readOnly"===t?d("archive_readOnlyForbidden"):"network"===t?d("archive_networkError"):e.error??d("archive_unknownError")},[d]),x=(0,i.useCallback)(async e=>{if(null===c){u(e.id),g(null);try{let t=await function(e,t=fetch){return tN(`/api/sessions/${encodeURIComponent(e)}/archive`,{method:"DELETE"},t)}(e.id);if(!t.ok)return void g(d("archive_restoreFailed",{error:m(t)}));l()}catch(e){g(d("archive_restoreFailed",{error:e instanceof Error?e.message:String(e)}))}finally{u(null)}}},[c,l,d,m]),v=(0,i.useCallback)(async e=>{if(null===c){u(e.id),g(null);try{let t=await function(e,t=fetch){return tN(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"},t)}(e.id);if(!t.ok)return void g(d("archive_deleteFailed",{error:m(t)}));h({sessionId:null}),l()}catch(e){g(d("archive_deleteFailed",{error:e instanceof Error?e.message:String(e)}))}finally{u(null)}}},[c,l,d,m]),y=[...e].sort((e,t)=>{let n=tB(e),r=tB(t);return n===r?0:n===-1/0?1:r===-1/0?-1:r-n}),b=p.sessionId?y.find(e=>e.id===p.sessionId)??null:null,w=b?tO(b):"",k=!!b&&c===b.id;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:s,"data-tooltip":d("archive_back"),"aria-label":d("archive_back"),className:"sidebar-icon-btn",style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsx)(e9,{size:14})}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,fontSize:12.5,fontWeight:600,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d("archive_viewTitle")}),(0,r.jsx)("span",{title:d("archive_viewCount",{count:t}),style:{flexShrink:0,minWidth:18,padding:"1px 6px",boxSizing:"border-box",borderRadius:999,background:"var(--bg-selected)",color:"var(--text-muted)",fontSize:10,fontWeight:600,textAlign:"center"},children:t})]}),f&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 10px",borderBottom:"1px solid var(--border)",background:"var(--status-danger-bg)",color:"var(--status-danger)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere",flexShrink:0},children:f}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",overflowY:"auto",padding:"4px 0",minHeight:80},children:[o&&0===y.length&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:d("sidebar_loading")}),!o&&0===y.length&&(0,r.jsxs)("div",{style:{padding:"18px 14px",color:"var(--text-muted)",fontSize:12,lineHeight:1.7},children:[d("archive_empty"),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:d("archive_emptyHint")})]}),y.map(e=>{let t=tO(e),i=c===e.id;return(0,r.jsxs)("div",{"data-archive-session-id":e.id,style:{display:"flex",alignItems:"center",gap:6,margin:"1px 6px",padding:"7px 8px",borderRadius:6,background:"transparent",opacity:i?.5:1},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{title:t,style:{fontSize:12,fontWeight:500,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.4},children:t}),(0,r.jsxs)("div",{style:{fontSize:10.5,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1.4,marginTop:1},children:[a(e.cwd,n)," \xb7 ",d("archive_archivedAt",{date:eK(e.archivedAt??e.modified,d)})]})]}),(0,r.jsx)("button",{type:"button",disabled:i,onClick:()=>void x(e),title:d("archive_restore"),style:{padding:"3px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:11,cursor:i?"not-allowed":"pointer",flexShrink:0},children:i?d("archive_restoring"):d("archive_restore")}),(0,r.jsx)("button",{type:"button",disabled:i,onClick:()=>h({sessionId:e.id}),title:d("archive_delete"),"aria-label":d("archive_delete"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:i?"not-allowed":"pointer",flexShrink:0},children:(0,r.jsx)(e7,{size:13})})]},e.id)})]}),(0,r.jsx)(tw,{open:null!==b,onClose:()=>{k||h({sessionId:null})},title:d("archive_delete"),description:b?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{fontWeight:600,color:"var(--text)",marginBottom:4},children:w}),(0,r.jsx)("div",{children:d("archive_deleteConfirm")})]}):d("archive_deleteConfirm"),width:400,closeLabel:d("dialog_close"),closeOnBackdrop:!k,closeOnEsc:!k,actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ti,{disabled:k,onClick:()=>h({sessionId:null}),children:d("archive_deleteCancel")}),(0,r.jsx)(ti,{danger:!0,disabled:k||!b,onClick:()=>{b&&v(b)},children:k?d("archive_deleting"):d("archive_deleteConfirmButton")})]})})]})}function tK(e,t){let n=new Set(e);for(let e of t)n.add(e);return n}function tJ(e){let t=e?.now??(()=>Date.now()),n={serverSessions:[],pendingById:new Map,pendingIds:new Set,deletedIds:new Set,archivedSessions:[],archivedCount:0,runningIds:new Set,startingIds:new Set,runningStartedAt:new Map,runningEpoch:new Map,unread:(0,eq.oJ)(),loading:!1,error:null,serverListLoaded:!1,listStatus:"idle"},r=new Set,i=()=>{for(let e of r)e()},o={getState:()=>n,getSnapshot(e=null){let t=function(e){let{serverSessions:t,pendingSessions:n,pendingIds:r=new Set(n.map(e=>e.id)),deletedIds:i}=e,o=new Map;for(let e of t)i?.has(e.id)||o.set(e.id,e);for(let e of n)!(i?.has(e.id)||o.has(e.id))&&r.has(e.id)&&o.set(e.id,e);return[...o.values()].sort(eP)}({serverSessions:n.serverSessions,pendingSessions:[...n.pendingById.values()],pendingIds:n.pendingIds,deletedIds:n.deletedIds}),r=tK(n.runningIds,n.startingIds),i=(0,eq.hA)(n.unread);for(let e of r)i.delete(e);return e&&i.delete(e),{sessions:t,archivedSessions:n.archivedSessions,archivedCount:n.archivedCount,runningIds:new Set(n.runningIds),startingIds:new Set(n.startingIds),effectiveRunningIds:r,unreadIds:i,loading:n.loading,error:n.error,serverListLoaded:n.serverListLoaded,listStatus:n.listStatus,runningStartedAt:new Map(n.runningStartedAt)}},subscribe:e=>(r.add(e),()=>{r.delete(e)}),applyServerList(e){let t=e.archivedSessions??[];n.serverSessions=[...e.sessions],n.archivedSessions=t,n.archivedCount=e.archivedCount??t.length,n.loading=!1,n.error=null,n.serverListLoaded=!e.provisional||n.serverListLoaded,n.listStatus="ready",((e,t)=>{let r=new Set(t.map(e=>e.id)),i=new Set(e.map(e=>e.id)),o=!1,l=new Map(n.pendingById);for(let e of[...l.keys()])(i.has(e)||r.has(e)||n.deletedIds.has(e))&&(l.delete(e),o=!0);let s=function(e,t){if(0===e.size)return e;let n=new Set(t.map(e=>e.id)),r=!1,i=new Set;for(let t of e){if(n.has(t)){r=!0;continue}i.add(t)}return r?i:e}(n.pendingIds,e);for(let e of[...s])(r.has(e)||n.deletedIds.has(e))&&s.delete(e);o&&(n.pendingById=l),n.pendingIds=s})(e.sessions,t);let r=new Set([...e.sessions.map(e=>e.id),...n.pendingIds]);if(n.unread=(0,eq.v7)(n.unread,r),e.runningSessionIds&&0===n.runningIds.size&&0===n.startingIds.size)o.applyRunningSnapshot({runningIds:e.runningSessionIds,runningStartedAt:e.runningStartedAt,selectedSessionId:e.selectedSessionId,now:e.now});else if(e.runningStartedAt){let t=new Map(n.runningStartedAt);for(let[n,r]of Object.entries(e.runningStartedAt))t.has(n)||"number"!=typeof r||t.set(n,r);n.runningStartedAt=t}i()},applyListError(e){n.loading=!1,n.error=e,n.listStatus="error",n.serverListLoaded=!0,i()},beginListLoad(){"idle"===n.listStatus&&(n.listStatus="loading"),n.loading=0===n.serverSessions.length&&0===n.pendingById.size,i()},upsertPending(e){if(n.deletedIds.has(e.id))return;let t=new Map(n.pendingById);t.set(e.id,e),n.pendingById=t;let r=new Set(n.pendingIds);r.add(e.id),n.pendingIds=r,i()},removePending(e){if(!n.pendingById.has(e)&&!n.pendingIds.has(e))return;let t=new Map(n.pendingById);t.delete(e),n.pendingById=t;let r=new Set(n.pendingIds);r.delete(e),n.pendingIds=r,i()},markDeleted(e){let t=new Set(n.deletedIds);t.add(e),n.deletedIds=t,o.removePending(e);let r=new Set(n.startingIds);r.delete(e),n.startingIds=r,i()},markStarting(e,r=t()){if(!e)return;let o=new Set(n.startingIds);o.add(e),n.startingIds=o;let l=new Map(n.runningStartedAt);l.has(e)||l.set(e,r),n.runningStartedAt=l,i()},clearStarting(e){if(!n.startingIds.has(e))return;let t=new Set(n.startingIds);if(t.delete(e),n.startingIds=t,!n.runningIds.has(e)&&n.runningStartedAt.has(e)){let t=new Map(n.runningStartedAt);t.delete(e),n.runningStartedAt=t}i()},applyRunningSnapshot(e){let r=new Set(e.runningIds),o=((e,t)=>{let r=new Set;for(let i of n.startingIds)!e.has(i)&&t.has(i)&&r.add(i);return r})(r,new Set(e.localInFlightIds??[])),l=n.runningIds,s=new Map(n.runningStartedAt),a=new Map(n.runningEpoch),d=e.now??t(),c=new Date(d).toISOString();if(e.runningStartedAt)for(let[t,i]of Object.entries(e.runningStartedAt)){if("number"!=typeof i)continue;let o=s.get(t);void 0!==o&&o!==i&&r.has(t)&&(a.set(t,(a.get(t)??0)+1),n.unread=(0,eq.du)(n.unread,new Set([t]),new Set,e.selectedSessionId??null,c)),s.set(t,i)}for(let e of r)s.has(e)||s.set(e,d);for(let e of[...s.keys()])r.has(e)||o.has(e)||s.delete(e);let u=tK(r,o);n.unread=(0,eq.du)(n.unread,l,u,e.selectedSessionId??null,c),n.runningIds=r,n.startingIds=o,n.runningStartedAt=s,n.runningEpoch=a,i()},markRead(e,r=new Date(t()).toISOString()){let o=(0,eq.AH)(n.unread,e,r);o!==n.unread&&(n.unread=o,i())},replaceUnread(e){n.unread=e,i()}};return o}let tV=new Map;function tY(e){return{value:e.value,images:e.images.map(e=>({...e}))}}function tX(e){return!e.value&&0===e.images.length}function tG(e){return`drafts.${e}`}function tZ(e){let t=tV.get(e);return t?tY(t):null}function tQ(e,t){if(tX(t)){tV.delete(e),(0,eA.dM)(tG(e),void 0),(0,eA.qs)();return}tV.set(e,tY(t));let n={...tY(t),updatedAt:Date.now()};(0,eA.dM)(tG(e),n)}function t0(e){tV.delete(e),(0,eA.dM)(tG(e),void 0),(0,eA.qs)()}function t1(e,t,n=0){let r=tZ(e);if(!r)return void t0(e);let i=""!==r.value&&r.value!==t,o=r.images.length>n,l=""===r.value&&r.images.length>0;i||o||l||t0(e)}var t2=n(54180),t4=n(61012);class t6 extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function t5(e){return new EventSource(e)}function t8(e){return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>e()):setTimeout(e,16)}function t3(e){"function"==typeof cancelAnimationFrame?cancelAnimationFrame(e):clearTimeout(e)}function t9(e,t,n=nt){return{id:n(),cwd:e,generation:t}}let t7="pending:";function ne(e){return`${t7}${e}`}function nt(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`intent-${Date.now()}-${Math.random().toString(36).slice(2)}`}function nn(e){let t=e instanceof Error?e.message:String(e);return/already processing|already running|streamingBehavior/i.test(t)?"busy":/shell command is running/i.test(t)?"bash":/compaction/i.test(t)?"compacting":/cannot be queued|Extension command/i.test(t)?"extension":/no (valid )?model|model not found|未选择模型/i.test(t)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(t)?"auth":/running lease|locked by another|another process/i.test(t)?"locked":"error"}function nr(e=ni){return e()}function ni(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function no(e){if("custom"!==e.role)return null;let t=e.renderedLines;return Array.isArray(t)&&t.length>0&&t.every(e=>"string"==typeof e)?t:null}function nl(e){if("custom"!==e.role)return null;let t="string"==typeof e.content?e.content:JSON.stringify(e.content);return`${e.customType}\u0000${e.display?"1":"0"}\u0000${t}`}function ns(e,t,n,r){let i=new Map,o=new Map;return e.forEach((e,n)=>{let r=no(e);if(!r)return;let l=t[n];if(l&&i.set(l,r),l)return;let s=nl(e);if(!s)return;let a=o.get(s)??[];a.push(r),o.set(s,a)}),n.map((e,t)=>{if("custom"!==e.role||no(e))return e;let n=r[t]?i.get(r[t]):void 0,l=n?null:nl(e),s=l?o.get(l)?.shift():void 0,a=n??s;return a?{...e,renderedLines:[...a]}:e})}function na(e,t){return"custom"===e.role&&Array.isArray(t)&&t.every(e=>"string"==typeof e)?{...e,renderedLines:t}:e}function nd(e){for(let t of[e.thinking,e.text,e.reasoning])if("string"==typeof t&&t.length>0)return t;return""}function nc(e){return"thinking"===e||"reasoning"===e||"redacted_thinking"===e}function nu(e){let t={...e,type:"thinking",thinking:nd(e)};return!0===e.deferred&&(t.deferred=!0),t}let np=/<think(?:ing)?>([\s\S]*?)<\/think(?:ing)?>/gi,nh=/<think(?:ing)?>/i;function nf(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function ng(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>{let t=function(e){if(!nf(e)||"toolCall"!==e.type)return null;let t={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};return Array.isArray(e.renderedCallLines)&&e.renderedCallLines.every(e=>"string"==typeof e)&&(t.renderedCallLines=[...e.renderedCallLines]),"string"==typeof e.toolLabel&&""!==e.toolLabel.trim()&&(t.toolLabel=e.toolLabel),"self"===e.toolShell&&(t.toolShell="self"),t}(e);return t||(nf(e)&&nc(e.type)?nu(e):e)});return{...e,content:n}}let nm="pidance.binary",nx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function nv(e){let t;if(!e||"object"!=typeof e||Array.isArray(e)||"binary"!==e.type||1!==e.version||"string"!=typeof e.path)return null;let n=e.path.trim();if(!n||n.length>4096)return null;let r=function(e){if("string"!=typeof e)return null;let t=e.replace(/[\\/\0]/g,"_").trim();return!t||t.length>180?null:t}(e.name),i=function(e){if("string"!=typeof e)return null;let t=e.trim().toLowerCase();return nx.test(t)?t:null}(e.mimeType);if(!r||!i||"number"!=typeof e.size||!Number.isSafeInteger(e.size)||e.size<0)return null;let o=e.kind;if("image"!==o&&"audio"!==o&&"video"!==o&&"file"!==o||o!==((t=i.toLowerCase()).startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"))return null;let l=void 0===e.previewPath?void 0:"string"==typeof e.previewPath&&e.previewPath.trim().length<=4096?e.previewPath.trim()||void 0:null;if(null===l)return null;let s=void 0===e.messageEntryId?void 0:"string"==typeof e.messageEntryId&&e.messageEntryId.trim()?e.messageEntryId.trim():null;return null===s?null:{type:"binary",version:1,kind:o,path:n,name:r,mimeType:i,size:e.size,...l?{previewPath:l}:{},...s?{messageEntryId:s}:{}}}function ny(e){return"string"==typeof e?e:Array.isArray(e)?e.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):""}function nb(e,t,n){return{key:t||`disk:${n}`,message:e,entryId:t,pending:!1}}function nw(e,t){return{key:e,message:t,entryId:"",pending:!0}}function nk(e,t){return e.map((e,n)=>nb(e,t[n]??"",n))}function nj(e){return e.map(e=>e.entryId)}function nS(e,t){return e.find(e=>e.key===t)}function nC(e,t,n,r){let i=e.findIndex(e=>e.key===t);if(i<0)return null;let o=[...e];return o[i]={...o[i],message:n,entryId:r||o[i].entryId,pending:!1},o}function n_(e,t){let n=e.findIndex(e=>e.key===t);if(n<0)return{timeline:[...e],dropped:!1};let r=e[n];if(!r.pending||r.entryId)return{timeline:[...e],dropped:!1};let i=[...e];return i.splice(n,1),{timeline:i,dropped:!0}}function nI(e,t){let n=new Map;return e.forEach((e,r)=>{let i=t[r];if(!i||n.has(i))return;let o=no(e);o&&n.set(i,o)}),n}function nR(e,t){if(0===t.size)return e;let n=!1,r=e.map(e=>{let r=e.entryId?t.get(e.entryId):void 0;return!r||nT(e.message.renderedLines,r)?e:(n=!0,{...e,message:{...e.message,renderedLines:[...r]}})});return n?r:e}function nT(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((e,n)=>e===t[n])}function nE(){return{isStreaming:!1,streamingMessage:null}}function nM(e){if(0===e.themeLines.size&&0===e.themeSourceLines.size)return;let t=new Set(nj(e.timeline));for(let n of[...e.themeLines.keys()])t.has(n)||e.themeLines.delete(n);for(let n of[...e.themeSourceLines.keys()])t.has(n)&&e.themeLines.has(n)||e.themeSourceLines.delete(n)}function nA(e,t){tQ(e,{value:t.value,images:t.images})}let nL=null;function nz(){var e;let t,r,i,o,l,s,a,d,c,u,p,h,f,g,m,x,v,y,b,w,k,j,S,C,_,I,R,T;return nL||(t=(e={async createAndPrompt(e,t){let n=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,type:"prompt",message:t.message,submissionId:t.submissionId,...t.images?.length?{images:(0,t2.py)(t.images)}:{},...t.binaryBlocks?.length?{binaryBlocks:t.binaryBlocks}:{},...t.provider&&t.modelId?{provider:t.provider,modelId:t.modelId}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}),signal:t.signal}),r=await n.json().catch(()=>({}));if(!n.ok||r.error||!r.sessionId)throw Error(r.error??`HTTP ${n.status}`);if(!r.data||"object"!=typeof r.data||!r.data.status)throw Error("Invalid prompt receipt: expected a status");return{sessionId:r.sessionId,receipt:r.data}},async postPrompt(e,t){let{submitAgentPrompt:r}=await Promise.resolve().then(n.bind(n,32383));return r(e,t,{signal:t.signal})},async ensureNewSession(e,t){let n=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,type:"ensure_session",...t?.provider&&t.modelId?{provider:t.provider,modelId:t.modelId}:{}})}),r=await n.json().catch(()=>({}));if(!n.ok||!r.sessionId)throw Error(r.error??`HTTP ${n.status}`);return r.sessionId},async wake(e,t){let n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state?wake=1`,{signal:t});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error("string"==typeof e.error?e.error:`HTTP ${n.status}`)}},async getAgentState(e){let t=await fetch(`/api/agent/${encodeURIComponent(e)}?light=1`,{cache:"no-store"}),n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);return n},async cancelSubmission(e){let t=await fetch(`/api/agent/submissions/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"cancel"}),signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`HTTP ${t.status}`);return{status:"confirmed"===(await t.json().catch(()=>({}))).status?"confirmed":"pending"}}}).restoreDraft??nA,r=e.now??(()=>Date.now()),i=e.makeSubmissionId??nr,o=e.schedule??((e,t)=>setTimeout(e,t)),l=e.clearSchedule??(e=>clearTimeout(e)),s=new Map,a=!0,d=new Map,c=(e,t)=>{let n=s.get(e);if(n)return n;let r=d.get(e);if(void 0!==r){let t=s.get(r);if(t)return t;d.delete(e)}if(!t)return null;let i={sessionId:e,snapshot:{sessionId:e,messages:[],entryIds:[],messageKeys:[],hasMoreAfter:!1,streamState:nE(),agentRunning:!1,turnMetrics:{},bashRunning:!1,pendingBash:null,sendInFlight:!1,submissions:[],promptRunId:0,finishingRunId:null,completedRunId:null,streamRunSeq:null,attachCount:0,timelineSeq:0},submissions:new Map,inFlight:new Map,promptAborts:new Map,eventStream:null,attachments:new Set,viewHandlers:new Set,snapshotListeners:new Set,consumedEntryIds:new Set,timeline:[],derived:{source:null,messages:[],entryIds:[],messageKeys:[]},submissionKeys:new Map,localKeySeq:0,hydrateSeq:0,hydrateAppliedSeq:0,themeLines:new Map,themeSourceLines:new Map,hasMoreAfter:!1,idleCloseTimer:null,hiddenCloseTimer:null,sseRetryTimer:null,sseRetryAttempt:0,metrics:{}};return s.set(e,i),i},u=e=>{let t=new Set;for(let n of e.attachments)n.onEvent&&t.add(n.onEvent);e.viewHandlers=t},p=e=>{for(let t of(e.derived.source!==e.timeline&&(e.derived={source:e.timeline,messages:e.timeline.map(e=>e.message),entryIds:nj(e.timeline),messageKeys:e.timeline.map(e=>e.key)}),e.snapshot={...e.snapshot,sessionId:e.sessionId,messages:e.derived.messages,entryIds:e.derived.entryIds,messageKeys:e.derived.messageKeys,hasMoreAfter:e.hasMoreAfter,turnMetrics:{...e.metrics},submissions:[...e.submissions.values()],attachCount:e.attachments.size},e.snapshotListeners))t(e.snapshot)},h=e=>{e.idleCloseTimer&&(l(e.idleCloseTimer),e.idleCloseTimer=null),e.attachments.size>0||e.snapshot.agentRunning||e.snapshot.bashRunning||e.snapshot.sendInFlight||e.inFlight.size>0||(e.idleCloseTimer=o(()=>{e.idleCloseTimer=null,(e=>{if(e.idleCloseTimer&&(l(e.idleCloseTimer),e.idleCloseTimer=null),e.sseRetryTimer&&(l(e.sseRetryTimer),e.sseRetryTimer=null,e.sseRetryAttempt=0),e.attachments.size>0||e.snapshot.agentRunning||e.snapshot.bashRunning||e.snapshot.sendInFlight||e.inFlight.size>0)return;let t=e.eventStream;t&&(e.eventStream=null,t.close(),p(e))})(e),x()},5e3))},f=e=>{e.hiddenCloseTimer&&(l(e.hiddenCloseTimer),e.hiddenCloseTimer=null),e.eventStream&&(e.hiddenCloseTimer=o(()=>{let t;e.hiddenCloseTimer=null,e.hiddenCloseTimer&&(l(e.hiddenCloseTimer),e.hiddenCloseTimer=null),e.sseRetryTimer&&(l(e.sseRetryTimer),e.sseRetryTimer=null,e.sseRetryAttempt=0),(t=e.eventStream)&&(e.eventStream=null,t.close(),p(e))},3e5))},g=e=>{e.hiddenCloseTimer&&(l(e.hiddenCloseTimer),e.hiddenCloseTimer=null)},m=e=>!(e.attachments.size>0||e.snapshotListeners.size>0||e.snapshot.agentRunning||e.snapshot.bashRunning||e.snapshot.sendInFlight||e.inFlight.size>0||e.promptAborts.size>0||e.timeline.some(e=>e.pending))&&!(e.submissionKeys.size>0)&&0!==e.timeline.length,x=()=>{for(let[e,t]of[...s])if(m(t))for(let[n,r]of(t.eventStream?.close(),t.eventStream=null,s.delete(e),[...d]))(r===e||n===e)&&d.delete(n)},v=e=>{e.snapshot.timelineSeq+=1},y=e=>(e.localKeySeq+=1,`local:${e.localKeySeq}`),b=(e,t,n)=>{let r=n??"",i={...t,entryId:r};e.timeline=function(e,t){let n=e.length;for(;n>0;){let t=e[n-1];if(!t.pending||!0!==t.duringStreamingStep)break;n-=1}return n===e.length?[...e,t]:[...e.slice(0,n),t,...e.slice(n)]}(e.timeline,{key:r||y(e),message:i,entryId:r,pending:!1}),v(e)},w=(e,t)=>"persisted"===e?e:t,k=(e,t,n,r)=>{let i=e.submissions.get(t),o=n;i&&(o=w(i.status,n),i.status=o,i.error=r),e.snapshot.sendInFlight=e.inFlight.size>0,e.inFlight.size<=1&&i?.delivered!==!0&&("rejected"===o||"unknown"===o)&&(e.snapshot.agentRunning=!1,e.snapshot.completedRunId=e.snapshot.promptRunId,e.snapshot.streamState=nE())},j=(e,n,r,i)=>(k(e,n.submissionId,r,i),n.delivered)?(p(e),{submissionId:n.submissionId,sessionId:e.sessionId,status:"accepted"}):(C(e,n.submissionId),t(n.draftKey,{value:n.message,images:n.images??[]}),p(e),{submissionId:n.submissionId,sessionId:e.sessionId,status:r,error:i}),S=(e,t,n)=>(k(e,t.submissionId,"rejected","queued"),C(e,t.submissionId),p(e),{submissionId:t.submissionId,sessionId:e.sessionId,status:"queued",queue:n}),C=(e,t)=>{let n=e.submissionKeys.get(t);if(e.submissionKeys.delete(t),void 0===n)return!1;let r=n_(e.timeline,n);return!!r.dropped&&(e.timeline=r.timeline,v(e),!0)},_=(e,t)=>{let n=t.type,r=t.streamRunSeq,i="number"==typeof r?r:null,o=t.turnMetrics;if(o&&("number"==typeof o.tokensPerSecond||"number"==typeof o.ttftMs)&&(e.metrics={...o}),"connected"===n)null!==i&&(e.snapshot.streamRunSeq=i),!0===t.isStreaming&&(e.snapshot.agentRunning=!0,e.snapshot.streamState={isStreaming:!0,streamingMessage:null});else if("agent_start"===n)o||(e.metrics={}),e.snapshot.promptRunId+=1,e.snapshot.agentRunning=!0,null!==i&&(e.snapshot.streamRunSeq=i),e.snapshot.completedRunId=null,e.snapshot.finishingRunId=null,e.snapshot.streamState={isStreaming:!0,streamingMessage:null},e.metrics={};else if("agent_end"===n||"prompt_done"===n){if(null!==i&&null!==e.snapshot.streamRunSeq&&i<e.snapshot.streamRunSeq)return;null!==i&&(e.snapshot.streamRunSeq=i),e.snapshot.agentRunning=!1,e.snapshot.completedRunId=e.snapshot.promptRunId,e.snapshot.streamState=nE()}else if("message_start"===n||"message_update"===n){let n=t.message;if(!e.snapshot.agentRunning||n?.role==="user")return;if(n){let r=na(n,t.renderedLines);e.snapshot.streamState={isStreaming:!0,streamingMessage:ng(r)}}}else if("prompt_error"===n){var l;let t,n={timeline:t=(l=e.timeline).filter(e=>!(e.pending&&!e.entryId)),dropped:t.length!==l.length};if(n.dropped){for(let[t,r]of(e.timeline=n.timeline,e.submissionKeys))nS(e.timeline,r)||e.submissionKeys.delete(t);v(e)}}else if("message_end"===n){let n=t.message,r="string"==typeof t.entryId&&t.entryId?t.entryId:null;if(n?.role==="user"){if(r&&e.consumedEntryIds.has(r))return void p(e);r&&e.consumedEntryIds.add(r);let t=[...e.submissions.values()].find(t=>("accepted"===t.status||"submitting"===t.status)&&!t.entryId&&e.submissionKeys.has(t.submissionId)),i=t?e.submissionKeys.get(t.submissionId)??null:null,o=function(e,t){let{key:n,message:r,entryId:i,fallbackKey:o}=t,l=r.entryId===i?r:{...r,entryId:i},s=ny(l.content),a=function(e,t){if(0===t.length)return -1;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.pending&&"user"===r.message.role&&ny(r.message.content)===t)return n}return -1}(e,s);if(n){let t=a<0||e[a]?.key===n?nS(e,n):void 0;if(t?.pending){let t=nC(e,n,l,i);if(t)return{timeline:t,outcome:"key"}}if(i?e.some(e=>e.entryId===i):s.length>0&&e.some(e=>e.entryId&&ny(e.message.content)===s)){if(a>=0){let t=nC(e,e[a].key,l,i);if(t)return{timeline:t,outcome:"text"}}return{timeline:[...e],outcome:"reconciled"}}}if(a>=0){let t=nC(e,e[a].key,l,i);if(t)return{timeline:t,outcome:"text"}}return i&&e.some(e=>e.entryId===i)?{timeline:[...e],outcome:"duplicate"}:{timeline:[...e,{key:o,message:l,entryId:i,pending:!1}],outcome:"appended"}}(e.timeline,{key:i,message:n,entryId:r??"",fallbackKey:r??y(e)});"duplicate"!==o.outcome&&(e.timeline=o.timeline,v(e)),t&&(e.submissionKeys.delete(t.submissionId),"duplicate"!==o.outcome&&(t.delivered=!0),null!==r&&(t.status=w(t.status,"persisted"),t.entryId=r))}else if(n?.role==="custom"&&n.customType===nm){let t=nv(n.details),i=t?.messageEntryId?e.timeline.findIndex(e=>e.entryId===t.messageEntryId):-1;i<0&&t?.messageEntryId&&(i=e.timeline.findLastIndex(e=>"user"===e.message.role&&!e.entryId));let o=i>=0?e.timeline[i]:void 0;if(t&&o?.message.role==="user"){if(!(o.message.binaryBlocks??[]).some(e=>e.path===t.path&&e.previewPath===t.previewPath)){let n=[...e.timeline];n[i]={...o,message:{...o.message,binaryBlocks:[...o.message.binaryBlocks??[],t]}},e.timeline=n,v(e)}}else e.snapshot.agentRunning&&b(e,n,r)}else n&&e.snapshot.agentRunning&&b(e,ng(na(n,t.renderedLines)),r);e.snapshot.streamState=nE()}for(let n of(p(e),e.viewHandlers))try{n(t)}catch{}h(e)},I=[500,1500,3e3],R=t=>{if(!a)return;t.idleCloseTimer&&(l(t.idleCloseTimer),t.idleCloseTimer=null),t.sseRetryTimer&&(l(t.sseRetryTimer),t.sseRetryTimer=null,t.sseRetryAttempt=0);let n=t.eventStream?.getCurrentSource();if(t.eventStream&&n&&2!==n.readyState&&t.eventStream.isCurrent(t.sessionId))return;t.eventStream?.close(),t.eventStream=null;let r=e=>_(t,e),i=e.createEventStream?e.createEventStream(t.sessionId,r):function(e={}){let t=e.createEventSource??t5,n=e.getEventsUrl??(e=>`/api/agent/${encodeURIComponent(e)}/events`),r=e.connectTimeoutMs??5e3,i=e.reconnectDelayMs??1e3,o=e.shouldAutoReconnect??(()=>!1),l=e.schedule??((e,t)=>setTimeout(e,t)),s=e.clearSchedule??(e=>clearTimeout(e)),a=e.scheduleFrame??t8,d=e.cancelFrame??t3,c=null,u=null,p=null,h=null,f=null,g=()=>{null!==h&&(s(h),h=null)},m=()=>{c&&(c.close(),c=null),u?.(),u=null},x=(e,v)=>{g(),f?.(),f=null,m();let y=t(n(e));c=y,u=(0,t4.D)(y),p=e;let b=null,w=null,k=()=>{w=null;let e=b;if(b=null,e&&c===y)try{v(e)}catch{}};return f=()=>{null!==w&&d(w),w=null,b=null},new Promise(t=>{let n=!1,u=null,p=e=>{n||(n=!0,null!==u&&(s(u),u=null),t({status:e,source:y}))};u=l(()=>p("timeout"),r),y.onmessage=e=>{try{if(c!==y)return;let t=JSON.parse(e.data);if("connected"===t.type&&p("connected"),"message_update"===t.type){b=t,null===w&&(w=a(k));return}null!==w&&(d(w),w=null),k(),v(t)}catch{}},y.onerror=()=>{2===y.readyState&&(p("closed"),c===y&&o()&&(c=null,h=l(()=>{o()&&x(e,v)},i)))}})};return{connect:x,async ensureConnected(e,t){let n=await x(e,t);if("connected"!==n.status&&1!==n.source.readyState)throw c===n.source&&(c=null,f?.(),f=null),n.source.close(),new t6(n.status)},close:()=>{g(),f?.(),f=null,m(),p=null},getCurrentSource:()=>c,isCurrent:e=>null!==c&&p===e&&2!==c.readyState}}({shouldAutoReconnect:()=>{var e;return!!(e={agentRunning:t.snapshot.agentRunning,visibilityState:"u"<typeof document?void 0:document.visibilityState}).agentRunning&&(void 0===e.visibilityState||"hidden"!==e.visibilityState)}});t.eventStream=i,i.ensureConnected(t.sessionId,r).catch(()=>{if(t.eventStream===i&&(t.eventStream=null),!(t.attachments.size>0))return;let e=t.sseRetryAttempt;if(e>=I.length)return;let n=I[e];t.sseRetryAttempt=e+1,t.sseRetryTimer&&l(t.sseRetryTimer),t.sseRetryTimer=o(()=>{t.sseRetryTimer=null,!(t.attachments.size>0)||t.eventStream&&t.eventStream!==i||t.snapshot.agentRunning||t.snapshot.sendInFlight||R(t)},n)})},T=(e,t)=>{let n=c(e,!0),r=n.sessionId,i=s.get(t);return i&&i!==n&&(i.eventStream?.close(),i.eventStream=null,s.delete(t)),s.delete(r),r!==e&&d.delete(r),n.sessionId=t,n.snapshot.sessionId=t,s.set(t,n),e!==t&&d.set(e,t),n},nL={getSnapshot(e){let t=c(e,!1);return t?t.snapshot:null},subscribe(e,t){let n=c(e,!0);return n.snapshotListeners.add(t),t(n.snapshot),()=>{n.snapshotListeners.delete(t)}},attach(e,t){let n=c(e,!0),r={onEvent:t};n.attachments.add(r),u(n),R(n),p(n);let i=!1;return{sessionId:n.sessionId,dispose:()=>{i||(i=!0,n.attachments.delete(r),u(n),p(n),h(n))}}},detach(e,t){t.dispose()},async submitPrompt(t){var n,o,l,s,a;let d,u,f=t.submissionId?.trim()||i(),g="persisted"===t.target.kind?t.target.sessionId:ne(t.target.intentId),m=c(g,!0),x=m.submissions.get(f);if(x&&("accepted"===x.status||"persisted"===x.status||"submitting"===x.status))return{submissionId:f,sessionId:m.sessionId,status:"accepted"};let y=m.inFlight.get(f);if(y)return y;let b={submissionId:f,sessionId:g,draftKey:t.draftKey,message:t.message,images:t.images,binaryBlocks:t.binaryBlocks,status:"submitting",delivered:!1,entryId:null},w=new AbortController;m.submissions.set(f,b),m.promptAborts.set(f,w),m.snapshot.sendInFlight=!0,m.snapshot.agentRunning=!0,m.snapshot.promptRunId+=1,m.snapshot.completedRunId=null,m.snapshot.finishingRunId=null,m.snapshot.streamState={isStreaming:!0,streamingMessage:null},m.metrics={};let C=`sub:${f}`;a=m.timeline,m.timeline=[...a,nw(C,(n=t.message,o=t.images,l=t.binaryBlocks,s=r(),d=o?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...n.trim()?[{type:"text",text:n}]:[],...d]:n,timestamp:s},l?.length&&(u.binaryBlocks=l.map(e=>({type:"binary",version:1,kind:e.mimeType.toLowerCase().startsWith("image/")?"image":e.mimeType.toLowerCase().startsWith("audio/")?"audio":e.mimeType.toLowerCase().startsWith("video/")?"video":"file",...e}))),u))],m.submissionKeys.set(f,C),v(m),p(m);let _=(async()=>{let n=g,r=!1;try{if("new"===t.target.kind){if(e.createAndPrompt){let{sessionId:i,receipt:o}=await e.createAndPrompt(t.target.cwd,{message:t.message,images:t.images,binaryBlocks:t.binaryBlocks,submissionId:f,...t.model?.provider?{provider:t.model.provider,modelId:t.model.modelId}:{},...t.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{},signal:w.signal});if(w.signal.aborted)throw new DOMException("aborted","AbortError");if(n=i,b.sessionId=i,T(g,i),r=!0,"rejected"===o.status)return j(m,b,"rejected","rejected");if("queued"===o.status&&o.queue)return S(m,b,o.queue);return k(m,f,"accepted"),p(m),{submissionId:f,sessionId:n,status:"accepted"}}if(!e.ensureNewSession)return j(m,b,"rejected","no ensure implementation");let i=await e.ensureNewSession(t.target.cwd,t.model);if(w.signal.aborted)throw new DOMException("aborted","AbortError");n=i,b.sessionId=i,T(g,i),r=!0}!r&&e.wake&&await e.wake(n,w.signal),R(m);let i=await e.postPrompt(n,{message:t.message,images:t.images,binaryBlocks:t.binaryBlocks,submissionId:f,signal:w.signal});if("rejected"===i.status)return j(m,b,"rejected","rejected");if("queued"===i.status&&i.queue)return S(m,b,i.queue);return k(m,f,"accepted"),p(m),{submissionId:f,sessionId:n,status:"accepted"}}catch(e){if(e instanceof Error&&("AbortError"===e.name||w.signal.aborted))return j(m,b,"unknown","aborted");return j(m,b,"unknown",e instanceof Error?e.message:String(e))}finally{m.inFlight.delete(f),m.promptAborts.delete(f),m.snapshot.sendInFlight=m.inFlight.size>0,p(m),h(m)}})();return m.inFlight.set(f,_),_},cancellationFor(e){let t=c(e,!1);if(!t)return null;let n=[...t.promptAborts.entries()][0];if(!n)return null;let[r,i]=n;return{submissionId:r,cancel:()=>i.abort(),signal:i.signal}},async abortSubmission(t,n){let r=c(t,!1);if(!r)return null;let i=n??[...r.promptAborts.keys()][0],o=i?r.promptAborts.get(i):void 0,l=i?r.inFlight.get(i):void 0;if(o?.abort(),i&&e.cancelSubmission)try{await e.cancelSubmission(i)}catch{}return l||Promise.resolve(null)},abort(e){let t=c(e,!1);if(t){for(let e of t.promptAborts.values())e.abort();t.snapshot.agentRunning=!1,t.snapshot.streamState=nE(),t.snapshot.sendInFlight=t.inFlight.size>0,p(t),h(t)}},setBashRunning(e,t,n){let r=c(e,!0);r.snapshot.bashRunning=t,r.snapshot.pendingBash=t?n??null:null,p(r)},getRunState(e){let t=c(e,!1)?.snapshot;return t?{promptRunId:t.promptRunId,agentRunning:t.agentRunning,sendInFlight:t.sendInFlight,finishingRunId:t.finishingRunId,completedRunId:t.completedRunId}:null},beginRunFinish(e,t){let n=c(e,!1);if(!n)return!1;let r=n.snapshot;return r.promptRunId===t&&null===r.finishingRunId&&(!!r.agentRunning||r.completedRunId===t)&&(r.finishingRunId=t,p(n),!0)},releaseRunFinish(e,t){let n=c(e,!1);n&&n.snapshot.finishingRunId===t&&(n.snapshot.finishingRunId=null,p(n))},completeRun(e,t){let n=c(e,!1);return!!n&&n.snapshot.promptRunId===t&&(n.snapshot.agentRunning=!1,n.snapshot.completedRunId=t,n.snapshot.streamState=nE(),p(n),!0)},importRunningRun(e,t){let n=c(e,!0),i=n.snapshot;i.agentRunning||i.sendInFlight||(i.agentRunning=!0,i.completedRunId=null,i.finishingRunId=null,i.promptRunId+=1,i.streamState={isStreaming:!0,streamingMessage:null},"number"==typeof t&&Number.isFinite(t)&&t>0||r(),n.metrics={},p(n))},seedTurnMetrics(e,t){let n=c(e,!0);n.metrics=t?{...t}:{},p(n)},async reconcile(t){var n;let r=c(t,!1);if(!r||!e.getAgentState)return null;let i=r.snapshot.promptRunId,o=await e.getAgentState(t),l=c(t,!1);if(l!==r||l.snapshot.promptRunId!==i)return{runId:i,stale:!0,live:!1,shouldFinish:!1};let s=!0===o.live||void 0===o.live&&!0===o.running;s&&!l.eventStream?.isCurrent(t)&&R(l);let a=o.state,d=!1===o.activeRun&&!0!==o.lockedByOther;return{runId:i,stale:!1,live:s,shouldFinish:!!(n={sendInFlight:l.snapshot.sendInFlight,clientRunning:l.snapshot.agentRunning,live:s,knownIdleWithoutLive:d,isStreaming:a?.isStreaming===!0,isPromptRunning:a?.isPromptRunning===!0,isCompacting:a?.isCompacting===!0}).clientRunning&&!n.sendInFlight&&(!!n.live||!!n.knownIdleWithoutLive)&&!n.isStreaming&&!n.isPromptRunning&&!n.isCompacting,state:a}},beginHydrate(e){let t=c(e,!0);return t.hydrateSeq+=1,t.hydrateSeq},hydrate(e,t,n=[],r){var i;let o,l,s,a=c(e,!0),d=r?.hydrateRequestSeq??++a.hydrateSeq;if(d<=a.hydrateAppliedSeq)return"superseded";if(r?.sinceSeq!==void 0&&a.snapshot.timelineSeq>r.sinceSeq)return"stale";a.hydrateSeq=Math.max(a.hydrateSeq,d),a.hydrateAppliedSeq=d,r?.hasMoreAfter!==void 0&&(a.hasMoreAfter=r.hasMoreAfter);let u=a.themeLines.size>0?nI(t,n):new Map,h=r?.mode??"replace",f=a.timeline,g="prepend"===h?function(e,t,n){let r=new Set(e.map(e=>e.entryId).filter(Boolean)),i=[];for(let e=0;e<n.length;e++){let o=n[e]??"";o&&r.has(o)||i.push(nb(t[e],o,e))}return 0===i.length?[...e]:[...i,...e]}(f,t,n):"tail"===h?function(e,t,n){if(0===n.length)return[...e];let r=nk(t,n),i=e.map(e=>e.entryId);if(i.every(e=>!e))return r;if(function(e,t){let n=t.filter(Boolean);if(0===n.length)return!1;let r=new Set(e.filter(Boolean));if(!n.every(e=>r.has(e)))return!1;let i=[...e].reverse().find(Boolean)??null,o=n[n.length-1];return null!==i&&o!==i}(i,n))return[...e];let o=r[0].entryId,l=o?i.indexOf(o):-1;return l<=0?r:[...e.slice(0,l),...r]}(f,t,n):nk(t,n),m="drop"===("retain"===(i=r?.pending)||"drop"===i?i:"replace"===h?"drop":"retain")?g:(o=new Set(g.map(e=>e.key)),l=function(e,t){let n=new Set(e.map(e=>e.entryId).filter(Boolean)),r=[...e].reverse().find(e=>e.entryId),i=0;if(r){let e=t.findIndex(e=>e.entryId===r.entryId);if(e<0)return 0;i=e+1}else for(let e=t.length-1;e>=0;e--)if(t[e].entryId&&"assistant"===t[e].message.role){i=e+1;break}let o=0;for(let e=i;e<t.length;e++){let r=t[e];r.entryId&&!n.has(r.entryId)&&"user"===r.message.role&&(o+=1)}return o}(f,g),0===(s=f.filter(e=>!(!e.pending||e.entryId||o.has(e.key))&&("user"!==e.message.role||!(l>0)||(l-=1,!1)))).length?g:[...g,...s]),x=m;if(u.size>0){let e=new Map;for(let[t,n]of u){let r=a.themeSourceLines.get(t),i=a.themeLines.get(t);r&&i&&nT(n,r)?e.set(t,i):(a.themeLines.delete(t),a.themeSourceLines.delete(t))}e.size>0&&(x=nR(m,e))}for(let e of(a.timeline=[...x],nM(a),nj(a.timeline)))e&&a.consumedEntryIds.add(e);return p(a),"applied"},refreshRenderedLines(e,t,n=[]){let r=c(e,!1);if(!r)return!1;let i=nI(t,n);if(0===i.size)return!1;let o=function(e){let t=new Map;for(let n of e){if(!n.entryId||t.has(n.entryId))continue;let e=no(n.message);e&&t.set(n.entryId,e)}return t}(r.timeline);for(let[e,t]of i){r.themeLines.set(e,t);let n=o.get(e);n&&!nT(n,t)?r.themeSourceLines.set(e,n):r.themeSourceLines.delete(e)}let l=nR(r.timeline,r.themeLines);return nM(r),l!==r.timeline&&(r.timeline=[...l],p(r),!0)},appendLocal(e,t){var n;let r=c(e,!0),i=y(r),o=!0===r.snapshot.agentRunning,l=o?{...t,_duringStreamingStep:!0}:t;return n=r.timeline,r.timeline=[...n,{...nw(i,l),...o?{duringStreamingStep:!0}:{}}],v(r),p(r),i},dropLocal(e,t){let n=c(e,!1);if(!n)return!1;let r=n_(n.timeline,t);return!!r.dropped&&(n.timeline=r.timeline,v(n),p(n),!0)},applyEvent(e,t){_(c(e,!0),t)},hasActiveEventStream(e){let t=c(e,!1);return t?.eventStream?.isCurrent(e)===!0},ensureEventsConnected(e){R(c(e,!0))},setTabVisibility(e){for(let t of(a=e,s.values()))e?g(t):f(t)},getEventSource:e=>c(e,!1)?.eventStream?.getCurrentSource()??null,getSubmission:(e,t)=>c(e,!1)?.submissions.get(t),resetForTests(){nL=null},debugSlotCount:()=>s.size,debugSlotIds:()=>[...s.keys()]}),nL}function nW(e){let t=new Set;if(!Array.isArray(e))return t;for(let n of e)if(n&&"object"==typeof n){let e=n.sessionId;"string"==typeof e&&e&&t.add(e)}return t}function n$({selectedSessionId:e,onSelectSession:t,onNewSession:n,initialSessionId:o,skipInitialProjectSelection:l,onInitialRestoreDone:c,restoreNonce:u=0,refreshKey:p,onSessionDeleted:k,onProjectAdded:j,onProjectRootsChange:S,catalogStore:C}){let{t:_}=(0,eU.s9)(),I=(0,i.useRef)(C??null);I.current||(I.current=C??tJ()),C&&(I.current=C);let R=I.current,[T,E]=(0,i.useState)(0),M=(0,i.useRef)(e);M.current=e;let A=(0,i.useMemo)(()=>R.getSnapshot(M.current),[T,e]),L=A.sessions,z=A.serverListLoaded,W=A.loading,P=A.error,[F,N]=(0,i.useState)(!1),B=A.archivedSessions,O=A.runningIds,U=(0,i.useRef)(L);U.current=L;let V=(0,i.useRef)(0),{cwd:Y}=eO(),{setIdentity:X}=eB(),[G,Z]=(0,i.useState)(""),[Q,ee]=(0,i.useState)(!1),[et,en]=(0,i.useState)(null),[er,ei]=(0,i.useState)(null),eo=(0,i.useRef)(!0),[el,es]=(0,i.useState)(!1),ea=A.effectiveRunningIds,[ed,eu]=(0,i.useState)(!1),[ef,eg]=(0,i.useState)(null),[ex,ev]=(0,i.useState)(null),{runningChildIds:ey,bySessionId:eb}=eT(),ew=(0,i.useMemo)(()=>[...eb.keys()],[eb]),ek=(0,i.useMemo)(()=>{let e=new Set(ey);for(let t of L)t.subagent?.parentSessionId&&ey.has(t.id)&&e.add(t.subagent.parentSessionId);return e},[ey,L]),[ej,eC]=(0,i.useState)(()=>new Set),[e_,eI]=(0,i.useState)(()=>Date.now()),[eR,eE]=(0,i.useState)(()=>new Map),eD=ea.size>0||ek.size>0;(0,i.useEffect)(()=>{if(!eD)return;let e=setInterval(()=>eI(Date.now()),1e3);return()=>clearInterval(e)},[eD]),(0,i.useEffect)(()=>{let e=Date.now();eI(e),eE(t=>(function(e,t,n,r){let i=new Map,o=e.size!==t.length;for(let l of t){let t=function(e,t){let n=e?.get(t);return"number"==typeof n?n:void 0}(n,l)??e.get(l)??r;e.get(l)!==t&&(o=!0),i.set(l,t)}return o?i:e})(t,[...ea,...ek],A.runningStartedAt,e))},[ea,ek,A.runningStartedAt]);let eN=A.unreadIds,[eK,eJ]=(0,i.useState)(""),[eY,eZ]=(0,i.useState)(!1),[e0,e3]=(0,i.useState)("meta"),[e7,te]=(0,i.useState)([]),[tn,ti]=(0,i.useState)([]),[tl,ta]=(0,i.useState)(null),[td,tc]=(0,i.useState)(!1),[tu,tf]=(0,i.useState)(null),tg=(0,i.useRef)(0),tm=(0,i.useRef)(null),[tx,tv]=(0,i.useState)(!1),[ty,tb]=(0,i.useState)(null),tw=(0,i.useRef)(null),tk=(0,i.useRef)(null),tj=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!tx||!tj.current)return;let e=requestAnimationFrame(()=>{let e=tk.current,t=tj.current;if(!e||!t)return;let n=e.offsetHeight;t.bottom+4+n<=window.innerHeight||tb(e=>e?{...e,top:Math.max(8,t.top-n-4)}:e)});return()=>cancelAnimationFrame(e)},[tx]);let[tS,tC]=(0,i.useState)(()=>q()),t_=(0,i.useRef)(0),tI=(0,i.useRef)(null),tR=(0,i.useRef)(function(){try{return null!==window.localStorage.getItem($)}catch{return!1}}()),tT=(0,i.useRef)({}),[tL,tz]=(0,i.useState)({}),[tW,t$]=(0,i.useState)(()=>new Set),tP=(0,i.useRef)(new Set),tH=(0,i.useRef)(null),tB=(0,i.useRef)(!1),tO=(0,i.useRef)(null),tK=(0,i.useRef)(new Set),tV=(0,i.useRef)(new Set),tY=em(),tX=(0,i.useRef)(!1),tG=(0,i.useRef)(0),tZ=(0,i.useRef)(0),tQ=(0,i.useRef)(null),t0=(0,i.useCallback)((e,t)=>{tG.current+=1;let n=[...e],r=nz(),i=[...R.getState().startingIds].filter(e=>r.getRunState(e)?.sendInFlight===!0);R.applyRunningSnapshot({runningIds:n,runningStartedAt:t,selectedSessionId:M.current,localInFlightIds:i,now:Date.now()})},[R]),t1=(0,i.useCallback)(e=>{tC(t=>{let n=e(t);if(n!==t){let e={...n,sidebarWidth:q().sidebarWidth};if(K(e),tR.current){let n=J(t),r=J(e),i=[];for(let e of Object.keys(r))if(JSON.stringify(n[e])!==JSON.stringify(r[e])){if("projectOrder"===e){i.push({key:`sidebarUi.${e}`,op:"set",value:r[e]});continue}if(x.has(e)){let t=Array.isArray(n[e])?n[e]:[],o=Array.isArray(r[e])?r[e]:[];for(let n of o.filter(e=>!t.includes(e)))i.push({key:`sidebarUi.${e}`,op:"add",value:n});for(let n of t.filter(e=>!o.includes(e)))i.push({key:`sidebarUi.${e}`,op:"remove",value:n});continue}(0,eA.dM)(`sidebarUi.${e}`,r[e]??null)}i.length>0&&(0,eA.ss)(i)}}return n})},[]),t2=(0,eA.Fd)(),t4=(0,i.useMemo)(()=>{let e=t2.projectAliases,t="object"!=typeof e||null===e||Array.isArray(e)?{}:e;return{...tS.projectAliases,...t}},[tS.projectAliases,t2]);(0,i.useEffect)(()=>{let e=t2.sidebarUi;void 0!==e&&tC(t=>{let n=function(e,t){if("object"!=typeof t||null===t||Array.isArray(t))return e;let n=H({...e,...t}),r=void 0!==t.projectRoots,i=r?null:D({added:t.addedProjectRoots,closed:t.closedProjectRoots,hasProjectRoots:!1}),o=null!==i&&0===e.projectRoots.length;return{...e,displayMode:n.displayMode,collapsedProjectRoots:n.collapsedProjectRoots,projectRoots:o?i.projectRoots:n.projectRoots,projectRootsMigrated:!r&&(e.projectRootsMigrated||o),showRecentSessions:n.showRecentSessions,pinnedSessionIds:n.pinnedSessionIds,projectSort:n.projectSort,projectOrder:n.projectOrder,ungroupedSessionIds:n.ungroupedSessionIds}}(t,e),r=JSON.stringify(J(t))===JSON.stringify(J(n));return(tR.current=!0,r&&t.projectRootsMigrated===n.projectRootsMigrated)?t:(K({...n,sidebarWidth:q().sidebarWidth}),n)})},[t2]);let t6=tS.displayMode,t5=tS.showRecentSessions,[t8,t3]=(0,i.useState)(5),t9=(0,i.useMemo)(()=>new Set(tS.collapsedProjectRoots),[tS.collapsedProjectRoots]);(0,i.useEffect)(()=>{S?.(tS.projectRoots)},[tS.projectRoots,S]),(0,i.useEffect)(()=>R.subscribe(()=>E(e=>e+1)),[R]);let t7=(0,i.useCallback)(async(e=!1)=>{let t=++V.current;if(e&&0===U.current.length&&!z){let e=ep();if(e&&e.length>0){if(!eo.current||!eF(t,V.current))return;R.applyServerList({sessions:e,archivedSessions:[],archivedCount:0,provisional:!0})}}R.beginListLoad();try{let n=await fetch("/api/sessions",{signal:AbortSignal.timeout(1e4)});if(!eo.current||!eF(t,V.current))return;if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(!eo.current||!eF(t,V.current))return;R.applyServerList({sessions:r.sessions,archivedSessions:r.archivedSessions??[],archivedCount:r.archivedCount??0,runningSessionIds:r.runningSessionIds,runningStartedAt:r.runningStartedAt,selectedSessionId:M.current,now:Date.now()}),eh(r.sessions),t_.current=0,tI.current&&(clearTimeout(tI.current),tI.current=null),e||(es(!0),tQ.current&&clearTimeout(tQ.current),tQ.current=setTimeout(()=>{eo.current&&es(!1)},2e3))}catch(e){if(!eo.current||!eF(t,V.current))return;if(t_.current<2){let e=t_.current+1;t_.current=e,tI.current&&clearTimeout(tI.current),tI.current=setTimeout(()=>{tI.current=null,eo.current&&ne.current(!1)},2e3*e);return}R.applyListError(String(e))}},[R,z,U]),ne=(0,i.useRef)(t7);ne.current=t7;let nt=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!nt.current;nt.current=!0,ne.current(e)},[p]);let nn=(0,i.useRef)({lastKey:"",attempts:0,lastAttemptAt:0});(0,i.useEffect)(()=>{let e=new Set(U.current.map(e=>e.id)),t=function(e){let t=[...e.missingIds].filter(Boolean).sort().join(",");if(!t)return{fire:!1,lastKey:"",attempts:0,lastAttemptAt:0};let n=e.maxAttempts??3,r=e.cooldownMs??4e3;return t!==e.lastKey?{fire:!0,lastKey:t,attempts:1,lastAttemptAt:e.now}:e.attempts>=n||e.now-e.lastAttemptAt<r?{fire:!1,lastKey:t,attempts:e.attempts,lastAttemptAt:e.lastAttemptAt}:{fire:!0,lastKey:t,attempts:e.attempts+1,lastAttemptAt:e.now}}({missingIds:ew.filter(t=>!e.has(t)),lastKey:nn.current.lastKey,attempts:nn.current.attempts,lastAttemptAt:nn.current.lastAttemptAt,now:Date.now()});nn.current={lastKey:t.lastKey,attempts:t.attempts,lastAttemptAt:t.lastAttemptAt},t.fire&&ne.current(!1)},[ew,L]),(0,i.useEffect)(()=>{let e=eM({perform:()=>ne.current(!1)}),t=()=>{"visible"===document.visibilityState&&e.notify()};return document.addEventListener("visibilitychange",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("focus",t),e.dispose()}},[]),(0,i.useEffect)(()=>{!tS.projectRootsMigrated||(0,eA.Vg)()&&t1(e=>e.projectRootsMigrated?{...e,projectRoots:e.projectRoots,projectRootsMigrated:!1}:e)},[tS.projectRootsMigrated,t2,t1]),(0,i.useEffect)(()=>{let e=(0,eq.zD)((0,eq.AR)(window.localStorage),(0,eq.mD)((0,eA.b3)("unreadSessionState")));R.replaceUnread(e)},[R,t2]),(0,i.useEffect)(()=>{let e=R.getState().unread;(0,eq.R)(window.localStorage,e);let t=tT.current;for(let[n,r]of Object.entries(e.readAt))t[n]!==r&&L.some(e=>e.id===n)&&(t[n]=r,(0,eA.dM)(`unreadSessionState.readAt.${n}`,r))},[L,T,R]),(0,i.useEffect)(()=>(0,ec.RD)(e=>{e&&"running"===e.type&&(tX.current=!0,t0(Array.isArray(e.runningSessionIds)?e.runningSessionIds.filter(e=>"string"==typeof e):[],e.runningStartedAt&&"object"==typeof e.runningStartedAt?e.runningStartedAt:void 0),eC(nW(e.pendingExtensionUi)))}),[t0]),(0,i.useEffect)(()=>{let e=eM({perform:()=>{if("visible"!==document.visibilityState)return;let e=++tZ.current,t=tG.current;fetch("/api/agent/running",{cache:"no-store"}).then(e=>e.json()).then(n=>{!Array.isArray(n.runningSessionIds)||eo.current&&(0,eq._i)(t,tG.current,e,tZ.current)&&(tX.current=!0,t0(n.runningSessionIds.filter(e=>"string"==typeof e),n.runningStartedAt&&"object"==typeof n.runningStartedAt?n.runningStartedAt:void 0),eC(nW(n.pendingExtensionUi)))}).catch(()=>void 0)}}),t=()=>{"visible"===document.visibilityState&&e.notify()};return window.addEventListener("focus",t),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("focus",t),document.removeEventListener("visibilitychange",t),e.dispose()}},[t0]),(0,i.useEffect)(()=>{el&&eS()},[el]),(0,i.useEffect)(()=>{let t=[...tK.current].filter(e=>!O.has(e));if(t.length>0)for(let r of t){var n;if(r.startsWith("__new__")||!((n={hidden:"hidden"===document.visibilityState,sessionId:r,visibleSessionId:e,notificationsEnabled:!0}).notificationsEnabled&&n.hidden&&n.sessionId&&n.sessionId!==n.visibleSessionId&&1))continue;let t=U.current.find(e=>e.id===r)?.name||U.current.find(e=>e.id===r)?.firstMessage||r;try{tY?.notify(_("desktop_runFinishedTitle"),_("desktop_runFinishedBody",{title:t}))}catch{}}tK.current=new Set(O),tV.current=new Set(ea)},[tY,ea,O,e,_]);let nr=(0,i.useRef)(new Set);(0,i.useEffect)(()=>{let e=nr.current,t=[...O].filter(t=>!e.has(t));nr.current=new Set(O),t.length>0&&t7(!1)},[O,t7]),(0,i.useEffect)(()=>{e&&R.markRead(e)},[e,R]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&Z(e.home)}).catch(()=>{})},[]);let ni=(0,i.useRef)(!1);(0,i.useEffect)(()=>{ni.current=!1},[u]),(0,i.useEffect)(()=>()=>{eo.current=!1,tI.current&&clearTimeout(tI.current)},[]);let no=(0,i.useCallback)(e=>{X({cwd:e,status:e?"ready":"idle",error:null})},[X]),[nl,ns]=(0,i.useState)(null);(0,i.useEffect)(()=>{ns(null)},[Y]),(0,i.useEffect)(()=>{if(!l||o){if(o&&!ni.current){if(P&&z){ni.current=!0,c?.({error:P});return}if(!z)return;let e=L.find(e=>e.id===o);if(e){ni.current=!0,t(e,!0),c?.({found:!0});return}ni.current=!0,c?.({found:!1});return}if(0!==L.length&&null===Y){let e=(function(e){let t=new Map;for(let n of e){let e=n.cwd,r=t.get(e);(!r||n.modified>r)&&t.set(e,n.modified)}return[...t.entries()].sort((e,t)=>t[1].localeCompare(e[1])).map(([e])=>e)})(L).filter(e=>tS.projectRoots.includes(e));e[0]&&no(e[0])}}},[L,Y,o,l,t,c,no,tS.projectRoots,z,P,u]);let na=(0,i.useCallback)(()=>{ee(!1)},[]),nd=(0,i.useCallback)(e=>{t1(t=>t.projectRoots.includes(e)?t:{...t,projectRoots:[...t.projectRoots,e]}),na(),j?.(e),no(e),n?.(e)},[t1,na,j,no,n]),nc=(0,i.useCallback)(()=>{ee(!0)},[]);(0,i.useEffect)(()=>{if(!tx)return;let e=e=>{!tw.current||tw.current.contains(e.target)||tk.current?.contains(e.target)||tv(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[tx]);let nu=(0,i.useCallback)(e=>{t(e)},[t]),np=(0,i.useCallback)(e=>{t1(t=>t.pinnedSessionIds.includes(e)?{...t,pinnedSessionIds:t.pinnedSessionIds.filter(t=>t!==e)}:t),R.markDeleted(e),k?.(e),t7()},[R,k,t7,t1]),nh=(0,i.useCallback)(async e=>{if(null===ef){eg(e),ev(null);try{let t=await function(e,t=fetch){return tN(`/api/sessions/${encodeURIComponent(e)}/archive`,{method:"POST"},t)}(e);if(!t.ok){let e=tU(t);ev("running"===e?_("archive_runningConflict"):"readOnly"===e?_("archive_readOnlyForbidden"):"network"===e?_("archive_networkError"):t.error??_("archive_unknownError"));return}t1(t=>t.pinnedSessionIds.includes(e)?{...t,pinnedSessionIds:t.pinnedSessionIds.filter(t=>t!==e)}:t),t7()}catch(e){ev(e instanceof Error?e.message:String(e))}finally{eg(null)}}},[ef,t7,_,t1]),nf=(0,i.useCallback)(()=>{eu(e=>(e||ev(null),!e))},[]),ng=(0,i.useCallback)(e=>{t1(t=>t.showRecentSessions===e?t:{...t,showRecentSessions:e})},[t1]),nm=(0,i.useMemo)(()=>new Set(tS.pinnedSessionIds),[tS.pinnedSessionIds]),nx=(0,i.useMemo)(()=>new Set(tS.ungroupedSessionIds),[tS.ungroupedSessionIds]),nv=(0,i.useMemo)(()=>(function(e){let{sessions:t,pinnedSessionIds:n}=e,r=new Map;for(let e of t)e.subagent||r.set(e.id,e);let i=[],o=new Set;for(let e of n){let t=r.get(e);!t||o.has(e)||(o.add(e),i.push(t))}return i})({sessions:L,pinnedSessionIds:tS.pinnedSessionIds}),[L,tS.pinnedSessionIds]),ny=(0,i.useCallback)(e=>{t1(t=>t.pinnedSessionIds.includes(e)?{...t,pinnedSessionIds:t.pinnedSessionIds.filter(t=>t!==e)}:{...t,pinnedSessionIds:[e,...t.pinnedSessionIds]})},[t1]),nb=(0,i.useMemo)(()=>(function(e){let{sessions:t,excludeIds:n,limit:r=20}=e,i=Math.max(0,Math.floor(r));return t.filter(e=>!(e.subagent||n?.has(e.id))).slice().sort(eP).slice(0,i)})({sessions:L,excludeIds:nm,limit:20}),[L,nm]);(0,i.useEffect)(()=>{t3(e=>0===nb.length?5:Math.min(Math.max(e,5),nb.length))},[nb.length]);let nw=(0,i.useCallback)((e=Y)=>{e&&(no(e),n?.(e))},[Y,n,no]),nk=(0,i.useCallback)(()=>{eJ(""),te([]),ti([]),ta(null),tf(null),tc(!1),tg.current+=1},[]),nj=(0,i.useCallback)(()=>{eY?(eZ(!1),nk()):(eZ(!0),setTimeout(()=>tm.current?.focus(),0))},[eY,nk]);(0,i.useEffect)(()=>{if(!eY||"fulltext"!==e0)return void tc(!1);let e=eK.trim();if(!e){te([]),ti([]),ta(null),tf(null),tc(!1);return}let t=++tg.current;tc(!0),tf(null);let n=setTimeout(()=>{(async()=>{try{let n=await fetch(`/api/sessions/search?q=${encodeURIComponent(e)}&limit=40`),r=await n.json().catch(()=>({}));if(t!==tg.current)return;if(!n.ok||r.error){tf(r.error??`HTTP ${n.status}`),te([]),ti([]),ta(null);return}te(r.hits??[]),ti(r.sessionIds??[]),ta(r.source??null)}catch(e){if(t!==tg.current)return;tf(e instanceof Error?e.message:String(e)),te([]),ti([]),ta(null)}finally{t===tg.current&&tc(!1)}})()},280);return()=>clearTimeout(n)},[eY,e0,eK]);let nS=(0,i.useMemo)(()=>(function(e,t={}){let{selectedCwd:n=null}=t,r=new Set(t.projectRoots??[]),i=m(t.ungroupedSessionIds),o=new Map;for(let t of e){if(i.has(t.id)||!r.has(t.cwd))continue;let e=o.get(t.cwd);e?e.push(t):o.set(t.cwd,[t])}for(let e of r)o.has(e)||o.set(e,[]);let l=[];for(let[e,t]of o)l.push({root:e,tree:h(t),latestActivity:function(e){let t="";for(let n of e)n.modified>t&&(t=n.modified);return t}(t)});return l.sort((e,t)=>e.latestActivity||t.latestActivity?e.latestActivity?t.latestActivity?t.latestActivity.localeCompare(e.latestActivity):t.root===n?1:-1:e.root===n?-1:1:e.root.localeCompare(t.root)),l})(L,{selectedCwd:Y,projectRoots:tS.projectRoots,ungroupedSessionIds:nx}),[L,Y,tS.projectRoots,nx]),nC=(0,i.useMemo)(()=>(function(e,t={}){return h(function(e,t={}){let n=new Set(t.projectRoots??[]),r=m(t.ungroupedSessionIds);return e.filter(e=>r.has(e.id)||!n.has(e.cwd))}(e,t))})(L,{projectRoots:tS.projectRoots,ungroupedSessionIds:nx}),[L,tS.projectRoots,nx]),n_=(0,i.useMemo)(()=>{let e=new Map,t=n=>{for(let r of n)e.set(r.session.id,r),r.children.length>0&&t(r.children)};for(let e of nS)t(e.tree);return t(nC),e},[nS,nC]),nI=eK.trim().toLowerCase(),nR="fulltext"===e0&&nI.length>0,nT=(0,i.useMemo)(()=>nR?new Set(tn):null,[nR,tn]),nE=nR?tn.length>0||td||!!tu:nI.length>0,nM=(0,i.useMemo)(()=>(function(e,t){let{mode:n,order:r=[],aliases:i,selectedRoot:o=null}=t,l=[...e];if("az"===n||"za"===n)return l.sort((e,t)=>{let r=y.compare(b(e,i),b(t,i));return"az"===n?r:-r}),l;if("fixed"===n){let e=new Map(r.map((e,t)=>[e,t]));return l.sort((t,n)=>{let r=e.has(t.root)?e.get(t.root):Number.MAX_SAFE_INTEGER,i=e.has(n.root)?e.get(n.root):Number.MAX_SAFE_INTEGER;return r!==i?r-i:n.latestActivity.localeCompare(t.latestActivity)}),l}return l.sort((e,t)=>e.latestActivity||t.latestActivity?e.latestActivity?t.latestActivity?t.latestActivity.localeCompare(e.latestActivity):t.root===o?1:-1:e.root===o?-1:1:e.root.localeCompare(t.root)),l})(nS,{mode:tS.projectSort,order:tS.projectOrder,aliases:t4,selectedRoot:Y}),[nS,tS.projectSort,tS.projectOrder,t4,Y]),nA=(0,i.useMemo)(()=>(function(e,t,n,r){let i=null!=r;if(!i&&!t)return e;let o=[];for(let l of e){if(!i){let e=n?.[l.root];if(l.root.toLowerCase().includes(t)||void 0!==e&&e.toLowerCase().includes(t)){o.push(l);continue}}let e=i?w(l.tree,r):f(l.tree,t);e.length>0&&o.push({...l,tree:e})}return o})(nM,nR?"":nI,t4,nT),[nM,nI,t4,nT,nR]),nL=(0,i.useMemo)(()=>nR?w(nC,nT??new Set):f(nC,nI),[nC,nR,nT,nI]),nP=!nE&&t9.has(v),nF=(0,i.useCallback)((e,n)=>{let r=L.find(t=>t.id===e);r&&t(r,!1,n??null)},[L,t]);(0,i.useEffect)(()=>{let t;if(!e)return;let n=function(e,t){for(let n of e){let e=g(n.tree,t);if(e.length>0)return{projectRoot:n.root,ancestors:e};if(n.tree.some(e=>e.session.id===t))return{projectRoot:n.root,ancestors:[]}}return null}(nS,e),r=n?null:(t=g(nC,e)).length>0?t:nC.some(t=>t.session.id===e)?[]:null;if(!n&&null===r)return;let i=n?n.projectRoot:v,o=n?n.ancestors:r??[];if(t1(e=>e.collapsedProjectRoots.includes(i)?{...e,collapsedProjectRoots:e.collapsedProjectRoots.filter(e=>e!==i)}:e),o.length>0){for(let e of o)tP.current.add(e);t$(e=>{if(!o.some(t=>e.has(t)))return e;let t=new Set(e);return o.forEach(e=>t.delete(e)),t})}},[e,nS,nC,t1]),(0,i.useLayoutEffect)(()=>{if(!e)return;let t=tO.current!==e;tO.current=e;let n=tH.current;if(!n)return;let r=Array.from(n.querySelectorAll("[data-session-id]")).filter(t=>t.dataset.sessionId===e);if(0===r.length)return;let i=!tB.current&&o===e,l=n.getBoundingClientRect(),s=r.find(e=>{let t=e.getBoundingClientRect();return t.bottom>l.top&&t.top<l.bottom});!i&&(s||!t)||((s??r.map(e=>{let t=e.getBoundingClientRect();return{el:e,distance:Math.min(Math.abs(t.top-l.top),Math.abs(t.bottom-l.bottom))}}).sort((e,t)=>e.distance-t.distance)[0].el).scrollIntoView({block:"nearest"}),i&&(tB.current=!0))},[e,o,nA]);let nH=(0,i.useCallback)(e=>{tP.current.add(e),t$(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),nD=(0,i.useCallback)(e=>{t1(t=>({...t,collapsedProjectRoots:t.collapsedProjectRoots.includes(e)?t.collapsedProjectRoots.filter(t=>t!==e):[...t.collapsedProjectRoots,e]}))},[t1]),nN=(0,i.useCallback)(()=>{nD(v)},[nD]),nB=(0,i.useCallback)(e=>{let t;if(en(null),t=ea instanceof Set?ea:new Set(ea),L.some(n=>n.cwd===e&&t.has(n.id)))return void ns({root:e,message:_("sidebar_closeProjectRunning")});ns(null);let r=L.filter(t=>t.cwd===e).map(e=>e.id);if(t1(t=>{if(!t.projectRoots.includes(e)&&0===r.length)return t;let n=new Set(t.ungroupedSessionIds),i=r.filter(e=>!n.has(e));return{...t,projectRoots:t.projectRoots.filter(t=>t!==e),ungroupedSessionIds:i.length>0?[...t.ungroupedSessionIds,...i]:t.ungroupedSessionIds}}),Y===e){let t=function(e,t,n){for(let r of e)if(r.root!==t&&!n.has(r.root))return r.root;return null}(nS,e,new Set);t?no(t):(no(null),n?.())}},[Y,nS,t1,no,n,L,ea,_]),nO=(0,i.useCallback)(e=>{en(null),ei(e)},[]),nU=(0,i.useCallback)(e=>{if(!er)return;let t=e.trim();if(!t)return;ei(null);let n={...t4};t===d(er)?delete n[er]:n[er]=t,t1(e=>({...e,projectAliases:n})),(0,eA.dM)("projectAliases",n)},[er,t4,t1]),nq=(0,i.useCallback)(e=>{t1(t=>t.displayMode===e?t:{...t,displayMode:e})},[t1]),nK=(0,i.useCallback)(e=>{t1(t=>{if(t.projectSort===e&&"fixed"!==e)return t;let n="fixed"===e?t.projectOrder.length>0?t.projectOrder:nA.map(e=>e.root):t.projectOrder;return{...t,projectSort:e,projectOrder:n}})},[t1,nA]),nJ=(0,i.useCallback)((e,t)=>{e&&t&&e!==t&&t1(n=>{let r,i,o,l="fixed"===n.projectSort&&n.projectOrder.length>0?[...n.projectOrder]:nA.map(e=>e.root);for(let e of nA)l.includes(e.root)||l.push(e.root);return l.includes(e)||l.push(e),l.includes(t)||l.push(t),{...n,projectSort:"fixed",projectOrder:(i=(r=[...l]).indexOf(e),o=r.indexOf(t),i<0||o<0||i===o||(r.splice(i,1),r.splice(o,0,e)),r)}})},[t1,nA]),nV=(0,i.useCallback)(()=>{let e=function(e,t={}){let n=e.map(e=>e.root);return t.includeUngrouped&&n.push(v),{projectRoots:n}}(nS,{includeUngrouped:nL.length>0});t1(t=>({...t,collapsedProjectRoots:e.projectRoots}))},[nS,nL,t1]),nY=(0,i.useCallback)(()=>{t1(e=>0===e.collapsedProjectRoots.length?e:{...e,collapsedProjectRoots:[]})},[t1]);return(0,r.jsx)(tp.Provider,{value:{startedAt:eR,now:e_},children:(0,r.jsx)(th.Provider,{value:ej,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 10px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(eX,{}),(0,r.jsxs)("div",{className:"sidebar-toolbar",style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)(eG,{label:_("sidebar_addProject"),onClick:nc,active:Q,children:(0,r.jsx)(eQ,{size:18})}),(0,r.jsx)(eG,{label:Y?_("sidebar_newSessionIn",{project:a(Y,G)}):_("sidebar_selectProject"),disabled:!Y,onClick:()=>nw(),children:(0,r.jsx)(e6,{size:18})}),(0,r.jsx)(eG,{label:_("sidebar_searchSessions"),active:eY,expanded:eY,onClick:nj,children:(0,r.jsx)(e5,{size:18})}),(0,r.jsx)(eG,{label:_("sidebar_archive"),active:ed,expanded:ed,onClick:nf,children:(0,r.jsx)(e4,{size:18})}),(0,r.jsxs)("div",{ref:tw,style:{position:"relative"},children:[(0,r.jsx)(eG,{label:_("sidebar_displayOptions"),active:tx,expanded:tx,onClick:()=>{let e=!tx;if(tv(e),e){let e=tw.current?.getBoundingClientRect();e&&(tj.current={top:e.top,bottom:e.bottom,right:e.right},tb({top:e.bottom+4,right:Math.max(8,window.innerWidth-e.right)}))}},children:(0,r.jsx)(e8,{size:18})}),tx&&(0,s.createPortal)((0,r.jsx)(eV,{open:tx,style:{position:"fixed",top:ty?.top??0,right:ty?.right??0,zIndex:600,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 20px rgba(0,0,0,0.10)",overflow:"hidden",minWidth:168},children:(0,r.jsxs)("div",{ref:tk,onKeyDown:e=>{"Escape"===e.key&&tv(!1)},children:[(0,r.jsx)(to,{label:_("sidebar_standard"),checked:"standard"===t6,onClick:()=>{nq("standard"),tv(!1)}}),(0,r.jsx)(to,{label:_("sidebar_compact"),checked:"compact"===t6,onClick:()=>{nq("compact"),tv(!1)}}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",margin:"2px 0"}}),(0,r.jsx)("div",{style:{padding:"6px 10px 2px",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.04em"},children:_("sidebar_projectSort")}),(0,r.jsx)(to,{label:_("sidebar_projectSortRecent"),checked:"recent"===tS.projectSort,onClick:()=>{nK("recent"),tv(!1)}}),(0,r.jsx)(to,{label:_("sidebar_projectSortAz"),checked:"az"===tS.projectSort,onClick:()=>{nK("az"),tv(!1)}}),(0,r.jsx)(to,{label:_("sidebar_projectSortZa"),checked:"za"===tS.projectSort,onClick:()=>{nK("za"),tv(!1)}}),(0,r.jsx)(to,{label:_("sidebar_projectSortFixed"),checked:"fixed"===tS.projectSort,onClick:()=>{nK("fixed"),tv(!1)}}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",margin:"2px 0"}}),(0,r.jsx)(to,{label:_("sidebar_collapseAll"),onClick:()=>{nV(),tv(!1)}}),(0,r.jsx)(to,{label:_("sidebar_expandAll"),onClick:()=>{nY(),tv(!1)}}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",margin:"2px 0"}}),(0,r.jsx)(to,{label:_("sidebar_recentSessions"),checked:t5,onClick:()=>{ng(!t5),tv(!1)}})]})}),document.body)]})]})]}),!ed&&eY&&(0,r.jsxs)("div",{style:{marginTop:8},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginBottom:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>e3("meta"),"aria-pressed":"meta"===e0,style:{flex:1,height:24,borderRadius:6,border:"1px solid var(--border)",background:"meta"===e0?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",fontSize:11,cursor:"pointer"},children:_("sidebar_searchModeMeta")}),(0,r.jsx)("button",{type:"button",onClick:()=>e3("fulltext"),"aria-pressed":"fulltext"===e0,style:{flex:1,height:24,borderRadius:6,border:"1px solid var(--border)",background:"fulltext"===e0?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",fontSize:11,cursor:"pointer"},children:_("sidebar_searchModeFulltext")})]}),(0,r.jsxs)("div",{style:{position:"relative"},children:[(0,r.jsx)("span",{style:{position:"absolute",left:9,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none",display:"flex"},children:(0,r.jsx)(e5,{size:13})}),(0,r.jsx)("input",{ref:tm,type:"search",value:eK,onChange:e=>eJ(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),eK||eZ(!1),nk())},placeholder:"fulltext"===e0?_("sidebar_searchPlaceholderFulltext"):_("sidebar_searchPlaceholder"),"aria-label":_("sidebar_searchSessions"),style:{width:"100%",height:30,boxSizing:"border-box",padding:"0 28px 0 29px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:11.5,outline:"none"}}),eK&&(0,r.jsx)("button",{type:"button",onClick:()=>nk(),"aria-label":_("sidebar_clearSearch"),title:_("sidebar_clearSearch"),style:{position:"absolute",right:4,top:"50%",transform:"translateY(-50%)",width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",borderRadius:5,background:"none",color:"var(--text-dim)",cursor:"pointer"},children:(0,r.jsx)(e9,{size:13})})]}),"fulltext"===e0&&eK.trim()&&(0,r.jsxs)("div",{style:{marginTop:6,fontSize:10.5,color:"var(--text-dim)",display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[td&&(0,r.jsx)("span",{children:_("sidebar_searchFulltextLoading")}),!td&&"fts"===tl&&(0,r.jsxs)("span",{children:[_("sidebar_searchFulltextSourceFts")," \xb7 ",_("sidebar_searchFulltextHits",{count:e7.length})]}),!td&&"jsonl"===tl&&(0,r.jsxs)("span",{children:[_("sidebar_searchFulltextSourceJsonl")," \xb7 ",_("sidebar_searchFulltextHits",{count:e7.length})]}),tu&&(0,r.jsx)("span",{style:{color:"var(--status-danger)"},children:tu})]})]})]}),!ed&&eY&&"fulltext"===e0&&e7.length>0&&(0,r.jsx)("div",{style:{flex:"0 0 auto",maxHeight:160,overflowY:"auto",overflowX:"hidden",borderBottom:"1px solid var(--border)",padding:"4px 0"},children:e7.slice(0,12).map((e,t)=>(0,r.jsxs)("button",{type:"button",onClick:()=>nF(e.sessionId,e.entryId),title:_("sidebar_searchFulltextSnippet"),style:{display:"block",width:"100%",textAlign:"left",padding:"6px 12px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",fontSize:11,lineHeight:1.4},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,r.jsxs)("div",{style:{color:"var(--text-dim)",fontSize:10,marginBottom:2},children:[e.role??"message"," \xb7 ",e.sessionId.slice(0,8)]}),(0,r.jsx)("div",{style:{overflow:"hidden",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",whiteSpace:"normal"},children:e.snippet})]},`${e.sessionId}-${e.timestamp}-${t}`))}),ed?(0,r.jsx)(tq,{sessions:B,count:B.length,homeDir:G,loading:W,onRefresh:t7,onBack:()=>eu(!1)}):(0,r.jsxs)(r.Fragment,{children:[ex&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 12px",borderBottom:"1px solid var(--border)",background:"var(--status-danger-bg)",color:"var(--status-danger)",fontSize:11,lineHeight:1.4,overflowWrap:"anywhere",flexShrink:0},children:ex}),(0,r.jsxs)("div",{ref:tH,style:{flex:"1 1 auto",overflowY:"auto",overflowX:"hidden",padding:"2px 0",minHeight:80},children:[W&&(0,r.jsx)("div",{style:{padding:"16px 14px",color:"var(--text-muted)",fontSize:12},children:_("sidebar_loading")}),P&&(0,r.jsxs)("div",{style:{padding:"12px 14px",color:"var(--status-danger)",fontSize:12,display:"flex",flexDirection:"column",gap:6},children:[(0,r.jsx)("div",{children:_("sidebar_loadFailed")}),(0,r.jsx)("div",{title:P,style:{color:"var(--text-muted)",fontSize:11,overflowWrap:"anywhere"},children:P.length>90?`${P.slice(0,90)}…`:P}),(0,r.jsx)("button",{type:"button",disabled:F,onClick:()=>{t_.current=0,N(!0),ne.current(!0).finally(()=>N(!1))},style:{alignSelf:"flex-start"},children:F?_("common_loading"):_("sidebar_loadFailedRetry")})]}),!W&&!P&&0===nA.length&&0===nL.length&&(("meta"===e0?nI.length>0:nR&&!td)?(0,r.jsx)("div",{style:{padding:"18px 14px",color:"var(--text-muted)",fontSize:12,lineHeight:1.55},children:_("sidebar_searchEmpty",{query:eK.trim()})}):(0,r.jsxs)("div",{style:{padding:"18px 14px",color:"var(--text-muted)",fontSize:12,lineHeight:1.7},children:[_("sidebar_noProjects"),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:_("sidebar_addProject")})]})),!nE&&nv.length>0&&(0,r.jsxs)("div",{style:{paddingBottom:5,borderBottom:"1px solid var(--border)",marginBottom:5},children:[(0,r.jsxs)("div",{"data-sidebar-depth":0,className:"sidebar-row",style:{display:"flex",alignItems:"center",gap:6,height:32,margin:"1px 6px",paddingLeft:32,paddingRight:8,color:"var(--text-muted)",fontSize:12.5,fontWeight:600,position:"relative",borderRadius:6},children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"sidebar-indicator-icon",style:{position:"absolute",left:6,top:"50%",display:"flex",width:20,height:20,alignItems:"center",justifyContent:"center",transform:"translateY(-50%)",color:"var(--text-dim)"},children:(0,r.jsx)(e2,{size:13})}),(0,r.jsx)("span",{style:{flex:1,fontSize:12.5,fontWeight:600},children:_("sidebar_pinnedSessions")})]}),nv.map(t=>{let n=n_.get(t.id);return n?(0,r.jsx)(tM,{node:n,selectedSessionId:e,runningSessionIds:ea,subagentRunningIds:ek,unreadSessionIds:eN,onSelectSession:nu,onRenamed:t7,onSessionDeleted:np,onSessionArchive:nh,isSessionPinned:e=>nm.has(e),onTogglePin:ny,depth:0,collapsedSessionIds:tW,searchActive:nE,onToggleCollapse:nH,displayMode:t6},t.id):(0,r.jsx)(tA,{session:t,isSelected:t.id===e,isRunning:ea.has(t.id)||ek.has(t.id),isUnread:eN.has(t.id),onClick:()=>nu(t),onRenamed:t7,onDeleted:np,onArchive:nh,isPinned:nm.has(t.id),onTogglePin:()=>ny(t.id),depth:0,displayMode:t6},t.id)})]}),!nE&&nb.length>0&&(0,r.jsxs)("div",{style:{paddingBottom:5,borderBottom:"1px solid var(--border)",marginBottom:5},children:[(0,r.jsxs)("div",{"data-sidebar-depth":0,role:"button",tabIndex:0,"aria-expanded":t5,"aria-label":t5?_("sidebar_collapseRecentSessions"):_("sidebar_expandRecentSessions"),onClick:()=>ng(!t5),onKeyDown:e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),ng(!t5))},className:"sidebar-row",style:{display:"flex",alignItems:"center",gap:6,height:32,margin:"1px 6px",paddingLeft:32,paddingRight:8,color:"var(--text-muted)",fontSize:12.5,fontWeight:600,position:"relative",cursor:"pointer",borderRadius:6},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,r.jsx)(tr,{collapsed:!t5,label:t5?_("sidebar_collapseRecentSessions"):_("sidebar_expandRecentSessions"),left:6,onClick:e=>{e.stopPropagation(),ng(!t5)}}),(0,r.jsx)("span",{"aria-hidden":"true",className:"sidebar-indicator-icon",style:{position:"absolute",left:6,top:"50%",display:"flex",width:20,height:20,alignItems:"center",justifyContent:"center",transform:"translateY(-50%)",color:"var(--text-dim)"},children:(0,r.jsx)(e1,{size:13})}),(0,r.jsx)("span",{style:{flex:1,fontSize:12.5,fontWeight:600},children:_("sidebar_recentSessions")})]}),t5&&(0,r.jsxs)("div",{children:[nb.slice(0,t8).map(t=>{let n=n_.get(t.id);return n?(0,r.jsx)(tM,{node:n,selectedSessionId:e,runningSessionIds:ea,subagentRunningIds:ek,unreadSessionIds:eN,onSelectSession:nu,onRenamed:t7,onSessionDeleted:np,onSessionArchive:nh,isSessionPinned:e=>nm.has(e),onTogglePin:ny,depth:0,collapsedSessionIds:tW,searchActive:nE,onToggleCollapse:nH,displayMode:t6},t.id):(0,r.jsx)(tA,{session:t,isSelected:t.id===e,isRunning:ea.has(t.id)||ek.has(t.id),isUnread:eN.has(t.id),onClick:()=>nu(t),onRenamed:t7,onDeleted:np,onArchive:nh,isPinned:nm.has(t.id),onTogglePin:()=>ny(t.id),depth:0,displayMode:t6},t.id)}),(0,r.jsx)(ts,{groupKey:"recent",total:nb.length,visibleCount:t8,searchActive:!1,onShowMore:()=>t3(e=>eH(e,nb.length,"more")),onShowFewer:()=>t3(e=>eH(e,nb.length,"fewer"))})]})]}),nA.map(t=>(0,r.jsx)(tE,{project:t,displayMode:t6,projectAliases:t4,selectedSessionId:e,runningSessionIds:ea,subagentRunningIds:ek,unreadSessionIds:eN,collapsedProjectRoots:t9,collapsedSessionIds:tW,searchActive:nE,onToggleProject:nD,onNewSession:nw,onSelectSession:nu,menuOpen:et===t.root,onMenuOpenChange:e=>en(e?t.root:null),onEditProject:()=>nO(t.root),onCloseProject:()=>nB(t.root),onRenamed:t7,onSessionDeleted:np,onToggleCollapse:nH,groupVisibleCounts:tL,onShowMore:e=>tz(t=>ez(t,e)),onShowFewer:e=>tz(t=>eW(t,e)),actionError:nl?.root===t.root?nl.message:null,onSessionArchive:nh,isSessionPinned:e=>nm.has(e),onTogglePin:ny,onProjectDrop:nE?void 0:nJ},t.root)),nL.length>0&&(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",marginTop:5,paddingTop:5},children:[(0,r.jsxs)("div",{className:"sidebar-row","data-sidebar-depth":0,role:"button",tabIndex:0,"aria-expanded":!nP,"aria-label":nP?_("sidebar_expandUngroupedSessions"):_("sidebar_collapseUngroupedSessions"),onClick:nN,onKeyDown:e=>{e.target===e.currentTarget&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),nN())},style:{display:"flex",alignItems:"center",gap:6,height:32,margin:"1px 6px",paddingLeft:32,paddingRight:8,color:"var(--text-muted)",fontSize:12.5,fontWeight:600,position:"relative",cursor:"pointer",borderRadius:6},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,r.jsx)(tr,{collapsed:nP,label:nP?_("sidebar_expandUngroupedSessions"):_("sidebar_collapseUngroupedSessions"),left:6,onClick:e=>{e.stopPropagation(),nN()}}),(0,r.jsx)("span",{"aria-hidden":"true",className:"sidebar-indicator-icon",style:{position:"absolute",left:6,top:"50%",display:"flex",width:20,height:20,alignItems:"center",justifyContent:"center",transform:"translateY(-50%)",color:"var(--text-dim)"},children:(0,r.jsx)(tt,{size:13})}),(0,r.jsx)("span",{style:{flex:1,fontSize:12.5,fontWeight:600},children:_("sidebar_ungroupedSessions")})]}),!nP&&(0,r.jsxs)("div",{children:[e$(nL,eL(tL,v),nE).map(t=>(0,r.jsx)(tM,{node:t,selectedSessionId:e,runningSessionIds:ea,subagentRunningIds:ek,unreadSessionIds:eN,onSelectSession:nu,onRenamed:t7,onSessionDeleted:np,onSessionArchive:nh,isSessionPinned:e=>nm.has(e),onTogglePin:ny,depth:0,collapsedSessionIds:tW,searchActive:nE,onToggleCollapse:nH,displayMode:t6},t.session.id)),(0,r.jsx)(ts,{groupKey:v,total:nL.length,visibleCount:eL(tL,v),searchActive:nE,onShowMore:e=>tz(t=>ez(t,e)),onShowFewer:e=>tz(t=>eW(t,e))})]})]})]})]}),(0,r.jsx)(tF,{open:Q,onClose:na,onAdded:nd}),(0,r.jsx)(tD,{projectRoot:er,initialName:er?t4[er]??d(er):"",onClose:()=>ei(null),onSaveName:nU})]})})})}function nP(e,t){let n=new Set,r=(e,t)=>{if("number"!=typeof e||!Number.isInteger(e)||e<0)return;n.add(e);let r="number"==typeof t&&Number.isInteger(t)&&t>1?t:1;for(let t=1;t<r;t+=1)n.add(e+t)};for(let t of e??[])r(t?.lineIndex,t?.rows);for(let e of t??[])r(e?.lineIndex,1);return n}function nF(e,t){let n=new Map;t.forEach((e,t)=>{n.has(e)||n.set(e,t)});let r=[],i=0;for(let t of e??[]){let e="number"==typeof t?.lineIndex?n.get(t.lineIndex):void 0;if(void 0===e){i+=1;continue}r.push({...t,lineIndex:e})}return{items:r,dropped:i}}function nH(e){switch(e){case"too-large":return"message_imageReason_tooLarge";case"unsupported-format":return"message_imageReason_unsupportedFormat";case"incomplete":return"message_imageReason_incomplete";case"empty":return"message_imageReason_empty";default:return null}}let nD=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,nN=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,nB=/\x1B\[([0-9;]*)m/g,nO=/\x1B_pi:c\x07/g,nU=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],nq=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function nK(e){return e.replace(nO,"").replace(nD,"")}function nJ(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(nN);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function nV(e,t){let n=nJ(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function nY(e){return nJ(e)[0]?.char}function nX(e,t){if(!Array.isArray(e))return{lines:[],sourceIndex:[]};let n=e.filter(e=>"string"==typeof e),r=t?.keep,i=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,o=[],l=[];n.forEach((e,t)=>{let n=e.replace(nO,""),s=nK(n).trimEnd();if(i.test(s)&&!r?.has(t))return;let a=n,d=nY(a);("│"===d||"┃"===d)&&" "===nY(a=nV(a,0))&&(a=nV(a,0));let c=function(e){let t=nJ(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),u=c>=0?nJ(a)[c]?.char:void 0;("│"===u||"┃"===u)&&(a=nV(a,c)),o.push(function(e){let t=e;for(;;){let e=nJ(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(a)),l.push(t)});let s=e=>""===nK(o[e]).trim(),a=e=>r?.has(l[e])===!0;for(;o.length>0&&s(0)&&!a(0);)o.shift(),l.shift();for(;o.length>0&&s(o.length-1)&&!a(o.length-1);)o.pop(),l.pop();return 0===o.length?{lines:n,sourceIndex:n.map((e,t)=>t)}:{lines:o,sourceIndex:l}}function nG(e){let t,n=[],r={},i=0;for(nB.lastIndex=0;null!==(t=nB.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=nU[r-30];else if(r>=90&&r<=97)n.color=nq[r-90];else if(r>=40&&r<=47)n.backgroundColor=nU[r-40];else if(r>=100&&r<=107)n.backgroundColor=nq[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,o,l]=[t[e+2],t[e+3],t[e+4]];[i,o,l].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${o}, ${l})`:n.backgroundColor=`rgb(${i}, ${o}, ${l})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return nU[e];if(e>=8&&e<16)return nq[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let nZ=new Map;function nQ(e){return[e.fontFamily??"",e.fontSize??"",e.lineHeight??""].join("|")}function n0(e,t,n){let r=e.get(t);if(void 0!==r)return r;let i=n();return!Number.isFinite(i)||i<=0?null:(e.set(t,i),i)}function n1(e,t,n){let r=document.createElement("span");r.textContent=t,r.style.cssText="position:absolute;visibility:hidden;white-space:pre",e.appendChild(r);let i=r.getBoundingClientRect(),o="width"===n?i.width/100:i.height;return r.remove(),o}function n2(e){let t=window.getComputedStyle(e);return n0(nZ,`ch|${nQ(t)}`,()=>n1(e,"0".repeat(100),"width"))}function n4(e){let t=window.getComputedStyle(e);return n0(nZ,`lh|${nQ(t)}`,()=>n1(e,"0","height"))}function n6({image:e,alt:t}){let n=(0,i.useRef)(null),[o,l]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let t=n.current;if(!t)return;let r=t?t.parentElement??t:null;if(!r)return;let i=n4(r);if(!i)return;let o=n2(r);l({height:i*Math.max(1,e.rows),width:o?o*Math.max(1,e.cols):0})},[e.cols,e.id,e.rows]),(0,r.jsx)("span",{ref:n,style:{display:"inline-block",lineHeight:0},children:(0,r.jsx)("img",{src:`data:${e.mime};base64,${e.base64}`,alt:t,"data-pidance-terminal-image":e.id,style:{display:"block",height:o?`${o.height}px`:`${Math.max(1,e.rows)}em`,width:o&&o.width>0?`${o.width}px`:"auto",maxWidth:"100%",objectFit:"contain"}})})}function n5({label:e,reason:t}){return(0,r.jsx)("span",{role:"note",title:t,style:{color:"var(--text-muted)"},children:e})}function n8({lines:e,images:t,imageFallbacks:n,keyPrefix:o,renderLine:l,imageAlt:s,fallbackLabel:a}){let d=Array.isArray(e)?e:[],c=new Map,u=new Set;for(let e of Array.isArray(t)?t:[])if("number"==typeof e?.lineIndex){c.set(e.lineIndex,e);for(let t=1;t<Math.max(1,e.rows);t+=1)u.add(e.lineIndex+t)}let p=new Map;for(let e of Array.isArray(n)?n:[])"number"==typeof e?.lineIndex&&p.set(e.lineIndex,e);return d.map((e,t)=>{if(u.has(t))return null;let n=c.get(t),h=p.get(t);return n||h?(0,r.jsxs)(i.Fragment,{children:[n?(0,r.jsx)(n6,{image:n,alt:s}):null,h?(0,r.jsx)(n5,{label:a(h.reason),reason:h.reason}):null,""!==e?l(e,`${o}-${t}`):null,t<d.length-1?"\n":null]},`${o}-${t}`):(0,r.jsxs)(i.Fragment,{children:[l(e,`${o}-${t}`),t<d.length-1?"\n":null]},`${o}-${t}`)})}let n3={pressing:!1,longPressFired:!1,scrolled:!1};function n9(e){return e.pressing?{pressing:!1,longPressFired:e.longPressFired,scrolled:e.scrolled}:e}function n7(e,t){return Math.abs(e)>10||Math.abs(t)>10}function re(e){let t=e.split(/[-_./]+/).filter(Boolean);return 0===t.length?e:t.map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function rt(e,t,n,r={}){return{kind:"message",source:"disk",messageIndex:t,keyPrefix:r.keyPrefix??"message",attachRef:r.attachRef??!0,showTimestamp:r.showTimestamp??function(e,t,n){if(e[t]?.role!=="assistant")return;let r=!0;for(let n=t+1;n<e.length;n++){let t=e[n].role;if("user"===t)break;if("assistant"===t){r=!1;break}}return r&&n&&t===e.length-1&&(r=!1),r}(e,t,n),...r.messageOverride?{messageOverride:r.messageOverride}:{}}}function rn(e,t){if(!t)return e.length;let n=e.length;for(;n>0;){let t=e[n-1];if(t?.role!=="user")break;let r=!0===t._duringStreamingStep,i=n-2>=0&&e[n-2]?.role==="user";if(!r&&!i)break;n--}return n}function rr(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.kind==="message"&&"live"===n.source)return n.messageOverride??null}return null}let ri="(max-width: 640px)";function ro(e){if(!window.matchMedia)return()=>{};let t=window.matchMedia(ri);return t.addEventListener("change",e),()=>t.removeEventListener("change",e)}function rl(){return!!window.matchMedia&&window.matchMedia(ri).matches}function rs(){return!1}function ra(){return(0,i.useSyncExternalStore)(ro,rl,rs)}var rd=n(94514),rc=n(67635),ru=n(31025),rp=n(93631),rh=n(66088),rf=n(99815),rg=n(12651),rm=n(41585),rx=n(62791),rv=n(10762),ry=n(9921),rb=n(32316),rw=n(65063),rk=n(7644);let rj="pi-theme",rS="pi-theme-style",rC=new Set,r_=null;function rI(e){return"light"===e||"dark"===e||"system"===e}function rR(e){return"chamber"===e||"fusion"===e}function rT(e){return"system"!==e?e:window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function rE(){if("u"<typeof document)return"light";let e=document.documentElement.dataset.themeMode??null;if(rI(e))return e;try{let e=localStorage.getItem(rj);if(rI(e))return e}catch{}return document.documentElement.classList.contains("dark")?"dark":"light"}function rM(){if("u"<typeof document)return"chamber";let e=document.documentElement.dataset.themeStyle??null;if(rR(e))return e;try{let e=localStorage.getItem(rS);if(rR(e))return e}catch{}return"chamber"}function rA(){if("u"<typeof document)return"light|chamber|light";let e=rE();return`${e}|${rM()}|${document.documentElement.classList.contains("dark")?"dark":"light"}`}function rL(){rC.forEach(e=>e())}function rz(){if("system"!==rE())return;let e=rT("system");document.documentElement.classList.toggle("dark","dark"===e),rL()}function rW(e){return rC.add(e),r_||(r_=window.matchMedia("(prefers-color-scheme: dark)")).addEventListener("change",rz),()=>{rC.delete(e),0===rC.size&&r_&&(r_.removeEventListener("change",rz),r_=null)}}function r$(e,t){let n=rT(e),r=document.documentElement;r.classList.toggle("dark","dark"===n),r.dataset.themeMode=e,r.dataset.themeStyle=t;try{localStorage.setItem(rj,e),localStorage.setItem(rS,t)}catch{}(0,eA.dM)("theme",{mode:e,style:t}),rL()}function rP(){let e=(0,eA.b3)("theme"),t="string"==typeof e?.mode?e.mode:null;if(!rI(t))return;let n="string"==typeof e?.style?e.style:null,r=rR(n)?n:rM();(t!==rE()||r!==rM())&&r$(t,r)}function rF(){let[e,t,n]=(0,i.useSyncExternalStore)(rW,rA,()=>"light|chamber|light").split("|"),r=(0,i.useCallback)((n,r,i)=>{if(e===n&&t===r)return;let o=()=>r$(n,r),l=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||l)return void o();let s=i?.x??window.innerWidth/2,a=i?.y??window.innerHeight/2,d=Math.hypot(Math.max(s,window.innerWidth-s),Math.max(a,window.innerHeight-a));document.startViewTransition(o).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${s}px ${a}px)`,`circle(${d}px at ${s}px ${a}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[e,t]),o=(0,i.useCallback)((e,n)=>{r(e,t,n)},[r,t]),l=(0,i.useCallback)((t,n)=>{r(e,t,n)},[e,r]),s=(0,i.useCallback)(e=>{o("dark"===n?"light":"dark",e)},[o,n]);return{theme:n,mode:e,themeStyle:t,toggleTheme:s,setTheme:o,setThemeStyle:l,isDark:"dark"===n}}(0,eA.zo)().then(rP),(0,eA.iX)(rP);var rH=n(28999);function rD(e){let t=(0,rH.A0)(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,o=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){o.length>0&&".."!==o[o.length-1]?o.pop():i||n||r||o.push(e);continue}o.push(e)}let l=o.join("/");return n?l:r?`//${l}`:i?`/${l}`:l}function rN(e,t,n=t){let r,i,o,l,s;if(!e)return null;let a=e.split("#",1)[0].split("?",1)[0].trim();if(!a)return null;let d=null,c=null,u=(0,rH.ex)(a),p=u.startsWith("\\\\"),h=(0,rH.A0)(u),f=h.toLowerCase();if(f.startsWith("/api/")||f.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!f.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(f.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=(0,rH.ex)(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${(0,rH.A0)(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let g=rD(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=rD(g).replace(/\/+$/,""),i=rD(n).replace(/\/+$/,""),l=(o=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(l===(s=o?i.toLowerCase():i)||l.startsWith(`${s}/`)))?null:g}var rB=n(88374),rO=n(5924),rU=n(94764),rq=n(63835),rK=n(84678),rJ=n(98164);let rV={...rU.j,attributes:{...rU.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...rU.j.strip||[],"iframe","object","style","form"]},rY=[rK.A,rJ.A],rX=[rK.A],rG=[rO.A,[rq.A,rV],[rB.A,{throwOnError:!1,strict:!1}]],rZ=[rO.A,[rq.A,rV]];var rQ=n(82482),r0=n(51914),r1=n(9199),r2=n(6962);let r4=null,r6=new Set,r5=new Set;function r8(){for(let e of r6)e()}function r3(){null!==r4&&(r4=null,r8())}async function r9(e){let t=e.fetchImpl??fetch;try{let r=await t("/api/files/save-as",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e.path,targetDirectory:e.targetDirectory})}),i=await r.json().catch(()=>null);if(!r.ok){var n;let e;return{ok:!1,message:(n=r.status,e=i?.error,"string"==typeof e&&e.trim()?e:403===n?"Access denied":404===n?"Not found":409===n?"Already exists":`HTTP ${n}`)}}let o="string"==typeof i?.path?i.path:"";if(!o)return{ok:!1,message:"Save failed"};return{ok:!0,path:o,name:"string"==typeof i?.name?i.name:o.split("/").pop()??o}}catch{return{ok:!1,message:"Save failed"}}}function r7({open:e,sourcePath:t,onClose:n}){let{t:o}=(0,eU.s9)(),l=(0,i.useRef)(null),[s,a]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(null),w=(0,i.useRef)(!1),k=(0,i.useCallback)(async e=>{let t=await tW(e);if(!t.ok){f(!0),c([]),p(null);return}f(!1),t.path&&(a(t.path),w.current||(w.current=!1)),c(t.entries),p(t.parentPath)},[]);(0,i.useEffect)(()=>{e&&(v(null),b(null),w.current=!1,k("~"))},[e,k]),(0,i.useEffect)(()=>{if(!e||w.current)return;let t=s.trim();if(!t)return;let n=setTimeout(()=>void k(t),250);return()=>clearTimeout(n)},[e,s,k]);let j=(0,i.useCallback)(e=>{w.current=!0,a(e),v(null),b(null),k(e)},[k]),S=(0,i.useCallback)(async()=>{let e=s.trim();if(!e||g)return;m(!0),b(null);let n=await r9({path:t,targetDirectory:e});if(m(!1),!n.ok){v(null),b(n.message);return}v(n.path),k(e)},[s,g,t,k]);return(0,r.jsx)(tw,{open:e,onClose:n,title:o("saveAs_title"),width:480,closeLabel:o("dialog_close"),initialFocusRef:l,actions:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ti,{onClick:n,children:o("sidebar_cancel")}),(0,r.jsx)(ti,{primary:!0,disabled:g||!s.trim(),onClick:()=>void S(),children:o(g?"saveAs_saving":"saveAs_save")})]}),children:(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:"save-as-directory",style:{display:"block",fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:6},children:o("saveAs_directory")}),(0,r.jsx)("input",{id:"save-as-directory",ref:l,value:s,onChange:e=>{a(e.target.value),b(null),v(null)},onKeyDown:e=>{"Enter"!==e.key||g||(e.preventDefault(),S())},placeholder:"~",spellCheck:!1,style:{width:"100%",boxSizing:"border-box",height:32,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("div",{style:{marginTop:6,fontSize:11,color:"var(--text-dim)"},children:o("saveAs_hint")}),(0,r.jsxs)("div",{className:"save-as-browse",style:{marginTop:10,maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6},children:[u?(0,r.jsx)("button",{type:"button",onClick:()=>j(u),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"4px 8px",border:"none",background:"transparent",color:"var(--text-muted)",fontSize:12,cursor:"pointer",borderRadius:5,fontFamily:"var(--font-mono)"},children:".."}):null,h?(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"var(--text-dim)"},children:o("sidebar_browseMissing")}):0===d.length?(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:11,color:"var(--text-dim)"},children:o("sidebar_browseEmpty")}):d.map(e=>(0,r.jsxs)("button",{type:"button",onClick:()=>j(e.path),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"4px 8px",border:"none",background:"transparent",color:"var(--text)",fontSize:12,cursor:"pointer",borderRadius:5,textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"›"}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path))]}),x?(0,r.jsx)("div",{role:"status",style:{marginTop:10,fontSize:12,color:"var(--status-running)",overflowWrap:"anywhere"},children:o("saveAs_savedTo",{path:x})}):null,y?(0,r.jsx)("div",{role:"alert",style:{marginTop:10,fontSize:12,color:"var(--status-danger)",overflowWrap:"anywhere"},children:y}):null]})})}let ie={"image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/jpeg":"jpg","image/png":"png","image/svg+xml":"svg","image/webp":"webp","image/x-icon":"ico"};function it(e){let t=e.source;if(t&&"object"==typeof t){if("base64"===t.type&&"string"==typeof t.data&&t.data.length>0){let e=ii(t.media_type);return{src:`data:${e};base64,${t.data}`,mimeType:e}}if("url"===t.type&&"string"==typeof t.url&&t.url.trim()){let e=t.url.trim();return io(e)?{src:e,mimeType:ir(t.media_type)}:null}}if("string"==typeof e.data&&e.data.length>0){let t=ii(e.mimeType);return{src:`data:${t};base64,${e.data}`,mimeType:t}}return null}function ir(e){if("string"!=typeof e)return;let t=e.trim().toLowerCase();return/^image\/[a-z0-9.+-]+$/.test(t)?t:void 0}function ii(e){return ir(e)??"image/png"}function io(e){let t=e.trim();if(!t)return!1;if(t.startsWith("data:"))return/^data:image\/[a-z0-9.+-]+;base64,/i.test(t);try{let e=new URL(t,"http://pidance.invalid").protocol;return"http:"===e||"https:"===e||"blob:"===e}catch{return!1}}let il={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:30,minHeight:30,padding:4,border:"1px solid rgba(255,255,255,0.22)",borderRadius:6,background:"rgba(255,255,255,0.10)",color:"#fff",cursor:"pointer",flexShrink:0};function is({src:e,fullSrc:t,downloadHref:n,downloadName:i,mimeType:o,alt:l,title:s,maxWidth:a=360,maxHeight:d=280}){let{t:c}=(0,eU.s9)(),u=t&&io(t)?t:e,p=n||u,h=i?.trim()||function(e,t){if(!e.startsWith("data:"))try{let t=new URL(e,"http://pidance.invalid"),n=decodeURIComponent(t.pathname.split("/").pop()??"");if(/^[^\\/:*?\"<>|]+\.[a-z0-9]{1,8}$/i.test(n))return n}catch{}return`image.${t?ie[t.toLowerCase()]??"png":"png"}`}(p,o),f=l||c("message_imageAlt");return e&&io(e)?(0,r.jsx)("button",{type:"button",onClick:()=>{r4={...{src:u,downloadHref:p,downloadName:h,mimeType:o,alt:f,title:s},id:`${Date.now()}-${Math.random().toString(36).slice(2)}`},r8()},"aria-label":c("message_openImage"),title:s||c("message_openImage"),style:{display:"block",maxWidth:a,maxHeight:d,margin:0,padding:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-subtle)",cursor:"zoom-in",overflow:"hidden",lineHeight:0},children:(0,r.jsx)("img",{src:e,alt:f,title:s,draggable:!1,decoding:"async",style:{display:"block",maxWidth:a,maxHeight:d,objectFit:"contain"}})}):null}function ia(){let{t:e}=(0,eU.s9)(),t=(0,i.useSyncExternalStore)(e=>(r6.add(e),()=>r6.delete(e)),()=>r4,()=>null),[n,o]=(0,i.useState)(1),[l,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),u=t?(0,rH.n$)(t.downloadHref):null,[p,h]=(0,i.useState)({x:0,y:0}),[f,g]=(0,i.useState)(()=>ty()),m=(0,i.useRef)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useCallback)((e,t)=>{let n=v.current,r=y.current;if(!n||!r||t<=1)return{x:0,y:0};let i=window.getComputedStyle(r),o=r.clientWidth-Number.parseFloat(i.paddingLeft)-Number.parseFloat(i.paddingRight),l=r.clientHeight-Number.parseFloat(i.paddingTop)-Number.parseFloat(i.paddingBottom),s=Math.max(0,(n.offsetWidth*t-o)/2),a=Math.max(0,(n.offsetHeight*t-l)/2);return{x:Math.min(s,Math.max(-s,e.x)),y:Math.min(a,Math.max(-a,e.y))}},[]),w=(0,i.useCallback)(()=>{o(1),h({x:0,y:0})},[]),k=(0,i.useCallback)(e=>{o(t=>{let n=Math.min(4,Math.max(1,Number((t+e).toFixed(2))));return h(e=>b(e,n)),n})},[b]);(0,i.useEffect)(()=>{var e;w(),x.current=null,a(!!t&&!!(e=t.downloadHref)&&r5.has(e)),c(!1)},[t?.id,t,w]),(0,i.useEffect)(()=>()=>r3(),[]),(0,i.useEffect)(()=>{if(!t)return;let e=()=>{g(ty()),h(e=>b(e,n))};e();let r=window.visualViewport;return r?.addEventListener("resize",e),r?.addEventListener("scroll",e),window.addEventListener("resize",e),window.addEventListener("orientationchange",e),()=>{r?.removeEventListener("resize",e),r?.removeEventListener("scroll",e),window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e)}},[t,b,n]),(0,i.useEffect)(()=>{if(!t)return;let e=e=>{"Escape"===e.key?(e.preventDefault(),r3()):"+"===e.key||"="===e.key?(e.preventDefault(),k(.25)):"-"===e.key?(e.preventDefault(),k(-.25)):"0"===e.key&&(e.preventDefault(),w())};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,k,w]);let j=(0,i.useCallback)(e=>{e.preventDefault(),k(e.deltaY<0?.25:-.25)},[k]),S=(0,i.useCallback)(e=>{m.current=!1,n<=1||(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),x.current={pointerId:e.pointerId,x:e.clientX,y:e.clientY,offsetX:p.x,offsetY:p.y})},[p.x,p.y,n]),C=(0,i.useCallback)(e=>{let t=x.current;if(!t||t.pointerId!==e.pointerId)return;let r=e.clientX-t.x,i=e.clientY-t.y;(Math.abs(r)>3||Math.abs(i)>3)&&(m.current=!0),h(b({x:t.offsetX+r,y:t.offsetY+i},n))},[b,n]),_=(0,i.useCallback)(e=>{x.current?.pointerId===e.pointerId&&(x.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),I=(0,i.useCallback)(e=>{if(m.current){m.current=!1;return}e.target===e.currentTarget&&r3()},[]);return t?(0,s.createPortal)((0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-label":e("message_imageViewer"),style:{position:"fixed",top:f.top,left:f.left,width:f.width,height:f.height,zIndex:1100,background:"color-mix(in srgb, #000 82%, transparent)",display:"flex",flexDirection:"column",overscrollBehavior:"contain"},children:[(0,r.jsxs)("div",{style:{position:"absolute",top:8,left:8,right:8,display:"flex",alignItems:"center",gap:6,padding:"6px 8px 6px 12px",borderRadius:9,background:"color-mix(in srgb, #000 55%, transparent)",backdropFilter:"blur(6px)",color:"#fff",zIndex:1},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:650},title:t.title||t.alt,children:t.title||t.alt}),(0,r.jsx)("button",{type:"button",onClick:()=>k(-.25),disabled:n<=1,"aria-label":e("message_zoomOut"),title:e("message_zoomOut"),style:{...il,opacity:n<=1?.45:1},children:(0,r.jsx)(rQ.A,{size:14,strokeWidth:1.9,"aria-hidden":"true"})}),(0,r.jsxs)("button",{type:"button",onClick:w,"aria-label":e("message_resetZoom"),title:e("message_resetZoom"),style:{...il,minWidth:48,fontSize:11},children:[Math.round(100*n),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>k(.25),disabled:n>=4,"aria-label":e("message_zoomIn"),title:e("message_zoomIn"),style:{...il,opacity:n>=4?.45:1},children:(0,r.jsx)(r0.A,{size:14,strokeWidth:1.9,"aria-hidden":"true"})}),(0,r.jsx)("button",{type:"button",onClick:w,"aria-label":e("message_resetZoom"),title:e("message_resetZoom"),style:il,children:(0,r.jsx)(r1.A,{size:14,strokeWidth:1.9,"aria-hidden":"true"})}),l&&u?(0,r.jsxs)("button",{type:"button",onClick:()=>c(!0),"aria-label":e("message_saveImageAs"),title:e("message_saveImageAs"),style:{...il,gap:5,fontSize:12},children:[(0,r.jsx)(r2.A,{size:14,strokeWidth:1.9,"aria-hidden":"true"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:e("message_saveImageAs")})]}):null,(0,r.jsxs)("a",{href:t.downloadHref,download:t.downloadName,onClick:()=>{var e;(e=t.downloadHref)&&r5.add(e),a(!0)},"aria-label":e("message_downloadImage"),title:e("message_downloadImage"),style:{...il,gap:5,textDecoration:"none",fontSize:12,display:l?"none":"inline-flex"},children:[(0,r.jsx)(r2.A,{size:14,strokeWidth:1.9,"aria-hidden":"true"}),(0,r.jsx)("span",{className:"hidden sm:inline",children:e("message_downloadImage")})]}),(0,r.jsx)("button",{type:"button",onClick:r3,"aria-label":e("message_closeImage"),title:e("message_closeImage"),style:{...il,fontSize:20,lineHeight:1},children:"\xd7"})]}),(0,r.jsx)("div",{ref:y,role:"group","aria-label":e("message_imageViewer"),onWheel:j,onPointerDown:S,onPointerMove:C,onPointerUp:_,onPointerCancel:_,onClick:I,onDoubleClick:()=>n>1?w():k(1),style:{flex:1,minHeight:0,display:"flex",alignItems:"center",justifyContent:"center",padding:"56px 12px 12px",overflow:"hidden",cursor:n>1?"grab":"zoom-in",touchAction:"none"},children:(0,r.jsx)("img",{ref:v,src:t.src,alt:t.alt,draggable:!1,decoding:"async",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain",userSelect:"none",WebkitUserSelect:"none",transform:`translate(${p.x}px, ${p.y}px) scale(${n})`,transformOrigin:"center center",transition:x.current?"none":"transform 0.12s ease-out"}})}),u?(0,r.jsx)(r7,{open:d,sourcePath:u,onClose:()=>c(!1)}):null]}),document.body):null}function id({code:e,isStreaming:t}){let{t:o}=(0,eU.s9)(),{isDark:l}=rF(),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)(null),g=`${l?"dark":"light"}
2
- ${e}`;(0,i.useEffect)(()=>{if(!s||t)return;let r=!1;return f(null),(async()=>{let{default:t}=await Promise.all([n.e(279),n.e(2280),n.e(3308)]).then(n.bind(n,43328));if(t.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:l?"dark":"default"}),!await t.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,o=await t.render(i,e);r||(c(o.svg),p(g))})().catch(()=>{r||f(g)}),()=>{r=!0}},[e,g,l,t,s]);let m=(0,r.jsx)("button",{onClick:()=>a(e=>!e),disabled:t,title:o(t?"markdown_previewAfterStreaming":s?"markdown_showSource":"markdown_preview"),className:["markdown-code-action",s?"is-active":""].filter(Boolean).join(" "),children:o(s?"markdown_source":"markdown_previewShort")});if(!s||t)return(0,r.jsx)(ic,{code:e,lang:"mermaid",headerAction:m});let x=h===g?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:o("markdown_invalidMermaid")}):d&&u===g?(0,r.jsx)("div",{className:"mermaid-block",dangerouslySetInnerHTML:{__html:d}}):(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":o("markdown_renderingMermaid")});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),m]}),x]})}function ic({code:e,lang:t,headerAction:n}){let{t:o}=(0,eU.s9)(),{isDark:l}=rF(),[s,a]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{tC(e).then(()=>{a(!0),setTimeout(()=>a(!1),1500)})},className:"markdown-code-action",children:o(s?"markdown_copied":"markdown_copy")})]})]}),(0,r.jsx)("div",{className:"markdown-code-body",children:(0,r.jsx)(rw.A,{language:t||"text",style:l?rk.xJ:rk.vs,showLineNumbers:!0,showInlineLineNumbers:!1,lineNumberStyle:{color:"var(--text-dim)",fontStyle:"normal",userSelect:"none"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))",userSelect:"text",WebkitUserSelect:"text"},codeTagProps:{style:{fontFamily:"var(--font-mono)",userSelect:"text",WebkitUserSelect:"text"}},children:e})})]})}let iu=(0,i.memo)(function({children:e,className:t,isStreaming:n,cwd:o,onOpenFile:l}){let s=(0,i.useMemo)(()=>{var t;let n,r,i;return n=(t=e).includes("\r\n")?"\r\n":"\n",r=t.split(/\r?\n/),i=null,r.map(e=>{let t=e.match(/^ {0,3}(`{3,}|~{3,})/);if(t){let n=t[1][0],r=t[1].length;return i?n===i.marker&&r>=i.size&&(i=null):i={marker:n,size:r},e}if(i)return e;let r=e.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(!r)return e;let o=r[2].trim();return o?`${r[1]}$$${n}${o}${n}${r[1]}$$`:e}).join(n)},[e]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(rb.oz,{remarkPlugins:rY,rehypePlugins:rG,components:{code({className:e,children:t,...i}){delete i.node;let o=e?.replace("language-","").toLowerCase()??"",l=String(t);return e?.includes("language-")||l.includes("\n")?"mermaid"===o?(0,r.jsx)(id,{code:l.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(ic,{code:l.replace(/\n$/,""),lang:o}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),img:({src:e,alt:t,title:n,...i})=>(delete i.node,"string"==typeof e&&e)?(0,r.jsx)(is,{src:e,fullSrc:e,alt:t,title:n,maxWidth:"100%",maxHeight:480}):null,a({href:e,children:t,...n}){delete n.node;let i=l?rN(e,o):null;return i&&l?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),l(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("div",{className:"markdown-table-scroll",children:e})}),thead:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-head",children:e}),tbody:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-body",children:e}),tr({children:e}){let t=i.Children.count(e)||1;return(0,r.jsx)("div",{className:"markdown-table-row",style:{gridTemplateColumns:`repeat(${t}, minmax(0, 1fr))`},children:e})},th:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-th",children:e}),td:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-td",children:e})},children:s})})});var ip=n(78916);function ih(e,t,n,r=!1){let i=new URLSearchParams({type:t});return n&&"read"===t&&i.set("mime",n),r&&i.set("messageMedia","1"),`/api/files/${(0,rH.HG)(e)}?${i.toString()}`}let ig={display:"flex",alignItems:"center",gap:8,minWidth:0,maxWidth:"100%",padding:"7px 9px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:12},im={display:"inline-flex",alignItems:"center",gap:4,flexShrink:0,color:"var(--accent)",textDecoration:"underline",textUnderlineOffset:2,fontSize:11};function ix({binary:e}){var t;let{t:n}=(0,eU.s9)(),i=ih(e.path,"read",e.mimeType,!0),o=ih(e.path,"download"),l=e.size<=0x1900000,s=`${e.name} \xb7 ${!Number.isFinite(t=e.size)||t<0?"":t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(+(t<10240))} KB`:t<0x40000000?`${(t/1048576).toFixed(+(t<0xa00000))} MB`:`${(t/0x40000000).toFixed(1)} GB`}`;if("image"===e.kind){let t=e.previewPath||e.path;return(0,r.jsx)("div",{style:{marginBottom:8,maxWidth:"100%"},children:(0,r.jsx)(is,{src:ih(t,"read",e.mimeType,!0),fullSrc:i,downloadHref:o,downloadName:e.name,mimeType:e.mimeType,alt:e.name,title:e.name,maxWidth:360,maxHeight:280})})}return"audio"===e.kind?(0,r.jsxs)("div",{style:{...ig,flexDirection:"column",alignItems:"stretch",maxWidth:480,marginBottom:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:s}),(0,r.jsxs)("a",{href:o,download:e.name,style:im,"aria-label":n("message_downloadOriginal"),children:[(0,r.jsx)(r2.A,{size:13,strokeWidth:1.9,"aria-hidden":"true"}),n("message_downloadOriginal")]})]}),l?(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:i,style:{width:"100%"}}):(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:n("message_mediaTooLargeToPlay")})]}):"video"===e.kind?(0,r.jsxs)("div",{style:{...ig,flexDirection:"column",alignItems:"stretch",maxWidth:640,marginBottom:8},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:s}),(0,r.jsxs)("a",{href:o,download:e.name,style:im,"aria-label":n("message_downloadOriginal"),children:[(0,r.jsx)(r2.A,{size:13,strokeWidth:1.9,"aria-hidden":"true"}),n("message_downloadOriginal")]})]}),l?(0,r.jsx)("video",{controls:!0,preload:"metadata",src:i,style:{display:"block",width:"100%",maxHeight:360,borderRadius:5,background:"var(--bg)",border:"1px solid var(--border)"}}):(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:n("message_mediaTooLargeToPlay")})]}):(0,r.jsxs)("div",{style:{...ig,marginBottom:8},children:[(0,r.jsx)(ip.A,{size:15,strokeWidth:1.8,color:"var(--text-dim)","aria-hidden":"true"}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.name,children:s}),(0,r.jsxs)("a",{href:o,download:e.name,style:im,"aria-label":n("message_downloadOriginal"),children:[(0,r.jsx)(r2.A,{size:13,strokeWidth:1.9,"aria-hidden":"true"}),n("message_downloadOriginal")]})]})}function iv({binaries:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:e.map((e,t)=>(0,r.jsx)(ix,{binary:e},`${e.path}-${t}`))})}n(92619).Buffer;let iy=["result","warning","error","output"];function ib(e){let t=e?.trim()??"";return""===t?null:t}function iw(e){return e.readOnly?{allowed:!1,reason:"readOnly"}:e.busy?{allowed:!1,reason:"busy"}:{allowed:!0}}let ik=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,ij=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function iS(e){let t=[],n=[],r=e.match(ij),i=r?.[1]??"",o=r?.index===void 0?e:e.slice(0,r.index);return i.replace(ik,(e,r,i)=>{let o=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?t.push(...o):n.push(...o),""}),{body:o.trim(),readFiles:t,modifiedFiles:n}}let iC=/(?:no body|no content|empty body)(?!\s*\w)/i,i_=new Set([400,413,422]);function iI(e,t={}){let n=(e??"").split("\n").map(e=>e.trim()).filter(Boolean);return 0===n.length?"":t.streaming?n[n.length-1]:n[0]}function iR(e){let t,n=[],r=null,i=0,o=0,l=[],s=[],a=()=>({lineNo:null,text:"",type:"empty"}),d=()=>{if(!r){l=[],s=[];return}let e=Math.max(l.length,s.length);for(let t=0;t<e;t++){let e=l[t]?{lineNo:l[t].lineNo,text:l[t].text,type:"removed"}:a(),n=s[t]?{lineNo:s[t].lineNo,text:s[t].text,type:"added"}:a();r.rows.push({type:"line",left:e,right:n})}l=[],s=[]};for(let a of e.split(/\r?\n/)){if(a.startsWith("--- ")){d(),t=iT(a.slice(4));continue}if(a.startsWith("+++ ")){d(),r={oldPath:t,newPath:iT(a.slice(4)),rows:[]},n.push(r);continue}let e=a.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(e){r||(r={rows:[]},n.push(r)),d(),i=Number(e[1]),o=Number(e[2]),r.rows.push({type:"hunk",text:a});continue}if(!r)continue;if(a.startsWith("\\ ")){d(),r.rows.push({type:"hunk",text:a});continue}let c=a[0],u=a.slice(1);" "===c?(d(),r.rows.push({type:"line",left:{lineNo:i++,text:u,type:"context"},right:{lineNo:o++,text:u,type:"context"}})):"-"===c?l.push({lineNo:i++,text:u}):"+"===c?s.push({lineNo:o++,text:u}):""!==a&&(d(),r.rows.push({type:"hunk",text:a}))}d();let c=n.filter(e=>e.rows.some(e=>"line"===e.type));return c.length>0?c:null}function iT(e){return e.split(" ")[0].trim()}function iE(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){let t=e.input;if("string"==typeof t&&t.length>0)return t}return"string"==typeof t?t:""}function iM(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function iA(e){return iL(e).length>0}function iL(e){if(!iM(e)||!iM(e.result))return[];let t=e.result.failures;if(!Array.isArray(t))return[];let n=[];for(let e of t){if("string"==typeof e){let t=e.trim();t&&n.push({filePath:t});continue}if(!iM(e))continue;let t="string"==typeof e.filePath?e.filePath.trim():"",r="string"==typeof e.message&&e.message.trim()?e.message.trim():void 0;(t||r)&&n.push(r?{filePath:t,message:r}:{filePath:t})}return n}function iz(e){if(!iM(e)||!iM(e.result))return[];let t=e.result.appliedFiles;if(!Array.isArray(t))return[];let n=[];for(let e of t){if("string"!=typeof e)continue;let t=e.trim();t&&!n.includes(t)&&n.push(t)}return n}function iW(){let e=[],t=[],n=[],r=()=>({lineNo:null,text:"",type:"empty"}),i=()=>{let i=Math.max(t.length,n.length);for(let o=0;o<i;o++)e.push({type:"line",left:t[o]??r(),right:n[o]??r()});t=[],n=[]};return{rows:e,context(t,n){i(),e.push({type:"line",left:{lineNo:n,text:t,type:"context"},right:{lineNo:n,text:t,type:"context"}})},removed(e,n){t.push({lineNo:n,text:e,type:"removed"})},added(e,t){n.push({lineNo:t,text:e,type:"added"})},finish(){i();for(let t=e.length-1;t>=0;t--)"line"!==e[t].type&&e.splice(t,1)}}}function i$(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e.files;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.filePath||"string"!=typeof e.diff)continue;let t=iW();for(let n of e.diff.split(/\r?\n/)){let e=n.match(/^([+\- ])\s*(\d+) (.*)$/);if(!e)continue;let[,r,i,o]=e,l=Number(i);"+"===r?t.added(o,l):"-"===r?t.removed(o,l):t.context(o,l)}t.finish();let r="add"===e.operation,i="delete"===e.operation;n.push({oldPath:r?void 0:e.filePath,newPath:i?void 0:e.movePath??e.filePath,rows:t.rows})}let r=n.filter(e=>e.rows.length>0);return r.length>0?r:null}function iP(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function iF(e){return e.toLowerCase().includes("apply_patch")}let iH={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},iD={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},iN={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"};function iB(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function iO(e){return null!==(iH[iB(e)]??null)}function iU(e){return null!==(iD[iB(e)]??null)}function iq(e){return null!==(iN[iB(e)]??null)}function iK(e,t,n,r=!1){let i=new URLSearchParams({type:t});return n&&"read"===t&&i.set("mime",n),r&&i.set("messageMedia","1"),`/api/files/${(0,rH.HG)(e)}?${i.toString()}`}function iJ(e,t,n=!1){return iK(e,"read",t,n)}function iV({imageBlocks:e,pathImages:t,pathAudio:n,pathVideo:i}){let o=e??[],l=t??[],s=n??[],a=i??[];return 0===o.length&&0===l.length&&0===s.length&&0===a.length?null:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:8},children:[(o.length>0||l.length>0)&&(0,r.jsxs)("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[o.map((e,t)=>{let n=it(e);return n?(0,r.jsx)(is,{src:n.src,fullSrc:n.src,mimeType:n.mimeType,alt:"",maxWidth:280,maxHeight:280},`b-${t}`):null}),l.map(e=>(0,r.jsx)(is,{src:iJ(e),fullSrc:iJ(e),downloadHref:iK(e,"download"),downloadName:e.replace(/\\/g,"/").split("/").pop()||"image",alt:e,title:e,maxWidth:280,maxHeight:280},e))]}),s.map(e=>(0,r.jsxs)("div",{style:{minWidth:200,maxWidth:420},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:e.split(/[\\/]/).pop()}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:iJ(e),style:{width:"100%"}})]},e)),a.map(e=>(0,r.jsxs)("div",{style:{minWidth:200,maxWidth:480},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:e.split(/[\\/]/).pop()}),(0,r.jsx)("video",{controls:!0,preload:"metadata",src:iJ(e),style:{width:"100%",maxHeight:320,borderRadius:6,background:"var(--bg)",border:"1px solid var(--border)"}})]},e))]})}let iY=new Map,iX=new Map;function iG(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)&&!0===e.deferredHeavy}function iZ(e){if(!e)return null;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(r)return i;let o=t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0});return`${o} ${i}`}let iQ=(0,i.memo)(function({message:e,isStreaming:t,toolResults:n,toolExecutionSnapshots:i,modelNames:o,cwd:l,onOpenFile:s,onReferenceFile:a,writtenFiles:d,entryId:c,onBranchHere:u,onNewSessionFromHere:p,onBranchFromAssistant:h,onNewSessionFromAnswer:f,forking:g,showTimestamp:m,prevTimestamp:x,sessionId:v,toolsActive:y,contextUsage:b,onCompactContext:w,hiddenThinkingLabel:k}){if("user"===e.role)return(0,r.jsx)(i0,{message:e,cwd:l,onOpenFile:s,entryId:c,onBranchHere:u,onNewSessionFromHere:p,forking:g});if("assistant"===e.role)return(0,r.jsx)(i1,{message:e,isStreaming:t,toolResults:n,toolExecutionSnapshots:i,modelNames:o,cwd:l,onOpenFile:s,onReferenceFile:a,writtenFiles:d,showTimestamp:m,prevTimestamp:x,sessionId:v,entryId:c,onBranchFromAssistant:h,onNewSessionFromAnswer:f,toolsActive:y,contextUsage:b,onCompactContext:w,hiddenThinkingLabel:k});if("toolResult"===e.role)return null;if("custom"===e.role){if(e.customType===nm){let t=nv(e.details);return t?(0,r.jsx)(ix,{binary:t}):null}if("compaction"===e.customType)return(0,r.jsx)(of,{message:e});if("pidance.command"===e.customType)return(0,r.jsx)(og,{message:e});if("branch_summary"===e.customType)return(0,r.jsx)(om,{message:e});if("pidance.activity"===e.customType){var j;let t=op(j=e.details)&&1===j.version&&"string"==typeof j.kind&&iy.includes(j.kind)&&"string"==typeof j.title&&""!==j.title.trim()&&"string"==typeof j.content&&(void 0===j.source||"string"==typeof j.source)&&(void 0===j.requestId||"string"==typeof j.requestId)&&(void 0===j.metadata||op(j.metadata))?j:null;if(t)return(0,r.jsx)(ok,{message:e,activity:t})}return(0,r.jsx)(oj,{message:e,cwd:l,onOpenFile:s})}return"bashExecution"===e.role?(0,r.jsx)(oC,{message:e,sessionId:v}):null},(e,t)=>{var n,r;return e.message===t.message&&e.isStreaming===t.isStreaming&&function(e,t,n){if(t===n||"assistant"!==e.role)return!0;for(let r of e.content??[])if("toolCall"===r.type&&t?.get(r.toolCallId)!==n?.get(r.toolCallId))return!1;return!0}(e.message,e.toolResults,t.toolResults)&&e.toolExecutionSnapshots===t.toolExecutionSnapshots&&e.modelNames===t.modelNames&&e.cwd===t.cwd&&e.onOpenFile===t.onOpenFile&&e.onReferenceFile===t.onReferenceFile&&((n=e.writtenFiles)===(r=t.writtenFiles)||(n&&r?n.length===r.length&&n.every((e,t)=>e===r[t]):(n?.length??0)===(r?.length??0)))&&e.entryId===t.entryId&&e.onBranchHere===t.onBranchHere&&e.onNewSessionFromHere===t.onNewSessionFromHere&&e.onBranchFromAssistant===t.onBranchFromAssistant&&e.onNewSessionFromAnswer===t.onNewSessionFromAnswer&&e.forking===t.forking&&e.showTimestamp===t.showTimestamp&&e.prevTimestamp===t.prevTimestamp&&e.sessionId===t.sessionId&&e.hiddenThinkingLabel===t.hiddenThinkingLabel});function i0({message:e,cwd:t,onOpenFile:n,entryId:o,onBranchHere:l,onNewSessionFromHere:s,forking:a}){let{t:d}=(0,eU.s9)(),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!1),f="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),g="string"==typeof e.content?[]:e.content.filter(e=>"image"===e.type),m=e.binaryBlocks??[],x=m.some(e=>"image"===e.kind),v=(0,i.useMemo)(()=>(function(e){let t,n=[],r=[],i=[],o=new Set,l=/(?:^|[\s`"'(\[]|-\s)((?:\/|[A-Za-z]:[\\/]|~\/)[^\s`"'\)\]]+\.(?:png|jpe?g|gif|webp|bmp|avif|svg|mp3|wav|ogg|oga|opus|m4a|aac|flac|weba|mp4|m4v|webm|ogv|mov|mkv|avi))\b/gim;for(;null!==(t=l.exec(e));){let e=t[1]?.replace(/[.,;:]+$/,"")??"";!(!e||o.has(e))&&(o.add(e),iq(e)?i.push(e):iU(e)?r.push(e):iO(e)&&n.push(e))}return{images:n,audio:r,video:i}})(f),[f]),y=iZ(e.timestamp),b=!!o&&!!l,w=!!o&&!!s;return(0,r.jsxs)("div",{style:{marginBottom:28,display:"flex",flexDirection:"column",alignItems:"flex-end"},onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:6,maxWidth:"85%"},children:(0,r.jsxs)("div",{style:{flex:1,minWidth:0,background:"var(--user-bg)",border:"1px solid color-mix(in srgb, var(--accent) 18%, var(--border))",borderRadius:"var(--radius-lg) var(--radius-lg) var(--radius-xs) var(--radius-lg)",padding:"11px 14px",fontSize:14,lineHeight:1.6,color:"var(--text)",wordBreak:"break-word"},children:[(0,r.jsx)(iV,{imageBlocks:x?[]:g,pathImages:v.images,pathAudio:v.audio,pathVideo:v.video}),m.length>0&&(0,r.jsx)(iv,{binaries:m}),f&&(0,r.jsx)(iu,{className:"markdown-user-message",cwd:t,onOpenFile:n,children:f})]})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,marginTop:3},children:[(0,r.jsx)("div",{style:{display:"flex",gap:3,opacity:+!!c,pointerEvents:c?"auto":"none",transition:"opacity 0.12s"},children:(0,r.jsx)("button",{onClick:()=>{tC(f).then(()=>{h(!0),setTimeout(()=>h(!1),1500)})},"data-tooltip":d("message_copy"),className:"instant-tooltip","aria-label":d("message_copy"),style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"3px 6px",height:22,background:"none",border:"none",borderRadius:5,color:p?"var(--accent)":"var(--text-dim)",cursor:"pointer",transition:"color 0.12s"},onMouseEnter:e=>{p||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{p||(e.currentTarget.style.color="var(--text-dim)")},children:p?(0,r.jsx)(rd.A,{size:11,strokeWidth:1.8}):(0,r.jsx)(rc.A,{size:11,strokeWidth:1.8})})}),(b||w)&&(0,r.jsxs)("div",{style:{display:"flex",gap:3,opacity:c||a?1:0,pointerEvents:c||a?"auto":"none",transition:"opacity 0.12s"},children:[b&&(0,r.jsx)("button",{onClick:()=>{l(o,f)},"data-tooltip":d("message_branchHereTooltip"),className:"instant-tooltip","aria-label":d("message_branchHere"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:22,padding:0,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsx)(ru.A,{size:14,strokeWidth:1.8})}),w&&(0,r.jsx)("button",{onClick:()=>{s(o,f)},disabled:a,"data-tooltip":d(a?"message_creating":"message_newSessionFromHereTooltip"),className:"instant-tooltip","aria-label":d("message_newSessionFromHere"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:22,padding:0,background:"none",border:"none",borderRadius:5,color:a?"var(--accent)":"var(--text-dim)",cursor:a?"not-allowed":"pointer",transition:"color 0.12s"},onMouseEnter:e=>{a||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{a||(e.currentTarget.style.color="var(--text-dim)")},children:(0,r.jsx)(rp.A,{size:14,strokeWidth:1.8})})]}),y&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:y})]})]})}function i1({message:e,isStreaming:t,toolResults:n,toolExecutionSnapshots:o,modelNames:l,cwd:s,onOpenFile:a,onReferenceFile:d,writtenFiles:c,showTimestamp:u,prevTimestamp:p,sessionId:h,entryId:f,onBranchFromAssistant:g,onNewSessionFromAnswer:m,toolsActive:x,contextUsage:v,onCompactContext:y,hiddenThinkingLabel:b}){var w,k,j;let S,C,_,I,R,{t:T}=(0,eU.s9)(),E=ra(),M=u?iZ(e.timestamp):null,A=(w=e.content??[],R=[],w.forEach((e,t)=>{if(nc(e.type))return void R.push({block:nu(e),sourceIndex:t});if("text"===e.type&&"string"==typeof e.text&&nh.test(e.text)){for(let n of(nh.lastIndex=0,function(e){let t,n=[],r=0;for(np.lastIndex=0;null!==(t=np.exec(e));)t.index>r&&n.push({type:"text",value:e.slice(r,t.index)}),n.push({type:"thinking",value:t[1]??""}),r=t.index+t[0].length;let i=e.slice(r),o=nh.exec(i);return o&&void 0!==o.index?(o.index>0&&n.push({type:"text",value:i.slice(0,o.index)}),n.push({type:"thinking",value:i.slice(o.index+o[0].length)})):i.length>0&&n.push({type:"text",value:i}),n}(e.text)))"thinking"===n.type?R.push({block:{type:"thinking",thinking:n.value},sourceIndex:t}):n.value.length>0&&R.push({block:{...e,type:"text",text:n.value},sourceIndex:t});return}R.push({block:e,sourceIndex:t})}),R).map(({block:e,sourceIndex:t})=>({block:e,originalIndex:t})).filter(({block:e})=>!function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===nd(e).trim()}(e,{isStreaming:t})),L=A.map(({block:e})=>e),[z,W]=(0,i.useState)(!1),[$,P]=(0,i.useState)(!1),F=(0,i.useRef)(null),[H,D]=(0,i.useState)(null),N=(0,i.useRef)(A);N.current=A;let B=(0,i.useRef)(new Map),[O,U]=(0,i.useState)(new Map),q=(0,i.useMemo)(()=>{if(!e.timestamp||!p)return;let t=Math.round((e.timestamp-p)/1e3);return t>0?t:void 0},[e.timestamp,p]),K=(0,i.useMemo)(()=>{let t=new Map;if(!n||!e.timestamp)return t;for(let[r,i]of n)if(i.timestamp&&e.timestamp){let n=Math.round((i.timestamp-e.timestamp)/1e3);n>0&&t.set(r,n)}return t},[n,e.timestamp]),J=(0,i.useMemo)(()=>new Map(o?.map(e=>[e.toolCallId,e])??[]),[o]),V=L.filter(e=>"text"===e.type).map(e=>e.text).join("\n");(0,i.useEffect)(()=>{if(!t){let e=new Date().getTime();U(t=>{let n=new Map(t);for(let[t,r]of B.current)n.has(t)||n.set(t,Math.round((e-r)/1e3));return n}),F.current=null,D(null);return}let e=setInterval(()=>{let e=N.current,t=e.map(({block:e})=>e),n=Date.now();e.forEach(({originalIndex:e})=>{B.current.has(e)||B.current.set(e,n)}),U(t=>{let r=!1,i=new Map(t);for(let t=0;t<e.length-1;t++){let o=e[t].originalIndex,l=e[t+1].originalIndex;if(!i.has(o)&&B.current.has(o)){let e=B.current.get(o),t=B.current.get(l)??n;i.set(o,Math.round((t-e)/1e3)),r=!0}}return r?i:t});let r=0;for(let e of t)"text"===e.type?r+=e.text?.length??0:"thinking"===e.type?r+=e.thinking?.length??0:"toolCall"===e.type&&(r+=JSON.stringify(e.input??{}).length);if(0===r)return;null===F.current&&(F.current=n);let i=(n-F.current)/1e3;i>.5&&D(r/4/i)},300);return()=>clearInterval(e)},[t]);let Y=e.stopReason,X="string"==typeof e.errorMessage?e.errorMessage.trim():"",G="error"===Y||X.length>0&&"end_turn"!==Y&&"toolUse"!==Y&&"length"!==Y,Z="aborted"===Y,Q=G||Z||X.length>0,ee="length"===e.stopReason;return 0!==L.length||t||Q||ee?(0,r.jsxs)("div",{style:{marginBottom:30},onMouseEnter:()=>W(!0),onMouseLeave:()=>W(!1),children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",marginBottom:8,display:"flex",alignItems:"center",gap:6},children:[e.provider&&(0,r.jsx)("span",{children:l?.[`${e.provider}:${e.model}`]??l?.[e.model]??e.model}),t&&(()=>{let e,t=0;for(let e of L)"text"===e.type?t+=e.text?.length??0:"thinking"===e.type?t+=e.thinking?.length??0:"toolCall"===e.type&&(t+=JSON.stringify(e.input??{}).length);let n=Math.round(t/4);return(0,r.jsx)(r.Fragment,{children:n>0&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text)"},title:T("message_estimatedTokensStreaming"),children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:2,fontSize:11,fontWeight:400},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1.5",x2:"5",y2:"8.5"}),(0,r.jsx)("polyline",{points:"2 6 5 8.5 8 6"})]}),n]}),null!==H&&(e=H>=50?"#53b3cb":H>=30?"#9bc53d":H>=15?"#f9c22e":"#e01a4f",(0,r.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",borderRadius:4,background:e,color:"#fff",fontSize:11,fontWeight:400},children:[H.toFixed(1)," t/s"]}))]})})})()]}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:A.map(({block:i,originalIndex:o},l)=>{var c;return(0,r.jsx)(i2,{block:i,toolResults:n,toolExecutionMap:J,isStreaming:t,activeStreamBlock:(c=A.length,!!t&&c>0&&l===c-1),streamingDuration:O.get(o)??("thinking"===i.type?q:void 0),toolCallDurations:K,cwd:s,onOpenFile:a,onReferenceFile:d,sessionId:h,entryId:f,blockIndex:o,toolsActive:x,startedAt:e.timestamp,hiddenThinkingLabel:b},`${f??"stream"}-${o}`)})}),!t&&Q&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:10,padding:"10px 12px",borderRadius:8,border:`1px solid ${Z?"var(--status-warning-border, var(--border))":"var(--status-danger-border, var(--border))"}`,background:Z?"var(--status-warning-bg, var(--bg-subtle))":"var(--status-danger-bg, var(--bg-subtle))",color:Z?"var(--status-warning, var(--text))":"var(--error-text, var(--status-danger, var(--text)))",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[(0,r.jsxs)("div",{style:{fontWeight:600,marginBottom:4*!!X},children:[Z?T("message_aborted"):T("message_apiError"),Y&&"error"!==Y&&"aborted"!==Y?(0,r.jsxs)("span",{style:{fontWeight:400,opacity:.8},children:[" (",Y,")"]}):null]}),X?(0,r.jsx)("div",{children:X}):null,!function(e){let t=(e??"").trim();if(!t||!iC.test(t))return!1;let n=function(e){for(let t of[/status code (\d{3})/i,/API error \((\d{3})\)/i,/\b([45]\d{2})\b/]){let n=e.match(t);if(n)return Number(n[1])}return null}(t);return null!==n&&i_.has(n)}(X)?null:(0,r.jsxs)("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("div",{children:T("message_unexplainedRejection")}),v&&null!==v.tokens?(0,r.jsx)("div",{style:{opacity:.85},children:T("message_unexplainedRejectionUsage",{tokens:v.tokens.toLocaleString(),window:v.contextWindow.toLocaleString()})}):null,y?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8,marginTop:2},children:[(0,r.jsx)("button",{type:"button",onClick:y,style:{padding:E?"8px 12px":"3px 10px",minHeight:E?40:void 0,borderRadius:5,border:"1px solid currentColor",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},children:T("message_compactContext")}),(0,r.jsx)("span",{style:{opacity:.85},children:T("message_compactContextHint")})]}):null]})]}),!t&&ee&&(0,r.jsxs)("div",{role:"alert",style:{marginTop:10,padding:"10px 12px",borderRadius:8,border:"1px solid var(--status-warning-border, var(--border))",background:"var(--status-warning-bg, var(--bg-subtle))",color:"var(--status-warning, var(--text))",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[(0,r.jsx)("div",{style:{fontWeight:600,marginBottom:4},children:T("message_truncatedTitle")}),(0,r.jsx)("div",{children:T("message_truncated")})]}),(0,r.jsx)(oy,{files:c,isStreaming:t,onOpenFile:a,onReferenceFile:d}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:4},children:[e.usage&&!t&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:(k=e.usage,j=e,S=[],k.input&&S.push(`${k.input.toLocaleString()} in`),k.output&&S.push(`${k.output.toLocaleString()} out`),k.cacheRead&&S.push(`${k.cacheRead.toLocaleString()} cache`),k.cost?.total&&S.push(`$${k.cost.total.toFixed(4)}`),C=j?.provider?.trim(),_=j?.model?.trim(),(C||_)&&S.push([C,_].filter(Boolean).join(" / ")),(I=j?.thinkingLevel?.trim())&&"off"!==I&&S.push(I),S.join(" \xb7 "))}),V&&!t&&(0,r.jsx)("button",{onClick:()=>{tC(V).then(()=>{P(!0),setTimeout(()=>P(!1),1500)})},"data-tooltip":T("message_copyAnswer"),className:"instant-tooltip","aria-label":T("message_copyAnswer"),style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"3px 6px",height:22,width:22,background:"none",border:"none",borderRadius:5,color:$?"var(--accent)":"var(--text-dim)",cursor:"pointer",transition:"opacity 0.12s, color 0.12s",opacity:+!!z,pointerEvents:z?"auto":"none"},onMouseEnter:e=>{$||(e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{$||(e.currentTarget.style.color="var(--text-dim)")},children:$?(0,r.jsx)(rd.A,{size:11,strokeWidth:1.8}):(0,r.jsx)(rc.A,{size:11,strokeWidth:1.8})}),f&&!t&&g&&(0,r.jsx)("button",{onClick:()=>{g(f)},"data-tooltip":T("message_branchFromAnswerTooltip"),className:"instant-tooltip","aria-label":T("message_branchFromAnswer"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:22,padding:0,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",opacity:+!!z,pointerEvents:z?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsx)(ru.A,{size:14,strokeWidth:1.8})}),f&&!t&&m&&(0,r.jsx)("button",{onClick:()=>{m(f)},"data-tooltip":T("message_newSessionFromAnswerTooltip"),className:"instant-tooltip","aria-label":T("message_newSessionFromAnswer"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:22,padding:0,background:"none",border:"none",borderRadius:5,color:"var(--text-dim)",cursor:"pointer",opacity:+!!z,pointerEvents:z?"auto":"none",transition:"opacity 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsx)(rp.A,{size:14,strokeWidth:1.8})}),M&&!t&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginLeft:"auto"},children:M})]})]}):null}function i2({block:e,toolResults:t,toolExecutionMap:n,isStreaming:i,activeStreamBlock:o,streamingDuration:l,toolCallDurations:s,cwd:a,onOpenFile:d,onReferenceFile:c,sessionId:u,entryId:p,blockIndex:h,toolsActive:f,startedAt:g,hiddenThinkingLabel:m}){if("text"===e.type)return(0,r.jsx)(i4,{block:e,isStreaming:i,cwd:a,onOpenFile:d});if("thinking"===e.type)return(0,r.jsx)(ot,{block:e,duration:l,isStreaming:!!o,sessionId:u,entryId:p,blockIndex:h,hiddenThinkingLabel:m});if("image"===e.type){let t=it(e);return t?(0,r.jsx)(is,{src:t.src,fullSrc:t.src,mimeType:t.mimeType,alt:"",maxWidth:520,maxHeight:360}):null}if("toolCall"===e.type){let i=t?.get(e.toolCallId),o=s?.get(e.toolCallId);return(0,r.jsx)(on,{block:e,result:i,snapshot:n?.get(e.toolCallId),duration:o,sessionId:u,onReferenceFile:c,pending:!i&&!0===f,startedAt:i||!0!==f?void 0:g})}return null}function i4({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(iu,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function i6(){return ra()?T:R}let i5={flexShrink:0,padding:0,border:"none",background:"none",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,lineHeight:1.4},i8=(0,i.createContext)(null);function i3({value:e,children:t}){return(0,r.jsx)(i8.Provider,{value:e,children:t})}let i9={flexShrink:0,fontSize:11,color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},i7={flex:1,minWidth:0,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"};function oe({label:e,expanded:t,onToggle:n,summary:i,summaryTitle:o,meta:l,showCommandLabel:s,running:a=!1,toggleTitle:d}){let{t:c}=(0,eU.s9)();return(0,r.jsxs)("button",{type:"button",onClick:n,"aria-expanded":t,className:a?"tool-row-running":void 0,title:t?d?.collapse??c("chat_hideProcess"):d?.expand??c("chat_showProcess"),"data-block-header":"true",style:{display:"flex",alignItems:"center",gap:7,width:"100%",boxSizing:"border-box",padding:"6px 10px",minWidth:0,border:"none",background:"none",color:"inherit",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:i5,children:e}),null!==i&&(0,r.jsx)("span",{style:i7,title:o??void 0,children:i}),s&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,textTransform:"uppercase",letterSpacing:"0.08em",flexShrink:0},children:c("message_toolCommand")}),l&&(0,r.jsx)("span",{style:{...i9,marginLeft:"auto"},children:l})]})}function ot({block:e,duration:t,isStreaming:n,sessionId:o,entryId:l,blockIndex:s,hiddenThinkingLabel:a}){var d;let{t:c}=(0,eU.s9)(),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(!1),[x,v]=(0,i.useState)(null),y=g?c("message_thinkingLoading"):x??(e.deferred?h:nd(e)),b=g?c("message_thinkingLoading"):iI(y,{streaming:n}),w="string"==typeof a&&""!==a?function(e){let t=Array.from(e);if(t.length<=60)return e;let n=Math.ceil(29.5),r=59-n;return`${t.slice(0,n).join("")}…${t.slice(t.length-r).join("")}`}(a):null,k=(0,i.useRef)(null),[j,S]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let t=k.current;if(!t||!0!==e.deferred||"u"<typeof IntersectionObserver)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&S(!0)},{rootMargin:"100% 0px"});return n.observe(t),()=>n.disconnect()},[e.deferred]),(0,i.useEffect)(()=>{(j||u)&&C()},[j,u]);let C=async()=>{if(e.deferred&&null===h&&!g){if(!o||!l)return void v(c("message_thinkingUnavailable"));m(!0),v(null);try{f(await function(e,t,n){let r=`${e}:${t}:${n}`,i=iY.get(r);if(i)return iY.delete(r),iY.set(r,i),i;let o=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw iY.delete(r),e});if(iY.set(r,o),iY.size>100){let e=iY.keys().next().value;e&&iY.delete(e)}return o}(o,l,s))}catch(e){v(e instanceof Error?e.message:String(e))}finally{m(!1)}}};(0,i.useEffect)(()=>{u&&C()},[u]);let _=async()=>{let t=!u;p(t),t&&e.deferred&&null===h&&await C()};return(0,r.jsxs)("div",{ref:k,style:{border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",fontSize:13,background:"var(--bg-panel)"},children:[(0,r.jsx)(oe,{label:(d=c("chat_blockThinking"),`${d}\xb7`),expanded:u,onToggle:()=>void _(),summary:u?null:w??b,summaryTitle:u||null===w||w===a?null:a,meta:void 0===t?null:ol(1e3*t)}),u&&(0,r.jsx)("div",{tabIndex:0,className:"chat-selectable",style:{...E,color:x?"var(--error-text)":"var(--text-muted)"},children:y})]})}function on({block:e,result:t,snapshot:n,duration:o,sessionId:l,onReferenceFile:s,pending:a,startedAt:d,defaultExpanded:c}){var u,p,h;let f,g,{t:m}=(0,eU.s9)(),x=i6(),[v,y]=(0,i.useState)(!0===c),b=(0,i.useContext)(i8),w=b?.revision;(0,i.useEffect)(()=>{b&&y(b.expanded)},[w]);let[k,j]=(0,i.useState)(()=>Date.now()),[S,C]=(0,i.useState)(void 0),[_,I]=(0,i.useState)(void 0),[R,T]=(0,i.useState)(!1),E=(0,i.useRef)(null),M=(0,i.useRef)(!0),A=(0,i.useRef)(!1),L=!t&&(n?.status==="running"||!0===a),z=iP(e.toolName),W=iF(e.toolName),$=t&&(void 0!==S||void 0!==_)?{...t,...void 0!==S?{details:S}:{},...void 0!==_?{content:_}:{}}:t,P=$&&!$.isError?function(e){let t=e.details;if(!op(t))return null;let n="string"==typeof t.patch?t.patch:null;if(n)return{text:n};let r="string"==typeof t.diff?t.diff:null;return r?{text:r}:null}($):null,F=W?function(e,t){if(!iF(e.toolName))return null;let n=function(e){if(!e.includes("*** Begin Patch")&&!/\*\*\* (?:Add|Delete|Update) File: /.test(e))return null;let t=[],n=null,r=null,i=null;for(let o of e.split(/\r?\n/)){let e=o.match(/^\*\*\* (Add|Delete|Update) File: (.+)$/);if(e){let o=e[1]?.toLowerCase()??"update",l=(e[2]??"").trim();n?.finish(),i=o,r={oldPath:"add"===o?void 0:l,newPath:"delete"===o?void 0:l,rows:(n=iW()).rows},t.push(r);continue}if(/^\*\*\* Move to: /.test(o)){let e=o.replace(/^\*\*\* Move to: /,"").trim();r&&"update"===i&&(r.newPath=e);continue}if(!n||!r)continue;let l=n;if(!o.startsWith("*** ")&&!("update"===i&&o.startsWith("@@"))){if("update"===i){let e=o[0],t=o.slice(1);"+"===e?l.added(t,null):"-"===e?l.removed(t,null):" "===e?l.context(t,null):""!==o&&l.context(o,null)}else if("add"===i){if(""===o)continue;l.added(o.startsWith("+")?o.slice(1):o,null)}else if("delete"===i){if(""===o)continue;l.removed(o.startsWith("-")?o.slice(1):o,null)}}}n?.finish();let o=t.filter(e=>e.rows.length>0);return o.length>0?o:null}(iE(e.input));if(n)return n;let r=t&&!t.isError?t.details:void 0;if(op(r)){let e=i$(r.preview);if(e)return e}return null}(e,$):null,H=W?0===(f=function(e){let t=[];for(let n of e.matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)){let e=(n[1]??"").trim();e&&!t.includes(e)&&t.push(e)}return t}(iE(e.input))).length?null:f.join(", ").slice(0,120):null,D=W?iL($?.details):[],N=W?iz($?.details):[],B=$?$.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,O=$?$.content.filter(e=>"image"===e.type):[],U=null!==B&&("(no output)"===B.trim()||""===B.trim()),q=($?.isError??!1)||W&&iA($?.details),K=function(e,t,n=!1,r=!1){return"running"===e||r?"var(--status-running)":"success"===e||n&&!t?"var(--status-success)":"error"===e||t?"var(--status-danger)":"cancelled"===e?"var(--text-dim)":"var(--text-muted)"}(n?.status,q,null!=$,a),J=function(e,t){if(t?.command)return t.command;let n=e.input;if(n&&"object"==typeof n&&"command"in n){let e=n.command;if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.command)return e.command;if("string"==typeof e.cmd)return e.cmd}}var r=e;let i=r.input;if(!i||"object"!=typeof i)return"";let o=Object.keys(i);return 0===o.length?"":"command"in i?String(i.command).slice(0,120):"path"in i?String(i.path).slice(0,120):"file_path"in i?String(i.file_path).slice(0,120):"pattern"in i?String(i.pattern).slice(0,120):"query"in i?String(i.query).slice(0,120):String(i[o[0]]).slice(0,120)}(e,n),V=or(n?.renderedCallLines??e.renderedCallLines),Y=or(n?.renderedLines),X=or(n?.renderedResultLines??$?.renderedResultLines),G=n?.toolLabel??e.toolLabel,Z=(n?.toolShell??e.toolShell)==="self"&&!!(V||Y||X),Q=G&&""!==G.trim()?(u=G.trim(),`${u}\xb7`):(p=(g=e.toolName.trim()||"tool").charAt(0).toUpperCase()+g.slice(1),`${p}\xb7`),ee=n?Math.max(0,("running"===n.status?k:n.endedAt??n.startedAt)-n.startedAt):void 0!==d?!0===a||void 0===o?Math.max(0,k-d):1e3*o:void 0===o?void 0:1e3*o,et=L?iI(n?.output,{streaming:!0})||J:H||J||iI(n?.output,{streaming:!1}),en=(h={hasSnapshot:void 0!==n,isRunning:L,hasResult:void 0!==$}).hasSnapshot&&(h.isRunning||!h.hasResult);return(0,i.useEffect)(()=>{if(!L)return;let e=setInterval(()=>j(Date.now()),500);return()=>clearInterval(e)},[L]),(0,i.useEffect)(()=>{v&&(M.current=!0)},[v]),(0,i.useEffect)(()=>{var e,t;e=E.current,t=v&&M.current,e&&t&&(A.current=!0,e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{A.current=!1}))},[v,n?.output,n?.renderedLines,Y]),(0,i.useEffect)(()=>{if(!v||!t||!l||R)return;let n=iG(t.details)&&void 0===S,r=t.content.some(e=>"text"===e.type&&/^\[\d+ tool result image(?:s)? omitted from initial history payload/.test(e.text))&&void 0===_;if(!n&&!r)return;let i=!1;return T(!0),(function(e,t){let n=`${e}:${t}`,r=iX.get(n);if(r)return iX.delete(n),iX.set(n,r),r;let i=fetch(`/api/sessions/${encodeURIComponent(e)}/tool-results/${encodeURIComponent(t)}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json(),n=Array.isArray(t.content)?t.content.filter(e=>"object"==typeof e&&null!==e&&("text"===e.type||"image"===e.type)):[];return{details:t.details??null,content:n}}).catch(e=>{throw iX.delete(n),e});if(iX.set(n,i),iX.size>50){let e=iX.keys().next().value;e&&iX.delete(e)}return i})(l,e.toolCallId).then(e=>{!i&&(n&&C(e.details),r&&I(e.content))}).catch(()=>{!i&&n&&C(t.details),!i&&r&&I(t.content)}).finally(()=>{i||T(!1)}),()=>{i=!0}},[v,t,l,e.toolCallId,S,_,R]),(0,r.jsxs)("div",{style:Z?{fontSize:12}:{borderRadius:"var(--radius-md)",overflow:"hidden",fontSize:12,border:"1px solid var(--border)",borderLeft:`3px solid ${K}`,background:"var(--tool-bg)"},children:[(!v||!J)&&(0,r.jsx)(oe,{label:Q,expanded:v,onToggle:()=>y(!v),summary:v?null:et,meta:void 0===ee?null:ol(ee),running:L}),v&&J&&(0,r.jsxs)("div",{style:Z?void 0:{background:"var(--bg-subtle)"},children:[(0,r.jsx)(oe,{label:Q,expanded:v,onToggle:()=>y(!v),summary:null,meta:void 0===ee?null:ol(ee),showCommandLabel:!0,running:L}),(0,r.jsx)("code",{style:{display:"block",padding:"0 10px 8px",maxHeight:x,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11.5,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:J})]}),v&&V&&(0,r.jsx)(oo,{lines:V,statusColor:K,bare:Z}),v&&!z&&!W&&(0,r.jsx)("div",{style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,maxHeight:x,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",background:Z?void 0:"var(--bg-subtle)",borderTop:Z?void 0:`1px solid color-mix(in srgb, ${K} 20%, var(--border))`,display:"flex",flexDirection:"column",gap:3},children:(function(e){let t=[];for(let[n,r]of Object.entries(e)){if(null==r)continue;let e="string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):"";if(e)t.push({key:n,value:e});else try{t.push({key:n,value:JSON.stringify(r).slice(0,200)})}catch{t.push({key:n,value:"[…]"})}}return t})(e.input).filter(e=>"command"!==e.key).map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",width:88,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.key}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:e.value})]},e.key))}),v&&en&&n&&(0,r.jsxs)("div",{style:Z?void 0:{borderTop:`1px solid color-mix(in srgb, ${K} 24%, var(--border))`,background:"var(--tool-bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"6px 10px 4px",color:"var(--text-dim)",fontSize:10,textTransform:"uppercase",letterSpacing:"0.08em"},children:[(0,r.jsx)("span",{children:m("message_toolLiveOutput")}),n.truncated&&(0,r.jsx)("span",{style:{color:"var(--warning)",textTransform:"none",letterSpacing:0},children:m("message_toolOutputTruncated")})]}),(0,r.jsx)("pre",{ref:E,tabIndex:0,onScroll:e=>{if(!A.current){var t;M.current=(t=e.currentTarget).scrollHeight-t.scrollTop-t.clientHeight<=24}},style:{margin:0,padding:"4px 10px 10px",maxHeight:x,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",color:Y||n.output?"var(--text-muted)":"var(--text-dim)",background:"var(--tool-bg)",fontFamily:"var(--font-mono)",fontSize:11.5,lineHeight:1.55,whiteSpace:"pre"},children:Y?oi(Y,"tool-live"):n.output||m("message_toolWaitingOutput")})]}),v&&$&&(0,r.jsxs)(r.Fragment,{children:[O.length>0&&(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 10px",background:"var(--bg-subtle)"},children:(0,r.jsx)(iV,{imageBlocks:O})}),X?(0,r.jsx)(oo,{lines:X,statusColor:K,bare:Z}):R&&iG(t?.details)&&!P&&!F?(0,r.jsx)("div",{style:{padding:"8px 10px",borderTop:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11},children:m("message_thinkingLoading")}):F?(0,r.jsx)(os,{files:F,isError:q}):P?(0,r.jsx)(os,{diff:P,isError:q}):(0,r.jsx)(oh,{text:B??"",isEmpty:U,isError:q}),D.length>0&&(0,r.jsxs)("div",{role:"alert",style:{padding:"8px 10px",borderTop:"1px solid var(--status-danger-border)",background:"var(--status-danger-bg)",color:"var(--error-text)",fontSize:12,lineHeight:1.5,overflowWrap:"anywhere"},children:[(0,r.jsx)("div",{style:{fontWeight:600,marginBottom:4},children:m("message_applyPatchFailed")}),(0,r.jsx)("ul",{style:{margin:0,paddingLeft:18,display:"flex",flexDirection:"column",gap:3},children:D.map((e,t)=>(0,r.jsxs)("li",{children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11.5},children:e.filePath||"?"}),e.message?` — ${e.message}`:null]},`${e.filePath}-${t}`))})]}),N.length>0&&(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"baseline",gap:6,padding:"6px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--text-dim)",fontSize:11},children:[(0,r.jsx)("span",{children:m("message_modifiedFiles")}),N.map(e=>(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:2,minWidth:0},children:[(0,r.jsx)("code",{title:e,style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text)",overflowWrap:"anywhere"},children:e}),s?(0,r.jsx)(ov,{filePath:e,onReferenceFile:s}):null]},e))]})]})]})}function or(e){return Array.isArray(e)&&e.length>0&&e.every(e=>"string"==typeof e)?e:null}function oi(e,t){return e.map((n,i)=>{var o;return(0,r.jsxs)("span",{children:[(o=`${t}-${i}`,nG(n).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${o}-${t}`):e.text)),i<e.length-1?"\n":null]},`${t}-${i}`)})}function oo({lines:e,statusColor:t,bare:n=!1}){let i=i6();return(0,r.jsx)("pre",{tabIndex:0,style:n?{margin:0,padding:"8px 10px",maxHeight:i,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,whiteSpace:"pre"}:{margin:0,padding:"8px 10px",maxHeight:i,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",borderTop:`1px solid color-mix(in srgb, ${t} 24%, var(--border))`,background:"var(--bg-subtle)",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,whiteSpace:"pre"},children:oi(e,"tool-rendered")})}function ol(e){let t=Number.isFinite(e)?Math.max(0,e):0;if(t<1e3)return`${Math.floor(t)}ms`;let n=t/1e3;if(n<10)return`${n.toFixed(1)}s`;if(n<60)return`${Math.round(n)}s`;let r=Math.round(n);return`${Math.floor(r/60)}m ${String(r%60).padStart(2,"0")}s`}function os({diff:e,files:t,isError:n=!1}){return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--status-danger-border)":"var(--status-success-border)"}`,background:"var(--bg)"},children:(0,r.jsx)(oa,{text:e?.text,files:t})})}function oa({text:e,files:t}){let n=(0,i.useMemo)(()=>t??iR(e??""),[t,e]);if(!n)return(0,r.jsx)(ou,{text:e??""});let o=n.length>1;return(0,r.jsx)("div",{style:{maxHeight:"min(560px, 50vh)",overflowY:"auto",overflowX:"hidden",overscrollBehavior:"auto",touchAction:"pan-y",background:"var(--bg)"},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===t?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[o&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(od,{title:e.oldPath||"Before",side:"left"}),(0,r.jsx)(od,{title:e.newPath||"After",side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(oc,{cell:e.left,side:"left"}),(0,r.jsx)(oc,{cell:e.right,side:"right"})]},t))})]},t))})}function od({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function oc({cell:e,side:t}){let n="added"===e.type?"var(--diff-added-bg)":"removed"===e.type?"var(--diff-removed-bg)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"var(--diff-added-text)":"removed"===e.type?"var(--diff-removed-text)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:o,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",userSelect:"text",WebkitUserSelect:"text"},children:e.text||"\xa0"})]})}function ou({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{className:"chat-selectable",style:{maxHeight:"min(520px, 45vh)",overflowY:"auto",overflowX:"hidden",overscrollBehavior:"auto",touchAction:"pan-y",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"var(--diff-added-bg)":"removed"===n?"var(--diff-removed-bg)":"hunk"===n?"var(--diff-hunk-bg)":"transparent",borderLeft:"added"===n?"3px solid var(--diff-added-border)":"removed"===n?"3px solid var(--diff-removed-border)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--diff-added-text)":"removed"===n?"var(--diff-removed-text)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function op(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oh({text:e,isEmpty:t,isError:n}){let{t:i}=(0,eU.s9)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--status-danger-border)":"var(--status-success-border)"}`,background:n?"var(--status-danger-bg)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--error-text)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",maxHeight:"min(400px, 45vh)",background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?`(${i("message_noOutput").toLowerCase()})`:e})})}function of({message:e}){let{t}=(0,eU.s9)(),n=oS(e.content),o=(0,i.useMemo)(()=>iS(n),[n]),l=iZ(e.timestamp),s=iI(n,{streaming:!1}),[a,d]=(0,i.useState)(!1),c=t(a?"message_collapse":"message_expand");return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>d(e=>!e),"aria-expanded":a,title:`${t("message_compaction")} \xb7 ${c}`,"aria-label":`${t("message_compaction")} \xb7 ${c}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 10px",border:"none",borderBottom:a?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontFamily:"inherit",fontSize:12,textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)(rh.A,{size:12,strokeWidth:1.8,"aria-hidden":"true",style:{flexShrink:0,transform:a?"none":"rotate(-90deg)",transition:"transform 0.15s ease"}}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:t("message_compaction")}),!a&&s&&(0,r.jsx)("span",{style:{minWidth:0,flex:"1 1 auto",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:12},children:s}),l&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:l})]}),a&&(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("message_conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("message_conversationCompactedDescription")}),o.body?(0,r.jsx)(iu,{className:"markdown-compaction-message",children:o.body}):(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:12},children:["(",t("message_noSummary"),")"]}),(0,r.jsx)(ox,{readFiles:o.readFiles,modifiedFiles:o.modifiedFiles})]})]})})}function og({message:e}){let{t}=(0,eU.s9)(),n=oS(e.content),i=e.details?.ok!==!1,o=e.details?.result,l=iZ(e.timestamp);return(0,r.jsxs)("div",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",border:"1px solid var(--border)",borderLeft:"2px solid var(--accent)",borderRadius:8,background:"var(--bg-subtle)"},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:t("message_command")}),(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflowWrap:"anywhere"},children:n}),i&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:"✓"}),!i&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:"✗"}),l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:l})]}),o&&(0,r.jsx)("div",{style:{marginTop:4,padding:"0 4px",color:"var(--text-muted)",fontSize:12},children:o})]})}function om({message:e}){let{t}=(0,eU.s9)(),n=oS(e.content),o=(0,i.useMemo)(()=>iS(n),[n]),l=(0,i.useMemo)(()=>(function(e){if(!e||"object"!=typeof e)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let n=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[],r=n(t.readFiles),i=n(t.modifiedFiles);return 0===r.length&&0===i.length?null:{readFiles:r,modifiedFiles:i}})(e.details),[e.details]),s=l?.readFiles??o.readFiles,a=l?.modifiedFiles??o.modifiedFiles,d=iZ(e.timestamp),c=iI(n,{streaming:!1}),[u,p]=(0,i.useState)(!1),h=t(u?"message_collapse":"message_expand");return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderLeft:"2px solid var(--accent)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>p(e=>!e),"aria-expanded":u,title:`${t("message_branchSummary")} \xb7 ${h}`,"aria-label":`${t("message_branchSummary")} \xb7 ${h}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 10px",border:"none",borderBottom:u?"1px solid var(--border)":"none",background:"var(--bg-panel)",color:"var(--text-muted)",fontFamily:"inherit",fontSize:12,textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)(rh.A,{size:12,strokeWidth:1.8,"aria-hidden":"true",style:{flexShrink:0,transform:u?"none":"rotate(-90deg)",transition:"transform 0.15s ease"}}),(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:t("message_branchSummary")}),!u&&c&&(0,r.jsx)("span",{style:{minWidth:0,flex:"1 1 auto",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:12},children:c}),d&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:d})]}),u&&(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text-muted)",fontSize:13,lineHeight:1.5},children:t("message_branchSummaryDescription")}),o.body?(0,r.jsx)(iu,{className:"markdown-compaction-message",children:o.body}):(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:12},children:["(",t("message_noSummary"),")"]}),(0,r.jsx)(ox,{readFiles:s,modifiedFiles:a})]})]})})}function ox({readFiles:e,modifiedFiles:t}){let{t:n}=(0,eU.s9)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} ${n("message_read").toLowerCase()}`),t.length>0&&i.push(`${t.length} ${n("message_modified").toLowerCase()}`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsxs)("summary",{children:[n("message_fileContext"),": ",i.join(", ")]}),t.length>0&&(0,r.jsx)(ob,{title:n("message_modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(ob,{title:n("message_readFiles"),files:e})]})}function ov({filePath:e,onReferenceFile:t}){let{t:n}=(0,eU.s9)(),i=n("files_insertIntoChat",{name:(0,rH.WP)(e)});return(0,r.jsx)("button",{type:"button",className:"file-row-action-btn message-file-action-btn",title:i,"aria-label":i,onClick:()=>t(e),style:{color:"var(--accent)",flexShrink:0},children:(0,r.jsx)(rf.A,{size:12,strokeWidth:2,"aria-hidden":"true"})})}function oy({files:e,isStreaming:t,onOpenFile:n,onReferenceFile:o}){let{t:l}=(0,eU.s9)(),[s,a]=(0,i.useState)(!1);return e&&0!==e.length?(0,r.jsxs)("div",{style:{marginTop:10,border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)(oe,{label:l("message_writtenThisTurn"),expanded:s,onToggle:()=>a(!s),summary:s?null:iI(e.map(e=>(0,rH.WP)(e)).join("\n"),{streaming:t}),meta:String(e.length),toggleTitle:{expand:l("message_writtenFilesExpand"),collapse:l("message_writtenFilesCollapse")}}),s&&(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"8px 10px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:e.map(e=>{let t=(0,rH.WP)(e);return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:2,maxWidth:"100%",minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:"message-file-open-btn",title:e,"aria-label":l("message_openWrittenFile",{name:t}),onClick:()=>n?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,flex:"1 1 auto",minWidth:0,maxWidth:"100%",padding:"2px 8px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11.5,cursor:n?"pointer":"default"},children:[(0,r.jsx)(rp.A,{size:12,strokeWidth:1.8}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),o?(0,r.jsx)(ov,{filePath:e,onReferenceFile:o}):null]},e)})})]}):null}function ob({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}let ow={result:{color:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-bg)",Icon:rg.A},warning:{color:"var(--status-warning)",border:"var(--status-warning-border)",background:"var(--status-warning-bg)",Icon:rm.A},error:{color:"var(--error-text)",border:"var(--status-danger-border)",background:"var(--status-danger-bg)",Icon:rx.A},output:{color:"var(--accent)",border:"var(--border)",background:"var(--bg)",Icon:rv.A}};function ok({message:e,activity:t}){let{t:n}=(0,eU.s9)(),o=i6(),[l,s]=(0,i.useState)(!1),a=iZ(e.timestamp),{color:d,border:c,background:u,Icon:p}=ow[t.kind],h=""!==t.content.trim(),f=function(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(t.length>=4)break;"string"==typeof r?t.push([n,r]):("number"==typeof r||"boolean"==typeof r)&&t.push([n,String(r)])}return t}(t.metadata);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("section",{"aria-label":`${t.kind}: ${t.title}`,style:{border:`1px solid ${c}`,borderLeft:`2px solid ${d}`,borderRadius:8,overflow:"hidden",background:u},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",minWidth:0},children:[(0,r.jsx)("span",{style:{display:"flex",color:d,flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)(p,{size:12,strokeWidth:1.8})}),(0,r.jsx)("span",{style:{color:d,fontFamily:"var(--font-mono)",fontSize:10,fontWeight:650,letterSpacing:.6,textTransform:"uppercase",flexShrink:0},children:t.kind}),(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:13,fontWeight:600,minWidth:0,overflowWrap:"anywhere"},children:t.title}),a&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,flexShrink:0},children:a})]}),h&&(0,r.jsx)("pre",{tabIndex:0,style:{margin:0,padding:"8px 12px",maxHeight:o,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",color:"var(--text)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.content}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"4px 10px",padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:[(0,r.jsx)("button",{onClick:()=>{tC(h?t.content:t.title).then(()=>{s(!0),setTimeout(()=>s(!1),1500)})},title:n("message_copy"),"aria-label":n("message_copy"),style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"3px 7px",border:"none",background:"none",color:l?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:l?(0,r.jsx)(rd.A,{size:11,strokeWidth:1.8}):(0,r.jsx)(rc.A,{size:11,strokeWidth:1.8})}),t.source&&(0,r.jsx)("span",{style:{overflowWrap:"anywhere"},children:t.source}),t.requestId&&(0,r.jsx)("span",{style:{overflowWrap:"anywhere"},title:t.requestId,children:t.requestId}),f.map(([e,t])=>(0,r.jsxs)("span",{style:{overflowWrap:"anywhere"},children:[e,"=",t]},e))]})]})})}function oj({message:e,cwd:t,onOpenFile:n}){var o,l,s;let a,{t:d}=(0,eU.s9)(),c=!1===e.display,[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(!1),x=oS(e.content),v="string"==typeof(o=e.content)?[]:o.filter(e=>"image"===e.type),y=void 0!==e.details,b=y?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",w=e.customType?re(e.customType):d("message_extensionDefaultType"),k=iZ(e.timestamp),j=or(e.renderedLines);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:c?"var(--bg-subtle)":"var(--bg)",opacity:j||!c||u?1:.82},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:w}),c&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:d("message_hiddenExtensionMessage")}),k&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:k}),c&&!j?(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-expanded":u,title:d(u?"message_collapse":"message_expand"),"aria-label":d(u?"message_collapse":"message_expand"),style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2px 6px",border:"1px solid var(--border)",borderRadius:6,background:"transparent",color:"var(--text-dim)",cursor:"pointer"},children:u?(0,r.jsx)(ry.A,{size:12,strokeWidth:1.8}):(0,r.jsx)(rh.A,{size:12,strokeWidth:1.8})}):null]}),j?(0,r.jsx)("pre",{style:{margin:0,padding:"6px 9px",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,whiteSpace:"pre"},children:oi(j,"custom-rendered")}):u?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[v.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!x},children:v.map((e,t)=>{let n=it(e);return n?(0,r.jsx)(is,{src:n.src,fullSrc:n.src,mimeType:n.mimeType,alt:"",maxWidth:240,maxHeight:240},t):null})}),x?(0,r.jsx)(iu,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:x}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:d("message_noMessages")})]}):(0,r.jsx)("button",{onClick:()=>p(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:x?(l=iI(x,{streaming:!1})||x,s=d("message_noExtensionMessage"),(a=l.replace(/\s+/g," ").trim())?a.length>140?`${a.slice(0,140)}...`:a:s):d("message_showExtensionMessage")}),!j&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[x||b?(0,r.jsx)("button",{onClick:()=>{tC(x||b).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},title:d("message_copy"),"aria-label":d("message_copy"),style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"3px 7px",border:"none",background:"none",color:g?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:g?(0,r.jsx)(rd.A,{size:11,strokeWidth:1.8}):(0,r.jsx)(rc.A,{size:11,strokeWidth:1.8})}):null,y&&!c&&(0,r.jsx)("button",{onClick:()=>{c?p(e=>!e):f(e=>!e)},title:d(c?u?"message_collapse":"message_expand":h?"message_hideDetails":"message_showDetails"),"aria-label":d(c?u?"message_collapse":"message_expand":h?"message_hideDetails":"message_showDetails"),style:{display:"flex",alignItems:"center",justifyContent:"center",marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer"},children:(c?u:h)?(0,r.jsx)(ry.A,{size:12,strokeWidth:1.8}):(0,r.jsx)(rh.A,{size:12,strokeWidth:1.8})})]}),!j&&y&&(c&&u||!c&&h)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:"min(360px, 45vh)",overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",fontFamily:"var(--font-mono)"},children:b})]})})}function oS(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function oC({message:e,sessionId:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),u=!e.output&&void 0===e.exitCode&&!e.cancelled,p=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,h=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,f=e.truncated&&h&&null===o,g=o??e.output;async function m(){if(h){a(!0),c(null);try{let e=await fetch(h),t=await e.json();t.success?l(t.data?.output??""):c(t.error??"failed")}catch(e){c(String(e))}finally{a(!1)}}}let x=e.excludeFromContext?"bash (local)":"bash",v={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:x,input:{command:e.command}},y=u?void 0:{role:"toolResult",toolCallId:v.toolCallId,toolName:x,content:g?[{type:"text",text:g}]:[],isError:p,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(on,{block:v,result:y,pending:u,startedAt:u?e.timestamp:void 0}),e.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[f&&(0,r.jsx)("button",{onClick:m,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:n(s?"message_loadingOutput":"message_viewFullOutput")}),(0,r.jsx)("a",{href:`${h}&download=1`,style:{marginLeft:10*!!f,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:n("message_downloadFullOutput")}),d&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",d,")"]})]})]})}function o_(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function oI(e){return"string"==typeof e&&e&&"auto"!==e?e:null}let oR=["off","minimal","low","medium","high","xhigh","max"];function oT(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function oE(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function oM(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function oA(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}let oL="var(--text-dim)";function oz({size:e=14,open:t=!1}){return t?(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:[(0,r.jsx)("path",{d:"M1 4.5A1 1 0 0 1 2 3.5H5.5L7 5h7.5v1H1V4.5Z",fill:oL}),(0,r.jsx)("path",{d:"M1 6h14.5L14 13H2L1 6Z",stroke:oL,strokeWidth:"1",fill:oL,fillOpacity:"0.12"})]}):(0,r.jsx)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:(0,r.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:oL,strokeWidth:"1",fill:oL,fillOpacity:"0.1"})})}function oW({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",children:[(0,r.jsx)("path",{d:"M3 2h7l3 3v9H3V2Z",stroke:oL,strokeWidth:"1",fill:oL,fillOpacity:"0.08"}),(0,r.jsx)("path",{d:"M10 2v3h3",stroke:oL,strokeWidth:"1",fill:"none",strokeLinejoin:"round"})]})}function o$({label:e,size:t=14}){let n=t/14;return(0,r.jsxs)("svg",{width:t,height:t,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("text",{x:"7",y:"9.5",textAnchor:"middle",fontSize:3.4*n,fontFamily:"var(--font-mono), monospace",fontWeight:"600",fill:oL,letterSpacing:"0",children:e})]})}function oP({size:e=14}){return(0,r.jsx)(o$,{label:"TS",size:e})}function oF({size:e=14}){return(0,r.jsx)(o$,{label:"TSX",size:e})}function oH({size:e=14}){return(0,r.jsx)(o$,{label:"JS",size:e})}function oD({size:e=14}){return(0,r.jsx)(o$,{label:"JSX",size:e})}function oN({size:e=14}){return(0,r.jsx)(o$,{label:"PY",size:e})}function oB({size:e=14}){return(0,r.jsx)(o$,{label:"{}",size:e})}function oO({size:e=14}){return(0,r.jsx)(o$,{label:"CSS",size:e})}function oU({size:e=14}){return(0,r.jsx)(o$,{label:"SC",size:e})}function oq({size:e=14}){return(0,r.jsx)(o$,{label:"HTM",size:e})}function oK({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M3.5 9.5V7l1.5 1.5L6.5 7v2.5",stroke:oL,strokeWidth:"0.9",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),(0,r.jsx)("path",{d:"M8 7v2.5M7 9l1 1.5 1-1.5",stroke:oL,strokeWidth:"0.9",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function oJ({size:e=14}){return(0,r.jsx)(o$,{label:"YML",size:e})}function oV({size:e=14}){return(0,r.jsx)(o$,{label:"TOM",size:e})}function oY({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M4 7.5l2 1.5-2 1.5",stroke:oL,strokeWidth:"0.95",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"}),(0,r.jsx)("path",{d:"M7.5 10.5h2.5",stroke:oL,strokeWidth:"0.95",strokeLinecap:"round"})]})}function oX({size:e=14}){return(0,r.jsx)(o$,{label:"RS",size:e})}function oG({size:e=14}){return(0,r.jsx)(o$,{label:"GO",size:e})}function oZ({size:e=14}){return(0,r.jsx)(o$,{label:"SQL",size:e})}function oQ({size:e=14}){return(0,r.jsx)(o$,{label:"GQL",size:e})}function o0({size:e=14}){return(0,r.jsx)(o$,{label:"TF",size:e})}function o1({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("rect",{x:"3.5",y:"6.5",width:"2",height:"1.5",rx:"0.3",stroke:oL,strokeWidth:"0.8"}),(0,r.jsx)("rect",{x:"6",y:"6.5",width:"2",height:"1.5",rx:"0.3",stroke:oL,strokeWidth:"0.8"}),(0,r.jsx)("rect",{x:"3.5",y:"8.5",width:"2",height:"1.5",rx:"0.3",stroke:oL,strokeWidth:"0.8"})]})}function o2({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"5.5",cy:"8.5",r:"1.5",stroke:oL,strokeWidth:"0.9"}),(0,r.jsx)("path",{d:"M7 8.5h2.5M8.5 8.5v1.5",stroke:oL,strokeWidth:"0.9",strokeLinecap:"round"})]})}function o4({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"5",cy:"6.5",r:"1",stroke:oL,strokeWidth:"0.85"}),(0,r.jsx)("circle",{cx:"9",cy:"6.5",r:"1",stroke:oL,strokeWidth:"0.85"}),(0,r.jsx)("circle",{cx:"5",cy:"10",r:"1",stroke:oL,strokeWidth:"0.85"}),(0,r.jsx)("path",{d:"M5 7.5V9",stroke:oL,strokeWidth:"0.85",strokeLinecap:"round"}),(0,r.jsx)("path",{d:"M9 7.5v.5a2 2 0 0 1-2 2H6",stroke:oL,strokeWidth:"0.85",strokeLinecap:"round",fill:"none"})]})}function o6({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("rect",{x:"4.5",y:"8.5",width:"5",height:"3",rx:"0.6",stroke:oL,strokeWidth:"0.9"}),(0,r.jsx)("path",{d:"M5.5 8.5V7.5a1.5 1.5 0 0 1 3 0v1",stroke:oL,strokeWidth:"0.9",strokeLinecap:"round",fill:"none"})]})}function o5({size:e=14}){return(0,r.jsx)(o$,{label:"DOC",size:e})}function o8({size:e=14}){return(0,r.jsx)(o$,{label:"PDF",size:e})}function o3({size:e=14}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",children:[(0,r.jsx)("path",{d:"M2.5 1h6l3 3v9h-9V1Z",stroke:oL,strokeWidth:"0.9",fill:oL,fillOpacity:"0.07",strokeLinejoin:"round"}),(0,r.jsx)("path",{d:"M8.5 1v3h3",stroke:oL,strokeWidth:"0.9",fill:"none",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"7",cy:"8.5",r:"1.3",stroke:oL,strokeWidth:"0.9"}),(0,r.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:oL,strokeWidth:"0.8",strokeLinecap:"round"})]})}function o9(e,t=14){let n=e.toLowerCase(),i=n.split(".").pop()??"";if("dockerfile"===n||n.startsWith("dockerfile."))return(0,r.jsx)(o1,{size:t});if(".env"===n||n.startsWith(".env."))return(0,r.jsx)(o2,{size:t});if(".gitignore"===n||".gitattributes"===n||".gitmodules"===n)return(0,r.jsx)(o4,{size:t});if("package-lock.json"===n||"yarn.lock"===n||"bun.lock"===n||"pnpm-lock.yaml"===n||"cargo.lock"===n)return(0,r.jsx)(o6,{size:t});if(n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")||[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n))return(0,r.jsx)(o3,{size:t});switch(i){case"ts":return(0,r.jsx)(oP,{size:t});case"tsx":return(0,r.jsx)(oF,{size:t});case"js":case"mjs":case"cjs":return(0,r.jsx)(oH,{size:t});case"jsx":return(0,r.jsx)(oD,{size:t});case"py":return(0,r.jsx)(oN,{size:t});case"json":case"jsonl":return(0,r.jsx)(oB,{size:t});case"css":case"less":return(0,r.jsx)(oO,{size:t});case"scss":return(0,r.jsx)(oU,{size:t});case"html":case"htm":return(0,r.jsx)(oq,{size:t});case"md":case"mdx":return(0,r.jsx)(oK,{size:t});case"yaml":case"yml":return(0,r.jsx)(oJ,{size:t});case"toml":return(0,r.jsx)(oV,{size:t});case"sh":case"bash":case"zsh":case"fish":return(0,r.jsx)(oY,{size:t});case"rs":return(0,r.jsx)(oX,{size:t});case"go":return(0,r.jsx)(oG,{size:t});case"sql":return(0,r.jsx)(oZ,{size:t});case"graphql":case"gql":return(0,r.jsx)(oQ,{size:t});case"tf":case"hcl":return(0,r.jsx)(o0,{size:t});case"docx":return(0,r.jsx)(o5,{size:t});case"pdf":return(0,r.jsx)(o8,{size:t});case"lock":return(0,r.jsx)(o6,{size:t});default:return(0,r.jsx)(oW,{size:t})}}let o7=RegExp("(?:\\s|(?:(?=\\p{Punctuation})[\\p{Script_Extensions=Han}\\p{Script_Extensions=Hiragana}\\p{Script_Extensions=Katakana}\\p{Script_Extensions=Hangul}\\p{Script_Extensions=Bopomofo}]|[,.:;!?()[]{}“”‘’…—]))","u"),le={status:"local"},lt=(e,t=0)=>Number.isFinite(e)?e:t,ln=i.useLayoutEffect;function lr(e){let{open:t,anchorRef:n,overlayRef:r,preferredPlacement:o="below",margin:l=8,gap:s=4,minHeight:a,maxHeight:d,maxWidth:c,align:u,width:p,minWidth:h,pollIntervalMs:f=250}=e,[g,m]=(0,i.useState)(null),x=(0,i.useRef)(0),v=(0,i.useCallback)(()=>{let e,t=n.current,i=r.current;if(!t||!i)return;let p=t.getBoundingClientRect();if(0===p.width&&0===p.height)return void m(e=>null===e?e:null);let h=function(e){let{anchor:t,desiredSize:n,viewport:r}=e,i=Math.max(0,lt(e.margin??8)),o=Math.max(0,lt(e.gap??4)),l=Math.max(0,lt(e.minHeight??0)),s=Math.max(0,lt(r.offsetLeft)),a=Math.max(0,lt(r.offsetTop)),d=s+i,c=a+i,u=s+Math.max(0,lt(r.width))-i,p=a+Math.max(0,lt(r.height))-i,h=Math.max(0,u-d),f=Math.max(0,p-c),g=Math.min(f,Math.max(0,lt(t.top)-o-c)),m=Math.min(f,Math.max(0,p-lt(t.bottom)-o)),x=e.preferredPlacement??"below",v="below"===x?"above":"below",y=Math.max(l,Math.max(0,lt(n.height))),b=("below"===x?m:g)>=y?x:("below"===v?m:g)>=y?v:m>=g?"below":"above",w=Math.max(0,"below"===b?m:g),k=Math.max(0,lt(n.width)),j=Math.min(Math.max("end"===e.align?lt(t.right)-k:lt(t.left),d),Math.max(d,u-k)),S=Math.min(Math.max("below"===b?lt(t.bottom)+o:lt(t.top)-o-Math.max(0,lt(n.height)),c),Math.max(c,p-Math.min(w,Math.max(0,lt(n.height)))));return{top:lt(S,c),left:lt(j,d),maxHeight:w,maxWidth:h,placement:b}}({anchor:{top:p.top,left:p.left,right:p.right,bottom:p.bottom},desiredSize:{width:i.offsetWidth,height:Math.min(i.offsetHeight,d??1/0)},viewport:(e=window.visualViewport)?{offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,width:e.width,height:e.height}:{offsetLeft:0,offsetTop:0,width:window.innerWidth,height:window.innerHeight},margin:l,gap:s,minHeight:a,preferredPlacement:o,align:u}),f={top:h.top,left:h.left,maxHeight:void 0===d?h.maxHeight:Math.min(h.maxHeight,d),maxWidth:void 0===c?h.maxWidth:Math.min(h.maxWidth,c),anchorWidth:p.width,placement:h.placement};m(e=>null!==e&&e.top===f.top&&e.left===f.left&&e.maxHeight===f.maxHeight&&e.maxWidth===f.maxWidth&&e.anchorWidth===f.anchorWidth&&e.placement===f.placement?e:f)},[n,r,l,s,a,d,c,o,u]);return ln(()=>{if(!t)return void m(null);v();let e=()=>{x.current||(x.current=requestAnimationFrame(()=>{x.current=0,v()}))};window.addEventListener("resize",e),window.addEventListener("scroll",e,!0);let i=window.visualViewport;i?.addEventListener("resize",e),i?.addEventListener("scroll",e);let o=new ResizeObserver(e),l=n.current,s=r.current;l&&o.observe(l),s&&o.observe(s);let a=f>0?window.setInterval(e,f):0;return()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e),i?.removeEventListener("resize",e),i?.removeEventListener("scroll",e),o.disconnect(),a&&window.clearInterval(a),x.current&&(cancelAnimationFrame(x.current),x.current=0)}},[t,v,n,r,f]),{style:(0,i.useMemo)(()=>{if(!g)return{position:"fixed",top:0,left:0,visibility:"hidden"};let e={position:"fixed",top:g.top,left:g.left,maxHeight:g.maxHeight,maxWidth:g.maxWidth,visibility:"visible"},t=e=>Math.max(0,Math.min(e,g.maxWidth));"anchor"===p?e.width=t(g.anchorWidth):"max"===p?e.width=g.maxWidth:"number"==typeof p&&(e.width=t(p));let n="anchor"===h?g.anchorWidth:"number"==typeof h?h:void 0;return void 0!==n&&(e.minWidth=Math.min(n,g.maxWidth)),e},[g,p,h]),placement:g?.placement??o,ready:null!==g}}var li=n(32383);function lo(e,t){let n=e.key.toLowerCase();return!e.ctrlKey&&!e.metaKey||"a"!==n&&("c"!==n||!(t.length>0))}let ll=new Set(["a","c","v","x","z","y","p","s","f","n","t","w","r","l","o"]),ls=new Set(["k"]);function la(e){return!!e.ctrlKey&&ls.has(e.key.toLowerCase())}function ld(e){return!!e.ctrlKey&&(" "===e.key||ll.has(e.key.toLowerCase()))}function lc(e){return 1===e.key.length&&!e.ctrlKey&&!e.altKey&&!e.metaKey}function lu(){return{interactive:!1,lastRoutedAt:0}}function lp(e,t){var n;return"ignore"===t.action||"exit-interaction"===t.action?{interactive:!1,lastRoutedAt:e.lastRoutedAt}:"Escape"===(n=t.key)||"Enter"===n?{interactive:!1,lastRoutedAt:t.now}:{interactive:!0===t.consumed,lastRoutedAt:t.now}}function lh(e,t,n){return!0===e.isComposing||229===e.keyCode||n<t}function lf(e){let t=e?.ownerDocument;return!!t&&(e===t.body||e===t.documentElement)}let lg={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},lm={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"};function lx(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=lm[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":lg[e.key]??null}function lv(e){return`\x1b[200~${e}\x1b[201~`}let ly=null;function lb(){if(ly)return ly;let e=globalThis.crypto;return ly=e&&"function"==typeof e.randomUUID?e.randomUUID():`client-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}function lw(e,t,n=16384){return"number"==typeof e&&!!Number.isFinite(e)&&!(e<=0)&&"number"==typeof t&&!!Number.isFinite(t)&&!(t<=0)&&e>t-(Number.isFinite(n)&&n>0?n:0)}function lk(e){return e.type.startsWith("image/")&&"image/svg+xml"!==e.type}function lj(){return`up-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function lS(e){if("number"!=typeof e||!Number.isFinite(e)||e<=0)return"";if(e>=1e6){let t=e/1e6;return`${Number.isInteger(t)?t:t.toFixed(1)}M`}return e>=1e3?`${Math.round(e/1e3)}K`:String(e)}let lC=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function l_(e,t){return lC.compare(e.name||e.modelId,t.name||t.modelId)||lC.compare(e.provider,t.provider)||lC.compare(e.modelId,t.modelId)}function lI(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let lR=[{name:"compact",description:"input_compactCommandDescription",source:"builtin"},{name:"reload",description:"input_reloadCommandDescription",source:"builtin"},{name:"name",description:"input_nameCommandDescription",source:"builtin"},{name:"session",description:"input_sessionCommandDescription",source:"builtin"},{name:"copy",description:"input_copyCommandDescription",source:"builtin"}],lT=["builtin","extension","prompt","skill"],lE={builtin:"input_builtIn",extension:"input_extensions",prompt:"input_prompts",skill:"input_skills"},lM={builtin:0,extension:1,prompt:2,skill:3};function lA(e,t){let n=e.name.toLowerCase(),r=e.description?.toLowerCase()??"";return n===t?0:n.startsWith(t)?1:n.includes(t)?2:r.includes(t)?3:4}function lL(e){return{mimeType:e.mimeType,...e.media?{media:e.media}:{},...e.original?{original:e.original}:{},...!e.media&&!e.original&&e.data?{data:e.data}:{}}}function lz(e){let t={mimeType:e.mimeType,...e.data?{data:e.data}:{},...e.media?{media:e.media}:{},...e.original?{original:e.original}:{}};return t.previewUrl=e.data?`data:${e.mimeType};base64,${e.data}`:(0,t2.zr)(t),t}function lW(e){return e.media?.original.path??e.original?.path??`${e.mimeType}:${e.data?.slice(0,64)??""}`}function l$(e){e.previewUrl?.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function lP(e,t){if(!e)return;let n=e.querySelector(`${t}[aria-checked="true"], ${t}[aria-selected="true"]`),r=e.querySelector(t);(n??r)?.focus({preventScroll:!0})}function lF({kind:e,text:t,state:n,stateLabel:i,imageCount:o}){return(0,r.jsxs)("div",{title:t,style:{display:"flex",alignItems:"center",gap:8,padding:"3px 10px",fontSize:12,color:"var(--text-muted)",minWidth:0},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:`1px solid ${"steer"===e?"color-mix(in srgb, var(--accent) 45%, transparent)":"var(--border)"}`,color:"steer"===e?"var(--accent)":"var(--text-dim)"},children:e}),o?(0,r.jsxs)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",gap:3,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:"1px solid var(--border)",color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("path",{d:"m21 15-5-5L5 21"})]}),o]}):null,n&&"waiting"!==n&&(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,fontFamily:"var(--font-mono)",padding:"1px 7px",borderRadius:999,border:`1px solid ${"unknown"===n?"color-mix(in srgb, var(--status-warning) 45%, transparent)":"color-mix(in srgb, var(--accent) 35%, transparent)"}`,color:"unknown"===n?"var(--status-warning)":"var(--text-dim)"},children:i??n}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]})}let lH=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:o,isStreaming:l,blocked:a=!1,model:d,isAutoModelSelection:c,modelNames:u,modelList:p,sessionTokens:h,modelAuthConfigured:f,onModelChange:g,onAbortCompaction:m,isCompacting:x,compactError:v,compactResult:y,thinkingLevel:b,thinkingReady:w,onThinkingLevelChange:k,defaultThinkingLevel:j,availableThinkingLevels:S,thinkingLevelMap:C,thinkingLevelMaps:_,retryInfo:R,queuedMessages:T,onRecallQueue:E,onSendQueueAsSteer:M,slashCommands:A,slashCommandsLoading:L,onLoadSlashCommands:z,onLoadCommandArgumentCompletions:W,autocompleteProviderCount:$,autocompleteTriggerCharacters:P,onLoadCompletionSuggestions:F,onApplyCompletionSuggestion:H,onBuiltinCommand:D,onAudioUnlock:N,onPromptWithStreamingBehavior:B,footerCollapsed:O,onFooterToggle:U,draftKey:q,cwd:K,sessionId:J,extensionWidgetKeysEnabled:V=!1},Y){var X,G;let Z,Q,et,en,er,ei,eo,el,{t:es}=(0,eU.s9)(),ea=ra(),[ed,ec]=(0,i.useState)("followUp"),[eu,ep]=(0,i.useState)(!1),eh=T?.followUpRows?.length?T.followUpRows:(T?.followUp??[]).map((e,t)=>({id:`legacy-${t}`,text:e,state:"waiting",imageCount:0}));(0,i.useEffect)(()=>{ec(ee());let e=e=>{"pidance.streamingEnterDefault"===e.key&&ec(ee())},t=()=>ec(ee());return window.addEventListener("storage",e),window.addEventListener("pidance:streaming-enter-changed",t),()=>{window.removeEventListener("storage",e),window.removeEventListener("pidance:streaming-enter-changed",t)}},[]);let[ef,eg]=(0,i.useState)(()=>q?tZ(q)?.value??"":"");!function(e){let{sessionId:t,enabled:n,composerEmpty:r,composerFocused:o}=e,l=(0,i.useRef)("");""===l.current&&(l.current=lb());let s=(0,i.useRef)(lu()),a=(0,i.useRef)(0),d=(0,i.useRef)(null),c=(0,i.useRef)({focused:o,empty:r});c.current={focused:o,empty:r},(0,i.useEffect)(()=>{n&&o&&r||(s.current=lu())},[n,o,r,t]),(0,i.useEffect)(()=>{if(!t)return;let e=e=>{d.current!==e&&(d.current=e,(0,li.$J)(t,{type:"editor_focus",focused:e,clientId:l.current}).catch(()=>{}))},n=()=>{let t=c.current.focused&&"visible"===document.visibilityState;t||(s.current=lu()),e(t)};return d.current=null,n(),document.addEventListener("visibilitychange",n),window.addEventListener("pagehide",n),window.addEventListener("focus",n),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pagehide",n),window.removeEventListener("focus",n),s.current=lu(),e(!1)}},[t,o]),(0,i.useEffect)(()=>{if(!n||!t){s.current=lu();return}let e=()=>{a.current=Date.now()+80},r=e=>{let n=Date.now(),r=function(e){if(e.composing||e.ctrlKey||e.altKey||e.metaKey)return"ignore";if(function(e){if(e.shiftKey)return!1;switch(e.key){case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"Escape":case"Enter":case"j":case"k":return!0;default:return!1}}(e))return e.interactive?"route-navigation":e.shiftKey||"ArrowDown"!==e.key&&"ArrowLeft"!==e.key?"ignore":"route-activation";return e.interactive?"exit-interaction":"ignore"}({key:e.key,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey,composing:e.defaultPrevented||lh(e,a.current,n),interactive:function(e,t,n=1e4){return!!e.interactive&&t-e.lastRoutedAt<=n}(s.current,n)});if("ignore"===r)return;if("exit-interaction"===r){s.current=lp(s.current,{action:r,key:e.key,consumed:!1,now:n});return}if(!c.current.focused||!c.current.empty){s.current=lu();return}let i=lx(e)??(lc(e)?e.key:null);i&&("route-navigation"===r&&(e.preventDefault(),e.stopPropagation()),(0,li.$J)(t,{type:"terminal_input",data:i,assertFocus:!0,clientId:l.current}).then(t=>{s.current=lp(s.current,{action:r,key:e.key,consumed:t?.consumed===!0,now:Date.now()})}).catch(()=>{s.current=lu()}))};return window.addEventListener("keydown",r,!0),window.addEventListener("compositionend",e,!0),()=>{window.removeEventListener("keydown",r,!0),window.removeEventListener("compositionend",e,!0)}},[n,t])}({sessionId:J??null,enabled:V,composerEmpty:0===ef.length,composerFocused:eu});let[em,ex]=(0,i.useState)(!1),[ev,ey]=(0,i.useState)(!1),[eb,ew]=(0,i.useState)(!0),[ek,ej]=(0,i.useState)(()=>q?tZ(q)?.images.map(lz)??[]:[]),[eS,eC]=(0,i.useState)(null),[e_,eI]=(0,i.useState)([]),eR=(0,i.useRef)(e_);eR.current=e_;let eT=ef.trimStart(),eE=0===ek.length&&eT.startsWith("!"),eM=eE&&eT.startsWith("!!"),[eL,ez]=(0,i.useState)(!1),[eW,e$]=(0,i.useState)([]),[eP,eF]=(0,i.useState)(0),[eH,eD]=(0,i.useState)(!1),[eN,eB]=(0,i.useState)(0),[eO,eq]=(0,i.useState)(null),[eK,eJ]=(0,i.useState)(!1),[eV,eY]=(0,i.useState)(0),[eX,eG]=(0,i.useState)(null),[eZ,eQ]=(0,i.useState)(!1),[e0,e1]=(0,i.useState)(null),e2=(0,i.useRef)(null),e4=(0,i.useRef)(!1),[e6,e5]=(0,i.useState)(!1),e8=(0,i.useRef)(null),e3=(0,i.useRef)(null),e9=(0,i.useRef)(null),e7=(0,i.useRef)(null),te=(0,i.useRef)(null),tt=(0,i.useRef)(null),tn=(0,i.useRef)(null),tr=(0,i.useRef)(null),ti=(0,i.useRef)(null),to=(0,i.useRef)(!1),tl=(0,i.useRef)(0),ts=(0,i.useRef)(!1),ta=(0,i.useRef)([]),td=(0,i.useRef)(null),tc=(0,i.useRef)([]),tu=(0,i.useRef)(0),tp=(0,i.useRef)([]),th=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(q),tm=(0,i.useRef)(null),[tx,tv]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tm.current=tg.current??null},[]),tb=(0,i.useCallback)(e=>{ty(),eg(e)},[ty]),[tw,tk]=(0,i.useState)(null),[tj,tS]=(0,i.useState)(null),tC=(0,i.useRef)(null),t_=(0,i.useCallback)((e,t)=>{let n=t.getBoundingClientRect(),r=n.right+6;r+120>window.innerWidth-8&&(r=Math.max(8,n.left-120-6)),tS({top:Math.max(8,Math.min(n.top,window.innerHeight-8-352)),left:r}),tk(e)},[]),tI=(0,i.useCallback)(()=>{tk(null),tS(null)},[]);(0,i.useEffect)(()=>{if(null===tw)return;let e=e=>{let t=e.target;if(!tC.current?.contains(t)&&!t?.closest?.("[data-depth-trigger]")){if(e9.current?.contains(t))return void window.setTimeout(()=>tI(),0);tI()}};return document.addEventListener("pointerdown",e),window.addEventListener("resize",tI),window.addEventListener("scroll",tI),()=>{document.removeEventListener("pointerdown",e),window.removeEventListener("resize",tI),window.removeEventListener("scroll",tI)}},[tI,tw]);let tR=(0,i.useCallback)(e=>{let t=[e.name];return"number"==typeof e.contextWindow&&t.push(`${es("input_modelContext")} ${lS(e.contextWindow)}`),"number"==typeof e.maxTokens&&t.push(`${es("input_modelMaxOutput")} ${lS(e.maxTokens)}`),"number"==typeof h&&h>0&&"number"==typeof e.contextWindow&&t.push(lw(h,e.contextWindow)?es("input_modelSessionOverflow",{tokens:lS(h),window:lS(e.contextWindow),reserve:lS(16384)}):es("input_modelSessionUsage",{tokens:lS(h),window:lS(e.contextWindow)})),t.join(" \xb7 ")},[es,h]),tT=j??"off",tE=(X=!1!==w,G=j?tT:null,X?oI(b)??(null!=G?oI(G):null):null),tM=(0,i.useCallback)((e,t)=>{var n;return n=_?.[`${e}:${t}`]??void 0,oR.filter(e=>n?.[e]!==null)},[_]),tA=(0,eA.Fd)(),tL=(0,i.useCallback)((e,t)=>{let n=(0,eA.b3)(`thinkingLevel.${e}:${t}`);return"string"==typeof n&&n?n:null},[tA]),tz=(0,i.useCallback)((e,t,n)=>{(0,eA.dM)(`thinkingLevel.${e}:${t}`,n),tI(),ex(!1),e3.current?.focus({preventScroll:!0}),g?.(e,t,n)},[tI,g]),tW=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!q)return;let e=!1;(0,eA.zo)().catch(()=>{e=!0}).then(()=>{if(tW.current===q||(tW.current=q,tv(q),e))return;let t=function(e){let t=(0,eA.b3)(tG(e));if(!t||"object"!=typeof t||Array.isArray(t)||"string"!=typeof t.value)return null;let n=Array.isArray(t.images)?t.images.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.mimeType&&!!(e.media||e.original||"string"==typeof e.data)):[],r={value:t.value,images:n};return tX(r)?null:(tV.set(e,tY(r)),r)}(q);if(!t)return;let n=tZ(q);n&&(""!==n.value||n.images.length>0)||(eg(t.value),t.images.length>0&&ej(t.images.map(lz)))})},[q,ej]);let t$=(0,i.useRef)(ef),tP=(0,i.useRef)(ek);t$.current=ef,tP.current=ek;let tF=(0,i.useCallback)(e=>{let t=e2.current;(t?t.value:ef).trim()||(tb(e),eq(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},[ef,tb]),tH=(0,i.useCallback)(e=>{if(!e?.length)return;let t=e.map(e=>e.previewUrl?e:lz(lL(e)));ej(e=>{let n=new Set(e.map(lW));return[...e,...t.filter(e=>!n.has(lW(e)))]})},[]),tD=(0,i.useCallback)((e,t)=>{if(!e.trim()&&!t?.length||(tH(t),!e.trim()))return;let n=e2.current,r=[e,n?n.value:ef].filter(e=>e.trim()).join("\n\n");tb(r),eq(null),requestAnimationFrame(()=>{n&&(n.focus(),n.setSelectionRange(r.length,r.length),n.style.height="auto",n.style.height=`${Math.min(n.scrollHeight,200)}px`)})},[ef,tb]),tN=(0,i.useCallback)(()=>{let e=tg.current,t=e?tZ(e):null;tb(t?.value??""),ej(e=>(e.forEach(l$),t?.images.map(lz)??[])),eq(null)},[tb]);(0,i.useImperativeHandle)(Y,()=>({focus(){e2.current?.focus()},insertIfEmpty:tF,prependText:tD,reloadDraft:tN,restoreDraft(e,t,n){if(n&&n!==tg.current){let r=tZ(n)??{value:"",images:[]},i=(t??[]).map(lL);tQ(n,{value:[e,r.value].filter(e=>e.trim()).join("\n\n"),images:[...i,...r.images]});return}tH(t),tD(e)},replaceText(e){let t=e2.current;tb(e),eq(null),requestAnimationFrame(()=>{if(!t)return;t.focus();let n=e.length;t.setSelectionRange(n,n),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},insertText(e){let t=e2.current;if(!t)return void tb(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),o=t.value.slice(r),l=i.length>0&&!i.endsWith(" ")?" ":"";tb(i+l+e+o),eq(null),requestAnimationFrame(()=>{if(!t)return;let r=n+l.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addFiles(e){t1(e)}}));let[tB,tO]=(0,i.useState)([]),tU=(0,i.useRef)(tB);tU.current=tB;let tq=(0,i.useCallback)(async e=>{eI(t=>t.map(t=>t.id===e.id?{...t,status:"uploading",error:void 0}:t));try{let t=await (0,t2.CS)(e.file,e.previewUrl);if(!(tg.current===e.draftKey&&eR.current.some(t=>t.id===e.id))){URL.revokeObjectURL(e.previewUrl),(0,t2.LH)((0,t2.I9)(t).flatMap(t2.wZ));return}ej(e=>[...e,t]),eI(t=>t.filter(t=>t.id!==e.id))}catch(n){let t=n instanceof Error?n.message:String(n);eI(n=>n.map(n=>n.id===e.id?{...n,status:"failed",error:t}:n))}},[]),tK=(0,i.useCallback)(async e=>{let t=e.filter(lk);if(!t.length)return;eC(null);let n=tg.current??null,r=t.map(e=>({id:lj(),file:e,previewUrl:URL.createObjectURL(e),status:"uploading",draftKey:n}));eI(e=>[...e,...r]),await Promise.all(r.map(e=>tq(e)))},[tq]),tJ=(0,i.useCallback)(async e=>{if(l||0===e.length)return;let t=e.filter(lk),n=e.filter(e=>!lk(e));if(t.length&&await tK(t),0===n.length)return;let r=n.map(e=>({id:lj(),name:e.name,mimeType:e.type||"application/octet-stream",size:e.size,status:"uploading"}));tO(e=>[...e,...r]),await Promise.all(n.map(async(e,t)=>{let n=r[t].id;try{let{path:t,name:r}=await (0,t2.Rc)(e,e.name,e.type);tO(e=>e.map(e=>e.id===n?{...e,path:t,name:r,status:"ready"}:e))}catch(t){let e=t instanceof Error?t.message:String(t);tO(t=>t.map(t=>t.id===n?{...t,status:"error",error:e}:t))}}))},[l,tK]),t1=(0,i.useCallback)(e=>{if(0===e.length)return;let t=e.filter(lk);t.length&&tK(t);let n=e.filter(e=>!lk(e));if(0!==n.length){if(l)return void tO(e=>[...e,...n.map(e=>({id:lj(),name:e.name,mimeType:e.type||"application/octet-stream",size:e.size,status:"error",error:es("input_uploadWhileStreaming")}))]);tJ(n)}},[l,tJ,tK,es]),t4=(0,i.useCallback)(e=>{ej(t=>{let n=[...t],[r]=n.splice(e,1);return r&&(l$(r),(0,t2.LH)((0,t2.I9)(r).flatMap(t2.wZ))),n})},[]),t6=(0,i.useCallback)(e=>{let t=e_.find(t=>t.id===e);t&&tq(t)},[e_,tq]),t5=(0,i.useCallback)(e=>{eI(t=>{let n=t.find(t=>t.id===e);return n&&URL.revokeObjectURL(n.previewUrl),t.filter(t=>t.id!==e)}),eC(null)},[]),t8=(0,i.useCallback)(e=>{let t=tU.current.find(t=>t.id===e);t?.status==="ready"&&t.path&&(0,t2.LH)([t.path]),tO(t=>t.filter(t=>t.id!==e))},[]),t3=(0,i.useCallback)(()=>{ej(e=>(e.forEach(l$),[]))},[]),t9=(0,i.useCallback)(()=>{eI(e=>(e.forEach(e=>URL.revokeObjectURL(e.previewUrl)),[]))},[]),t7=(0,i.useCallback)(()=>{tO([])},[]),ne=(0,i.useCallback)(()=>{tb(""),t$.current="",eq(null),q&&t0(q),tg.current&&tg.current!==q&&t0(tg.current),eC(null),t3(),t7(),t9(),e2.current&&(e2.current.style.height="auto")},[t3,t7,t9,q,tb]),nt=(0,i.useCallback)(e=>{let t=tU.current.filter(e=>"ready"===e.status&&e.path);if(0===t.length)return e;let n=t.map(e=>`- path=${e.path}`).join("\n"),r=`${es("input_attachedFilesPrompt")}
3
- ${n}`;return e.trim()?`${e.trim()}
4
-
5
- ${r}`:r},[es]),nn=(0,i.useRef)(null),nr=(0,i.useCallback)(()=>{let e=nn.current;if(nn.current=null,e){if(e.key&&e.key!==tg.current){let t=tZ(e.key)??{value:"",images:[]};tQ(e.key,{value:[e.value,t.value].filter(e=>e.trim()).join("\n\n"),images:[...e.images.map(lL),...t.images]});return}tH(e.images),e.value.trim()&&tD(e.value),e.uploads.length&&tO(t=>{let n=new Set(t.map(e=>e.path).filter(Boolean));return[...t,...e.uploads.filter(e=>!n.has(e.path))]})}},[tH,tD]);(0,i.useEffect)(()=>{var e;q&&tg.current===q&&(e={draftKey:q,value:ef,touched:tm.current===q,hydratedKey:tx}).draftKey&&(""!==e.value||e.touched||e.hydratedKey===e.draftKey)&&tQ(q,{value:ef,images:ek.map(lL)})},[ek,q,ef,tx]),(0,i.useEffect)(()=>{let e=tg.current;if(e===q)return;e&&tQ(e,{value:t$.current,images:tP.current.map(lL)});let t=q?tZ(q):null;tg.current=q,eg(t?.value??""),eq(null),eI(e=>(e.forEach(e=>URL.revokeObjectURL(e.previewUrl)),[])),ej(e=>(e.forEach(l$),t?.images.map(lz)??[]))},[q]),(0,i.useEffect)(()=>{let e=e2.current;e&&(e.style.height="auto",ef&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ef]),(0,i.useEffect)(()=>()=>{tP.current.forEach(l$)},[]);let ni=tB.some(e=>"ready"===e.status&&e.path),no=e_.some(e=>"uploading"===e.status)||tB.some(e=>"uploading"===e.status),nl=e_.some(e=>"failed"===e.status),ns=ek.length>0||ni,na=(0,i.useCallback)(async()=>{let t=ef.trim();if(!t&&!ek.length&&!ni)return;if(N?.(),l&&!ek.length&&!ni&&B){ne(),B(t,"followUp",void 0);return}if(l)return;if(no||nl){nl&&eC(es("input_imageUploadBlocked"));return}let n=tg.current,r=ek.slice(),i=tB.filter(e=>"ready"===e.status&&"string"==typeof e.path),o=!r.length&&!i.length&&t.startsWith("/")&&!!D;if(o&&e4.current)return;let s=nt(t),a=(0,t2.FZ)(r,i.map(e=>({path:e.path,name:e.name,mimeType:e.mimeType,size:e.size})));if(nn.current={key:n??null,value:t$.current,images:r,uploads:i.map(e=>({...e,status:"ready"})),imageKeys:r.map(lW),uploadPaths:i.map(e=>e.path)},ne(),o&&D){e4.current=!0,e5(!0);try{let e=await D(t);if(e.handled)return void(e.error?nr():nn.current=null)}finally{e4.current=!1,e5(!1)}}!1===await e(s,r.length?r:void 0,a.length?a:void 0)?nr():nn.current=null},[ef,ek,tB,ni,no,nl,l,D,B,e,ne,nr,N,nt,es]),nd=ef.startsWith("/")&&!/\s/.test(ef.slice(1))?ef.slice(1).toLowerCase():null,nc=null===nd?[]:[...lR,...A??[]].filter(e=>{let t=e.name.toLowerCase(),n=e.description?.toLowerCase()??"";return t.includes(nd)||n.includes(nd)}).sort((e,t)=>{let n=lA(e,nd)-lA(t,nd);return 0!==n?n:lM[e.source]-lM[t.source]||lC.compare(e.name,t.name)}),nu=(()=>{let e=e2.current?.selectionStart??ef.length,t=ef.lastIndexOf("\n",Math.max(0,e-1))+1,n=ef.slice(t,e);if(!n.startsWith("/"))return null;let r=n.indexOf(" ");if(-1===r)return null;let i=n.slice(1,r);return i&&(A??[]).find(e=>e.name===i&&e.hasArgumentCompletions)?{name:i,prefix:n.slice(r+1)}:null})(),np=null!==nu,nh=nu?.name??null,nf=nu?.prefix??null,ng=null===nh||null===nf?null:`${nh} ${nf}`;(0,i.useEffect)(()=>{tu.current+=1,e$([]),eF(0)},[ng]),(0,i.useEffect)(()=>{if(null===nh||null===nf||!W){e$([]),eD(!1);return}let e=++tu.current;eD(!0);let t=setTimeout(()=>{Promise.resolve(W(nh,nf)).then(t=>{tu.current===e&&(e$(Array.isArray(t)?t:[]),eF(0))}).catch(()=>{tu.current===e&&e$([])}).finally(()=>{tu.current===e&&eD(!1)})},120);return()=>clearTimeout(t)},[nh,nf,W]);let nm=(0,i.useCallback)(e=>{if(!nu)return;let t=e2.current?.selectionStart??ef.length,n=ef.lastIndexOf("\n",Math.max(0,t-1))+1,r="/"+nu.name+" ";if(!ef.slice(n,t).startsWith(r))return;let i=n+r.length;if(i>t)return;let o=ef.slice(0,i)+e.value+ef.slice(t),l=i+e.value.length;eg(o),eF(0),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[nu,ef]),nx=(()=>{let e=new Map;for(let t of lT)e.set(t,{source:t,items:[]});return nc.forEach((t,n)=>{e.get(t.source)?.items.push({command:t,index:n})}),lT.map(t=>e.get(t)).filter(e=>e.items.length>0)})(),nv=1===nc.length?es(nd?"input_matchCountOne":"input_commandCountOne"):es(nd?"input_matchCount":"input_commandCount",{count:nc.length}),ny=(!!ef.trim()||ek.length>0||ni)&&!no&&!nl,nb=(P??[]).join("\0"),nw=(0,i.useMemo)(()=>""===nb?[]:nb.split("\0"),[nb]),nk=($??0)>0&&!!F,{state:nj,schedule:nS,cancel:nC}=function(e){let{enabled:t,onLoad:n,debounceMs:r=120,timeoutMs:o=800}=e,[l,s]=(0,i.useState)(le),a=(0,i.useRef)(n);a.current=n;let d=(0,i.useMemo)(()=>{var e;let t,n,i,l,d,c,u,p,h;return t=(e={debounceMs:r,timeoutMs:o,request:(e,t)=>a.current({...e,signal:t}),onOutcome:(e,t,n)=>{if(!n){let t;s("plugin"===(t="items"===e.kind?{source:"plugin",items:e.items,prefix:e.prefix}:"empty"===e.kind?{source:"none",items:[],prefix:""}:{source:"local",items:[],prefix:""}).source?{status:"plugin",items:t.items,prefix:t.prefix}:"none"===t.source?{status:"none"}:le)}}}).timers??{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},n=null,i=null,l=null,d=0,c=0,u=0,p=()=>{null!==n&&(t.clearTimeout(n),n=null)},h=()=>{null!==i&&(t.clearTimeout(i),i=null)},{schedule(r){p(),h(),d+=1,l?.abort(),l=null;let o=d;n=t.setTimeout(()=>{n=null;let s=new AbortController;l=s,c+=1,u+=1;let a=!1,p=t=>{a||(a=!0,h(),e.onOutcome(t,r,o!==d))},f=e.timeoutMs??0;f>0&&(i=t.setTimeout(()=>{i=null,s.abort(),p({kind:"timeout"})},f)),e.request(r,s.signal).then(e=>{p(e)}).catch(()=>{p({kind:"error"})}).finally(()=>{c-=1})},e.debounceMs)},cancel:()=>{p(),h(),d+=1,l?.abort(),l=null,c=0},inflightCount:()=>c,sentCount:()=>u}},[r,o]);(0,i.useEffect)(()=>()=>d.cancel(),[d]);let c=(0,i.useCallback)(()=>{d.cancel(),s(le)},[d]);return{state:l,schedule:(0,i.useCallback)(e=>{e&&t?(s({status:"pending"}),d.schedule(e)):c()},[c,t,d]),cancel:c}}({enabled:nk,onLoad:F??(()=>Promise.resolve({kind:"no-provider"}))}),n_=(0,i.useCallback)((e,t)=>(function(e){if(e.providerCount<=0)return null;let t=Math.max(0,Math.min(e.cursor,e.text.length)),n=e.text.slice(0,t),r=n.lastIndexOf("\n")+1,i=e.cwd?oT(n):null,o=r;for(let n=t-1;n>=r;n-=1){let t=e.text[n]??"";if(o7.test(t))break;o=n}let l=o<t?e.text[o]??"":"";if(!(null!==i||""!==l&&e.triggerCharacters.includes(l)))return null;let s=n.split("\n").length-1;return{lines:e.text.split("\n"),cursorLine:s,cursorCol:t-r}})({text:e,cursor:t,providerCount:$??0,triggerCharacters:nw,cwd:K}),[$,K,nw]),nI=(0,i.useCallback)((e,t)=>{let n=t??e.length;if(to.current)return void nS(null);if(!K){eq(null),nS(n_(e,n));return}eq(oT(e.slice(0,n))),nS(n_(e,n))},[n_,K,nS]),nR=eO?.query??null,nT=i.useMemo(()=>null!==nR&&eX&&eX.cwd===K?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:oM(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:oM(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||oE(e.entry.path)-oE(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(eX.entries,nR):[],[nR,eX,K]),nE=!!(nR&&eX?.truncated&&eX.cwd===K);(0,i.useEffect)(()=>{if(!nE||!K||!nR)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(K)}&q=${encodeURIComponent(nR)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>e1({cwd:K,query:nR,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nE,nR,K]);let nM=nE&&null!==e0&&e0.cwd===K&&e0.query===nR,nA=nM?e0.matches:nT,nL="plugin"===nj.status?nj.items.map(e=>({kind:"plugin",item:e})):"local"===nj.status?nA.map(e=>({kind:"file",entry:e})):[],nz=eK&&(null!==eO||"local"!==nj.status),nW=null===eO?null:`${eO.start}:${+!!eO.quoted}:${eO.query}`;(0,i.useEffect)(()=>{if(null===nW){eJ(!1),eY(0);return}eJ(!0),eY(0)},[nW]);let n$=null!==eO;(0,i.useEffect)(()=>{if(!n$||!K)return;let e=th.current;e&&e.cwd===K&&Date.now()-e.fetchedAt<1e4||tf.current===K||(tf.current=K,eQ(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(K)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{eG({cwd:K,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>oE(e.path)-oE(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),th.current={cwd:K,fetchedAt:Date.now()}}).catch(()=>{th.current=null}).finally(()=>{tf.current=null,eQ(!1)}))},[n$,K]);let nP=(0,i.useCallback)(e=>{if(!eO)return;let t=e2.current,n=t?.selectionStart??ef.length,r=ef.slice(0,eO.start),i=ef.slice(n);eO.quoted&&i.startsWith('"')&&(i=i.slice(1));let o=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let o=i?`@"${r}" `:`@${r} `;return{text:o,cursorOffset:o.length}}(e.path,e.isDir,eO.quoted),l=r+o.text+i,s=r.length+o.cursorOffset;eg(l),eq(oT(l.slice(0,s))),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(s,s),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[eO,ef]),nF=(0,i.useCallback)(e=>{if("file"===e.kind)return void nP(e.entry);let t=e2.current,n=t?.selectionStart??ef.length,r=ef.slice(0,n),i=r.split("\n").length-1,o=n-(r.lastIndexOf("\n")+1),l="plugin"===nj.status?nj.prefix:"",s=t?.value??ef;(async()=>{let t=await H?.({lines:ef.split("\n"),cursorLine:i,cursorCol:o,item:e.item,prefix:l});if(!t||(e2.current?.value??ef)!==s)return;let n=t.lines.join("\n"),r=t.lines.slice(0,t.cursorLine).reduce((e,t)=>e+t.length+1,0)+t.cursorCol;eg(n),nI(n,r),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(r,r),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})})()},[nP,H,nj,nI,ef]);(0,i.useEffect)(()=>{null!==eO||"plugin"===nj.status&&0!==nj.items.length&&(eJ(!0),eY(0))},[nj,eO]),(0,i.useEffect)(()=>{let e=e2.current;nI(e?.value??ef,e?.selectionStart??null)},[nk,nb,nI]),(0,i.useEffect)(()=>{eV>=nL.length&&eY(Math.max(0,nL.length-1))},[nL.length,eV]),(0,i.useEffect)(()=>{tp.current.length=nL.length},[nL.length]),(0,i.useEffect)(()=>{eK&&tp.current[eV]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eV,eK]);let nH=(0,i.useCallback)(e=>{let t=`/${e.name} `;eg(t),ez(!1),eB(0),requestAnimationFrame(()=>{let e=e2.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nD=(0,i.useCallback)(e=>{let t=ef.trim();if(!t&&!ni&&0===ek.length||no)return;if(nl)return void eC(es("input_imageUploadBlocked"));N?.();let r=nt(t),i=ek.length?ek:void 0;if(r.startsWith("/")&&B){B(r,"steer"===e?"steer":"followUp",i),ne();return}let l="steer"===e?n:o;l&&(l(r,i),ne())},[ef,ek.length,ni,no,nl,B,n,o,ne,N,nt,es]),nN=(0,i.useCallback)(()=>{if(!M)return;if(ek.length||no)return void M();let e=ef.trim(),t=e||ni?nt(e).trim():"";N?.(),M(t||void 0),t&&ne()},[M,ek.length,no,ef,ni,nt,N,ne]),nB=(0,i.useCallback)(e=>{let t=nc.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eN-1);if("right"===e)return Math.min(t,eN+1);let n=ta.current[eN];if(!n)return"down"===e?Math.min(t,eN+1):Math.max(0,eN-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,o=r.top+r.height/2,l=-1,s=1/0;for(let n=0;n<=t;n+=1){if(n===eN)continue;let t=ta.current[n];if(!t)continue;let r=t.getBoundingClientRect(),a=r.top+r.height/2-o;if("down"===e?a<=4:a>=-4)continue;let d=1e3*Math.abs(a)+Math.abs(r.left+r.width/2-i);d<s&&(l=n,s=d)}return l>=0?l:"down"===e?Math.min(t,eN+1):Math.max(0,eN-1)},[nc.length,eN]),nO=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tl.current<100,s=to.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(np&&eW.length>0){if("ArrowDown"===e.key){e.preventDefault(),eF(e=>Math.min(eW.length-1,e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eF(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tu.current+=1,e$([]),eD(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&eW[eP]){e.preventDefault(),nm(eW[eP]);return}}if(eL&&null!==nd){if("ArrowDown"===e.key){e.preventDefault(),eB(nB("down"));return}if("ArrowUp"===e.key){e.preventDefault(),eB(nB("up"));return}if("ArrowRight"===e.key){e.preventDefault(),eB(nB("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),eB(nB("left"));return}if("Escape"===e.key){e.preventDefault(),ez(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nc[eN]){e.preventDefault(),nH(nc[eN]);return}}if(nz&&!s){if("ArrowDown"===e.key){e.preventDefault(),eY(e=>Math.min(Math.max(0,nL.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),eY(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),eJ(!1),nC();return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nL[eV]){e.preventDefault(),nF(nL[eV]);return}}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}if("Enter"===e.key&&!e.shiftKey){if(ea)return;e.preventDefault();let t=e.ctrlKey||e.metaKey,r=T?.followUp.length??0,i=T?.followUp.length??0,s=!!ef.trim()||ni;if(!t&&!s&&i>0&&M||t&&r>0&&M)return void nN();if(l&&(n||o)){let e="steer"!==ed;nD(t?e?"steer":"followup":e?"followup":"steer")}else na()}},[l,ea,ed,n,o,t,eL,nd,nc,eN,nH,np,eW,eP,nm,nD,na,nB,nz,eK,eO,nL,eV,nF,nC,T,M,nN]),nU=(0,i.useCallback)(()=>{let e=e2.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nq=(0,i.useCallback)(e=>{let t=Array.from(e.clipboardData?.items??[]).filter(e=>"file"===e.kind).map(e=>e.getAsFile()).filter(e=>null!==e);0!==t.length&&(e.preventDefault(),t1(t))},[t1]);(0,i.useEffect)(()=>{if(null===nd){ez(!1),eB(0),ts.current=!1;return}ez(!0),eB(0),!ts.current&&z&&(ts.current=!0,Promise.resolve(z()).catch(()=>{ts.current=!1}))},[nd,z]),(0,i.useEffect)(()=>{eN>=nc.length&&eB(Math.max(0,nc.length-1))},[nc.length,eN]),(0,i.useEffect)(()=>{ta.current.length=nc.length},[nc.length]),(0,i.useEffect)(()=>{eL&&ta.current[eN]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eN,eL]),(0,i.useEffect)(()=>{tc.current.length=eW.length},[eW.length]),(0,i.useEffect)(()=>{np&&tc.current[eP]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eP,np]);let nK=(0,i.useMemo)(()=>{let e=p&&p.length>0?p.map(e=>({provider:e.provider,modelId:e.id,name:e.name,contextWindow:e.contextWindow,maxTokens:e.maxTokens})):Object.entries(u??{}).map(([e,t])=>{let n=e.indexOf(":");return n>0?{provider:e.slice(0,n),modelId:e.slice(n+1),name:t}:{provider:d?.provider??"unknown",modelId:e,name:t}});return d&&!e.some(e=>e.provider===d.provider&&e.modelId===d.modelId)&&e.push({provider:d.provider,modelId:d.modelId,name:d.modelId}),e.sort(l_)},[p,u,d]),nJ=[];for(let e of nK){let t=nJ.find(t=>t.provider===e.provider);t?t.options.push(e):nJ.push({provider:e.provider,options:[e]})}let nV=d?nK.find(e=>e.modelId===d.modelId&&e.provider===d.provider)?.name??d.modelId:null,nY=y?Math.max(0,y.tokensBefore-y.estimatedTokensAfter):0,nX=y?.reason==="auto"?"input_compactionReason_auto":y?.reason==="threshold"?"input_compactionReason_threshold":y?.reason==="overflow"?"input_compactionReason_overflow":null,nG=y?nX?es("input_compactionResultWithReason",{before:lI(y.tokensBefore),after:lI(y.estimatedTokensAfter),saved:lI(nY),reason:es(nX)}):es("input_compactionResult",{before:lI(y.tokensBefore),after:lI(y.estimatedTokensAfter),saved:lI(nY)}):null,nZ=(0,i.useId)(),nQ=(0,i.useId)(),n0=(0,i.useId)(),n1=lr({open:eL&&null!==nd,anchorRef:tt,overlayRef:tn,preferredPlacement:"above",gap:8,margin:8,maxHeight:460,width:"anchor"}),n2=lr({open:np&&(eW.length>0||eH),anchorRef:tt,overlayRef:td,preferredPlacement:"above",gap:8,margin:8,maxHeight:260,width:"anchor"}),n4=lr({open:nz,anchorRef:tt,overlayRef:tr,preferredPlacement:"above",gap:8,margin:8,maxHeight:400,width:"anchor"}),n6=lr({open:em,anchorRef:e3,overlayRef:e9,preferredPlacement:"above",gap:6,margin:8,minWidth:"anchor",width:ea?"max":void 0}),n5=eL&&null!==nd,n8=n5&&nc.length>0?`${nZ}-opt-${eN}`:nz&&nL.length>0?`${nQ}-opt-${eV}`:void 0,n3=n5?nZ:nz?nQ:void 0;return(0,i.useEffect)(()=>{if(!(ev||em))return;let e=e=>{if("Escape"===e.key&&!e.defaultPrevented)if(e.preventDefault(),ev){var t;ey(!1),t=e7.current,t?.querySelector("button")?.focus({preventScroll:!0})}else em&&(ex(!1),e3.current?.focus({preventScroll:!0}))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[ev,em]),(0,i.useEffect)(()=>{ev&&lP(te.current,'[role="menuitemradio"]')},[ev]),(0,i.useEffect)(()=>{em&&lP(e9.current,'[role="option"]')},[em]),(0,i.useEffect)(()=>{let e=e=>{let t=e.target,n=tC.current?.contains(t);!e8.current||e8.current.contains(t)||!e9.current||e9.current.contains(t)||n||(ex(!1),tI()),e7.current&&!e7.current.contains(t)&&te.current&&!te.current.contains(t)&&ey(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[tI]),(0,r.jsxs)("div",{style:{flexShrink:0,background:"transparent",padding:`0 ${ea?16:18}px 8px`},children:[(0,r.jsx)("input",{ref:ti,type:"file",multiple:!0,disabled:a,style:{display:"none"},onChange:e=>{t1(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsxs)("fieldset",{disabled:a,"aria-disabled":a||void 0,"aria-busy":e6||void 0,style:{border:0,padding:0,margin:0,minWidth:0},children:[eh.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:es("input_queued",{count:eh.length})}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>ew(e=>!e),"aria-expanded":eb,"aria-label":eb?es("input_collapseQueue"):es("input_expandQueue"),title:eb?es("input_collapseQueue"):es("input_expandQueue"),className:"instant-tooltip tooltip-up",style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"1px solid var(--border)",borderRadius:6,background:"transparent",color:"var(--text-dim)",cursor:"pointer"},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:eb?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})}),M&&(0,r.jsxs)("button",{type:"button",onClick:nN,"data-tooltip":es("input_sendQueueAsSteerTooltip"),className:"instant-tooltip tooltip-up",style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--accent)",background:"transparent",border:"1px solid color-mix(in srgb, var(--accent) 45%, var(--border))",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap",fontWeight:600},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--accent) 10%, transparent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),(0,r.jsx)("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),es("input_sendQueueAsSteer")]}),E&&(0,r.jsxs)("button",{type:"button",onClick:E,"data-tooltip":es("input_recall"),className:"instant-tooltip tooltip-up",style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:7,cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),es("input_recall")]})]})]}),eb&&eh.map(e=>{let t;return(0,r.jsx)(lF,{kind:"follow-up",text:e.text,state:e.state,stateLabel:"unknown"===(t=e.state)?es("input_queueStateUnknown"):"claimed"===t?es("input_queueStateClaimed"):void 0,imageCount:e.imageCount},e.id)})]}),R&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-warning) 28%, transparent)",borderRadius:6,fontSize:12,color:"var(--status-warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),es("input_retrying")," (",R.attempt,"/",R.maxAttempts,")",R.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",R.errorMessage]})]}),v&&(0,r.jsx)("div",{style:{marginBottom:8,padding:"5px 10px",background:"color-mix(in srgb, var(--status-danger) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-danger) 28%, transparent)",borderRadius:6,fontSize:12,color:"var(--status-danger)",display:"flex",alignItems:"center",gap:6},children:v}),nG&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"color-mix(in srgb, var(--status-success) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-success) 28%, transparent)",borderRadius:6,fontSize:12,color:"var(--status-success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nG]}),(ek.length>0||e_.length>0||tB.length>0||eS)&&(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginBottom:6,flexWrap:"wrap",alignItems:"center"},children:[eS&&(0,r.jsx)("div",{role:"alert",style:{flexBasis:"100%",color:"var(--status-danger)",fontSize:11},children:eS}),e_.map(e=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},title:e.error,children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:`1px solid ${"failed"===e.status?"var(--status-danger)":"var(--border)"}`,display:"block",opacity:"uploading"===e.status?.45:1}}),"failed"===e.status?(0,r.jsx)("button",{type:"button",onClick:()=>t6(e.id),style:{position:"absolute",inset:0,borderRadius:6,border:"none",background:"color-mix(in srgb, var(--bg-panel) 82%, transparent)",color:"var(--status-danger)",fontSize:11,cursor:"pointer",padding:0},children:es("input_imageRetry")}):(0,r.jsx)("div",{"aria-hidden":"true",style:{position:"absolute",inset:0,borderRadius:6,display:"flex",alignItems:"center",justifyContent:"center",background:"color-mix(in srgb, var(--bg-panel) 70%, transparent)",color:"var(--text-muted)",fontSize:10},children:es("input_imageUploading")}),(0,r.jsx)("button",{type:"button",onClick:()=>t5(e.id),"aria-label":es("input_removeAttachment"),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},e.id)),ek.map((e,t)=>(0,r.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:6,border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button",onClick:()=>t4(t),"aria-label":es("input_removeAttachment"),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`img-${t}`)),tB.map(e=>{let t=iq(e.name)?"video":iU(e.name)?"audio":iO(e.name)?"image":"file",n="error"===e.status?"var(--status-danger)":"uploading"===e.status?"var(--text-dim)":"var(--text-muted)";return(0,r.jsxs)("div",{title:e.error||e.path||e.name,style:{position:"relative",display:"flex",alignItems:"center",gap:6,maxWidth:220,padding:"6px 10px",borderRadius:8,border:`1px solid ${"error"===e.status?"color-mix(in srgb, var(--status-danger) 40%, var(--border))":"var(--border)"}`,background:"var(--bg-panel)",fontSize:12,color:n},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,textTransform:"uppercase",letterSpacing:.4,color:"var(--text-dim)"},children:t}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"uploading"===e.status?es("input_uploadingAttachment"):e.name}),(0,r.jsx)("button",{type:"button",onClick:()=>t8(e.id),"aria-label":es("input_removeAttachment"),style:{flexShrink:0,width:16,height:16,borderRadius:"50%",background:"var(--bg)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},e.id)})]}),(0,r.jsxs)("div",{ref:tt,style:{position:"relative"},children:[n5&&(0,r.jsxs)("div",{ref:tn,style:{...n1.style,zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"above"===n1.placement?"0 -6px 20px rgba(0,0,0,0.12)":"0 6px 20px rgba(0,0,0,0.12)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:L?es("input_loadingCommands"):`${es("input_slashCommands")} \xb7 ${nv}`}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("input_tabEnter")})]}),(0,r.jsx)("div",{id:nZ,role:"listbox","aria-label":es("input_slashCommands"),style:{flex:1,minHeight:0,overflowY:"auto",padding:10},children:L||0!==nc.length?nx.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:es(lE[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===eN;return(0,r.jsxs)("button",{id:`${nZ}-opt-${t}`,role:"option","aria-selected":n,ref:e=>{ta.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nH(e)},onMouseEnter:()=>eB(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:7,background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word"},children:["/",e.name]}),e.description&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:e.description})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:es("input_noCommands")})})]}),np&&(eW.length>0||eH)&&(0,r.jsxs)("div",{ref:td,style:{...n2.style,zIndex:118,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"above"===n2.placement?"0 -6px 20px rgba(0,0,0,0.12)":"0 6px 20px rgba(0,0,0,0.12)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:eH&&0===eW.length?es("input_commandArgsLoading"):es("input_commandArgs",{name:nu?.name??""})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("input_tabEnter")})]}),(0,r.jsx)("div",{role:"listbox","aria-label":es("input_commandArgs",{name:nu?.name??""}),style:{flex:1,minHeight:0,overflowY:"auto",padding:4},children:eW.map((e,t)=>{let n=t===eP;return(0,r.jsxs)("button",{ref:e=>{tc.current[t]=e},role:"option","aria-selected":n,type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>eF(t),style:{width:"100%",minWidth:0,display:"flex",alignItems:"center",gap:8,padding:"7px 9px",minHeight:ea?44:32,border:`1px solid ${n?"var(--accent)":"transparent"}`,borderRadius:6,background:n?"var(--bg-selected)":"transparent",color:"var(--text)",fontSize:12,fontFamily:"var(--font-mono)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.label}),e.description&&(0,r.jsx)("span",{style:{marginLeft:"auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:e.description})]},`${e.value}:${t}`)})})]}),nz&&(Z=eZ&&(!eX||eX.cwd!==K),Q="plugin"===nj.status||"none"===nj.status,et="pending"===nj.status,en=1===nL.length?es("input_matchCountOne"):es("input_matchCount",{count:nL.length}),er=eX?.truncated&&!nM?eO.query?` \xb7 ${es("input_searchingAllFiles")}`:` \xb7 ${es("input_indexTruncated")}`:"",(0,r.jsxs)("div",{ref:tr,style:{...n4.style,zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"above"===n4.placement?"0 -6px 20px rgba(0,0,0,0.12)":"0 6px 20px rgba(0,0,0,0.12)",overflow:"hidden",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{children:Q?`${es("input_suggestions")} \xb7 ${en}`:Z?es("input_loadingFiles"):`${es("input_files")} \xb7 ${en}${er}`}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:es("input_tabEnter")})]}),(0,r.jsx)("div",{id:nQ,role:"listbox","aria-label":Q?es("input_suggestions"):es("input_files"),style:{flex:1,minHeight:0,overflowY:"auto",padding:4},children:(!Z||Q||et)&&0===nL.length?(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:et?es("input_searching"):Q?es("input_noMatchingSuggestions"):nE&&!nM?es("input_searching"):es("input_noMatchingFiles")}):nL.map((e,t)=>{let n=t===eV,i="plugin"===e.kind?e.item:null,o="file"===e.kind?e.entry.path:"",l="file"===e.kind&&e.entry.isDir,s=i?i.label:o.split("/").pop()??o,a=i?"":o.slice(0,o.length-s.length);return(0,r.jsxs)("button",{id:`${nQ}-opt-${t}`,role:"option","aria-selected":n,ref:e=>{tp.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nF(e)},onMouseEnter:()=>eY(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",minHeight:ea?44:void 0,border:"none",borderRadius:6,background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:i?null:l?(0,r.jsx)(oz,{size:14}):o9(s,14)}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i?(0,r.jsxs)(r.Fragment,{children:[i.label,i.description?(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginLeft:8},children:i.description}):null]}):(0,r.jsxs)(r.Fragment,{children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),s,l&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})})]},i?`p:${i.value}`:`${l?"d":"f"}:${o}`)})})]})),(0,r.jsxs)("div",{className:"chat-input-shell",style:{display:"flex",gap:8,alignItems:"flex-end",background:"var(--bg-elevated)",border:`1px solid ${eE?"var(--tool-bg)":l&&(n||o)?"color-mix(in srgb, var(--status-warning) 45%, var(--border-strong))":"var(--border-strong)"}`,borderRadius:"var(--radius-lg)",padding:"10px 10px 10px 10px",boxShadow:"var(--shadow-input)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>ti.current?.click(),disabled:a,"data-tooltip":es("input_attachFile"),className:"instant-tooltip tooltip-up","aria-label":es("input_attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:9,color:ns?"var(--accent)":"var(--text-muted)",cursor:a?"not-allowed":"pointer",opacity:a?.5:1,transition:"background 0.12s, color 0.12s",alignSelf:"flex-end"},onMouseEnter:e=>{a||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=ns?"var(--accent)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=ns?"var(--accent)":"var(--text-muted)"},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"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"})})}),(0,r.jsx)("textarea",{ref:e2,value:ef,role:"combobox","aria-expanded":n5||nz,"aria-controls":n3,"aria-activedescendant":n8,"aria-autocomplete":"list",onChange:e=>{tb(e.target.value),nI(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nI(t.value,t.selectionStart)},onKeyDown:nO,onCompositionStart:()=>{to.current=!0,nC()},onCompositionEnd:e=>{to.current=!1,tl.current=Date.now();let t=e.currentTarget;nI(t.value,t.selectionStart)},onInput:nU,onFocus:()=>ep(!0),onBlur:()=>ep(!1),onPaste:nq,placeholder:l&&(n||o)?es("input_placeholderSteer"):l?es("input_placeholderRunning"):es("input_placeholderMessage"),rows:1,style:{flex:1,background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.45,fontFamily:"inherit",minHeight:32,maxHeight:200,padding:"5px 0",boxSizing:"border-box",overflow:"auto"}}),(eo=(ei=l&&(n||o))?ny:!!((ef.trim()||ek.length||ni)&&!no),el=ei?es("input_sendQueueTooltip"):void 0,(0,r.jsxs)("button",{type:"button",onClick:()=>{ei?nD("followup"):na()},disabled:!eo,"data-tooltip":el,className:el?"instant-tooltip tooltip-up":void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",gap:6,padding:"7px 14px",background:eo?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:8,color:eo?"var(--accent-foreground)":"var(--text-dim)",cursor:eo?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",boxShadow:eo?"0 1px 3px color-mix(in srgb, var(--accent) 30%, transparent)":"none",transition:"background 0.15s, box-shadow 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),es("input_send")]}))]})]}),eE&&(0,r.jsx)("div",{className:"text-xs px-2 py-1",style:{color:eM?"var(--text-muted)":"var(--accent)",marginTop:4},children:es("input_shellStatus",{scope:eM?es("input_shellLocal"):es("input_shellModel")})}),(0,r.jsxs)("div",{style:{marginTop:8,display:ea?"grid":"flex",gridTemplateColumns:ea?"minmax(0, 1fr) auto":void 0,alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",gap:2,maxWidth:ea?"100%":void 0},children:[U&&(0,r.jsx)("button",{type:"button",onClick:U,"aria-expanded":!O,"aria-label":O?es("footer_expand"):es("footer_collapse"),title:O?es("footer_expand"):es("footer_collapse"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:ea?26:24,height:ea?26:24,padding:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:O?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}):(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})})}),nK.length>0&&g&&(0,r.jsxs)("div",{ref:e8,style:{position:"relative",flex:"0 1 auto",minWidth:ea?96:140},children:[(0,r.jsxs)("button",{ref:e3,"aria-haspopup":"listbox","aria-expanded":em,"aria-controls":n0,onClick:()=>{let e=!em;ex(e),e&&(ey(!1),ez(!1),eJ(!1))},title:l?es("input_changeAppliesNextTurn"):d?tR({modelId:d.modelId,name:nV??d.modelId,provider:d.provider,contextWindow:p?.find(e=>e.provider===d?.provider&&e.id===d?.modelId)?.contextWindow,maxTokens:p?.find(e=>e.provider===d?.provider&&e.id===d?.modelId)?.maxTokens}):void 0,style:{display:"flex",alignItems:"center",gap:ea?4:6,justifyContent:"flex-start",padding:ea?"6px 8px":"8px 12px",height:32,width:"auto",minWidth:ea?96:140,maxWidth:ea?220:340,overflow:"hidden",background:em?"var(--bg-hover)":"none",border:"none",borderRadius:9,color:"var(--text-muted)",cursor:"pointer",fontSize:ea?11:12,transition:"background 0.12s, color 0.12s",flex:"0 1 auto"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background=em?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nV??es("input_modelTitle")}),tE?(0,r.jsxs)("span",{style:{flexShrink:0,fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:2},children:["\xb7",tE]}):null]}),em&&(0,s.createPortal)((0,r.jsx)("div",{ref:e9,id:n0,role:"listbox","aria-label":es("input_modelTitle"),onKeyDown:e=>(function(e,t){let n,r=e.key;if("ArrowDown"!==r&&"ArrowUp"!==r&&"Home"!==r&&"End"!==r)return;let i=Array.from(e.currentTarget.querySelectorAll(t));if(0===i.length)return;e.preventDefault();let o=i.indexOf(document.activeElement);n="Home"===r?0:"End"===r?i.length-1:"ArrowDown"===r?o<0?0:(o+1)%i.length:o<0?i.length-1:(o-1+i.length)%i.length,i[n]?.focus({preventScroll:!0})})(e,'[role="option"]'),style:{...n6.style,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"above"===n6.placement?"0 -4px 16px rgba(0,0,0,0.10)":"0 4px 16px rgba(0,0,0,0.10)",overflow:"hidden",overflowY:"auto"},children:nJ.map((e,t)=>{let n=f?.[e.provider]===!1;return(0,r.jsxs)("div",{children:[nJ.length>1&&(0,r.jsxs)("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",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.provider}),n&&(0,r.jsx)("span",{title:es("models_authRequiredToViewModels"),style:{flexShrink:0,fontSize:9,padding:"1px 6px",borderRadius:999,border:"1px solid var(--border)",color:"var(--text-dim)",textTransform:"none",letterSpacing:0,fontWeight:400},children:es("models_authRequired")})]}),e.options.map(e=>{let t=e.modelId===d?.modelId&&e.provider===d?.provider,i=n&&!t,o=i?es("models_authRequiredToViewModels"):tR(e),l=tL(e.provider,e.modelId),a=function(e,t,n,r="off"){return t?oI(n)??oI(e)??r:oI(e)??r}(l,t,b,tT),c=tM(e.provider,e.modelId),u=`${e.provider}:${e.modelId}`,p=tw===u,f=()=>{!i&&g&&(ex(!1),tI(),e3.current?.focus({preventScroll:!0}),g(e.provider,e.modelId,function(e,t="off"){return oI(e)??t}(l,tT)))};return(0,r.jsxs)("div",{role:"option","aria-selected":t,"aria-disabled":i||void 0,title:o,tabIndex:i?-1:0,onClick:f,onKeyDown:e=>{i||("Enter"===e.key||" "===e.key)&&(e.preventDefault(),f())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",minHeight:ea?44:void 0,background:t?"var(--bg-selected)":"none",border:"none",color:i?"var(--text-dim)":t?"var(--text)":"var(--text-muted)",cursor:i?"not-allowed":"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap",opacity:i?.55:1,boxSizing:"border-box"},onMouseEnter:e=>{t||i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||i||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:"1 1 auto",minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:e.name}),"number"==typeof e.contextWindow&&(0,r.jsxs)("span",{style:{flexShrink:0,display:"inline-flex",alignItems:"center",gap:4,fontSize:10,color:lw(h,e.contextWindow)?"var(--status-warning)":"var(--text-dim)",fontFamily:"var(--font-mono)"},children:[lw(h,e.contextWindow)&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"}),(0,r.jsx)("path",{d:"M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"})]}),lS(e.contextWindow)]}),(0,r.jsxs)("button",{type:"button","data-depth-trigger":u,"aria-label":es("input_modelThinkingLevel"),"aria-expanded":p,disabled:i,onClick:e=>{e.stopPropagation(),e.preventDefault(),i||(p?tI():t_(u,e.currentTarget))},style:{display:"inline-flex",alignItems:"center",gap:3,flexShrink:0,minWidth:44,minHeight:ea?44:32,justifyContent:"center",padding:"0 6px",borderRadius:6,border:"none",background:p?"var(--bg-selected)":"var(--bg-subtle)",color:"var(--text-muted)",cursor:i?"not-allowed":"pointer",fontSize:11,fontFamily:"var(--font-mono)"},children:[a,(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"9 18 15 12 9 6"})})]}),p&&tj&&(0,s.createPortal)((0,r.jsx)("div",{ref:tC,role:"listbox","aria-label":es("input_modelThinkingLevel"),style:{position:"fixed",top:tj.top,left:tj.left,zIndex:10070,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 4px 16px rgba(0,0,0,0.12)",padding:4,display:"flex",flexDirection:"column",gap:2,minWidth:116},onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),children:c.map(t=>(0,r.jsx)("button",{type:"button",role:"option","aria-selected":t===a,onClick:n=>{n.stopPropagation(),tz(e.provider,e.modelId,t)},style:{minHeight:ea?44:30,padding:"0 10px",border:"none",borderRadius:6,background:t===a?"var(--bg-selected)":"none",color:t===a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",textAlign:"left"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background=t===a?"var(--bg-selected)":"none"},children:t},t))}),document.body)]},u)})]},e.provider)})}),document.body)]})]}),!ea&&(0,r.jsx)("div",{style:{flex:1}}),(0,r.jsx)("div",{style:{flex:"0 0 auto",display:"flex",alignItems:"center",justifyContent:"flex-end",marginLeft:"auto"},children:(l||x)&&(0,r.jsxs)("button",{type:"button",onClick:()=>{x&&m?m():t()},"data-tooltip":x?es("input_stopCompaction"):es("chat_cancel"),className:"instant-tooltip tooltip-up",style:{display:"flex",alignItems:"center",gap:6,padding:ea?"6px 10px":"8px 14px",height:32,background:"color-mix(in srgb, var(--status-danger) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--status-danger) 30%, transparent)",borderRadius:9,color:"var(--status-danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--status-danger) 16%, transparent)"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--status-danger) 8%, transparent)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),x?es("input_stopCompaction"):es("input_stop")]})})]})]})})]})});function lD(e,t){return nG(e).map((e,n)=>e.style?(0,r.jsx)("span",{style:e.style,children:e.text},`${t}-${n}`):e.text)}function lN({request:e,onInput:t,onExit:n,queuedCount:o=0,onKeytrapElement:l,autoFocus:s=!0}){let{t:a}=(0,eU.s9)(),d=(0,i.useRef)(null),c=(0,i.useRef)(!1),u=(0,i.useRef)(e);u.current=e;let p=nP(e.images,e.imageFallbacks),h=nX(e.lines??[],{keep:p}),f=h.lines,g=nF(e.images,h.sourceIndex).items,m=nF(e.imageFallbacks,h.sourceIndex).items;(0,i.useEffect)(()=>{s&&d.current?.focus()},[e.id,s]),(0,i.useEffect)(()=>{if(l)return l(d.current),()=>l(null)},[l]);let x=e=>{e&&t(u.current,e)};return(0,r.jsx)("div",{style:{flexShrink:0,padding:"0 12px 8px"},"data-extension-editor-takeover":e.id,children:(0,r.jsxs)("section",{role:"group","aria-label":a("chat_editorTakeover"),className:"extension-panel-shell extension-panel-shell--expanded",style:{margin:"0 auto"},children:[(0,r.jsxs)("header",{className:"extension-panel-header",style:{display:"flex",alignItems:"center",gap:8,cursor:"default"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a("chat_editorTakeover")}),(0,r.jsx)("button",{type:"button",className:"extension-card-btn",onClick:n,"aria-label":a("chat_editorTakeoverExit"),title:a("chat_editorTakeoverExit"),children:a("chat_editorTakeoverExit")})]}),(0,r.jsx)("textarea",{ref:d,"aria-label":a("chat_editorTakeover"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,className:"extension-panel-keytrap",onKeyDown:e=>{if(c.current||e.nativeEvent.isComposing||!lo(e,window.getSelection()?.toString()??""))return;let t=lx(e);t&&(e.preventDefault(),e.stopPropagation(),x(t))},onInput:e=>{if(c.current||e.nativeEvent.isComposing)return;let t=e.currentTarget.value;e.currentTarget.value="",t&&x(t)},onCompositionStart:()=>{c.current=!0},onCompositionEnd:e=>{c.current=!1;let t=e.currentTarget;queueMicrotask(()=>{let e=t.value;t.value="",e&&x(e)})},onPaste:e=>{e.preventDefault();let t=e.clipboardData.getData("text");t&&x(lv(t))}}),(0,r.jsx)("pre",{className:"extension-panel-ansi",style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:(0,r.jsx)(n8,{lines:f.length?f:[""],images:g,imageFallbacks:m,keyPrefix:"editor-line",renderLine:lD,imageAlt:a("message_imageAlt"),fallbackLabel:e=>{let t=nH(e);return a("message_imageUnavailable",{reason:t?a(t):e})}})}),(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-dim)",padding:"4px 10px 0"},children:[a("chat_editorTakeoverHint"),o>0?` ${a("chat_editorTakeoverQueued",{count:o})}`:""]})]})})}function lB({onReenter:e}){let{t}=(0,eU.s9)();return(0,r.jsx)("div",{style:{flexShrink:0,padding:"0 12px 6px"},children:(0,r.jsxs)("div",{role:"status",style:{display:"flex",alignItems:"center",gap:8,maxWidth:900,margin:"0 auto",fontSize:12,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0},children:t("chat_editorTakeoverCollapsed")}),(0,r.jsx)("button",{type:"button",className:"extension-card-btn",onClick:e,"aria-label":t("chat_editorTakeoverReenter"),title:t("chat_editorTakeoverReenter"),children:t("chat_editorTakeoverReenter")})]})})}function lO(e){return"user"===e.role?{bg:"var(--bg-selected)",border:"var(--accent)"}:{bg:"var(--bg-hover)",border:"var(--text-dim)"}}function lU({messages:e,plan:t,scrollContainer:n,messageRefs:o}){let[l,s]=(0,i.useState)(0),[a,d]=(0,i.useState)(1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[m,x]=(0,i.useState)([]),v=(0,i.useRef)(!1),y=(0,i.useRef)(null),b=(0,i.useMemo)(()=>{let n=rr(t),r=rn(e,null!=n);return[...e.slice(0,r),...n?[n]:[],...e.slice(r)]},[t,e]),w=(0,i.useRef)(b);w.current=b;let k=(0,i.useRef)(t);k.current=t;let j=(0,i.useCallback)(()=>{let e=n.current;if(!e)return;let t=e.scrollHeight,r=e.clientHeight,i=t-r;u(i>20),i<=0?(s(0),d(1)):(s(e.scrollTop/i),d(r/t))},[n]),S=(0,i.useRef)(null),C=(0,i.useCallback)(()=>{S.current||(S.current=setTimeout(()=>{S.current=null;let e=n.current;if(!e)return;let t=e.scrollHeight;if(t<=0)return;let r=o.current,i=[],l=0,s=w.current,a=rr(k.current??[]);for(let n=0;n<s.length;n++){let o=s[n];if(a&&o===a||"user"!==o.role&&"assistant"!==o.role)continue;let d=r?.[l];if(l++,("user"===o.role||"assistant"===o.role&&(o.content??[]).some(e=>"text"===e.type))&&d){let n=d.getBoundingClientRect(),r=e.getBoundingClientRect(),l=n.top-r.top+e.scrollTop,s=n.height;i.push({topRatio:l/t,heightRatio:s/t,msg:o,index:i.length})}}x(i)},150))},[n,o]);(0,i.useEffect)(()=>{let e=n.current;if(e)return e.addEventListener("scroll",j,{passive:!0}),()=>e.removeEventListener("scroll",j)},[n,j]),(0,i.useEffect)(()=>{let e=n.current;if(!e)return;let t=()=>{j(),C()},r=new ResizeObserver(t);return r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild),t(),()=>{r.disconnect(),S.current&&(clearTimeout(S.current),S.current=null)}},[n,C,j]),(0,i.useEffect)(()=>{let e=setTimeout(()=>{j(),C()},50);return()=>clearTimeout(e)},[e.length,C,j]);let _=(0,i.useCallback)(e=>{let t=n.current;if(!t)return;let r=t.scrollHeight-t.clientHeight;r<=0||(t.scrollTop=Math.max(0,Math.min(1-a,e))/(1-a)*r)},[n,a]),I=(0,i.useCallback)(e=>{if(!c)return;v.current=!0;let t=e.currentTarget.getBoundingClientRect(),n=(e.clientY-t.top)/t.height,r=n-l*(1-a),i=r>=0&&r<=a?r:a/2;_(n-i);let o=e=>{v.current&&_((e.clientY-t.top)/t.height-i)},s=()=>{v.current=!1,window.removeEventListener("mousemove",o),window.removeEventListener("mouseup",s)};window.addEventListener("mousemove",o),window.addEventListener("mouseup",s)},[c,a,l,_]),R=y.current?.clientHeight??600,T=(0,i.useMemo)(()=>{if(!p||0===m.length)return[];let e=m.map(e=>Math.round(e.topRatio*R-11));for(let t=0;t<10;t++){for(let t=1;t<e.length;t++){let n=e[t-1]+22+2;e[t]<n&&(e[t]=n)}for(let t=e.length-2;t>=0;t--){let n=e[t+1]-22-2;e[t]>n&&(e[t]=n)}}for(let t=0;t<e.length;t++)e[t]=Math.max(0,Math.min(R-22,e[t]));return e},[p,m,R]);if(!c)return null;let E=l*(1-a)*100,M=100*a,A=null!==f&&m.length>0?m.reduce((e,t)=>Math.abs(t.topRatio-f)<Math.abs(m[e].topRatio-f)?t.index:e,0):null;return(0,r.jsxs)("div",{ref:y,onMouseDown:I,onMouseEnter:()=>h(!0),onMouseLeave:()=>{h(!1),g(null)},onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();g((e.clientY-t.top)/t.height)},style:{width:18,height:"100%",position:"relative",cursor:"default",userSelect:"none",borderLeft:"1px solid var(--border)",background:"var(--bg-panel)",overflow:"visible"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:0,right:0,top:`${E}%`,height:`${M}%`,background:"var(--bg-hover)",borderTop:"1px solid var(--border-strong)",borderBottom:"1px solid var(--border-strong)",pointerEvents:"none",zIndex:1}}),m.map(e=>{let t=lO(e.msg),n="user"===e.msg.role,i=100*e.topRatio;return(0,r.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,r.jsx)("div",{style:{width:n?6:5,height:n?6:5,borderRadius:n?2:"50%",background:t.bg,border:`1.5px solid ${t.border}`,flexShrink:0,transition:"transform 0.1s",transform:p&&A===e.index?"scale(1.6)":"scale(1)"}})},e.index)}),(0,r.jsx)("div",{style:{position:"absolute",left:"50%",top:0,bottom:0,width:1,background:"var(--border)",transform:"translateX(-50%)",zIndex:0}}),p&&m.map((e,t)=>{let n=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??[],n=t.filter(e=>"text"===e.type).map(e=>e.text).join(" ");if(n)return n.slice(0,200);let r=t.filter(e=>"toolCall"===e.type).map(e=>e.toolName);if(r.length)return r.join(", ")}return""}(e.msg),i=lO(e.msg),o=A===e.index;return n&&0!==T.length?(0,r.jsx)("div",{style:{position:"absolute",top:T[t],right:"100%",marginRight:6,background:"var(--bg)",borderTop:`1px solid ${o?i.border:"var(--border)"}`,borderRight:`1px solid ${o?i.border:"var(--border)"}`,borderBottom:`1px solid ${o?i.border:"var(--border)"}`,borderLeft:`2px solid ${i.border}`,borderRadius:4,padding:"3px 8px",width:220,zIndex:100,pointerEvents:"none",opacity:o?1:.45,transition:"top 0.1s, opacity 0.1s"},children:(0,r.jsx)("div",{style:{fontSize:11,color:o?"var(--text)":"var(--text-muted)",lineHeight:1.4,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n})},e.index):null})]})}function lq(e,t,n){return Math.max(0,e-t-n)}function lK(e,t){return t?40:Math.max(48,Math.round(.1*e))}function lJ(e,t){switch(t.kind){case"send":case"reset":case"jump-button":return"following";case"up-intent":return"released";case"scroll":if(function(e,t=1){return e<=t}(t.distance,t.bottomTolerance??1)||"down"===t.direction&&t.distance<=t.zoneSize)return"following";if("up"===t.direction&&"following"===e)return"released";return e}}function lV(e){return"following"===e}function lY({renderKey:e,scrollContainer:t,outline:n,entryIds:o,jumpTo:l,jumpingTo:s,jumpPinRef:a,railHandleRef:d,isAtLiveTail:c}){let{t:u}=(0,eU.s9)(),[p,h]=(0,i.useState)(0),[f,g]=(0,i.useState)(null),[m,x]=(0,i.useState)(null);(0,i.useRef)(o).current=o;let v=(0,i.useRef)(null),y=(0,i.useRef)([]),b=(0,i.useRef)([]),w=(0,i.useRef)(null),[k,j]=(0,i.useState)({up:!1,down:!1}),[S,C]=(0,i.useState)(()=>!!window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches);(0,i.useEffect)(()=>{if(!window.matchMedia)return;let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=()=>C(e.matches);return t(),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]);let _=(0,i.useCallback)(()=>{var e;let t,n=w.current;if(!n)return;let r=(t=Math.max(0,(e={scrollTop:n.scrollTop,viewportHeight:n.clientHeight,contentHeight:n.scrollHeight}).contentHeight-e.viewportHeight))<=1?{up:!1,down:!1}:{up:e.scrollTop>1,down:e.scrollTop<t-1};j(e=>e.up===r.up&&e.down===r.down?e:r)},[]),I=(0,i.useRef)(""),R=(0,i.useRef)(0),T=(0,i.useCallback)(()=>{let r=t.current;if(!r||null!==a.current)return;let i=r.getBoundingClientRect().top,l=i+r.clientHeight;I.current!==e&&(I.current=e,b.current=Array.from(r.querySelectorAll("[data-message-entry-id]")));let s=b.current;R.current+=1;let d=null,u=1/0,p=null,h=-1/0;for(let e of s){let t=e.getAttribute("data-message-entry-id");if(!t)continue;let n=e.getBoundingClientRect().top;n>=i&&n<=l?n<u&&(u=n,d=t):n<i&&n>h&&(h=n,p=t)}let f=function(e){let{outline:t,loadedEntryIds:n,topVisibleEntryId:r,isAtLiveTail:i,isAtScrollBottom:o=!1}=e;if(0===t.length)return null;if(o&&i)return t[t.length-1].entryId;if(0===n.length)return null;let l=new Map;n.forEach((e,t)=>{e&&!l.has(e)&&l.set(e,t)});let s=null!==r&&l.has(r)?l.get(r):0,a=null,d=null;for(let e of t){let t=l.get(e.entryId);if(void 0!==t){if(null===d&&(d=e.entryId),t>s)break;a=e.entryId}}return null!==a?a:null!==d?d:i?t[t.length-1].entryId:null}({outline:n,loadedEntryIds:o,topVisibleEntryId:d??p,isAtLiveTail:c,isAtScrollBottom:r.scrollHeight-r.scrollTop-r.clientHeight<=lK(r.clientHeight,!1)});null!==f&&x(f)},[o,c,n,e,t,a]);d.current={setActive:x,syncActive:T},(0,i.useEffect)(()=>()=>{d.current=null},[d]);let E=(0,i.useRef)(S);E.current=S;let M=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useCallback)(()=>{null!==M.current&&(cancelAnimationFrame(M.current),M.current=null),A.current=null},[]),z=(0,i.useCallback)((e,t)=>{L(),A.current=t;let n=e.scrollTop;if("auto"===function(e,t=24){return e.reducedMotion||Math.abs(e.targetTop-e.currentTop)<t?"auto":"smooth"}({reducedMotion:E.current,currentTop:n,targetTop:t})){e.scrollTop=t,A.current=null;return}let r=t-n,i=performance.now(),o=t=>{let l,s=Math.min(1,(t-i)/lX);if(e.scrollTop=n+r*((l=Math.min(1,Math.max(0,s)))<.5?4*l*l*l:1-(-2*l+2)**3/2),s<1){M.current=requestAnimationFrame(o);return}M.current=null,A.current=null};M.current=requestAnimationFrame(o)},[L]);(0,i.useEffect)(()=>L,[L]),(0,i.useEffect)(()=>{let e=t.current;if(!e)return;let n=null,r=()=>{null===n&&(n=requestAnimationFrame(()=>{n=null,T()}))};e.addEventListener("scroll",r,{passive:!0});let i=new ResizeObserver(r);return i.observe(e),e.firstElementChild&&i.observe(e.firstElementChild),T(),()=>{e.removeEventListener("scroll",r),null!==n&&cancelAnimationFrame(n),i.disconnect()}},[t,T]),(0,i.useEffect)(()=>{let e=setTimeout(T,60);return()=>clearTimeout(e)},[e,n.length,T]);let W=(0,i.useRef)(null);W.current=m;let $=(0,i.useRef)(n);$.current=n;let P=(0,i.useRef)(null),F=(0,i.useRef)(""),H=(0,i.useCallback)(()=>{var e;let t=w.current,n=$.current,r=W.current,i=null===r?-1:n.findIndex(e=>e.entryId===r),o=i>=0?y.current[i]??null:null,l=(e={hasActive:i>=0,hasItem:null!==o,clientHeight:t?.clientHeight??0,contentHeight:t?.scrollHeight??0}).hasActive?e.hasItem&&e.clientHeight>0&&e.contentHeight>0?"scroll":"retry":"skip";if("skip"===l)return;if("retry"===l){let e=`${r??""}|${i}|${n.length}`;if(F.current===e)return;F.current=e,null===P.current&&(P.current=requestAnimationFrame(()=>{P.current=null,H()}));return}if(!t||!o)return;let s=t.getBoundingClientRect(),a=o.getBoundingClientRect(),d=function(e){let{scrollTop:t,viewportHeight:n,contentHeight:r,itemTop:i,itemHeight:o}=e,l=Math.max(0,r-n);if(0===l)return 0;let s=i+o/2-n/2;return Number.isFinite(s)?Math.min(l,Math.max(0,s)):t}({scrollTop:t.scrollTop,viewportHeight:t.clientHeight,contentHeight:t.scrollHeight,itemTop:a.top-s.top+t.scrollTop,itemHeight:a.height});1>Math.abs(d-t.scrollTop)||null!==M.current&&null!==A.current&&1>Math.abs(A.current-d)||(z(t,d),_())},[z,_]);(0,i.useEffect)(()=>{H()},[m,n,p,H]),(0,i.useEffect)(()=>()=>{null!==P.current&&cancelAnimationFrame(P.current)},[]),(0,i.useEffect)(()=>{let e=w.current;if(!e)return;let t=()=>_(),n=()=>{_(),H()};e.addEventListener("scroll",t,{passive:!0});let r=new ResizeObserver(n);return r.observe(e),e.firstElementChild&&r.observe(e.firstElementChild),n(),()=>{e.removeEventListener("scroll",t),r.disconnect()}},[_,H,n.length,p]),(0,i.useEffect)(()=>{let e=v.current;if(!e)return;let t=()=>h(e.clientHeight),n=new ResizeObserver(t);return n.observe(e),t(),()=>n.disconnect()},[n.length]);let D=(0,i.useCallback)(e=>{let t=v.current,n=y.current[e],r=t?.getBoundingClientRect(),i=n?.getBoundingClientRect(),o=r&&i?i.top-r.top+i.height/2:p/2;return Math.max(8,Math.min(Math.max(8,p-180-8),o-90))},[p]),N=(0,i.useCallback)(e=>{if("ArrowDown"!==e.key&&"ArrowUp"!==e.key)return;e.preventDefault();let t=null===f?0:n.findIndex(e=>e.ordinal===f),r="ArrowDown"===e.key?Math.min(n.length-1,t+1):Math.max(0,t-1),i=n[r];i&&(g(i.ordinal),l(i.entryId))},[f,n,l]);if(0===n.length||p>0&&p<120)return null;let B=18*n.length-4,O=null===f?null:n.findIndex(e=>e.ordinal===f),U=null===m?-1:n.findIndex(e=>e.entryId===m);return(0,r.jsxs)("div",{ref:v,"data-message-nav":"true",role:"navigation","aria-label":u("nav_userMessages"),onKeyDown:N,onMouseLeave:()=>g(null),style:{width:18,height:"100%",position:"relative",userSelect:"none"},children:[(0,r.jsxs)("div",{style:{position:"absolute",top:"50%",transform:"translateY(-50%)",left:4,maxHeight:"min(320px, 100%)",display:"flex",flexDirection:"column"},children:[(0,r.jsx)("span",{"aria-hidden":"true","data-nav-scroll-hint":"up",style:{position:"absolute",top:-9,left:2,width:0,height:0,borderLeft:"4px solid transparent",borderRight:"4px solid transparent",borderBottom:"5px solid var(--border)",opacity:+!!k.up,transition:S?"none":"opacity 0.18s ease",pointerEvents:"none"}}),(0,r.jsx)("div",{ref:w,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:B>320?"flex-start":"center",gap:4,overflowY:"auto",scrollbarWidth:"none"},children:n.map((e,t)=>{let n=f===e.ordinal,i=U===t,o=s===e.entryId;return(0,r.jsx)("button",{type:"button","data-nav-index":e.ordinal,"data-nav-entry":e.entryId,ref:e=>{y.current[t]=e},"aria-label":function(e,t=120){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}(e.text)||u("nav_userMessages"),"aria-current":i?"true":void 0,disabled:o,onClick:()=>void l(e.entryId),onMouseEnter:()=>g(e.ordinal),onFocus:()=>g(e.ordinal),style:{width:24,height:14,flexShrink:0,padding:0,border:"none",background:"none",cursor:o?"progress":"pointer",display:"flex",alignItems:"center",justifyContent:"flex-start"},children:(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"block",width:n||i?24:12,height:2,borderRadius:1,background:n?"var(--text)":i?"var(--text-dim)":"var(--border)",transition:S?"none":"width 0.18s ease, background 0.18s ease"}})},e.entryId)})}),(0,r.jsx)("span",{"aria-hidden":"true","data-nav-scroll-hint":"down",style:{position:"absolute",bottom:-9,left:2,width:0,height:0,borderLeft:"4px solid transparent",borderRight:"4px solid transparent",borderTop:"5px solid var(--border)",opacity:+!!k.down,transition:S?"none":"opacity 0.18s ease",pointerEvents:"none"}})]}),null!==O&&n[O]&&(0,r.jsx)("div",{role:"tooltip","data-nav-preview":"true",style:{position:"absolute",left:"100%",top:D(O),width:340,maxWidth:340,maxHeight:180,overflow:"hidden",padding:"8px 10px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"0 6px 24px rgba(0,0,0,0.16)",color:"var(--text)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere",display:"-webkit-box",WebkitLineClamp:10,WebkitBoxOrient:"vertical",pointerEvents:"none",zIndex:60},children:n[O].text.trim()||u("nav_userMessages")})]})}let lX=420;function lG({title:e,accessibilityLabel:t,overlay:n=!1,extraHeader:o,footer:l,children:s,panelStyle:a}){let{t:d}=(0,eU.s9)(),c=t??("string"==typeof e?e:void 0),[u,p]=(0,i.useState)(!0),h=()=>p(e=>!e),f=["extension-panel-shell",n?"extension-panel-shell--overlay":"",u?"extension-panel-shell--expanded":""].filter(Boolean).join(" ");return(0,r.jsxs)("section",{role:"dialog","aria-modal":"true","aria-label":c,className:f,style:{width:I,...a},children:[(0,r.jsxs)("header",{className:"extension-panel-header",role:"button",tabIndex:0,"aria-expanded":u,"aria-label":d(u?"extension_panelCollapse":"extension_panelExpand"),title:d(u?"extension_panelCollapse":"extension_panelExpand"),onClick:h,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||e.target===e.currentTarget&&(e.preventDefault(),h())},children:[(0,r.jsx)("span",{className:`extension-panel-chevron${u?" is-expanded":""}`,"aria-hidden":"true",children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})})}),(0,r.jsx)("div",{className:"extension-panel-title",children:e}),o?(0,r.jsx)("div",{className:"extension-panel-header-actions",onClick:e=>e.stopPropagation(),children:o}):null]}),u?(0,r.jsx)("div",{className:"extension-panel-body",children:s}):null,u&&l?(0,r.jsx)("footer",{className:"extension-panel-footer",children:l}):null]})}function lZ(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.max(0,Math.ceil((e-t)/1e3)):null}let lQ={minWidth:0,width:"100%",minHeight:40,padding:"8px 12px",border:"1px solid var(--border)",borderRadius:8,outline:"none",background:"var(--bg)",color:"var(--text)",font:"inherit",fontSize:14,boxSizing:"border-box"};function l0({request:e,disabled:t=!1,onRespond:n}){let{t:o}=(0,eU.s9)(),l=(0,i.useRef)(null),[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)({requestId:e.id,value:""}),[u,p]=(0,i.useState)({requestId:e.id,value:"editor"===e.method?e.prefill??"":""}),h=u.requestId===e.id?u.value:"",f=d.requestId===e.id?d.value:"",[g,m]=(0,i.useState)(()=>Date.now()),x="number"==typeof e.expiresAt&&Number.isFinite(e.expiresAt)?e.expiresAt:null;(0,i.useEffect)(()=>{if(null===x)return;let e=null,t=()=>{null!==e&&(clearInterval(e),e=null)},n=()=>{if("u">typeof document&&"hidden"===document.visibilityState)return;let e=Date.now();m(e),e>=x&&t()};n(),e=setInterval(n,1e3);let r=()=>{("u"<typeof document||"hidden"!==document.visibilityState)&&n()};return document.addEventListener("visibilitychange",r),()=>{t(),document.removeEventListener("visibilitychange",r)}},[x,e.id]);let v=lZ(x,g),y=null!==v&&v<=0,b=s===e.id,w=t||y||b,k=e.id,j=r=>{var i;let o;t||l.current===k||(i=Date.now(),null!==(o=lZ(e.expiresAt,i))&&o<=0)||(l.current=k,a(k),n(r))},S=t=>{c({requestId:e.id,value:t})},C="select"===e.method?e.options:[],_=!b&&null!==v&&v>0?o("extension_expiresIn",{seconds:String(v)}):null,I=y?o("extension_expired"):b?o("extension_responseSent"):t&&null===_?o("extension_waitingEnded"):null,R=(0,r.jsx)("button",{type:"button",className:"extension-card-btn",disabled:w,title:o("extension_cancel"),"aria-label":o("extension_cancel"),onClick:()=>j({cancelled:!0}),children:o("extension_cancel")}),T="confirm"===e.method?(0,r.jsxs)(r.Fragment,{children:[R,(0,r.jsx)("button",{type:"button",className:"extension-card-btn extension-card-btn--primary",disabled:w,title:o("extension_confirm"),"aria-label":o("extension_confirm"),onClick:()=>j({confirmed:!0}),children:o("extension_confirm")})]}):"input"===e.method||"editor"===e.method?(0,r.jsxs)(r.Fragment,{children:[R,(0,r.jsx)("button",{type:"button",className:"extension-card-btn extension-card-btn--primary",disabled:w,title:o("extension_submit"),"aria-label":o("extension_submit"),onClick:()=>j({value:"editor"===e.method?h:f}),children:o("extension_submit")}),"editor"===e.method?(0,r.jsx)("span",{className:"extension-panel-hint",children:o("extension_ctrlEnterHint")}):null]}):R;return(0,r.jsx)("div",{className:"extension-panel-inline",children:(0,r.jsxs)(lG,{title:(0,r.jsx)(iu,{className:"markdown-body--extension",children:e.title}),accessibilityLabel:e.title,footer:(0,r.jsxs)(r.Fragment,{children:[T,_?(0,r.jsx)("span",{className:"extension-panel-hint","aria-live":"off",suppressHydrationWarning:!0,children:_}):null,I?(0,r.jsx)("span",{className:"extension-panel-status",role:"status","aria-live":"polite",children:I}):null]}),children:["confirm"===e.method&&(0,r.jsx)("div",{className:"extension-panel-copy",children:(0,r.jsx)(iu,{className:"markdown-body--extension",children:e.message})}),"input"===e.method&&(0,r.jsx)("input",{value:f,disabled:w,placeholder:e.placeholder,"aria-label":e.title,autoComplete:"off",autoFocus:!0,onChange:e=>S(e.target.value),onKeyDown:e=>{if(!e.nativeEvent.isComposing){if("Enter"===e.key){e.preventDefault(),j({value:f});return}"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),f.length>0?S(""):e.currentTarget.blur())}},style:lQ}),"editor"===e.method&&(0,r.jsx)("textarea",{value:h,disabled:w,placeholder:e.prefill??"","aria-label":e.title,autoComplete:"off",autoFocus:!0,onChange:t=>p({requestId:e.id,value:t.target.value}),onKeyDown:e=>{e.nativeEvent.isComposing||((e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),j({value:h})),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),j({cancelled:!0})))},className:"extension-panel-editor"}),"select"===e.method&&(0,r.jsx)("div",{role:"group","aria-label":o("extension_selectAnOption"),className:"extension-option-list",children:C.map((e,t)=>(0,r.jsx)("button",{type:"button",className:"extension-option-btn",disabled:w,title:e,onClick:()=>j({value:e}),children:e},`${t}-${e}`))})]})})}let l1={center:{alignItems:"center",justifyContent:"center"},"top-left":{alignItems:"flex-start",justifyContent:"flex-start"},"top-center":{alignItems:"flex-start",justifyContent:"center"},"top-right":{alignItems:"flex-start",justifyContent:"flex-end"},"bottom-left":{alignItems:"flex-end",justifyContent:"flex-start"},"bottom-center":{alignItems:"flex-end",justifyContent:"center"},"bottom-right":{alignItems:"flex-end",justifyContent:"flex-end"},"left-center":{alignItems:"center",justifyContent:"flex-start"},"right-center":{alignItems:"center",justifyContent:"flex-end"}};function l2(e,t){return nG(e).map((e,n)=>e.style?(0,r.jsx)("span",{style:e.style,children:e.text},`${t}-${n}`):e.text)}function l4({request:e,onInput:t,onMouse:n,onBounds:o}){let{t:l}=(0,eU.s9)(),s=(0,i.useRef)(null),a=(0,i.useRef)(null),d=(0,i.useRef)(!1),[c,u]=(0,i.useState)(!1),p=(0,i.useRef)(null),h=(0,i.useRef)(null),f=(0,i.useRef)(e);f.current=e;let g=nP(e.images,e.imageFallbacks),m=nX(e.lines,{keep:g}),x=m.lines,v=nF(e.images,m.sourceIndex).items,y=nF(e.imageFallbacks,m.sourceIndex).items,b=x.map(e=>nK(e)).join("\n"),w=function(e){if(!e)return;let t=function(e){if(void 0===e)return;let t="number"==typeof e?{top:e,right:e,bottom:e,left:e}:e;if(void 0===t.top&&void 0===t.right&&void 0===t.bottom&&void 0===t.left)return;let n=e=>`${e??0}em`,r=e=>`${e??0}ch`;return`max(${n(t.top)}, env(safe-area-inset-top, 0px)) max(${r(t.right)}, env(safe-area-inset-right, 0px)) max(${n(t.bottom)}, env(safe-area-inset-bottom, 0px)) max(${r(t.left)}, env(safe-area-inset-left, 0px))`}(e.margin);return{containerStyle:{...l1[e.anchor]??l1.center,...t?{padding:t}:{}},panelStyle:{width:function(e){let t=function(e){if(void 0!==e)return"number"==typeof e?`${e}ch`:e}(e);if(void 0!==t)return t.endsWith("%")?t:`min(${t}, 100%)`}(e.width)??I,minWidth:void 0===e.minWidth?void 0:`min(${e.minWidth}ch, 100%)`,maxHeight:function(e){if(void 0===e)return;let t="number"==typeof e?`${1.5*e}em`:e;return t.endsWith("%")?t:`min(${t}, 100%)`}(e.maxHeight)}}}(e.layout);(0,i.useEffect)(()=>{if(e.hidden)return;let t=s.current;t&&(void 0===e.focus||"panel"===e.focus?t.focus():t.blur())},[e.focus,e.hidden,e.id]),(0,i.useEffect)(()=>{if(e.hidden||!o)return;let t=()=>{var t;let n=a.current,r=n?.closest('[data-chat-scroller="true"]')??null,i=n?function(e){let{bodyRect:t,containerRect:n,charWidth:r,lineHeight:i}=e,o=e=>"number"==typeof e&&Number.isFinite(e)&&e>0?e:null,l=o(r),s=o(i);return null!==l&&null!==s&&Number.isFinite(t.width)&&Number.isFinite(t.height)&&Number.isFinite(t.left)&&Number.isFinite(t.top)&&Number.isFinite(n.left)&&Number.isFinite(n.top)&&!(t.width<=0)&&!(t.height<=0)?{row:Math.floor((t.top-n.top)/s),col:Math.floor((t.left-n.left)/l),width:Math.max(1,Math.floor(t.width/l)),height:Math.max(1,Math.floor(t.height/s))}:null}({bodyRect:n.getBoundingClientRect(),containerRect:(r??document.documentElement).getBoundingClientRect(),charWidth:n2(n),lineHeight:n4(n)}):null,l="visible"===document.visibilityState,s={previous:h.current,next:e.id};t=p.current,l&&null!==i&&(s&&s.previous!==s.next||null===t||t.row!==i.row||t.col!==i.col||t.width!==i.width||t.height!==i.height)&&(p.current=i,h.current=e.id,i&&o(f.current,i))};t();let n="u"<typeof ResizeObserver?null:new ResizeObserver(t);return n&&a.current&&n.observe(a.current),window.addEventListener("resize",t),window.addEventListener("scroll",t,!0),document.addEventListener("visibilitychange",t),()=>{n?.disconnect(),window.removeEventListener("resize",t),window.removeEventListener("scroll",t,!0),document.removeEventListener("visibilitychange",t)}},[o,e.hidden,e.id]);let k=async()=>{try{await navigator.clipboard.writeText(b),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return e.hidden?null:(0,r.jsx)("div",{className:"extension-panel-overlay",style:w?.containerStyle,children:(0,r.jsxs)(lG,{overlay:!0,panelStyle:w?.panelStyle,title:l("chat_extensionPanel"),footer:(0,r.jsx)("button",{type:"button",className:"extension-card-btn",title:l("extension_cancel"),"aria-label":l("extension_cancel"),onClick:()=>t(e,"\x03"),children:l("extension_cancel")}),extraHeader:(0,r.jsx)("button",{type:"button",className:"extension-card-btn",onClick:()=>{k()},"aria-label":c?l("extension_copied"):l("extension_copy"),children:c?l("extension_copied"):l("extension_copy")}),children:[(0,r.jsx)("textarea",{ref:s,"aria-label":l("chat_extensionPanel"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(d.current||n.nativeEvent.isComposing||!lo(n,window.getSelection()?.toString()??""))return;let r=lx(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(d.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{d.current=!0},onCompositionEnd:n=>{d.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,lv(r))},className:"extension-panel-keytrap"}),(0,r.jsx)("pre",{ref:a,className:"extension-panel-ansi",onClick:t=>{let r=function(e){let t=e.currentTarget,n=t.getBoundingClientRect(),r=window.getComputedStyle(t),i=Number.parseFloat(r.fontSize)||12,o=Number.parseFloat(r.lineHeight)||1.5*i,l=n2(t);if(null===l)return null;let s=Math.max(0,Math.floor((e.clientX-n.left+t.scrollLeft)/l)),a=Math.max(0,Math.floor((e.clientY-n.top+t.scrollTop)/o));return{type:"click",button:0===e.button?"left":1===e.button?"middle":"right",x:s,y:a,screenX:s,screenY:a,width:Math.max(1,Math.floor(n.width/l)),height:Math.max(1,Math.floor(n.height/o)),shift:e.shiftKey,alt:e.altKey,ctrl:e.ctrlKey,clickCount:e.detail}}(t);r&&n?.(e,r)},children:(0,r.jsx)(n8,{lines:x.length?x:[""],images:v,imageFallbacks:y,keyPrefix:"panel-line",renderLine:l2,imageAlt:l("message_imageAlt"),fallbackLabel:e=>{let t=nH(e);return l("message_imageUnavailable",{reason:t?l(t):e})}})})]})})}let l6="PI_SUBAGENT_ASYNC_JSON:",l5=/\u001b\[[0-9;?]*[A-Za-z]/g,l8=/[↓↑←→].*(?:inspect|查看|导航|选择|navigate|select)/i,l3=new Set(["queued","running","complete","failed","partial","paused","stopped","rejected"]);function l9(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function l7(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function se(e){return"string"==typeof e&&e?e:void 0}function st(e,t={}){let n=t.now??Date.now(),r=Math.max(1,Math.floor(t.maxRows??8)),i=e=>"running"===e?0:"queued"===e?1:2,o=[...e.runs].sort((e,t)=>i(e.state)-i(t.state)),l=[],s=e.omittedRuns,a=0,d=(e,t)=>({id:e.id,label:e.label,state:e.state,depth:t,elapsedMs:void 0===e.startedAt?null:Math.max(0,(e.endedAt??e.updatedAt??n)-e.startedAt),tool:"running"===e.state?e.activity?.currentTool??null:null,toolMs:"running"===e.state&&e.activity?.currentToolStartedAt!==void 0&&e.activity?.lastActivityAt!==void 0?Math.max(0,e.activity.lastActivityAt-e.activity.currentToolStartedAt):null,turns:e.activity?.turnCount??null,tools:e.activity?.toolCount??null});for(let e of o){if(a>=r){s+=1;continue}for(let t of(a+=1,l.push(d(e,0)),e.children??[])){if(l.length>=3*r){s+=1;break}l.push(d(t,1))}}return{rows:l,running:e.runs.filter(e=>"running"===e.state).length,queued:e.runs.filter(e=>"queued"===e.state).length,total:e.runs.length+e.omittedRuns,hidden:s,byteLimitExceeded:e.byteLimitExceeded}}function sn(e){if(null===e)return null;if(e<1e3)return`${Math.max(0,Math.round(e))}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m${String(t%60).padStart(2,"0")}s`:`${Math.floor(n/60)}h${String(n%60).padStart(2,"0")}m`}function sr({snapshot:e}){let{t}=(0,eU.s9)(),n=(0,i.useMemo)(()=>st(e),[e]);return 1===e.runs.length&&e.runs[0],n.running>0||n.queued,(0,r.jsx)("div",{style:{padding:"7px 9px",display:"flex",flexDirection:"column",gap:3},children:n.rows.map(e=>{let{glyph:n,color:i}=function(e){switch(e){case"running":return{glyph:"●",color:"var(--accent)"};case"queued":return{glyph:"◦",color:"var(--text-muted)"};case"complete":return{glyph:"✓",color:"var(--status-success)"};case"paused":case"stopped":return{glyph:"■",color:"var(--status-warning, var(--text-muted))"};default:return{glyph:"✗",color:"var(--status-danger)"}}}(e.state),o=sn(e.elapsedMs),l=(e=>{let n=[];if(e.tool){let t=sn(e.toolMs);n.push(t?`${e.tool} ${t}`:e.tool)}return null!==e.turns&&e.turns>0&&n.push(t("subagent_widgetTurns",{count:e.turns})),null!==e.tools&&e.tools>0&&n.push(t("subagent_widgetTools",{count:e.tools})),n})(e);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:5,paddingLeft:14*e.depth,fontSize:11.5,lineHeight:1.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{color:i,flexShrink:0},children:n}),(0,r.jsx)("span",{style:{color:"var(--text)",flexShrink:0},children:e.label}),(0,r.jsx)("span",{style:{color:i,flexShrink:0},children:t(function(e){switch(e){case"running":return"subagent_state_running";case"queued":return"subagent_state_queued";case"complete":return"subagent_state_complete";case"failed":return"subagent_state_failed";case"partial":return"subagent_state_partial";case"paused":return"subagent_state_paused";case"stopped":return"subagent_state_stopped";default:return"subagent_state_rejected"}}(e.state))}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",flexShrink:0},children:o}),l.length>0&&(0,r.jsxs)("span",{style:{color:"var(--text-dim)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["⎿ ",l.join(" \xb7 ")]})]},`${e.id}:${e.depth}`)})})}var si=n(38798);function so({projectRoots:e,targetCwd:t,onTargetChange:n}){let{t:o}=(0,eU.s9)(),l=(0,i.useMemo)(()=>!t||e.includes(t)?[...e]:[t,...e],[e,t]);return(0,r.jsx)("div",{className:"guide-selectors",children:(0,r.jsxs)("div",{className:"guide-selector",children:[(0,r.jsx)(si.A,{size:12,className:"guide-selector-icon","aria-hidden":!0}),(0,r.jsxs)("select",{className:"guide-select",value:t??"",disabled:0===l.length,onChange:e=>{let t=e.target.value;t&&n(t)},"aria-label":o("guide_projectTitle"),children:[(0,r.jsx)("option",{value:"",disabled:!0,children:o(0===l.length?"guide_noProjects":"guide_projectPlaceholder")}),l.map(e=>(0,r.jsx)("option",{value:e,title:e,children:d(e)},e))]})]})})}let sl={pending:"todo_pending",in_progress:"todo_inProgress",completed:"todo_completed"},ss={high:"todo_high",medium:"todo_medium",low:"todo_low"},sa={high:"var(--status-danger)",medium:"var(--status-warning)",low:"var(--text-dim)"};function sd({status:e}){return(0,r.jsx)("span",{className:"in_progress"===e?"animate-[pulse_1.5s_ease-in-out_infinite]":void 0,style:{display:"inline-flex",flex:"0 0 14px",color:"completed"===e?"var(--status-success)":"in_progress"===e?"var(--accent)":"var(--text-dim)"},"aria-hidden":"true",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),"completed"===e?(0,r.jsx)("polyline",{points:"8.5 12.5 11 15 15.8 9.6"}):"in_progress"===e?(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5",fill:"currentColor",stroke:"none"}):null]})})}function sc({todos:e,collapsed:t,onToggle:n}){let{t:o}=(0,eU.s9)(),l=(0,i.useId)();if(0===e.length)return null;let s=e.reduce((e,t)=>e+ +("completed"===t.status),0),a=e.find(e=>"in_progress"===e.status)??null,d=e.reduce((e,t)=>e+ +("in_progress"===t.status),0),c=Math.round(s/e.length*100),u=s===e.length;return(0,r.jsxs)("section",{"aria-label":o("todo_toggle"),style:{marginBottom:8,overflow:"hidden",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)"},children:[(0,r.jsxs)("button",{type:"button","aria-controls":l,"aria-expanded":!t,title:t?o("todo_expand"):o("todo_collapse"),onClick:n,style:{display:"flex",width:"100%",minHeight:32,alignItems:"center",gap:8,padding:"5px 9px",border:0,background:"transparent",color:"var(--text-muted)",cursor:"pointer",font:"inherit",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:t?"none":"rotate(90deg)",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:650,letterSpacing:.45,textTransform:"uppercase"},children:o("todo_toggle")}),(0,r.jsxs)("span",{style:{flexShrink:0,color:u?"var(--status-success)":"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:10},children:[s,"/",e.length]}),(0,r.jsx)("span",{role:"progressbar","aria-label":o("todo_complete"),"aria-valuemin":0,"aria-valuemax":e.length,"aria-valuenow":s,title:`${c}% ${o("todo_complete")}`,style:{width:46,height:3,flexShrink:0,overflow:"hidden",borderRadius:999,background:"color-mix(in srgb, var(--border) 78%, transparent)"},children:(0,r.jsx)("span",{style:{display:"block",width:`${c}%`,height:"100%",borderRadius:"inherit",background:u?"var(--status-success)":"var(--accent)",transition:"width 0.2s ease"}})}),a?(0,r.jsxs)("span",{className:"hidden min-[520px]:flex",style:{minWidth:0,alignItems:"center",gap:5,color:"var(--text-muted)",fontSize:11},children:[(0,r.jsx)("span",{className:"animate-[pulse_1.5s_ease-in-out_infinite]","aria-hidden":"true",style:{width:5,height:5,flexShrink:0,borderRadius:"50%",background:"var(--accent)"}}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:10},children:d>1?`${d} ${o("todo_active")}`:o("todo_active")}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a.activeForm??a.content})]}):(0,r.jsx)("span",{style:{flex:1}})]}),!t&&(0,r.jsx)("ul",{id:l,style:{maxHeight:224,margin:0,padding:"3px 0 5px",overflowY:"auto",borderTop:"1px solid var(--border)",listStyle:"none"},children:e.map(e=>{let t="completed"===e.status;return(0,r.jsxs)("li",{style:{display:"flex",alignItems:"flex-start",gap:8,padding:"4px 10px",color:t?"var(--text-dim)":"var(--text)",fontSize:12,lineHeight:1.45,opacity:t?.78:1},children:[(0,r.jsx)("span",{style:{paddingTop:2},children:(0,r.jsx)(sd,{status:e.status})}),(0,r.jsxs)("span",{className:"sr-only",children:[o(sl[e.status]),": "]}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflowWrap:"anywhere",textDecoration:t?"line-through":"none",textDecorationColor:"color-mix(in srgb, var(--text-dim) 60%, transparent)"},children:e.content}),e.blockedBy&&e.blockedBy.length>0?(0,r.jsx)("span",{style:{display:"block",marginTop:1,color:"var(--text-dim)",fontSize:10},children:o("todo_blockedBy",{list:e.blockedBy.join(", ")})}):null]}),e.priority?(0,r.jsx)("span",{title:`${o(ss[e.priority])} ${o("todo_priority")}`,style:{flexShrink:0,paddingTop:1,color:sa[e.priority],fontFamily:"var(--font-mono)",fontSize:9,fontWeight:"high"===e.priority?700:550,letterSpacing:.35,textTransform:"uppercase"},children:o(ss[e.priority])}):null]},e.id)})})]})}let su="pidance:capability-notices-seen.v1";function sp(e){if("string"!=typeof e)return null;let t=/Extension UI "([^"]{1,80})"/.exec(e);return t?.[1]?.trim()||null}function sh(e){if(!e)return new Set;try{let t=e.getItem(su);if(!t)return new Set;let n=JSON.parse(t);if(!Array.isArray(n))return new Set;return new Set(n.filter(e=>"string"==typeof e&&e.length>0))}catch{return new Set}}function sf(){try{return window.localStorage}catch{return null}}function sg(e){return!!e&&sh(sf()).has(e)}function sm(e){e&&function(e,t){if(e&&t)try{let n=sh(e);if(n.has(t))return;n.add(t);let r=[...n].slice(-64);e.setItem(su,JSON.stringify(r))}catch{}}(sf(),e)}let sx=["ctrl","alt","shift","super"];[...ll];let sv=/^f([1-9]|1[0-2])$/;function sy(e){if("string"!=typeof e)return null;let t=e.toLowerCase().split("+").map(e=>e.trim()).filter(e=>e.length>0);if(0===t.length)return null;let n=t[t.length-1];if(!n||sx.includes(n))return null;let r=t.slice(0,-1);return r.some(e=>!sx.includes(e))?null:[...sx.filter(e=>r.includes(e)),n].join("+")}let sb={escape:"escape",esc:"escape",enter:"enter",tab:"tab"," ":"space",spacebar:"space",backspace:"backspace",delete:"delete",del:"delete",insert:"insert",home:"home",end:"end",pageup:"pageup",pagedown:"pagedown",arrowup:"up",arrowdown:"down",arrowleft:"left",arrowright:"right",clear:"clear"},sw={"!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0"};function sk(e){let t=sy(e);return t?t.split("+").map(e=>1===e.length?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)).join("+"):e}function sj(e){if(!e.sessionId)return{kind:"no-session"};if(e.failed)return{kind:"failed"};let t=e.payload?.state;return t?{kind:"ready",entries:Array.isArray(t.extensionShortcuts)?t.extensionShortcuts:[],diagnostics:Array.isArray(t.extensionShortcutDiagnostics)?t.extensionShortcutDiagnostics:[]}:{kind:"no-state"}}let sS={base:"Pidance",sessionKey:null,override:null},sC=new Set;function s_(e){if(e!==sS)for(let t of(sS=e,sC))t()}function sI(e){return e.isNew?e.intentId?{kind:"new",intentId:e.intentId}:null:e.persistedSessionId?{kind:"persisted",sessionId:e.persistedSessionId}:null}var sR=n(99838);function sT(e,t){if(!t||"object"!=typeof e||null===e||Array.isArray(e))return null;let n=e.sessionQueue,r=("object"!=typeof n||null===n||Array.isArray(n)?void 0:n[t])??e[`sessionQueue.${t}`];if(null==r)return null;let i=Array.isArray(r);if(!i&&!Array.isArray(r.items))return null;let o=(0,sR.jG)(r);return{items:o.items,revision:i?null:o.revision}}function sE(e){return"select"===e||"confirm"===e||"input"===e||"editor"===e}function sM(e){return e.blockingQueue??[]}function sA(e){let t=e[0];return t?{dialog:t}:{dialog:null}}function sL(e,t){let n=sA(t);return{...e,blockingQueue:t,dialog:n.dialog}}function sz(e,t){let n=sM(e);return 0===n.length?e.dialog?.id===t?{...e,dialog:null,blockingQueue:[]}:e:-1===n.findIndex(e=>e.id===t)?e:sL(e,n.filter(e=>e.id!==t))}function sW(e,t){return null===e||null===t?e===t:e.length===t.length&&e.every((e,n)=>e===t[n])}function s$(e,t){switch(t.method){case"select":case"confirm":case"input":case"editor":{if(!sE(t.method))return{state:e,effects:[]};let n=sM(e);if(n.some(e=>e.id===t.id))return{state:e,effects:[]};return{state:sL(e,[...n,t]),effects:[]}}case"editorComponent":{if(t.closed)return null===e.editorTakeover?{state:e,effects:[]}:{state:{...e,editorTakeover:null},effects:[]};if(!Array.isArray(t.lines))return{state:e,effects:[]};let n=e.editorTakeover?.id===t.id?e.editorTakeover:null,r=Array.isArray(t.images)?t.images.length>0?t.images:void 0:n?.images,i=Array.isArray(t.imageFallbacks)?t.imageFallbacks.length>0?t.imageFallbacks:void 0:n?.imageFallbacks,o={type:"extension_ui_request",id:t.id,method:"editorComponent",lines:t.lines,...r?{images:r}:{},...i?{imageFallbacks:i}:{}};if(n&&function(e,t){if(null===e||null===t)return e===t;if(e.id!==t.id||!sW(e.lines??null,t.lines??null))return!1;let n=e=>Array.isArray(e)?e.length:0;return n(e.images)===n(t.images)&&n(e.imageFallbacks)===n(t.imageFallbacks)&&JSON.stringify(e.images??null)===JSON.stringify(t.images??null)&&JSON.stringify(e.imageFallbacks??null)===JSON.stringify(t.imageFallbacks??null)}(n,o))return{state:e,effects:[]};return{state:{...e,editorTakeover:o},effects:[]}}case"editorComponentSubmit":return{state:e,effects:[{type:"editorSubmit",text:t.text,..."string"==typeof t.clientId&&t.clientId?{clientId:t.clientId}:{}}]};case"notify":return{state:e,effects:[{type:"notice",id:t.id,message:t.message,noticeType:t.notifyType??"info",activityRecord:!0===t.activityRecord}]};case"setStatus":{let n=e.statuses.findIndex(e=>e.key===t.statusKey);if(!t.statusText){if(-1===n)return{state:e,effects:[]};return{state:{...e,statuses:e.statuses.filter(e=>e.key!==t.statusKey)},effects:[]}}let r={key:t.statusKey,text:t.statusText};if(-1!==n&&e.statuses[n].text===r.text)return{state:e,effects:[]};let i=[...e.statuses.filter(e=>e.key!==t.statusKey),r];return{state:{...e,statuses:i},effects:[]}}case"setWidget":{let n=e.widgets.findIndex(e=>e.key===t.widgetKey);if(!t.widgetLines){if(-1===n)return{state:e,effects:[]};return{state:{...e,widgets:e.widgets.filter(e=>e.key!==t.widgetKey)},effects:[]}}let r=-1===n?void 0:e.widgets[n]?.images,i=-1===n?void 0:e.widgets[n]?.imageFallbacks,o=Array.isArray(t.widgetImages)?t.widgetImages.length>0?t.widgetImages:void 0:r,l=Array.isArray(t.widgetImageFallbacks)?t.widgetImageFallbacks.length>0?t.widgetImageFallbacks:void 0:i,s={key:t.widgetKey,lines:t.widgetLines,...o?{images:o}:{},...l?{imageFallbacks:l}:{},placement:t.widgetPlacement??"aboveEditor",interactive:!0===t.widgetInteractive},a=-1===n?null:e.widgets[n];if(a&&a.placement===s.placement&&a.lines===s.lines&&a.images===s.images&&a.imageFallbacks===s.imageFallbacks&&a.interactive===s.interactive)return{state:e,effects:[]};let d=[...e.widgets.filter(e=>e.key!==t.widgetKey),s];return{state:{...e,widgets:d},effects:[]}}case"setHeader":case"setFooter":{let n="setHeader"===t.method?"header":"footer",r=Array.isArray(t.lines)&&t.lines.length>0?t.lines:null;if(sW(e[n],r))return{state:e,effects:[]};return{state:{...e,[n]:r},effects:[]}}case"setTitle":return t.title?{state:e,effects:[{type:"setTitle",title:t.title}]}:{state:e,effects:[]};case"terminalInputListeners":return{state:{...e,terminalInputListenerCount:t.count},effects:[]};case"autocompleteProviders":return{state:{...e,autocompleteProviderCount:t.count,autocompleteTriggerCharacters:Array.isArray(t.triggerCharacters)?t.triggerCharacters.filter(e=>"string"==typeof e&&""!==e):[]},effects:[]};case"setHiddenThinkingLabel":return e.hiddenThinkingLabel===t.label?{state:e,effects:[]}:{state:{...e,hiddenThinkingLabel:t.label},effects:[]};case"setWorkingMessage":return e.workingMessage===t.message?{state:e,effects:[]}:{state:{...e,workingMessage:t.message},effects:[]};case"setToolsExpanded":return{state:{...e,toolsExpanded:t.toolsExpanded,toolsExpandedRevision:e.toolsExpandedRevision+1},effects:[]};case"setTheme":return{state:e,effects:[{type:"setThemeMode",mode:"light"===t.mode?"light":"dark"}]};case"setWorkingVisible":return e.workingVisible===t.visible?{state:e,effects:[]}:{state:{...e,workingVisible:t.visible},effects:[]};case"setWorkingIndicator":{if(null===t.frames)return null===e.workingIndicator?{state:e,effects:[]}:{state:{...e,workingIndicator:null},effects:[]};let n=t.intervalMs??120;return{state:{...e,workingIndicator:{frames:t.frames,intervalMs:n}},effects:[]}}case"set_editor_text":return{state:e,effects:[{type:"setEditorText",text:t.text,appliedToTakeover:!0===t.appliedToTakeover,..."string"==typeof t.clientId&&t.clientId?{clientId:t.clientId}:{}}]};case"custom":if(t.closed)return t.id===e.customUi?.id?{state:{...e,customUi:null},effects:[]}:{state:e,effects:[]};{let n=Array.isArray(t.lines)?t.lines.filter(e=>"string"==typeof e):[],r="editor"===t.focus&&e.customUi?.focus!=="editor"?[{type:"focusEditor"}]:[],i=e.customUi,o=Array.isArray(t.images)?t.images:i?.images??[],l=Array.isArray(t.imageFallbacks)?t.imageFallbacks:i?.imageFallbacks??[];return{state:{...e,customUi:{...t,lines:n,images:o.length>0?o:void 0,imageFallbacks:l.length>0?l:void 0}},effects:r}}default:return{state:e,effects:[]}}}function sP(e){let t=e.findIndex(e=>"transient"===e.tier&&!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function sF(e,t){switch(t.type){case"add":{if("important"===t.notice.tier)return{...e,visible:[...e.visible,t.notice]};let n=e.visible.filter(e=>"transient"===e.tier).length,r=e.visible.some(e=>"transient"===e.tier&&e.exiting);if(r||n>=5)return{visible:r?e.visible:sP(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]}}case"dismiss":return{...e,visible:e.visible.map(e=>e.id===t.id?{...e,exiting:!0}:e),pending:e.pending.filter(e=>e.id!==t.id)};case"toggle_pin":return{...e,visible:e.visible.map(e=>e.id===t.id&&"important"===e.tier?{...e,pinned:!e.pinned}:e)};case"mark_oldest_transient_exiting":return{...e,visible:sP(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.filter(e=>"transient"===e.tier).length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=sP(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}let sH=null,sD=["pending","in_progress","completed"],sN=["high","medium","low"],sB=["pending","in_progress","completed","deleted"];function sO(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function sU(e,t){let{cancelled:n,newSessionId:r}=e??{};return n||!r?{kind:"noop"}:{kind:"switch-session",sessionId:r,...t?{prefill:t}:{}}}function sq(e,t,n){if(e.noop)return!1;let r=e.editorText;return"string"==typeof r&&("replace"===n?t?.replaceText(r):""!==r&&t?.insertIfEmpty(r)),!0}let sK=new Set(["ArrowUp","PageUp","Home"]);function sJ(e,t){if(!(e instanceof Element))return!1;let n=e;for(;n&&n!==t;){if(n instanceof HTMLElement){var r;let e=getComputedStyle(n).overflowY;if(("auto"===e||"scroll"===e)&&(r={scrollTop:n.scrollTop,scrollHeight:n.scrollHeight,clientHeight:n.clientHeight}).scrollHeight-r.clientHeight>1&&r.scrollTop>0)return!0}n=n.parentElement}return!1}var sV=n(37494);function sY(e,t){return e&&t?e.provider===t.provider&&e.modelId===t.modelId:!e&&!t}class sX extends Error{constructor(e,t){super("timeout"===t.kind?`加载超时(已尝试 ${e} 次)`:`加载失败(已尝试 ${e} 次)`),this.attempts=e,this.failure=t,this.name="LoadFailedError"}}function sG(){let e=Error("Aborted");return e.name="AbortError",e}async function sZ(e){let t=e.fetchImpl??fetch,n=Math.max(1,e.maxRetries+1),r={kind:"network"};for(let o=1;o<=n;o+=1){if(e.signal.aborted)throw sG();let l=function(e,t){let n=new AbortController,r=!1,i=()=>n.abort();e.aborted?n.abort():e.addEventListener("abort",i,{once:!0});let o=setTimeout(()=>{r=!0,n.abort()},t);return{signal:n.signal,timedOut:()=>r,cleanup:()=>{clearTimeout(o),e.removeEventListener("abort",i)}}}(e.signal,e.timeoutMs);try{var i;let n=await t(e.url,{signal:l.signal});if(n.ok||404===n.status||!((i=n.status)>=500||408===i||429===i))return n;r={kind:"http",status:n.status,detail:`HTTP ${n.status}`}}catch(t){if(e.signal.aborted)throw sG();r=l.timedOut()?{kind:"timeout",detail:`超时 ${e.timeoutMs}ms`}:t instanceof Error&&"AbortError"===t.name?{kind:"network",detail:t.message}:{kind:"network",detail:t instanceof Error?t.message:String(t)}}finally{l.cleanup()}if(e.onAttemptFailed?.(r,o),o<n&&(await function(e,t){return new Promise(n=>{t?t(n,e):setTimeout(n,e)})}(e.retryDelayMs*o,e.schedule),e.signal.aborted))throw sG()}throw new sX(n,r)}let sQ=["off","minimal","low","medium","high","xhigh","max"],s0=["off","streaming","idle"];function s1(e){return"string"==typeof e&&sQ.includes(e)}let s2=["cmd","path","pattern","query","file","name"];function s4(e){return"string"==typeof e&&e.length>0?e:null}function s6(e){return"string"==typeof e&&e.length>0?e:void 0}function s5(e){if(Array.isArray(e)&&0!==e.length&&e.every(e=>"string"==typeof e))return[...e]}function s8(e){if(null==e)return"";if("string"==typeof e)return e.replace(/\r/g,"");if("object"==typeof e){if(Array.isArray(e.content)){let t=[];for(let n of e.content){if("string"==typeof n){t.push(n.replace(/\r/g,""));continue}"object"==typeof n&&null!==n&&"text"===n.type&&"string"==typeof n.text&&t.push(n.text.replace(/\r/g,""))}if(t.length>0||0===e.content.length)return t.join("\n")}if("string"==typeof e.text)return e.text.replace(/\r/g,"")}try{let t=JSON.stringify(e);return void 0===t?String(e):t}catch{return String(e)}}function s3(e){return e.length<=65536?{text:e,truncated:!1}:{text:e.slice(0,65536),truncated:!0}}function s9(e){if("object"!=typeof e||null===e)return;let t=e.command;if("string"==typeof t)return t;if("object"==typeof t&&null!==t){let e="string"==typeof t.command?t.command:t.cmd;if("string"==typeof e)return e}for(let t of s2){let n=e[t];if("string"==typeof n&&n.length>0)return n}}function s7(e,t){if("object"!=typeof t||null===t)return e;let n=s4(t.toolCallId);if(!n)return e;let r=e.get(n),i=s6(t.toolName)??r?.toolName??"",o=s9(t.args)??r?.command,l=s5(t.renderedCallLines)??r?.renderedCallLines,s=s6(t.toolLabel)??r?.toolLabel,a=("self"===t.toolShell?"self":void 0)??r?.toolShell;if(r?.status==="running")return i===r.toolName&&o===r.command&&l===r.renderedCallLines&&s===r.toolLabel&&a===r.toolShell?e:new Map(e).set(n,{...r,toolName:i,command:o,renderedCallLines:l,toolLabel:s,toolShell:a});let d={toolCallId:n,toolName:i,command:o,renderedCallLines:l,toolLabel:s,toolShell:a,output:"",startedAt:Date.now(),status:"running"};return new Map(e).set(n,d)}function ae(e){return Array.from(e.values())}function at(e){return{id:e.id,text:e.text,...e.media?.length?{media:e.media.map(e=>({...e}))}:{}}}function an(e,t){return t?.error!==void 0?t.definitiveRejection?.(t.error)?"rejected":"unknown":e&&"object"==typeof e?!0===e.conflict?"conflict":!0===e.ok?"accepted":"boolean"==typeof e.ok?"rejected":"unknown":"unknown"}function ar(e){return"string"==typeof e?{text:e}:e}let ai={items:[],inFlight:[],pending:[],revision:0,serverRevision:null,admittedAttemptIds:[]};function ao(){let e=globalThis.crypto;return e&&"function"==typeof e.randomUUID?e.randomUUID():`att-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function al(e,t){return e[t]??ai}function as(e){return e.pending.length?e.pending[e.pending.length-1]:null}function aa(e){let t=as(e);return t?t.payloads.map(e=>e.text):e.items.filter(e=>"claimed"!==e.state).map(e=>e.text)}function ad(e){let t=e=>e?.length?e.filter(e=>"original"===e.role).length||e.length:0;if(e.pending.length){let n=e.pending[e.pending.length-1];return n.payloads.map((e,r)=>({id:`pending-${r}`,text:e.text,state:"uncertain"===n.state?"unknown":"waiting",imageCount:t(e.media)}))}return[...e.items.map(e=>({id:e.id,text:e.text,state:e.state,imageCount:t(e.media)})),...e.inFlight.map((e,t)=>({id:`inflight-${t}`,text:e,state:"claimed",imageCount:0}))]}function ac(e,t,n){return{...e,[t]:n}}function au(e,t,n){let r=al(e,t),i=n.revision;if("number"==typeof i&&"number"==typeof r.serverRevision&&i<r.serverRevision)return e;let o=[...n.items],l=n.admittedAttemptIds?[...n.admittedAttemptIds]:r.admittedAttemptIds;return ac(e,t,{...r,items:o,inFlight:[...n.inFlight??[]],serverRevision:"number"==typeof i?i:r.serverRevision,admittedAttemptIds:l,pending:ap(r.pending,o,new Set(l))})}function ap(e,t,n,r){let i=t.filter(e=>"claimed"!==e.state).map(at),o=e=>!(e.id||e.attemptId&&(n.has(e.attemptId)||r?.has(e.attemptId)));return e.map(e=>{let t=[...i,...e.payloads.filter(o)],n=e.candidates.filter(o);return t.length===e.payloads.length&&t.every((t,n)=>t===e.payloads[n])&&n.length===e.candidates.length?e:{...e,payloads:t,candidates:n}})}function ah(e,t,n,r){let i=new Set,o=[];for(let l of e.pending)if(!(l.revision>=t))for(let e of(i.add(l.revision),l.candidates)){let t=e.attemptId;!t||r.has(t)||n.has(t)||(r.add(t),o.push(e))}return{revisions:i,resolved:o}}function af(e,t){return!!e.sessionId&&e.sessionId===t.sessionId&&(void 0===e.generation||void 0===t.generation||e.generation===t.generation)}function ag(e,t,n){return void 0!==e.clientId?e.clientId!==n?"ignore":(t?.replaceText?.(e.text),"replace"):(t?.insertIfEmpty?.(e.text),"insert-if-empty")}function am(e,t,n){if(e[t]!==n)return e;let r={...e};return delete r[t],r}function ax(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message??null};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function av(e){return new Promise(t=>setTimeout(t,e))}function ay(e){return e instanceof Error&&"AbortError"===e.name}function ab(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}let aw="pi-sound-enabled",ak="pidance:sound-enabled-changed";function aj(){try{let e=localStorage.getItem(aw);return null===e||"true"===e}catch{return!0}}function aS(e){try{localStorage.setItem(aw,String(e))}catch{}window.dispatchEvent(new CustomEvent(ak,{detail:{enabled:e}}))}function aC(e){return"u">typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}let a_=[];function aI({session:e,newSessionCwd:t,newSessionIntentId:n,guideDefaultCwd:o,projectRoots:s,onGuideTargetChange:a,onAgentEnd:d,onAgentRunningChange:c,onSessionCreated:u,onSessionForked:p,modelsRefreshKey:h,chatInputRef:f,onBranchDataChange:g,onSystemPromptChange:m,onSessionStatsChange:x,onSessionStatsPanelOpen:v,onContextUsageChange:y,onTurnMetricsChange:b,onOpenFile:w,onReferenceFile:k,entryJumpRequest:j,onEntryJumpHandled:S,footerCollapsed:C,onFooterToggle:_}){var R;let T,{t:E}=(0,eU.s9)(),{soundEnabled:M,onSoundToggle:A,playDoneSound:L,unlockAudio:z}=function(){let[e,t]=(0,i.useState)(()=>aj()),n=(0,i.useRef)(e);(0,i.useEffect)(()=>{n.current=e},[e]),(0,i.useEffect)(()=>{let e=()=>{let e=aj();n.current=e,t(e)},r=t=>{t.key===aw&&e()};return window.addEventListener("storage",r),window.addEventListener(ak,e),()=>{window.removeEventListener("storage",r),window.removeEventListener(ak,e)}},[]);let r=(0,i.useRef)(null),o=(0,i.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),l=(0,i.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=o();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[o]),s=(0,i.useCallback)(()=>{let e=!n.current;e&&l(!0),n.current=e,aS(e),t(e)},[l]);return{soundEnabled:e,onSoundToggle:s,setSoundEnabled:(0,i.useCallback)(e=>{e&&l(!0),n.current=e,aS(e),t(e)},[l]),playDoneSound:(0,i.useCallback)(()=>{if(!n.current)return;let e=o();if(!e)return;let t=()=>{try{let t;t=e.currentTime,[523.25,659.25].forEach((n,r)=>{let i=e.createOscillator(),o=e.createGain();i.connect(o),o.connect(e.destination),i.type="sine",i.frequency.value=n;let l=t+.18*r;o.gain.setValueAtTime(0,l),o.gain.linearRampToValueAtTime(.18,l+.02),o.gain.exponentialRampToValueAtTime(.001,l+.45),i.start(l),i.stop(l+.45)})}catch{}};"suspended"===e.state?e.resume().then(t).catch(()=>{}):t()},[o]),unlockAudio:l,soundEnabledRef:n}}(),W=ra(),$=e?.readOnly===!0,[P,F]=(0,i.useState)(()=>{if(o)return o;try{return localStorage.getItem("pidance.draftTargetCwd")}catch{return null}}),H=(0,i.useCallback)(e=>{F(e);try{e?localStorage.setItem("pidance.draftTargetCwd",e):localStorage.removeItem("pidance.draftTargetCwd")}catch{}e&&a?.(e)},[a]);(0,i.useEffect)(()=>{o&&H(o)},[o,H]);let D=P??t,N=(0,i.useRef)(L);N.current=L;let B=(0,i.useRef)(M);B.current=M;let O=(0,i.useCallback)(()=>{B.current&&N.current(),d?.()},[d]),U=(0,i.useRef)(!1),q=(0,i.useRef)(null),{loading:K,historyLoading:J,hasMoreBefore:V,error:Y,retryLoadSession:X,messages:G,entryIds:Z,messageKeys:Q,streamState:ee,agentRunning:et,turnMetrics:en,bashRunning:er,pendingBash:ei,modelNames:eo,modelList:el,modelAuthConfigured:ea,modelThinkingLevels:eu,modelThinkingLevelMaps:ep,thinkingLevel:eh,thinkingReady:ef,retryInfo:eg,contextUsage:em,forkingEntryId:ex,isCompacting:ev,compactError:ey,compactResult:eb,displayModel:ew,sessionStats:ek,defaultThinkingLevel:ej,slashCommands:eS,slashCommandsLoading:eC,queuedMessages:e_,notices:eI,liveNoticeActivities:eR,dismissNotice:eT,toggleNoticePin:eE,extensionDialog:eL,extensionCustomUi:ez,extensionEditorTakeover:eW,extensionStatuses:e$,extensionWidgets:eP,extensionHeader:eF,extensionFooter:eH,extensionTerminalInputListenerCount:eD,extensionShortcuts:eN,extensionWorkingMessage:eB,extensionWorkingVisible:eO,extensionWorkingIndicator:eq,hiddenThinkingLabel:eK,extensionToolsExpandedRequest:eJ,respondToExtensionUi:eV,sendExtensionCustomInput:eY,sendExtensionCustomMouse:eX,sendExtensionCustomBounds:eG,sendExtensionWidgetMouse:eZ,sendExtensionEditorInput:eQ,runExtensionShortcut:e0,todos:e1,isAutoModelSelection:e2,agentPhase:e4,toolExecutionSnapshots:e6,isNew:e5,sessionIdRef:e8,scrollContainerRef:e3,jumpButtonVisible:e9,jumpToBottom:e7,loadOlderHistory:te,loadNewerHistory:tt,jumpToEntry:tn,notifyBrowsingHistory:tr,hasMoreAfter:ti,lockedByOther:to,handleSend:tl,handleAbort:ts,handleModelChange:ta,handleCompact:td,handleSteer:tc,handleFollowUp:tu,handlePromptWithStreamingBehavior:tp,handleAbortCompaction:th,handleRecallQueue:tf,handleSendQueueAsSteer:tg,handleBuiltinSlashCommand:tm,handleThinkingLevelChange:tx,loadSlashCommands:tv,loadCommandArgumentCompletions:ty,loadCompletionSuggestions:tb,applyCompletionSuggestion:tw,extensionAutocompleteProviderCount:tk,extensionAutocompleteTriggerCharacters:tj,dismissEditorTakeover:t_,reenterEditorTakeover:tI,reportEditorTakeoverView:tR,handleBranchHere:tT,handleBranchFromAssistant:tE,handleNewSessionFromHere:tM,handleNewSessionFromAnswer:tA}=function(e){let{t}=(0,eU.s9)(),{session:n,newSessionCwd:r,newSessionIntentId:o,onAgentEnd:l,onAgentRunningChange:s,onSessionCreated:a,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,f=null===n&&null!==r,g=(0,i.useRef)(r),m=(0,i.useRef)(o??null);g.current=r,m.current=o??null;let x=tS(n),v=x.readOnly,[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)(!f),[j,S]=(0,i.useState)(!1),[C,_]=(0,i.useState)(!1),[I,R]=(0,i.useState)(!1),[T,E]=(0,i.useState)(null),[M,A]=(0,i.useState)(null),L=(0,i.useRef)(null);L.current=M;let[z,W]=(0,i.useState)([]),[$,P]=(0,i.useState)([]),[F,H]=(0,i.useState)([]),D=(0,i.useRef)(0),N=(0,i.useRef)(null),B=(0,i.useRef)(new Map),O=(0,i.useRef)(new Set),U=(0,i.useCallback)(e=>{let t=O.current;for(t.delete(e),t.add(e);t.size>8;){let e=t.values().next().value;if(void 0===e)break;t.delete(e)}},[]),q=(0,i.useCallback)(()=>{N.current?.abort();let e=new AbortController;return N.current=e,e.signal},[]),K=(0,i.useRef)(!1),J=(0,i.useRef)(!1),V=(0,i.useRef)(!1),[Y,X]=(0,i.useReducer)(ax,{isStreaming:!1,streamingMessage:null}),[G,Z]=(0,i.useState)(!1),[Q,ee]=(0,i.useState)({}),[et,en]=(0,i.useState)(!1),[er,ei]=(0,i.useState)(!1),[eo,el]=(0,i.useState)(null),[es,ea]=(0,i.useState)({}),[ed,eu]=(0,i.useState)([]),[ep,eh]=(0,i.useState)({}),[ef,eg]=(0,i.useState)({}),[em,ex]=(0,i.useState)({}),[ev,ey]=(0,i.useState)(null),[eb,ew]=(0,i.useState)(null),[ek,ej]=(0,i.useState)(null),[eS,eC]=(0,i.useState)(null),e_=(0,i.useRef)(null);e_.current=eS;let[eI,eR]=(0,i.useState)(!1),eT=(0,i.useRef)(!1);eT.current=eI;let eE=(0,i.useRef)(null),eL=(0,i.useRef)(0),ez=(0,i.useRef)(!1),eW=(0,i.useCallback)(e=>{var t;s1(e.remoteLevel)&&(t={viewSessionId:nm.current,targetSessionId:e.targetSessionId,generation:eL.current,capturedGeneration:e.capturedGeneration,userTouched:ez.current,localLevel:e_.current,remoteLevel:e.remoteLevel,source:e.source}).viewSessionId&&t.viewSessionId===t.targetSessionId&&t.generation===t.capturedGeneration&&("disk"===t.source||t.userTouched||(!t.localLevel||t.localLevel===t.remoteLevel)&&1)&&eC(e.remoteLevel)},[]),e$=f?eS??ek??"off":eS??"off",[eP,eF]=(0,i.useState)(null),[eH,eD]=(0,i.useState)(null),eN=(0,i.useRef)(0),eB=(0,i.useCallback)(e=>{eN.current+=1,eD(e)},[]),[eO,eq]=(0,i.useState)(null),[eK,eJ]=(0,i.useState)(null),[eV,eY]=(0,i.useState)(null),eX=(0,i.useRef)(null);eX.current=eV;let eG=(0,i.useRef)({}),eZ=(0,i.useRef)(0),eQ=(0,i.useRef)({}),[e0,e1]=(0,i.useState)(null),e2=(0,i.useRef)(new Map),e4=(0,i.useRef)(new Map),[e6,e5]=(0,i.useState)(!1),e8=(0,i.useRef)(!1);e8.current=e6;let[e3,e9]=(0,i.useState)(null),[e7,te]=(0,i.useState)(null),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)([]),[to,tl]=(0,i.useState)([]),[ts,ta]=(0,i.useState)(!1),{notices:td,liveNoticeActivities:tc,addNotice:tu,addLiveActivity:tp,clearLiveActivities:th,dismissNotice:tf,toggleNoticePin:tg}=function(e){let t,n,r,o,l=(sH||(t=new Map,n=null,r=new Set,o=()=>{for(let e of r)e()},sH={subscribe:e=>(r.add(e),()=>{r.delete(e)}),enqueue(e){let n=e.id??`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=e.type,i=(e=>{let n=t.get(e);if(n)return n;let r=[];return t.set(e,r),r})(e.sessionId??null);return i.some(e=>e.id===n)||(i.push({id:n,sessionId:e.sessionId??null,message:e.message.trim(),type:r,tier:"warning"===r||"error"===r?"important":"transient",pinned:!1,activityRecord:!0===e.activityRecord}),o()),n},activate(e){n!==e&&(n=e,o())},getVisible:()=>(function(e,t){let n=e.get(t)??[],r=[],i=[];for(let e of n)if("transient"===e.tier){if(r.length>=3)continue;r.push({id:e.id,message:e.message,type:e.type,tier:"transient",pinned:!1,activityRecord:e.activityRecord})}else{if(i.length>=3)continue;i.push({id:e.id,message:e.message,type:e.type,tier:"important",pinned:e.pinned,activityRecord:e.activityRecord})}return[...i,...r]})(t,n),queueLength:e=>(t.get(e??null)??[]).length,dismiss(e){let r=t.get(n);if(!r)return;let i=r.filter(t=>t.id!==e);i.length!==r.length&&(t.set(n,i),o())},togglePin(e){let r=t.get(n);if(!r)return;let i=r.map(t=>t.id===e&&"important"===t.tier?{...t,pinned:!t.pinned}:t);i.some((e,t)=>e!==r[t])&&(t.set(n,i),o())},expireTransient(e){let r=t.get(n);if(!r)return;let i=r.filter(t=>t.id!==e||"transient"!==t.tier);i.length!==r.length&&(t.set(n,i),o())},clearSession(e){t.has(e)&&(t.set(e,[]),o())},resetForTests(){t=new Map,n=null,o()}}),sH),s=e??null,[,a]=(0,i.useReducer)(e=>e+1,0),[,d]=(0,i.useReducer)(sF,{visible:[],pending:[]}),[c,u]=(0,i.useState)([]);(0,i.useEffect)(()=>l.subscribe(()=>a()),[l]),(0,i.useEffect)(()=>{l.activate(s)},[l,s]);let p=(0,i.useCallback)(e=>{let t=e.message.trim();t&&l.enqueue({sessionId:e.sessionId??s,id:e.id??("u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`),message:t,type:e.type??"info",activityRecord:!0===e.activityRecord})},[l,s]),h=(0,i.useCallback)(e=>{u(t=>t.some(t=>t.activity.requestId===e.requestId)?t:[...t,{activity:e,timestamp:Date.now()}])},[]),f=(0,i.useCallback)(()=>{u([])},[]),g=(0,i.useCallback)(e=>{l.dismiss(e)},[l]),m=(0,i.useCallback)(e=>{l.togglePin(e)},[l]);return(0,i.useEffect)(()=>{let e=l.getVisible().find(e=>"transient"===e.tier);if(!e)return;let t=setTimeout(()=>{l.expireTransient(e.id)},5e3);return()=>clearTimeout(t)},[l,s,l.getVisible().length]),{notices:l.getVisible(),liveNoticeActivities:c,addNotice:p,addLiveActivity:h,clearLiveActivities:f,dismissNotice:g,toggleNoticePin:m}}(n?.id??null),[tm,tx]=(0,i.useState)(null),{extensionDialog:tv,extensionCustomUi:ty,extensionEditorTakeover:tb,extensionStatuses:tw,extensionWidgets:tk,extensionHeader:tj,extensionFooter:t_,extensionTerminalInputListenerCount:tI,extensionShortcuts:tR,extensionAutocompleteProviderCount:tT,extensionAutocompleteTriggerCharacters:tE,extensionWorkingMessage:tM,extensionWorkingVisible:tA,extensionWorkingIndicator:tL,extensionHiddenThinkingLabel:tz,extensionToolsExpandedRequest:tW,extensionUiStateRef:t$,commitExtensionUiState:tP,patchExtensionUiState:tF,dismissExtensionUiRequest:tH,settledRequestIdsRef:tD,markExtensionUiRequestSettled:tN,clearSettledExtensionUiRequests:tB}=function(){var e;let[t,n]=(0,i.useState)(null),[r,o]=(0,i.useState)(null),[l,s]=(0,i.useState)(null),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(0),[f,g]=(0,i.useState)([]),[m,x]=(0,i.useState)(0),[v,y]=(0,i.useState)([]),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(!0),[S,C]=(0,i.useState)(null),[_,I]=(0,i.useState)(null),[R,T]=(0,i.useState)(null),[E,M]=(0,i.useState)(null),[A,L]=(0,i.useState)(null),z=(0,i.useRef)((e={customUi:r,statuses:a,widgets:c},{dialog:null,customUi:e?.customUi??null,editorTakeover:null,statuses:e?.statuses??[],widgets:e?.widgets??[],header:null,footer:null,terminalInputListenerCount:e?.terminalInputListenerCount??0,shortcuts:e?.shortcuts??[],autocompleteProviderCount:0,autocompleteTriggerCharacters:[],workingMessage:null,workingVisible:!0,workingIndicator:null,hiddenThinkingLabel:null,toolsExpanded:null,toolsExpandedRevision:0,blockingQueue:[]})),W=(0,i.useRef)([]),$=(0,i.useCallback)(e=>{z.current=e,n(e.dialog),o(e.customUi),s(e.editorTakeover),d(e.statuses),u(e.widgets),h(e.terminalInputListenerCount),g(e.shortcuts),x(e.autocompleteProviderCount),y(e.autocompleteTriggerCharacters),w(e.workingMessage),j(e.workingVisible),C(e.workingIndicator),I(e.hiddenThinkingLabel),T(e.header),M(e.footer),L(null===e.toolsExpanded?null:{expanded:e.toolsExpanded,revision:e.toolsExpandedRevision})},[]),P=(0,i.useCallback)(e=>{$({...z.current,...e})},[$]),F=(0,i.useCallback)(e=>{let t=z.current,n=sz(t,e);n!==t&&$(n)},[$]),H=(0,i.useCallback)(e=>{var t;let n;t=W.current,(n=t.filter(t=>t!==e)).push(e),W.current=n.length>64?n.slice(n.length-64):n},[]),D=(0,i.useCallback)(()=>{W.current=[]},[]);return{extensionDialog:t,extensionCustomUi:r,extensionEditorTakeover:l,extensionStatuses:a,extensionWidgets:c,extensionTerminalInputListenerCount:p,extensionShortcuts:f,extensionAutocompleteProviderCount:m,extensionAutocompleteTriggerCharacters:v,extensionWorkingMessage:b,extensionWorkingVisible:k,extensionWorkingIndicator:S,extensionHiddenThinkingLabel:_,extensionHeader:R,extensionFooter:E,extensionUiStateRef:z,commitExtensionUiState:$,patchExtensionUiState:P,extensionToolsExpandedRequest:A,dismissExtensionUiRequest:F,settledRequestIdsRef:W,markExtensionUiRequestSettled:H,clearSettledExtensionUiRequests:D}}(),tO=(0,i.useCallback)(e=>{if(!e)return;let t=t$.current,n=function(e,t){let n="string"==typeof t?.id&&t.id?t.id:null;if(!n||e.customUi?.id===n)return e;let r=Array.isArray(t?.lines)?t.lines.filter(e=>"string"==typeof e):[],i=t?.layout&&"object"==typeof t.layout?t.layout:void 0,o=t?.hidden===!0;return{...e,customUi:{type:"extension_ui_request",id:n,method:"custom",lines:r,...Array.isArray(t?.images)&&t.images.length>0?{images:t.images}:{},...Array.isArray(t?.imageFallbacks)&&t.imageFallbacks.length>0?{imageFallbacks:t.imageFallbacks}:{},...o?{hidden:o}:{},...i?{layout:i}:{}}}}(t,e);n!==t&&tP(n)},[tP,t$]),tU=(0,i.useCallback)(e=>{e?.extensionTerminalInputListenerCount!==void 0&&tF({terminalInputListenerCount:e.extensionTerminalInputListenerCount})},[tF]),tq=(0,i.useCallback)(e=>{e?.extensionAutocompleteProviderCount!==void 0&&tF({autocompleteProviderCount:e.extensionAutocompleteProviderCount,autocompleteTriggerCharacters:Array.isArray(e.extensionAutocompleteTriggerCharacters)?e.extensionAutocompleteTriggerCharacters.filter(e=>"string"==typeof e&&""!==e):[]})},[tF]),tK=(0,i.useCallback)(e=>{e?.hiddenThinkingLabel!==void 0&&tF({hiddenThinkingLabel:e.hiddenThinkingLabel})},[tF]),tJ=(0,i.useCallback)(e=>{if(!e)return;let t=t$.current;for(let[n,r]of[["header",e.extensionHeader],["footer",e.extensionFooter]]){if(void 0===r)continue;let e=Array.isArray(r)&&r.length>0?r:null;sW(t[n],e)||tF({[n]:e})}},[t$,tF]),tV=(0,i.useCallback)(e=>{if(!e||void 0===e.extensionEditorComponent)return;let t=e.extensionEditorComponent,n=t$.current.editorTakeover;if(null===t){n&&tF({editorTakeover:null});return}let r="string"==typeof t.id&&t.id?t.id:null;if(!r||n?.id===r)return;let i=Array.isArray(t.lines)?t.lines.filter(e=>"string"==typeof e):[];tP(s$(t$.current,{type:"extension_ui_request",id:r,method:"editorComponent",lines:i,...Array.isArray(t.images)&&t.images.length>0?{images:t.images}:{},...Array.isArray(t.imageFallbacks)&&t.imageFallbacks.length>0?{imageFallbacks:t.imageFallbacks}:{}}).state)},[tP,t$,tF]),tY=(0,i.useCallback)(e=>{let t=e?.extensionShortcuts;if(!Array.isArray(t))return;let n=t$.current.shortcuts;n.length===t.length&&n.every((e,n)=>{let r=t[n];return e.key===r?.key&&e.available===r?.available&&e.reason===r?.reason&&e.description===r?.description&&e.extensionPath===r?.extensionPath})||tF({shortcuts:t})},[t$,tF]),tX=(0,i.useRef)(new Set),tG=(0,i.useCallback)(e=>!tX.current.has(e)&&(tX.current.add(e),!0),[]),t0=(0,i.useCallback)(e=>{if(e)for(let t of function(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)n&&"object"==typeof n&&"string"==typeof n.id&&n.id&&"string"==typeof n.message&&n.message.trim()&&"warning"===n.notifyType&&t.push({id:n.id,message:n.message,notifyType:"warning"});return t}(e.extensionCapabilityNotices)){let n=sp(String(t.message));if(sg(n)){tG(t.id);continue}sm(n),tG(t.id)&&tu({id:t.id,message:t.message,type:t.notifyType,sessionId:e.sessionId??null})}},[tu,tG]),t6=(0,i.useCallback)(e=>{var t;if(!e)return;void 0!==e.extensionStatuses&&tF({statuses:e.extensionStatuses??[]}),void 0!==e.extensionWidgets&&tF({widgets:e.extensionWidgets??[]}),tU(e),tY(e),tq(e),tV(e),tK(e),tJ(e),t0(e);let n=function(e,t){if(0===t.length||0===e.length)return e;let n=new Set(t),r=e.filter(e=>!n.has(e.id));return r.length===e.length?e:r}(Array.isArray(t=e.pendingExtensionRequests)?t.filter(e=>!!e&&"extension_ui_request"===e.type&&"string"==typeof e.id&&!!e.id&&sE(e.method)):[],tD.current),r=t$.current.blockingQueue??[],i=n.length===r.length&&n.every((e,t)=>e.id===r[t]?.id);n.length>0&&!i?tF({blockingQueue:n,...sA(n)}):void 0!==e.pendingExtensionRequests&&0===n.length&&r.length>0&&tF({blockingQueue:[],dialog:null}),tO(e.activeCustomUi)},[tO,t0,tV,tK,tU,tJ,t$,tF,tD]),t5=(0,i.useCallback)(e=>{let t=e&&"extension_ui_settled"===e.type&&"string"==typeof e.id&&e.id?e.id:null;t&&(tN(t),tH(t))},[tH,tN]),[t8,t3]=(0,i.useState)({steering:[],followUp:[],followUpRows:[],followUpRevision:null}),t9=(0,i.useRef)({}),t7=(0,i.useRef)(n?.id??null),nt=(0,i.useRef)(Promise.resolve()),ni=(0,i.useCallback)(()=>al(t9.current,t7.current??""),[]),no=(0,i.useCallback)(e=>{t3(t=>{let n=ni();return{steering:e??t.steering,followUp:aa(n),followUpRows:ad(n),followUpRevision:n.serverRevision}})},[ni]),nl=(0,i.useCallback)((e,t)=>{t9.current=au(t9.current,e,t)},[]),na=(0,i.useCallback)((e,t)=>{let n,r,i=(n=Array.isArray(t?.inFlight)?t.inFlight.filter(e=>"string"==typeof e):[],r=Array.isArray(t?.followUpItems)?(0,sR.hh)(t.followUpItems):(t?.followUp??[]).map((e,t)=>({id:`srv-${t}`,text:e,state:"waiting"})),{steering:t?.steering??[],items:r,inFlight:n,revision:"number"==typeof t?.followUpRevision?t.followUpRevision:null,admittedAttemptIds:Array.isArray(t?.admittedAttemptIds)?t.admittedAttemptIds.filter(e=>"string"==typeof e):void 0});nl(e,{items:i.items,inFlight:i.inFlight,revision:i.revision,...i.admittedAttemptIds?{admittedAttemptIds:i.admittedAttemptIds}:{}}),t7.current===e&&t3({steering:i.steering,followUp:aa(al(t9.current,e)),followUpRows:ad(al(t9.current,e)),followUpRevision:al(t9.current,e).serverRevision})},[nl]),nd=(0,i.useCallback)(e=>{let t=e??{};return{items:(0,sR.hh)(t.items),inFlight:Array.isArray(t.inFlight)?t.inFlight.filter(e=>"string"==typeof e):[],revision:"number"==typeof t.revision?t.revision:null,admittedAttemptIds:Array.isArray(t.admittedAttemptIds)?t.admittedAttemptIds.filter(e=>"string"==typeof e):void 0}},[]),nc=(0,i.useCallback)(e=>{let t="string"==typeof e?.sessionId&&e.sessionId?e.sessionId:t7.current;t&&(nl(t,nd(e)),t7.current===t&&no())},[nl,no,nd]),nu=(0,i.useCallback)((e,t)=>{t&&(nl(e,{items:t.items,inFlight:t.inFlight,revision:t.revision,...Array.isArray(t.admittedAttemptIds)?{admittedAttemptIds:t.admittedAttemptIds.filter(e=>"string"==typeof e)}:{}}),t7.current===e&&no())},[nl,no]),[np,nh]=(0,i.useState)(!1),nf=(0,i.useRef)(null),ng=(0,i.useRef)(null),nm=(0,i.useRef)(n?.id??null),nx=(0,i.useRef)(null);nx.current=sI({isNew:f,intentId:o??m.current,persistedSessionId:f?null:n?.id??null});let nv=(0,i.useRef)(null);(0,i.useEffect)(()=>{s?.(G,nm.current??n?.id??null)},[G,n?.id,s]);let ny=(0,i.useRef)(n?.id??null),nb=(0,i.useRef)([]),nw=(0,i.useCallback)(e=>{let t=e??nm.current??(m.current?ne(m.current):null);return!!t&&nz().getRunState(t)?.agentRunning===!0},[]),nk=(0,i.useRef)(!1),nj=(0,i.useRef)(!1),nS=(0,i.useRef)(0),nC=(0,i.useRef)(!1),n_=(0,i.useRef)(0),nI=(0,i.useRef)(null),nR=(0,i.useRef)(async()=>{}),nT=(0,i.useRef)(null),nE=(0,i.useRef)(null),nM=(0,i.useRef)(null),nA=(0,i.useRef)(void 0),{scrollContainerRef:nL,jumpButtonVisible:nW,jumpToBottom:n$,notifyAutoFollowSend:nP,notifyAutoFollowBranchReset:nF,notifyAutoFollowEnd:nH,notifyBrowsingHistory:nD}=function({isMobile:e,loading:t,isNew:n,messages:r,agentRunning:o,bashRunning:l}){let s=(0,i.useRef)(null),a=(0,i.useRef)("following"),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(!1),p=(0,i.useRef)(!1),h=(0,i.useRef)(!1),f=(0,i.useRef)(!1),g=(0,i.useRef)(0),m=(0,i.useRef)(0),x=(0,i.useRef)(0),v=(0,i.useRef)(0),y=(0,i.useRef)(0),b=(0,i.useRef)(0),w=(0,i.useRef)(!1),k=(0,i.useRef)(!1),j=(0,i.useRef)(!1),S=(0,i.useRef)(!1),C=(0,i.useRef)(null),_=(0,i.useRef)(0),I=(0,i.useRef)(null),[R,T]=(0,i.useState)(null);k.current=e;let E=(0,i.useCallback)(()=>{var e,t,n,r;let i=s.current;if(!i)return void c(!1);let o=(e=a.current,t=i.scrollHeight-i.clientHeight,n=lq(i.scrollHeight,i.scrollTop,i.clientHeight),r=lK(i.clientHeight,k.current),"released"===e&&t>20&&n>r);c(e=>e===o?e:o)},[]),M=(0,i.useCallback)(()=>{let e=s.current;e&&(e.style.overflowAnchor="released"===a.current?"auto":"none")},[]),A=(0,i.useCallback)(e=>{a.current!==e&&(a.current=e,"released"===e&&(f.current=!1),M(),E())},[M,E]),L=(0,i.useCallback)((e="instant")=>{let t=s.current;if(!t)return;if(S.current){if("function"==typeof t.matches&&(t.matches(":active")||null!==t.querySelector(":active"))){_.current=Date.now();return}if(Date.now()-_.current<4e3)return;S.current=!1,C.current=null,I.current=null}let n=Math.max(0,t.scrollHeight-t.clientHeight);if("smooth"===e){y.current=Date.now()+700,t.scrollTo({top:n,behavior:"smooth"});return}g.current=n,t.scrollTop=n},[]),z=(0,i.useCallback)(()=>{a.current="following",p.current=!0,c(!1)},[]),W=(0,i.useCallback)(()=>{a.current="following",h.current=!0,c(!1)},[]),$=(0,i.useCallback)(()=>{A(lJ(a.current,{kind:"up-intent"})),D.current?.()},[A]),P=(0,i.useCallback)(()=>{b.current=Date.now()+1500,f.current=lV(a.current)},[]),F=(0,i.useCallback)(()=>{S.current=!1,C.current=null,I.current=null,A(lJ(a.current,{kind:"jump-button"})),L(j.current?"instant":"smooth")},[A,L]),H=(0,i.useCallback)(()=>{v.current=Date.now()+150},[]),D=(0,i.useRef)(null);return D.current=H,(0,i.useCallback)(()=>{y.current=Date.now()+700},[]),(0,i.useEffect)(()=>{let e=s.current;T(t=>t===e?t:e)},[t,r.length,n]),(0,i.useEffect)(()=>{R&&M()},[R,M]),(0,i.useEffect)(()=>{if(!R)return;let e=()=>{A(lJ(a.current,{kind:"up-intent"}))},t=t=>{t.deltaY>=0||sJ(t.target,R)||e()},n=null,r=null,i=e=>{n=e.touches[0]?.clientY??null,r=e.target},o=t=>{if(null===n)return;let i=t.touches[0]?.clientY;void 0!==i&&i-n>(k.current?12:4)&&(sJ(r,R)||e(),n=null)},l=t=>{!sK.has(t.key)||t.target instanceof Element&&t.target.closest("input, textarea, [contenteditable='true']")||e()},s=e=>{if(_.current=Date.now(),"touch"===e.pointerType){S.current=!0,C.current=e.pointerId;return}if(0!==e.button)return;let t=e.target;t instanceof Element&&t.closest("input, textarea, [contenteditable='true'], button, a")||(S.current=!0,C.current=e.pointerId,I.current={pointerId:e.pointerId,x:e.clientX,y:e.clientY})},d=e=>{var t;let n=I.current;n&&S.current&&n.pointerId===e.pointerId&&Math.hypot((t={x:e.clientX,y:e.clientY}).x-n.x,t.y-n.y)>=4&&(I.current=null,a.current=lJ(a.current,{kind:"up-intent"}),M())},c=e=>{if(C.current!==e.pointerId)return;let t=S.current;C.current=null,I.current=null,S.current=!1,t&&window.getSelection()?.type==="Range"?(a.current=lJ(a.current,{kind:"up-intent"}),M()):"following"===a.current&&requestAnimationFrame(()=>{lV(a.current)&&L("instant")}),E()},u=()=>{C.current=null,I.current=null,S.current=!1};return R.addEventListener("pointerdown",s),window.addEventListener("pointermove",d),window.addEventListener("pointerup",c),window.addEventListener("pointercancel",c),window.addEventListener("blur",u),R.addEventListener("wheel",t,{passive:!0}),R.addEventListener("touchstart",i,{passive:!0}),R.addEventListener("touchmove",o,{passive:!0}),window.addEventListener("keydown",l),()=>{R.removeEventListener("pointerdown",s),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",c),window.removeEventListener("pointercancel",c),window.removeEventListener("blur",u),R.removeEventListener("wheel",t),R.removeEventListener("touchstart",i),R.removeEventListener("touchmove",o),window.removeEventListener("keydown",l)}},[R,A,E,L,M]),(0,i.useEffect)(()=>{if(!R)return;g.current=R.scrollTop,x.current=R.scrollHeight,m.current=R.clientHeight;let e=()=>{var e;let t=Date.now(),n=g.current,r=R.scrollTop;g.current=r;let i=m.current,o=x.current;(m.current=R.clientHeight,x.current=R.scrollHeight,t<v.current||t<y.current||(e={previousScrollHeight:o,nextScrollHeight:R.scrollHeight,previousClientHeight:i,nextClientHeight:R.clientHeight}).previousClientHeight>0&&e.nextClientHeight!==e.previousClientHeight||e.previousScrollHeight>0&&e.nextScrollHeight!==e.previousScrollHeight)?E():(A(lJ(a.current,{kind:"scroll",distance:lq(R.scrollHeight,r,R.clientHeight),direction:r<n?"up":r>n?"down":"none",zoneSize:lK(R.clientHeight,k.current),bottomTolerance:k.current?16:1})),E())};return R.addEventListener("scroll",e,{passive:!0}),()=>R.removeEventListener("scroll",e)},[R,A,E]),(0,i.useEffect)(()=>{let e=o||l;w.current&&!e&&(b.current=Date.now()+1500,requestAnimationFrame(()=>{lV(a.current)&&(L("instant"),requestAnimationFrame(()=>{lV(a.current)&&L("instant")}))})),w.current=e},[o,l,L]),(0,i.useEffect)(()=>{if(!R)return;let e=R.firstElementChild,t=new ResizeObserver(()=>{let e=Date.now();if(!lV(a.current))return void E();if(x.current=R.scrollHeight,m.current=R.clientHeight,!(e<y.current)){if(e<v.current)return void E();L("instant"),E()}});return t.observe(R),e&&t.observe(e),()=>t.disconnect()},[R,L,E]),(0,i.useEffect)(()=>{0===r.length||s.current&&(p.current||h.current||f.current?(p.current=!1,h.current=!1,f.current=!1,u.current=!0,lV(a.current)&&L("instant")):u.current||(u.current=!0,L("instant")),E())},[r,L,E]),(0,i.useEffect)(()=>{if(!window.matchMedia)return;let e=window.matchMedia("(prefers-reduced-motion: reduce)"),t=()=>{j.current=e.matches};return t(),e.addEventListener("change",t),()=>e.removeEventListener("change",t)},[]),(0,i.useCallback)(()=>"following"===a.current,[]),{scrollContainerRef:s,jumpButtonVisible:d,jumpToBottom:F,notifyAutoFollowSend:z,notifyAutoFollowBranchReset:W,notifyAutoFollowEnd:P,notifyBrowsingHistory:$}}({isMobile:e.isMobile??!1,loading:w,isNew:f,messages:z,agentRunning:G,bashRunning:er}),nN=(0,i.useRef)(null),nB=(0,i.useRef)(!1),nO=(0,i.useRef)(!1),nU=(0,i.useRef)(null),nq=(0,i.useMemo)(()=>{let e=function(e){let t=[],n=!1;for(let i of e){var r;if("assistant"===i.role){let e=i.content;if(!Array.isArray(e))continue;for(let i of e){let e=function(e){if(!sO(e)||"toolCall"!==e.type)return null;let t=sO(e.input)?e.input:sO(e.arguments)?e.arguments:{};return{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:t}}(i);if(null===e||"string"!=typeof(r=e.toolName)||"todowrite"!==r.toLowerCase().replace(/[_-]/g,""))continue;let o=function(e){if(!sO(e.input)||!Array.isArray(e.input.todos))return null;let t=[];for(let[i,o]of e.input.todos.entries()){var n,r;if(!sO(o)||"string"!=typeof o.content||0===o.content.length||!("string"==typeof(n=o.status)&&sD.includes(n))||!("string"==typeof(r=o.priority)&&sN.includes(r)))return null;t.push({id:`todo-${i}-${function(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,0x1000193);return(t>>>0).toString(16).padStart(8,"0")}(`${i}\u0000${o.content}\u0000${o.status}\u0000${o.priority}`)}`,content:o.content,status:o.status,priority:o.priority})}return t}(e);null!==o&&(t=o,n=!0)}continue}if("toolResult"===i.role&&"todo"===i.toolName){let e=function(e){if(!sO(e)||!Array.isArray(e.tasks)||"number"!=typeof e.nextId)return null;let t=[];for(let r of e.tasks){var n;if(!sO(r)||"number"!=typeof r.id||"string"!=typeof r.subject||0===r.subject.length||!("string"==typeof(n=r.status)&&sB.includes(n))||void 0!==r.activeForm&&"string"!=typeof r.activeForm||void 0!==r.blockedBy&&!(Array.isArray(r.blockedBy)&&r.blockedBy.every(e=>"number"==typeof e)))return null;t.push({id:r.id,subject:r.subject,status:r.status,activeForm:"string"==typeof r.activeForm?r.activeForm:void 0,blockedBy:Array.isArray(r.blockedBy)?r.blockedBy:void 0})}let r=new Map(t.map(e=>[e.id,e])),i=[];for(let e of t){if("deleted"===e.status)continue;let t=(e.blockedBy??[]).filter(e=>{let t=r.get(e);return void 0===t||"pending"===t.status||"in_progress"===t.status}).map(e=>r.get(e)?.subject??`#${e}`);i.push({id:`todo-${e.id}`,content:e.subject,status:e.status,activeForm:e.activeForm,blockedBy:t.length>0?t:void 0})}return i}(i.details);if(null===e)continue;t=e,n=!0}}return n?t:null}(Y.streamingMessage?[...z,Y.streamingMessage]:z),t=n?.id??nm.current??"";if(e)return nU.current={sessionId:t,todos:e},e;let r=nU.current;return r&&r.sessionId===t?r.todos:[]},[z,Y.streamingMessage,n?.id]),nK=function(e,t,n=null){return e??t??n??null}(eV,y?.context.model??e0,f?eb:null),nJ=f?ev??eb:nK,nV=(0,i.useMemo)(()=>{if(eH)return null;for(let e=z.length-1;e>=0;e--){let t=z[e];if("assistant"!==t.role)continue;let n=t.usage;if(!n)continue;let r=(n.input??0)+(n.cacheRead??0)+(n.cacheWrite??0);if(r<=0)continue;let i=nJ?ed.find(e=>e.provider===nJ.provider&&e.id===nJ.modelId)?.contextWindow??0:0;return{percent:i>0?r/i*100:null,contextWindow:i,tokens:r}}return null},[eH,z,nJ,ed]),nY=(0,i.useMemo)(()=>{if(tm)return tm;let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},t=0,r=0,i=0,o=0,l=0;for(let n of z){if("user"===n.role&&(r+=1),"toolResult"===n.role&&(o+=1),"assistant"!==n.role)continue;i+=1;let s=n.usage;l+=n.content.filter(e=>"toolCall"===e.type).length,s&&(e.input+=s.input??0,e.output+=s.output??0,e.cacheRead+=s.cacheRead??0,e.cacheWrite+=s.cacheWrite??0,t+=s.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===z.length)?null:{sessionFile:y?.filePath||void 0,sessionId:nm.current??n?.id??"",sessionName:n?.name,userMessages:r,assistantMessages:i,toolCalls:l,toolResults:o,totalMessages:z.length,tokens:e,cost:t,...eH??nV?{contextUsage:eH??nV??void 0}:{}}},[z,tm,eH,nV,y?.filePath,n?.id,n?.name]),nX=(0,i.useCallback)(async(e,n=!1,r=!1,i=!1,o=!1,l)=>{let s=++D.current,a=eL.current,d=q(),c=!1;try{var u,p;n&&k(!0);let t=nz(),h=t.getSnapshot(e)?.timelineSeq??0;r&&eq(null);let f=t.beginHydrate(e),g=new URLSearchParams({deferThinking:"1",deferMedia:"1",limit:String(100)}),m=await sZ({url:`/api/sessions/${encodeURIComponent(e)}?${g}`,signal:d,timeoutMs:12e3,maxRetries:2,retryDelayMs:1500});if(s!==D.current||nm.current!==e)return null;if(404===m.status)return n&&(b(null),A(null),W([]),nb.current=[],ny.current=e,P([]),H([]),J.current=!1,_(!1),E(null)),null;if(!m.ok)throw Error(`HTTP ${m.status}`);let x=await m.json();if(s!==D.current||nm.current!==e)return null;let v=t.getRunState(e);if(v?.finishingRunId!==null&&v?.finishingRunId!==v?.promptRunId)return null;let y=x.context.entryIds??[],w=x.context.messages??[],j=ny.current===e,S=nz().getSnapshot(e),C=(S?.entryIds.length??0)>0,I=j&&S?ns(S.messages,S.entryIds,w,y):w,R=nz().hydrate(e,I,y,{sinceSeq:h,hydrateRequestSeq:f,mode:j&&C?"tail":"replace",pending:"retain",hasMoreAfter:!0===x.context.hasMoreAfter});if("superseded"===R)return null;o&&nF(),b(x),A(x.leafId),l?.(),ny.current=e;let T=nb.current,M=!0===x.context.hasMoreBefore||"number"==typeof x.context.totalMessageCount&&x.context.totalMessageCount>T.length;J.current=M,_(M);let L=e4.current.get(e)??null;if(u=eG.current,void 0===u[e]&&eY(e=>(function(e){let{override:t,persisted:n,lastDiskObserved:r}=e;return!t||n&&r&&!sY(n,r)||sY(t,n)?null:t})({override:e,persisted:x.context.model,lastDiskObserved:L})),E(null),s1(x.context.thinkingLevel)&&eW({targetSessionId:e,capturedGeneration:a,remoteLevel:x.context.thinkingLevel,source:"disk"}),eE.current=e,eR(!0),x.context.model?.provider&&x.context.model?.modelId&&(e2.current.set(e,{provider:x.context.model.provider,modelId:x.context.model.modelId}),e4.current.set(e,{provider:x.context.model.provider,modelId:x.context.model.modelId}),e1({provider:x.context.model.provider,modelId:x.context.model.modelId})),c=!0,n&&k(!1),!r)return!!i||null;try{let t=await sZ({url:`/api/sessions/${encodeURIComponent(e)}/state`,signal:d,timeoutMs:12e3,maxRetries:2,retryDelayMs:1500}).catch(e=>{if(ay(e))throw e;return console.warn("[pidance] hot state load failed; falling back to the on-disk projection:",e),null});if(t?.ok){let n=await t.json();if(s!==D.current||nm.current!==e)return null;let r=(0,li.Us)(n);if(r&&n.state)return en(!1),p=n.state,void 0!==p.contextUsage&&eD(p.contextUsage??null),void 0!==p.systemPrompt&&eq(p.systemPrompt??null),void 0!==p.thinkingLevel&&s1(p.thinkingLevel)&&eW({targetSessionId:e,capturedGeneration:a,remoteLevel:p.thinkingLevel,source:"live-hydrate"}),p.model?.provider&&p.model?.modelId&&(e2.current.set(e,{provider:p.model.provider,modelId:p.model.modelId}),e1({provider:p.model.provider,modelId:p.model.modelId})),void 0!==p.queuedMessages&&na(e,p.queuedMessages),t6(p),{running:r,live:r,activeRun:!0===n.activeRun,lockedByOther:!1,state:n.state};return en(!0===n.lockedByOther),r||t3({steering:[],followUp:aa(ni()),followUpRows:ad(ni()),followUpRevision:ni().serverRevision}),{running:!1,live:!1,activeRun:!1,lockedByOther:!0===n.lockedByOther}}return en(!1),{running:!1,live:!1,activeRun:!1,lockedByOther:!1}}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return ay(e)||(e instanceof sX?(console.warn("[pidance] session detail load failed:",e.failure,"attempts:",e.attempts),E(t("chat_loadFailed",{attempts:e.attempts}))):E(String(e))),null}finally{n&&!c&&k(!1)}},[tK,tJ,t6,na,eW,q,nF,tF,ni]),nG=(0,i.useCallback)(()=>{let e=nm.current;e&&(E(null),nX(e,!0,!0))},[nX]),nZ=(0,i.useCallback)(async e=>{let t=nz(),n=t.getSnapshot(e),r=(n?.entryIds??(e===nm.current?nb.current??[]:[])).filter(e=>!!e),i=r[0],o=r[r.length-1];if(!i||!o||!(n?.messages??[]).some(e=>"custom"===e.role&&Array.isArray(e.renderedLines)))return;let l=B.current;l.get(e)?.abort();let s=new AbortController;l.set(e,s);let a=n?.hasMoreAfter===!0,d=Math.min(500,Math.max(r.length,100)),c=e===nm.current?L.current:null,u=t=>{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1",limit:String(d)});for(let[e,r]of t)n.set(e,r);return c&&n.set("leafId",c),`/api/sessions/${encodeURIComponent(e)}/context?${n}`},p=null,h=null,f=!1,g=!1;try{for(let n=0;n<4;n++){if(n>0&&f&&g)return;let l=new URLSearchParams;if(0===n)a?(l.set("around",r[Math.floor(r.length/2)]),l.set("toEnd","0")):(l.set("around",i),l.set("toEnd","1"));else if(!f&&p)l.set("after",p);else{if(g||!h)return;l.set("before",h)}let d=await fetch(u(l),{signal:s.signal,cache:"no-store"});if(!d.ok)return;let c=await d.json(),m=c.context?.messages??[],x=c.context?.entryIds??[];if(0===m.length||0===x.length)return;if(t.refreshRenderedLines(e,m,x),nm.current!==e){x.includes(o)&&x.includes(i)||U(e);return}if(0===n){if(p=x[x.length-1]??null,h=x[0]??null,f=x.includes(o),g=x.includes(i),!a&&f||f&&g)return;continue}if(!f&&p&&l.get("after")===p){if(x.includes(o)){f=!0;continue}let e=x[x.length-1]??null;e&&e!==p?p=e:f=!0;continue}if(x.includes(i)){g=!0;continue}let v=x[0]??null;v&&v!==h?h=v:g=!0}}catch(e){ay(e)||console.debug("theme refresh failed:",e)}finally{l.get(e)===s&&l.delete(e)}},[U]),nQ=(0,i.useCallback)(()=>{let e=nm.current;if(e){if("u">typeof document&&"hidden"===document.visibilityState)return void U(e);nZ(e)}},[nZ,U]);(0,i.useEffect)(()=>(0,sV.yb)(nQ),[nQ]);let n0=(0,i.useCallback)(async()=>{let e=nm.current;if(!e||!J.current||K.current)return!1;let t=nb.current[0];if(!t)return!1;K.current=!0,S(!0);let n=nz().beginHydrate(e);try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1",before:t,limit:String(100)});M&&r.set("leafId",M);let i=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${r}`,{signal:q()});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();if(nm.current!==e)return!1;let l=o.context.entryIds??[],s=o.context.messages??[];if(0===l.length)return J.current=!1,_(!1),!1;let a=nb.current,d=nz().hydrate(e,s,l,{hydrateRequestSeq:n,mode:"prepend",pending:"retain"});if("applied"!==d)return!1;let c=nb.current??a;nb.current=c;let u=!0===o.context.hasMoreBefore||"number"==typeof o.context.totalMessageCount&&o.context.totalMessageCount>c.length;return J.current=u,_(u),!0}catch(e){return ay(e)||console.error("Failed to load older history:",e),!1}finally{K.current=!1,S(!1)}},[M]),n1=(0,i.useCallback)(async(e,t)=>{try{let n=new URLSearchParams({deferThinking:"1",deferMedia:"1",limit:String(100)});t&&n.set("leafId",t);let r=`/api/sessions/${encodeURIComponent(e)}/context?${n}`,i=nz(),o=i.beginHydrate(e),l=i.getSnapshot(e)?.timelineSeq??0,s=await fetch(r,{signal:q()});if(!s.ok)throw Error(`HTTP ${s.status}`);let a=await s.json();if(nm.current!==e)return;let d=a.context.entryIds??[],c=nz().getSnapshot(e),u=ny.current===e&&c?ns(c.messages,c.entryIds,a.context.messages,d):a.context.messages,p=nz().hydrate(e,u,d,{sinceSeq:l,hydrateRequestSeq:o,mode:"replace",pending:"drop"});if("applied"!==p)return;nF(),ny.current=e;let h=!0===a.context.hasMoreBefore||"number"==typeof a.context.totalMessageCount&&a.context.totalMessageCount>d.length;J.current=h,_(h)}catch(e){ay(e)||console.error("Failed to load context:",e)}},[nF,q]),n2=(0,i.useRef)(0),n4=(0,i.useCallback)(async(e,t)=>{let n=nm.current;if(!n||!e)return!1;let r=++n2.current,i=L.current,o=()=>n2.current===r&&nm.current===n&&L.current===i,l=nz(),s=l.beginHydrate(n),a=l.getSnapshot(n)?.timelineSeq??0;nD();try{let r=new URLSearchParams({around:e,deferThinking:"1",deferMedia:"1",toEnd:t?.toEnd!==!1&&G?"1":"0"});t?.limit&&r.set("limit",String(t.limit)),i&&r.set("leafId",i);let d=await fetch(`/api/sessions/${encodeURIComponent(n)}/context?${r}`,{signal:q()});if(!d.ok)return!1;let c=await d.json();if(!o())return!1;let u=c.context.entryIds??[],p=c.context.messages??[];if(0===u.length)return!1;let h=l.hydrate(n,p,u,{sinceSeq:a,hydrateRequestSeq:s,mode:"replace",pending:"retain",hasMoreAfter:!0===c.context.hasMoreAfter});if("applied"!==h||!o())return!1;ny.current=n,J.current=!0===c.context.hasMoreBefore,_(J.current);let f=!0===c.context.hasMoreAfter;return V.current=f,R(f),!0}catch(e){return ay(e)||console.error("Failed to jump to entry:",e),!1}},[G,q,nD]),n6=(0,i.useCallback)(async()=>{let e=nm.current;if(!e||!V.current||K.current)return!1;let t=nb.current[nb.current.length-1];if(!t)return!1;K.current=!0,S(!0);let n=nz(),r=n.beginHydrate(e),i=n.getSnapshot(e)?.timelineSeq??0;try{let o=new URLSearchParams({after:t,deferThinking:"1",deferMedia:"1"});M&&o.set("leafId",M);let l=await fetch(`/api/sessions/${encodeURIComponent(e)}/context?${o}`,{signal:q()});if(!l.ok)return!1;let s=await l.json();if(nm.current!==e)return!1;let a=s.context.entryIds??[],d=s.context.messages??[];if(0===a.length)return V.current=!1,R(!1),!1;let c=n.hydrate(e,[...n.getSnapshot(e)?.messages??[],...d],[...nb.current,...a],{sinceSeq:i,hydrateRequestSeq:r,mode:"replace",pending:"retain",hasMoreAfter:!0===s.context.hasMoreAfter});if("applied"!==c)return!1;return V.current=!0===s.context.hasMoreAfter,R(V.current),!0}catch(e){return ay(e)||console.error("Failed to load newer history:",e),!1}finally{K.current=!1,S(!1)}},[M,q]),n5=(0,i.useCallback)(async e=>{if(v)return},[v]),n8=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=nm.current,r=g.current;f&&r&&n&&!nB.current&&(nB.current=!0,a?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t},m.current))},[f,a]),n3=(0,i.useCallback)(async()=>{if(nm.current)return nm.current;let e=g.current;if(!f||!e)return nm.current;if(nN.current)return nN.current;let t=m.current,n=(async()=>{let n,r=ev??eb,i=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,type:"ensure_session",...r?{provider:r.provider,modelId:r.modelId}:{},...(n=oI(e$)??void 0)?{thinkingLevel:n}:{}})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=(await i.json()).sessionId;return m.current===t&&(nm.current=o),o})();nN.current=n;try{return await n}finally{nN.current===n&&(nN.current=null)}},[f,ev,eb,e$]),n9=(0,i.useCallback)(async()=>{if(v)return tl([]),[];let e=nm.current??n?.id??null;if(!e){let e=g.current;if(!e)return tl([]),[];ta(!0);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`);if(!t.ok)return tl([]),[];let n=((await t.json()).skills??[]).map(e=>({name:`skill:${e.name}`,description:e.description,source:"skill"}));return tl(n),n}catch(e){return console.error("Failed to load skills for guide:",e),tl([]),[]}finally{ta(!1)}}ta(!0);try{let t=await (0,li.$J)(e,{type:"get_commands"}),n=t?.commands??[];return tl(n),n}catch(e){return console.error("Failed to load slash commands:",e),tl([]),[]}finally{ta(!1)}},[v,n?.id,li.$J]),n7=(0,i.useCallback)(async(e,t)=>{let r=nm.current??n?.id??null;if(!r||v||!e)return[];try{let n=await (0,li.$J)(r,{type:"get_command_argument_completions",name:e,prefix:t});return n?.items??[]}catch{return[]}},[v,n?.id,li.$J]),re=(0,i.useCallback)(async e=>{let t=nm.current??n?.id??null;if(!t||v)return{kind:"unavailable"};try{let n=await (0,li.$J)(t,{type:"completion_suggestions",lines:e.lines,cursorLine:e.cursorLine,cursorCol:e.cursorCol,...!0===e.force?{force:!0}:{}},{signal:e.signal});return n?.result??{kind:"error"}}catch{return{kind:"error"}}},[v,n?.id,li.$J]),rt=(0,i.useCallback)(async e=>{let t=nm.current??n?.id??null;if(!t||v)return null;try{let n=await (0,li.$J)(t,{type:"completion_apply",lines:e.lines,cursorLine:e.cursorLine,cursorCol:e.cursorCol,item:e.item,prefix:e.prefix});return n?.result??null}catch{return null}},[v,n?.id,li.$J]),rn=(0,i.useCallback)(e=>{if(!x.canConnectEvents)return;let t=nz();t.ensureEventsConnected(e),nf.current=t.getEventSource(e)},[x.canConnectEvents]),rr=(0,i.useCallback)(async(e,t)=>{if(!x.canSendSessionCommands)return;let n=nm.current,r=t$.current,i=sz(r,e.id);if(i!==r&&(tP(i),n))try{if(await (0,li.$J)(n,{type:"extension_ui_response",id:e.id,...t}),"cancelled"in t&&!0===t.cancelled&&nw())try{await (0,li.$J)(n,{type:"abort"})}catch{}}catch(e){console.error("Failed to send extension UI response:",e)}},[x.canSendSessionCommands,tP,t$]),ri=(0,i.useCallback)(async(e,t)=>{if(!x.canSendSessionCommands)return;let n=nm.current;if(n&&t$.current.customUi?.id===e.id)try{await (0,li.$J)(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[x.canSendSessionCommands,t$]),ro=(0,i.useCallback)(async(e,t)=>{if(!x.canSendSessionCommands)return;let n=nm.current;if(n&&t$.current.customUi?.id===e.id)try{await (0,li.$J)(n,{type:"extension_ui_mouse",id:e.id,event:t})}catch(e){console.error("Failed to send extension custom UI mouse event:",e)}},[x.canSendSessionCommands,t$]),rl=(0,i.useCallback)(async(e,t)=>{if(!x.canSendSessionCommands)return;let n=nm.current;if(n&&t$.current.customUi?.id===e.id)try{await (0,li.$J)(n,{type:"custom_panel_bounds",id:e.id,bounds:t})}catch(e){console.error("Failed to send extension custom UI bounds:",e)}},[x.canSendSessionCommands,t$]),rs=(0,i.useCallback)(async(e,t)=>{if(!x.canSendSessionCommands)return;let n=nm.current;if(n)try{await (0,li.$J)(n,{type:"extension_ui_widget_mouse",key:e,event:t})}catch(e){console.error("Failed to send extension widget mouse event:",e)}},[x.canSendSessionCommands]),ra=(0,i.useCallback)(async e=>{let n=nm.current;if(!n)return;let r=sk(e);try{let i=await (0,li.$J)(n,{type:"run_extension_shortcut",key:e});i?.ok===!1&&tu({type:"error",message:t("shortcut_runFailed",{key:r,reason:i.error??""})})}catch(e){tu({type:"error",message:t("shortcut_runFailed",{key:r,reason:e instanceof Error?e.message:String(e)})})}},[tu,nm,t]),{handleFork:rd,handleNavigate:rc,handleLeafChange:ru,handleBranchHere:rp,handleBranchFromAssistant:rh,handleNewSessionFromHere:rf,handleNewSessionFromAnswer:rg,navigateBranch:rm,setBranchLabel:rx,branchActions:rv}=function(e){let{sessionIdRef:t,isReadOnly:n,canWrite:r,getAgentRunning:o,bashRunningRef:l,branchBusyRef:s,branchBusy:a,setBranchBusy:d,setForkingEntryId:c,setActiveLeafId:u,sendAgentCommand:p,loadSession:h,loadContext:f,addNotice:g,chatInputRef:m,onSessionForked:x}=e,v=(0,i.useCallback)(async e=>{if(n||l.current)return;let r=t.current;if(r){c(e);try{let t=await p(r,{type:"fork",entryId:e}),n=sU(t);"switch-session"===n.kind&&x?.(n.sessionId)}catch(e){console.error("Fork failed:",e)}finally{c(null)}}},[n,l,t,c,p,x]),y=(0,i.useCallback)(async e=>{if(l.current||s.current)return;let r=t.current;if(r){if(n){u(e),await f(r,e);return}p(r,{type:"navigate_tree",targetId:e}).catch(()=>{}),u(e),await f(r,e)}},[n,l,s,t,u,p,f]),b=(0,i.useCallback)(async e=>{if(l.current||s.current)return;u(e);let r=t.current;r&&(await f(r,e),e&&!n&&p(r,{type:"select_leaf_exact",entryId:e}).catch(()=>{}))},[n,l,s,t,u,p,f]),w=(0,i.useCallback)(async(e,r)=>{if(!iw({readOnly:n,busy:o()||l.current||s.current}).allowed)return;let i=t.current;if(i){s.current=!0,d(!0);try{let t=await p(i,{type:"navigate_tree",targetId:e,summarize:!1});if(!sq({noop:!!t?.cancelled,editorText:t?.editorText},m?.current,"replace"))return;r?.trim()&&m?.current?.replaceText(r.trim()),await h(i,!1,!1,!0,!0)}catch(e){g({type:"error",message:e instanceof Error?e.message:String(e)})}finally{s.current=!1,d(!1)}}},[g,n,o,l,s,t,d,p,m,h]),k=(0,i.useCallback)(async e=>{if(!iw({readOnly:n,busy:o()||l.current||s.current}).allowed)return;let r=t.current;if(r){s.current=!0,d(!0);try{let t=await p(r,{type:"branch_from_assistant",assistantEntryId:e});if(t?.cancelled)return;await h(r,!1,!1,!0,!0)}catch(e){g({type:"error",message:e instanceof Error?e.message:String(e)})}finally{s.current=!1,d(!1)}}},[g,n,o,l,s,t,d,p,h]),j=(0,i.useCallback)(async(e,r)=>{if(!iw({readOnly:n,busy:o()||l.current||s.current}).allowed)return;let i=t.current;if(i){s.current=!0,d(!0);try{let t=await p(i,{type:"fork",entryId:e}),n=sU(t,r);"switch-session"===n.kind&&x?.(n.sessionId,n.prefill)}catch(e){g({type:"error",message:e instanceof Error?e.message:String(e)})}finally{s.current=!1,d(!1)}}},[g,n,o,l,s,t,d,p,x]),S=(0,i.useCallback)(async e=>{if(!iw({readOnly:n,busy:o()||l.current||s.current}).allowed)return;let r=t.current;if(r){s.current=!0,d(!0);try{let t=await p(r,{type:"create_session_from_leaf",entryId:e}),n=sU(t);"switch-session"===n.kind&&x?.(n.sessionId)}catch(e){g({type:"error",message:e instanceof Error?e.message:String(e)})}finally{s.current=!1,d(!1)}}},[g,n,o,l,s,t,d,p,x]),C=(0,i.useCallback)(async(e,r)=>{let i=iw({readOnly:n,busy:o()||l.current||s.current});if(!i.allowed)return{kind:"busy"===i.reason?"busy":"error"};let a=function(e,t){switch(t.mode){case"direct":return{type:"navigate_tree",targetId:e,summarize:!1};case"summary":return{type:"navigate_tree",targetId:e,summarize:!0};case"custom":{let n=t.focus.trim();if(!n)return null;return{type:"navigate_tree",targetId:e,summarize:!0,customInstructions:n}}}}(e,r);if(!a)return{kind:"error"};let c=t.current;if(!c)return{kind:"error"};s.current=!0,d(!0);try{let e=await p(c,a);if(!sq({noop:!!(e?.cancelled||e?.aborted),editorText:e?.editorText},m?.current,"insertIfEmpty"))return{kind:"cancelled"};if(!await h(c,!1,!1,!0,!0)){let e="Failed to refresh session after switching branches";return g({type:"error",message:e}),{kind:"error",message:e}}return{kind:"ok"}}catch(t){let e=t instanceof Error?t.message:String(t);return g({type:"error",message:e}),{kind:"error",message:e}}finally{s.current=!1,d(!1)}},[g,n,o,l,s,t,d,p,m,h]),_=(0,i.useCallback)(async(e,r)=>{var i;let a,c,u=iw({readOnly:n,busy:o()||l.current||s.current});if(!u.allowed)return{kind:"busy"===u.reason?"busy":"error"};let f=(i=e,"tooLong"===(c=(a=(r??"").trim()).length>120?{kind:"tooLong",maxLength:120}:""===a?{kind:"clear"}:{kind:"set",label:a}).kind?null:{type:"set_branch_label",targetId:i,label:"set"===c.kind?c.label:""});if(!f)return{kind:"error"};let m=t.current;if(!m)return{kind:"error"};s.current=!0,d(!0);try{if(await p(m,f),!await h(m,!1,!1,!0)){let e="Failed to refresh session after saving the bookmark";return g({type:"error",message:e}),{kind:"error",message:e}}return{kind:"ok"}}catch(t){let e=t instanceof Error?t.message:String(t);return g({type:"error",message:e}),{kind:"error",message:e}}finally{s.current=!1,d(!1)}},[g,n,o,l,s,t,d,p,h]),I=(0,i.useMemo)(()=>({canWrite:r,busy:a,navigate:C,setLabel:_}),[r,a,C,_]);return{handleFork:v,handleNavigate:y,handleLeafChange:b,handleBranchHere:w,handleBranchFromAssistant:k,handleNewSessionFromHere:j,handleNewSessionFromAnswer:S,navigateBranch:C,setBranchLabel:_,branchActions:I,branchBusy:a}}({sessionIdRef:nm,isReadOnly:v,canWrite:x.canSendSessionCommands,getAgentRunning:()=>nw(),bashRunningRef:nj,branchBusyRef:nC,branchBusy:np,setBranchBusy:nh,setForkingEntryId:eJ,setActiveLeafId:A,sendAgentCommand:li.$J,loadSession:nX,loadContext:n1,addNotice:tu,chatInputRef:e.chatInputRef,onSessionForked:d}),ry=(0,i.useRef)(()=>{}),rb=(0,i.useRef)(null),rw=(0,i.useCallback)(t=>{let n=s$(t$.current,t);for(let t of(tP(n.state),n.effects))if("notice"===t.type){let e=sp(String(t.message));if(sg(e)){tG(t.id);continue}sm(e),tG(t.id),tu({id:t.id,message:t.message,type:t.noticeType,activityRecord:t.activityRecord}),t.activityRecord&&tp({version:1,kind:"error"===t.noticeType?"error":"warning",title:"error"===t.noticeType?"Extension error":"Extension warning",content:t.message,source:"extension.ui.notify",requestId:t.id,metadata:{notifyType:t.noticeType}})}else if("setTitle"===t.type)!function(e){var t;let n;s_((t=sS,(n="string"==typeof e?e.trim():"")?{...t,override:n}:t))}(t.title);else if("setThemeMode"===t.type){var r;r=t.mode,rE()!==r&&r$(r,rM())}else if("focusEditor"===t.type)e.chatInputRef?.current?.focus();else if("editorSubmit"===t.type){let n=t.clientId;(void 0===n?e.editorTakeoverDisplayedRef?.current===!0:n===lb())&&ry.current(t.text)}else if("setEditorText"===t.type&&e.editorTakeoverDisplayedRef?.current===!0){if(!t.appliedToTakeover){let n=t$.current.editorTakeover;n?rb.current?.(n,lv(t.text)):ag(t,e.chatInputRef?.current??null,lb())}}else"setEditorText"===t.type&&ag(t,e.chatInputRef?.current??null,lb())},[tu,tp,tG,tP,e.chatInputRef,e.editorTakeoverDisplayedRef,t$]),rk=(0,i.useCallback)((e,t)=>{if(!t||!af({sessionId:e},{sessionId:nm.current}))return;let n=t.turnMetrics??null,r=n&&(void 0!==n.tokensPerSecond||void 0!==n.ttftMs)?n:null;nz().seedTurnMetrics(e,r)},[]),rj=(0,i.useCallback)((e,t)=>{!t||af({sessionId:e},{sessionId:nm.current})&&(void 0!==t.contextUsage&&eD(t.contextUsage??null),rk(e,t),void 0!==t.systemPrompt&&eq(t.systemPrompt??null),s1(t.thinkingLevel)&&eW({targetSessionId:e,capturedGeneration:eL.current,remoteLevel:t.thinkingLevel,source:"live-hydrate"}),t.model?.provider&&t.model?.modelId&&e1({provider:t.model.provider,modelId:t.model.modelId}),void 0!==t.isCompacting&&e5(t.isCompacting),t6(t),void 0!==t.queuedMessages&&na(e,t.queuedMessages))},[t6,na,eW,rk,e1]),rS=(0,i.useCallback)(async(e,t)=>{if(!e)return;let n=nz(),r=n.getRunState(e);if(nm.current===e&&r&&r.promptRunId===t&&!r.sendInFlight&&n.beginRunFinish(e,t))try{let r=await nX(e,!1,!0,!1,!1,()=>{n.getRunState(e)?.promptRunId===t&&nH()});r&&"object"==typeof r&&"running"in r&&rj(e,r.state)}finally{let r=n.getRunState(e),i=!!(r&&nm.current===e&&r.promptRunId===t&&r.finishingRunId===t);if(n.completeRun(e,t),n.releaseRunFinish(e,t),!i)return;tn(null),eF(null);{let e=function(e,t=Date.now()){let n=!1,r=new Map(e);for(let[e,i]of r)"running"===i.status&&(r.set(e,{...i,status:"cancelled",endedAt:i.endedAt??t}),n=!0);return n?r:e}(rT.current);rT.current=e,ti(ae(e))}X({type:"end"}),l?.()}},[nX,l,rj,X,Z,tn,eF,nH,t]),rC=(0,i.useCallback)(async(e,t)=>{let n=nz();await av(800);let r=Date.now();for(;Date.now()-r<2e4;){let r=n.getRunState(e);if(!r?.agentRunning||void 0!==t&&r.promptRunId>t+1)return;try{let t=await n.reconcile(e);if(!t||t.stale)return;if(rj(e,t.state),t.shouldFinish)return void await rS(e,t.runId)}catch{}await av(600)}},[rj,rS]),r_=(0,i.useCallback)(async e=>{let t=n_.current+1;for(n_.current=t;nj.current&&n_.current===t&&nm.current===e;){await av(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}?light=1`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nX(e),n_.current!==t||nm.current!==e)return;nz().setBashRunning(e,!1);return}catch{}}},[nX]),rI=(0,i.useCallback)(async e=>{let t=nz(),n=eN.current;try{let r=await t.reconcile(e);if(!r||r.stale)return!1;let i=r.state,o=af({sessionId:e},{sessionId:nm.current});return o&&e5(i?.isCompacting??!1),rk(e,i),i?.contextUsage!==void 0&&af({sessionId:e,generation:n},{sessionId:nm.current,generation:eN.current})&&eD(i.contextUsage??null),i?.queuedMessages!==void 0&&na(e,i.queuedMessages),o&&t6(i),r.shouldFinish&&await rS(e,r.runId),!0===r.live}catch{return!1}},[t6,na,rS]);(0,i.useEffect)(()=>{let e=null,t=()=>{let n=nm.current,r=12e4;if(n){let e=nz();e.getRunState(n)?.agentRunning?r=15e3:e.hasActiveEventStream(n)||(r=15e3),12e4!==r&&rI(n)}e=setTimeout(t,r)},n=()=>{let e=nm.current;e&&rI(e)},r=()=>{"visible"===document.visibilityState&&n()};return e=setTimeout(t,15e3),document.addEventListener("visibilitychange",r),window.addEventListener("online",n),()=>{null!==e&&clearTimeout(e),document.removeEventListener("visibilitychange",r),window.removeEventListener("online",n)}},[G,rI]);let rR=(0,i.useCallback)(async()=>{let e=nm.current;if(!e)return;let t=nz();t.getEventSource(e)&&t.getEventSource(e)?.close?.(),rn(e),rI(e),nX(e,!1,!0);let n=O.current;n.size>0&&(O.current=new Set,(async()=>{for(let e of n)t.getSnapshot(e)&&await nZ(e)})())},[rn,rI,nX,nZ]);(0,i.useEffect)(()=>{let e=n?.id;if(!e||n?.readOnly)return;let t=!1,r=null,i=0,o=()=>{null!==r&&(clearTimeout(r),r=null)},l=async()=>{let n=await rI(e);t||n||i>=6||(i+=1,o(),r=setTimeout(()=>{r=null,l()},1500))},s=(0,ec.RD)(t=>{t?.type==="running"&&Array.isArray(t.runningSessionIds)&&t.runningSessionIds.includes(e)&&(nz().hasActiveEventStream(e)||(i=0,o(),l()))});return()=>{t=!0,o(),s()}},[n?.id,n?.readOnly,rI]),(0,i.useEffect)(()=>{let e=n?.id;if(!e||f||n?.readOnly)return;let t=!1,r=()=>{"visible"===document.visibilityState&&fetch(`/api/sessions/${encodeURIComponent(e)}/state`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(n=>{!t&&n&&nm.current===e&&en(!0===n.lockedByOther)}).catch(()=>void 0)},i=eM({perform:r}),o=()=>{"visible"===document.visibilityState&&i.notify()};document.addEventListener("visibilitychange",o),window.addEventListener("focus",o);let l=et?window.setInterval(r,1e3):window.setInterval(()=>{"visible"===document.visibilityState&&fetch(`/api/sessions/${encodeURIComponent(e)}/lock`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(n=>{!t&&n&&nm.current===e&&en(!0===n.lockedByOther)}).catch(()=>void 0)},3e3);return()=>{t=!0,document.removeEventListener("visibilitychange",o),window.removeEventListener("focus",o),i.dispose(),l&&window.clearInterval(l)}},[n?.id,n?.readOnly,f,et]),(0,i.useEffect)(()=>{let e=eM({perform:()=>rR()}),t=nz(),n=()=>{let n="visible"===document.visibilityState;t.setTabVisibility(n),n&&e.notify()},r=()=>{"visible"===document.visibilityState&&(t.setTabVisibility(!0),e.notify())};t.setTabVisibility("visible"===document.visibilityState),document.addEventListener("visibilitychange",n),window.addEventListener("focus",r);let i=(0,t4.DF)(()=>{t.setTabVisibility("visible"===document.visibilityState),e.notify()});return()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("focus",r),i(),e.dispose()}},[rR]);let rT=(0,i.useRef)(new Map),rA=(0,i.useCallback)(e=>{rT.current=e,ti(ae(e))},[]);nI.current=(0,i.useCallback)((e,n)=>{switch(e.type){case"agent_start":var r;rA(0===(r=rT.current).size?r:new Map),tn({kind:"waiting_model"}),X({type:"start"});break;case"agent_end":case"prompt_done":{if("agent_end"===e.type){let t=e.contextUsage;t&&"number"==typeof t.contextWindow&&t.contextWindow>0&&eB(t)}let t=nm.current,n=t?nz().getRunState(t)?.promptRunId:void 0;t&&void 0!==n&&rS(t,n);break}case"prompt_error":nm.current&&(0,eA.dM)(`sessionQueueHold.${nm.current}`,!0),tu({type:"error",message:e.errorMessage??t("input_commandFailed")});break;case"extension_error":nm.current&&(0,eA.dM)(`sessionQueueHold.${nm.current}`,!0),tu({type:"error",message:e.error??"Extension command failed"});break;case"leaf_drift":tu({type:"warning",message:t("session_leafDrift")});break;case"message_start":case"message_update":{if(!nw())break;let t=e.message;if(t?.role==="user")break;tn(null);break}case"message_end":{let t=e.contextUsage;t&&"number"==typeof t.contextWindow&&t.contextWindow>0&&eB(t),tn({kind:"waiting_model"});break}case"tool_execution_start":{rA(s7(rT.current,e));let t=e.toolCallId,n=e.toolName;tn(e=>{let r=e?.kind==="running_tools"?[...e.tools]:[];return r.some(e=>e.id===t)||r.push({id:t,name:n}),{kind:"running_tools",tools:r}});break}case"tool_execution_update":rA(function(e,t){if("object"!=typeof t||null===t)return e;let n=s4(t.toolCallId);if(!n)return e;let r=e.get(n);if(!r||"running"!==r.status)return e;let{text:i,truncated:o}=s3(s8(t.partialResult)),l=r.command??s9(t.args),s=Object.prototype.hasOwnProperty.call(t,"renderedLines")?s5(t.renderedLines):r.renderedLines;return i===r.output&&o===(r.truncated??!1)&&l===r.command&&s===r.renderedLines?e:new Map(e).set(n,{...r,output:i,truncated:o||void 0,command:l,renderedLines:s})}(rT.current,e));break;case"tool_call":rA(s7(rT.current,{toolCallId:e.toolCallId,toolName:e.toolName,args:e.input??e.args,renderedCallLines:e.renderedCallLines}));break;case"tool_result":rA(function(e,t){if("object"!=typeof t||null===t)return e;let n=s4(t.toolCallId);if(!n)return e;let r=e.get(n),i=s5(t.renderedResultLines);return r&&i?new Map(e).set(n,{...r,renderedResultLines:i}):e}(rT.current,{toolCallId:e.toolCallId,renderedResultLines:e.renderedResultLines}));break;case"rendered_lines_update":rA(function(e,t){if("object"!=typeof t||null===t)return e;let n=s4(t.toolCallId);if(!n)return e;let r=e.get(n);if(!r)return e;let i=s5(t.renderedCallLines),o=s5(t.renderedResultLines);return i||o?new Map(e).set(n,{...r,...i?{renderedCallLines:i}:{},...o?{renderedResultLines:o}:{}}):e}(rT.current,{toolCallId:e.toolCallId,renderedCallLines:e.renderedCallLines,renderedResultLines:e.renderedResultLines}));break;case"tool_execution_end":{rA(function(e,t){if("object"!=typeof t||null===t)return e;let n=s4(t.toolCallId);if(!n)return e;let r=Date.now(),i=e.get(n),o=s6(t.toolName)??i?.toolName??"",l=!0===t.isError?"error":"success",s=s5(t.renderedResultLines)??i?.renderedResultLines;if(!i){let{text:i,truncated:a}=s3(s8(t.result));return new Map(e).set(n,{toolCallId:n,toolName:o,output:i,startedAt:r,endedAt:r,status:l,renderedResultLines:s,truncated:a||void 0})}if("running"!==i.status)return s&&s!==i.renderedResultLines?new Map(e).set(n,{...i,renderedResultLines:s}):e;let{output:a,truncated:d}=i;if(0===a.length&&null!==t.result&&void 0!==t.result){let e=s3(s8(t.result));a=e.text,d=e.truncated}return new Map(e).set(n,{...i,toolName:o,output:a,truncated:d,renderedResultLines:s,endedAt:r,status:l})}(rT.current,e));let t=e.toolCallId;tn(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"follow_up_flushed":case"follow_up_queue_changed":nc(e);break;case"follow_up_flush_error":tu({type:"error",message:e.errorMessage??"Follow-up queue flush failed"});break;case"thinking_level_changed":{let t=e.level;t&&eT.current&&eE.current===nm.current&&eW({targetSessionId:nm.current,capturedGeneration:eL.current,remoteLevel:t,source:"event"});break}case"queue_update":t3({steering:[...e.steering??[]],followUp:aa(ni()),followUpRows:ad(ni()),followUpRevision:ni().serverRevision});break;case"auto_retry_start":eF({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":eF(null),!1===e.success&&tu({type:"error",message:"string"==typeof e.finalError&&e.finalError.trim()?e.finalError.trim():t("message_apiError")});break;case"auto_compaction_start":case"compaction_start":e5(!0),e9(null),te(null);break;case"auto_compaction_end":case"compaction_end":e5(!1),e.errorMessage?(e9(e.errorMessage),te(null)):!e.aborted&&(eD(e=>e?{...e,tokens:null,percent:null}:null),te(ab(e.result,e.reason??"auto")),nm.current&&nX(nm.current,!1,!0));break;case"extension_ui_request":rw(e);break;case"extension_ui_settled":t5(e)}},[tu,nc,t5,rA,rS,rw,nX,ni,t]);let rL=(0,i.useCallback)(async(r,i,o)=>{if(v)return!1;if(et)return tu({type:"error",message:t("chat_sessionLocked")}),!1;let l=r.trim();if(!l&&!i?.length&&!o?.length||nw()||nj.current)return!1;if(nC.current)return tu({type:"info",message:t("input_branchSwitchInProgress")}),!1;let s=!i?.length&&!o?.length&&l.startsWith("/");if(!i?.length&&!o?.length&&l.startsWith("!")){let e=l.startsWith("!!"),t=(e?l.slice(2):l.slice(1)).trim();return!!t&&(await nA.current?.(t,e)??!1)}if(nO.current=!1,nk.current=!1,tn(s?{kind:"running_command"}:{kind:"waiting_model"}),nP(),f&&g.current&&m.current&&a){let e=m.current,t=g.current;a({id:ne(e),path:"",cwd:t,projectRoot:t,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:1,firstMessage:l},e)}let d=nz(),c=nr(),u=m.current,p=n?.id??(f&&u?`new:${u}`:g.current?`new:${g.current}`:"new"),h=sI({isNew:f,intentId:u,persistedSessionId:f?null:n?.id??null}),x=()=>{var e,t;return null!==h&&(e=h,t=nx.current,e&&t?e.kind===t.kind&&("new"===e.kind&&"new"===t.kind?e.intentId===t.intentId:"persisted"===e.kind&&"persisted"===t.kind&&e.sessionId===t.sessionId):!e&&!t)},y=e=>{if(!x())return!1;let n="locked"===nn(e);return n&&en(!0),tu({type:"error",message:n?t("chat_sessionLocked"):e&&"rejected"!==e?e:t("chat_sendFailed")}),tn(null),!1},b=null;try{var w;let e=(w={isNew:f,intentId:u,cwd:g.current,persistedSessionId:n?.id??null,ensuredSessionId:f?nm.current:null}).isNew?w.ensuredSessionId?{kind:"persisted",sessionId:w.ensuredSessionId}:w.intentId&&w.cwd?{kind:"new",intentId:w.intentId,cwd:w.cwd}:null:w.persistedSessionId?{kind:"persisted",sessionId:w.persistedSessionId}:null;if(!e)return!1;if("new"===e.kind){let n=ev??eb,s=await d.submitPrompt({target:e,submissionId:c,message:r,images:i,binaryBlocks:o,draftKey:p,model:n??void 0,...f&&e$?{thinkingLevel:e$}:{}});if(b=s.sessionId,x()&&(nm.current=s.sessionId,m.current===u&&n8(1,r)),"queued"===s.status)return nu(s.sessionId,s.queue),tu({type:"info",message:t("input_queuedWhileBusy")}),x()&&t1(p,l,i?.length??0),!0;if("accepted"!==s.status)return nu(s.sessionId,s.queue),y(s.error);x()&&(nO.current=!0)}else if("persisted"===e.kind){if(b=e.sessionId,nk.current)return!1;let n=await d.submitPrompt({target:e,submissionId:c,message:r,images:i,binaryBlocks:o,draftKey:p});if("queued"===n.status)return nu(e.sessionId,n.queue),tu({type:"info",message:t("input_queuedWhileBusy")}),t1(p,l,i?.length??0),!0;if("accepted"!==n.status)return x()&&nu(e.sessionId,n.queue),y(n.error);x()&&(nO.current=!0)}if(x()&&nO.current&&b&&((0,eA.dM)(`sessionQueueHold.${b}`,null),t1(p,l,i?.length??0)),x()&&s&&b){let e=d.getRunState(b)?.promptRunId;rC(b,e)}return!0}catch(r){if(nk.current||r instanceof Error&&"AbortError"===r.name)return x()&&!nO.current&&tn(null),!1;if(console.error("Failed to send message:",r),nO.current)return x()&&(nO.current=!1),tu({type:"warning",message:t("chat_sendSubmittedSwitched")}),!0;if(!x())return!1;let n=!1;{let e=nz(),t=b??nm.current;t&&(n=e.dropLocal(t,`sub:${c}`))}n&&e.chatInputRef?.current?.insertIfEmpty(l);{let e=r instanceof Error?r.message:String(r),n="locked"===nn(e);n&&en(!0),tu({type:"error",message:n?t("chat_sessionLocked"):e})}return x()&&tn(null),!1}},[f,v,et,ev,eb,n,n8,rC,tu,nP,e.chatInputRef,t,a]);nA.current=(0,i.useCallback)(async(r,i)=>{if(v)return!1;if(et)return tu({type:"error",message:t("chat_sessionLocked")}),!1;if(nw()||nj.current||nC.current)return!1;let o=`${i?"!!":"!"}${r}`,l={command:r,excludeFromContext:i,startedAt:Date.now()},s=nz(),a=++nS.current,d=n?.id??nm.current;!d&&f&&m.current&&(d=ne(m.current)),d&&s.setBashRunning(d,!0,l);try{let e=nm.current??n?.id??await n3();if(!e)throw Error("Unable to create a session for the shell command");return d=e,s.setBashRunning(e,!0,l),n8(1,o),await (0,li.$J)(e,{type:"bash",command:r,excludeFromContext:i}),await nX(e),!0}catch(t){return console.error("Failed to execute shell command:",t),tu({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(o),!1}finally{d&&nS.current===a&&s.setBashRunning(d,!1)}},[tu,v,et,n3,nX,e.chatInputRef,n8,n,t]);let rz=(0,i.useCallback)(async()=>{if(v)return;let e=f&&m.current?ne(m.current):null,t=nm.current,n=t??e;if(!n)return;if(nk.current=!0,t&&(0,eA.dM)(`sessionQueueHold.${t}`,!0),nj.current){if(!t)return;try{await (0,li.$J)(t,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}let r=nz(),i=r.cancellationFor(n);if(i){i.cancel();try{await r.abortSubmission(n)}catch{}}if(t&&!t.startsWith("pending:"))try{await (0,li.$J)(t,{type:"abort"})}catch(e){console.error("Failed to abort:",e)}},[f,v]),rW=(0,i.useCallback)(async e=>{var n,r;let{sessionId:i,model:o,thinkingLevel:l,onFailure:s}=e,a=++eZ.current;n=eG.current,eG.current={...n,[i]:a};let d=(eQ.current[i]??Promise.resolve()).catch(()=>void 0).then(async()=>{o&&await (0,li.$J)(i,{type:"set_model",provider:o.provider,modelId:o.modelId}),l&&s1(l)&&await (0,li.$J)(i,{type:"set_thinking_level",level:l})});eQ.current[i]=d;try{return await d,eG.current=am(eG.current,i,a),!0}catch(e){return r=eG.current,r[i]===a&&(s?.(),tu({type:"error",message:t("models_switchFailed",{error:e instanceof Error?e.message:String(e)})})),eG.current=am(eG.current,i,a),!1}},[tu,t]),rP=(0,i.useCallback)(async(e,t,n)=>{if(v)return;if(f){ey({provider:e,modelId:t});let r=oI(n);r&&(ez.current=!0,eL.current+=1,eC(r));let i=nm.current;if(!i&&nN.current)try{i=await nN.current??null}catch{i=null}if(!i)return;await rW({sessionId:i,model:{provider:e,modelId:t},thinkingLevel:n});return}let r=nm.current;if(!r)return;let i=e_.current,o=eX.current;n&&s1(n)&&(ez.current=!0,eL.current+=1,eC(n));let l=eL.current;eY({provider:e,modelId:t}),await rW({sessionId:r,model:{provider:e,modelId:t},thinkingLevel:n,onFailure:()=>{nm.current!==r||eL.current===l&&(eY(o),eC(i))}})},[f,v,ey,rW]),rF=(0,i.useCallback)(async()=>{if(v)return;let e=nm.current;if(e&&!e6){e5(!0),e9(null),te(null);try{let t=await (0,li.$J)(e,{type:"compact"});te(ab(t,"manual")),await nX(e,!0)}catch(e){e9(e instanceof Error?e.message:String(e)),te(null)}finally{e5(!1)}}},[e6,v,nX]),rH=(0,i.useCallback)(async e=>{let[t]=await Promise.all([fetch("/api/models",e?{signal:e}:void 0),(0,eA.zo)()]);if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();ea(n.models),eh(n.thinkingLevels??{}),eg(n.thinkingLevelMaps??{}),ex(n.authConfigured??{});let r=n.modelList??[];eu(r);let i=n.defaultModel?r.find(e=>e.id===n.defaultModel?.modelId&&e.provider===n.defaultModel?.provider):void 0,o=n.authConfigured??{},l=i??r.find(e=>!1!==o[e.provider])??r[0];ew(l?{provider:l.provider,modelId:l.id}:null)},[]),rD=(0,i.useCallback)(async(e,t)=>{let n=nm.current;if(n)try{await fetch(`/api/sessions/${encodeURIComponent(n)}/command-entry`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({command:e,ok:!0,result:t})})}catch(e){console.error("Failed to record command entry:",e)}},[]),rN=(0,i.useCallback)(async e=>{if(v||!e.startsWith("/"))return{handled:!1};let n=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!n)return{handled:!1};let[,r,i=""]=n,o=i.trim(),l=nm.current??await n3();l&&f&&n8();let s=e=>(e.handled&&(e.error?tu({type:"error",message:e.error}):"openSessionStats"!==e.action&&tu({type:"success",message:e.message??t("input_commandCompleted")})),e);try{switch(r){case"compact":{if(!l||e6)return s({handled:!0,error:"No active session to compact"});e5(!0),e9(null),te(null);let e=await (0,li.$J)(l,{type:"compact",...o?{customInstructions:o}:{}});return te(ab(e,"manual")),await rD(`/compact${o?` ${o}`:""}`,"Compacted context"),await nX(l,!0)&&n8(),s({handled:!0,message:"Compacted context"})}case"reload":if(!l)return s({handled:!0,error:"No active session to reload"});return await (0,li.$J)(l,{type:"reload"}),await rD("/reload","Reloaded session resources"),await Promise.all([nX(l,!1,!0),n5(l),n9(),rH()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!l)return s({handled:!0,error:"No active session to name"});if(!o)return s({handled:!0,error:"Usage: /name <name>"});return await (0,li.$J)(l,{type:"set_session_name",name:o}),await rD(`/name ${o}`,`Session renamed to ${o}`),await nX(l)&&n8(),s({handled:!0,message:`Session renamed to ${o}`});case"session":{if(!l)return s({handled:!0,error:"No active session"});let e=await (0,li.$J)(l,{type:"get_session_stats"});return e&&tx(e),await rD("/session","Opened session stats"),await nX(l),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!l)return s({handled:!0,error:"No active session"});let e=await (0,li.$J)(l,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await tC(t),await rD("/copy","Copied last assistant message"),await nX(l),s({handled:!0,message:"Copied last assistant message"})}default:return{handled:!1}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===r&&e5(!1)}},[tu,n3,e6,f,v,rH,nX,n9,n5,n8,h,rD]),rB=(0,i.useCallback)(e=>{switch(e){case"busy":return t("input_rejectedBusy");case"compacting":return t("input_rejectedCompacting");case"bash":return t("input_rejectedBash");case"media":return t("input_imageSendRetry");case"locked":return t("chat_sessionLocked");case"model":return t("input_rejectedModel");case"auth":return t("input_rejectedAuth");default:return t("chat_sendFailed")}},[t]),rO=(0,i.useCallback)((e,t)=>{if(!e)return;let n=nm.current;if(!n)return;let r=()=>{if(t?.writeDraft===!1)return;let r=tZ(n)??{value:"",images:[]};tQ(n,{value:[e,r.value].filter(e=>e.trim()).join("\n\n"),images:r.images})},i=t$.current.editorTakeover;x.canSendSessionCommands&&i?(0,li.$J)(n,{type:"editor_component_set_text",requestId:i.id,text:e}).then(e=>{e?.applied!==!0&&r()}).catch(r):r()},[x.canSendSessionCommands,t$]),rU=(0,i.useCallback)((t,n)=>{var r;let i=n.images??(r=n.media??[],(0,t2.kZ)(r).map(e=>(0,t2.Pk)(e))),o=e.chatInputRef?.current;if(o)return void o.restoreDraft(n.text,i.length?i:void 0,t);t===nm.current&&rO(n.text,{writeDraft:!1});let l=tZ(t)??{value:"",images:[]};tQ(t,{value:[n.text,l.value].filter(e=>e.trim()).join("\n\n"),images:[...i,...l.images]})},[e.chatInputRef,rO,tQ]),rq=(0,i.useCallback)((e,t)=>{let n=t.map(e=>e.text).filter(e=>e.trim()).join("\n\n"),r=t.flatMap(e=>e.media??[]);(n||0!==r.length)&&rU(e,{text:n,media:r})},[rU]),rK=(0,i.useCallback)(async(e,n)=>{var r,i;let o,l,s,a,d,c,u,p=al(t9.current,e),h="set"===n.kind?n.payloads:"dispatch"===n.kind?p.items.filter(e=>"claimed"!==e.state).map(at):[],f="dispatch"===n.kind&&n.extra?.trim()?{text:n.extra.trim(),...n.extraAttemptId?{attemptId:n.extraAttemptId}:{}}:null,g="set"===n.kind?n.payloads.filter(e=>!!e.attemptId):f?.attemptId?[f]:[],m=(r=t9.current,i={payloads:h,candidates:g},a=(s=al(r,e)).revision+1,d=i.payloads.map(ar),c=[...i.candidates??[]],u=i.submissionId??ao(),{book:ac(r,e,{...s,pending:[...s.pending,{revision:a,payloads:d,candidates:c,state:"sending",submissionId:u}],revision:a}),revision:a,payloads:d,candidates:c,submissionId:u});t9.current=m.book,t7.current===e&&no();let x=nt.current.catch(()=>void 0).then(async()=>{var t;let r=al(t9.current,e);if(t=m.revision,!r.pending.some(e=>e.revision===t))return{disposition:"rejected",receipt:void 0};let i=r.pending.find(e=>e.revision===m.revision),o="set"===n.kind?{type:"set_follow_up_queue",items:i?i.payloads:n.payloads,expectedRevision:r.serverRevision}:"dispatch"===n.kind?{type:"dispatch_follow_up_queue",...n.extra?.trim()?{extra:n.extra.trim()}:{},...n.extraAttemptId?{extraAttemptId:n.extraAttemptId}:{},expectedRevision:r.serverRevision}:{type:"recall_follow_up_queue",itemIds:r.items.filter(e=>"claimed"!==e.state).map(e=>e.id)},l=await (0,li.$J)(e,{...o,submissionId:m.submissionId});return{disposition:an(l),receipt:l}});nt.current=x.then(()=>void 0,()=>void 0);try{o=await x}catch(e){l=e,o={disposition:an(void 0,{error:e,definitiveRejection:li.LY}),receipt:void 0}}let v=function(e,t,n,r,i){let o=al(e,t);if(!o.pending.some(e=>e.revision===n))return{book:e,restore:[],resolved:[],uncertain:!1};if("unknown"===r)return{book:ac(e,t,{...o,pending:o.pending.map(e=>e.revision===n?{...e,state:"uncertain"}:e)}),restore:[],resolved:[],uncertain:!0};if("accepted"===r){let r,l,s,a,d,c;if(!i||null===i.revision)return{book:ac(e,t,{...o,pending:o.pending.map(e=>e.revision===n?{...e,state:"uncertain"}:e)}),restore:[],resolved:[],uncertain:!0};let u=(l=al(r=au(e,t,i),t),s=new Set(i.admittedAttemptIds??l.admittedAttemptIds),d=ah(l,n,s,a=new Set).resolved,c=ap(l.pending.filter(e=>e.revision>n),i.items,s,a),{book:ac(r,t,{...l,pending:c}),resolved:d});return{book:u.book,restore:[],resolved:u.resolved,uncertain:!1}}let l=i&&"number"==typeof i.revision?i:void 0,s=l?au(e,t,l):e,a=al(s,t),d=new Set(l?.admittedAttemptIds??a.admittedAttemptIds),c=new Set,u=l?ah(a,n,d,c):{revisions:new Set,resolved:[]},p=a.pending.filter(e=>e.revision>=n),h=[];for(let e of p)for(let t of e.candidates){let e=t.attemptId;!e||c.has(e)||d.has(e)||(c.add(e),h.push(t))}let f=a.pending.filter(e=>e.revision<n&&!u.revisions.has(e.revision));return{book:s===e&&f.length===a.pending.length?s:ac(s,t,{...a,pending:f}),restore:h,resolved:u.resolved,uncertain:!1}}(t9.current,e,m.revision,o.disposition,o.receipt?nd(o.receipt):void 0);return t9.current=v.book,v.restore.length&&rq(e,v.restore),v.resolved.length&&(rq(e,v.resolved),tu({type:"info",message:t("input_queueUnconfirmedRestored")})),t7.current===e&&no(),"accepted"===o.disposition&&rn(e),{...o,error:l,restored:v.restore.length}},[tu,rn,no,rq,nd,t]),rJ=(0,i.useCallback)(async(e,n)=>{let r=n??t7.current??nm.current;if(!r)return;let i=await rK(r,{kind:"set",payloads:e.map(e=>"string"==typeof e?{text:e}:e)});if("accepted"!==i.disposition){if("conflict"===i.disposition)throw Error(t("input_queueConflict"));if("unknown"===i.disposition)throw Error(t("input_sendResultUnknown"));throw Error(t("input_queuePersistFailed"))}},[rK,t]),rV=(0,i.useCallback)(async(e,n)=>{if(v)return;let r=nm.current;if(!r)return;let i=nz().getEventSource(r);i&&2!==i.readyState||rn(r),nP();let o={role:"user",content:(n?.length,e),timestamp:Date.now()},l=nz(),s=l.appendLocal(r,o),a=(0,t2.py)(n);try{let t=await (0,li.$J)(r,{type:"steer",message:e,...a?.length?{images:a}:{}});if(t?.status==="rejected"){l.dropLocal(r,s),rU(r,{text:e,images:n}),nm.current===r&&tu({type:"error",message:rB(t.reason)});return}t?.status==="queued"&&(nu(r,t.queue),rn(r))}catch(i){l.dropLocal(r,s),rU(r,{text:e,images:n}),nm.current===r&&tu({type:"error",message:t("input_sendResultUnknown")}),console.error("Failed to steer:",i)}},[nu,tu,rn,v,nP,e.chatInputRef,rB,rU,t]),rY=(0,i.useCallback)(e=>{let t=e instanceof Error?e.message:String(e);return/Extension command .* cannot be queued/.test(t)},[]),rX=(0,i.useCallback)(e=>e&&!1===e.ok?"conflict"in e&&e.conflict?t("input_queueConflict"):"reason"in e?rB(e.reason):t("chat_sendFailed"):t("chat_sendFailed"),[rB,t]),rG=(0,i.useCallback)(()=>{if(!x.canSendSessionCommands)return;let e=t$.current.editorTakeover,t=nm.current;e&&t&&(0,li.$J)(t,{type:"editor_takeover_dismiss",requestId:e.id,clientId:lb()}).catch(()=>{})},[x.canSendSessionCommands,t$]),rZ=(0,i.useCallback)(()=>{if(!x.canSendSessionCommands)return;let e=t$.current.editorTakeover,t=nm.current;if(!e||!t)return;let n=tZ(t)?.value??"";(0,li.$J)(t,{type:"editor_component_set_text",requestId:e.id,text:n}).catch(()=>{})},[x.canSendSessionCommands,t$]),rQ=(0,i.useCallback)((e,t,n)=>{if(!x.canSendSessionCommands)return;let r=n??nm.current;r&&e&&(0,li.$J)(r,{type:"editor_takeover_view",requestId:e,shown:t,clientId:lb()}).catch(()=>{})},[x.canSendSessionCommands]),r0=(0,i.useCallback)(async(e,t)=>{if(!x.canSendSessionCommands)return;let n=nm.current;if(n&&t$.current.editorTakeover?.id===e.id)try{await (0,li.$J)(n,{type:"editor_component_input",data:t,clientId:lb()})}catch(e){console.error("Failed to send extension editor component input:",e)}},[x.canSendSessionCommands,t$]);ry.current=(0,i.useCallback)(async e=>{let t="string"==typeof e?e:"";if(t.trim()){if(nw()||nj.current||e8.current)return void nM.current?.(t,"followUp",void 0);{let e=await nE.current?.(t);if(e?.handled){e.error&&rO(t);return}!1===await nT.current?.(t)&&rO(t)}}},[rO]),nE.current=rN,rb.current=r0;let r1=(0,i.useCallback)(async(n,r,i)=>{if(v)return;let o=nm.current;if(!o)return;let l=(0,t2.py)(i),s=(r,l)=>{let s=e.chatInputRef?.current;s?s.restoreDraft(n,i,o):rU(o,{text:n,images:i}),nm.current===o&&tu({type:"error",message:r?rB(r):l??t("chat_sendFailed")})};if(n.trim().startsWith("/")){try{let e=await (0,li.$J)(o,{type:"prompt",message:n,...l?.length?{images:l}:{}});e?.status==="rejected"?s(e.reason):e?.status==="queued"&&(nu(o,e.queue),rn(o))}catch(e){s(void 0,e instanceof Error?e.message:String(e))}return}if("followUp"===r)return void await nR.current(n,i);try{let e=await (0,li.$J)(o,{type:"steer",message:n,...l?.length?{images:l}:{}});if(e?.status==="rejected")return void s(e.reason);if(e?.status==="queued"){nu(o,e.queue),rn(o);return}}catch(e){if(rY(e)){try{let e=await (0,li.$J)(o,{type:"prompt",message:n,...l?.length?{images:l}:{}});e?.status==="rejected"?s(e.reason):e?.status==="queued"&&nu(o,e.queue)}catch(e){s(void 0,e instanceof Error?e.message:String(e))}return}s(void 0,e instanceof Error?e.message:String(e)),console.error("Failed to steer:",e)}},[nu,tu,rn,rY,v,e.chatInputRef,rB,rU,t]),r2=(0,i.useCallback)(async(e,n)=>{if(v)return;let r=nm.current;if(!r)return;let i=e.trim();if(!i&&!n?.length)return;let o=nw()||e6;nP();let l=function(e,t){let n=ao();if(!t?.length)return e?[{text:e,attemptId:n}]:[];let r=t.flatMap(e=>(0,t2.I9)(e));return 0===r.length?null:[{text:e,media:r,attemptId:n}]}(i,n),s=()=>rU(r,{text:i,images:n}),a=e=>{nm.current===r&&tu({type:"error",message:e})},d=async()=>{if(!l)return{ok:!1,error:t("input_queueMediaMissing")};let e=al(t9.current,r);try{let t;return await rJ([...(t=as(e))?t.payloads:e.items.filter(e=>"claimed"!==e.state).map(at),...l],r),{ok:!0}}catch(r){let e=r instanceof Error?r.message:String(r),n=e===t("input_queueConflict")||e===t("input_queuePersistFailed");return console.error("Failed to write follow-up queue:",r),{ok:!1,error:n?e:t("input_sendResultUnknown")}}};if(n?.length&&o){let e=await d();return e.ok?void rn(r):void a(e.error)}if(n?.length||!o){let e=(0,t2.py)(n);try{let t=await (0,li.$J)(r,{type:"prompt",message:i,...e?.length?{images:e}:{}});if(t?.status==="queued"){nu(r,t.queue),rn(r);return}if(t?.status==="rejected"){var c;if(c=t.reason,"busy"!==c&&"compacting"!==c&&"bash"!==c){s(),a(rB(t.reason));return}let e=await d();if(!e.ok)return void a(e.error);rn(r)}}catch(e){console.error("Failed to send prompt:",e),s(),a(t("input_sendResultUnknown"))}return}let u=await d();u.ok?rn(r):a(u.error)},[nu,tu,rn,e6,v,nP,rB,rU,t,rJ]);nR.current=r2,nT.current=rL,nM.current=r1;let r4=(0,i.useCallback)(async()=>{if(v||!e6)return;let e=nm.current;if(e)try{await (0,li.$J)(e,{type:"abort_compaction"}),e5(!1),e9(null),te(null)}catch(e){e9(e instanceof Error?e.message:String(e))}},[e6,v]),r6=(0,i.useCallback)(async()=>{if(v)return;let e=nm.current;if(!e)return;let n=al(t9.current,e);if(!n.items.some(e=>"claimed"!==e.state)&&!n.pending.length)return;let r=await rK(e,{kind:"recall"});if("accepted"!==r.disposition){nm.current===e&&tu({type:"error",message:"rejected"===r.disposition?t("input_queueRecallFailed"):t("input_sendResultUnknown")});return}let i=(r.receipt?.recalled??[]).map(at);i.length&&rq(e,i),(r.receipt?.skipped??[]).length&&nm.current===e&&tu({type:"info",message:t("input_queueRecallPartial")})},[tu,v,rq,rK,t]),r5=(0,i.useCallback)(async e=>{var n;if(v)return;let r=nm.current;if(!r)return;let i=al(t9.current,r),o=(n=aa(i),[...n,...e?.trim()?[e.trim()]:[]].map(e=>e.trim()).filter(e=>e.length>0).join("\n")),l=i.items.some(e=>"claimed"!==e.state&&e.media?.length);if(!o&&!l&&!e?.trim())return;nP();let s=nz(),a=o?s.appendLocal(r,{role:"user",content:o,timestamp:Date.now()}):null,d=e?.trim()?e:void 0,c=d?ao():void 0,u=await rK(r,{kind:"dispatch",extra:d,extraAttemptId:c});"accepted"===u.disposition?rn(r):(a&&s.dropLocal(r,a),nm.current===r&&tu({type:"error",message:"unknown"===u.disposition?t("input_sendResultUnknown"):rX(u.receipt)}))},[tu,rn,v,nP,rX,rK,t]),r8=(0,i.useCallback)(async e=>{if(v)return;let t=e_.current;ez.current=!0,eL.current+=1;let n=eL.current,r=nm.current;eC(e);let i=nm.current??await nN.current;i&&await rW({sessionId:i,thinkingLevel:e,onFailure:()=>{nm.current!==(r??i)||eL.current===n&&eC(t)}})},[rW,v]),r3=(0,i.useCallback)(async e=>{if(v||nw()||nj.current||nC.current)return;let t=nm.current;if(t)try{await (0,li.$J)(t,{type:"prompt",message:e}),await nX(t,!1,!0)}catch(e){console.error("Workspace history prompt failed:",e),tu({type:"error",message:String(e)})}},[tu,v,nX]),r9=(0,i.useCallback)(async()=>{await r3("/undo")},[r3]),r7=(0,i.useCallback)(async()=>{await r3("/redo")},[r3]),ie=(0,i.useCallback)(async e=>{let t="string"==typeof e?e.trim():"",n=t?`/checkpoint ${t}`:"/checkpoint";await r3(n)},[r3]),it=(0,eA.Fd)(),ir=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=nm.current;if(!e)return;let t=!1;return fetch("/api/preferences",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(n=>{if(t||nm.current!==e)return;let r=sT(n?.prefs,e);null!==r&&(nl(e,{items:r.items,revision:r.revision}),ir.current=JSON.stringify(r.items),t7.current===e&&no())}).catch(()=>void 0),()=>{t=!0}},[nl,no,n?.id]),(0,i.useEffect)(()=>{let e=nm.current;if(!e)return;let t=sT(it,e);if(null===t)return;let n=JSON.stringify(t.items);n!==ir.current&&(nl(e,{items:t.items,revision:t.revision}),ir.current=n,t7.current===e&&no())},[nl,no,it,n?.id]),(0,i.useEffect)(()=>{var e;tP({...0===sM(e=t$.current).length&&!e.dialog?e:{...e,dialog:null,blockingQueue:[]},customUi:null,editorTakeover:null,statuses:[],widgets:[],header:null,footer:null,terminalInputListenerCount:0,autocompleteProviderCount:0,autocompleteTriggerCharacters:[],workingMessage:null,workingVisible:!0,workingIndicator:null,hiddenThinkingLabel:null,toolsExpanded:null,toolsExpandedRevision:0}),tB(),th()},[n?.id,r,tP,t$,tB,th]);let ii=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=ii.current,t=n?.id??null;e&&e!==t&&(nv.current?.abort(),nv.current=null),ii.current=n&&!0!==n.readOnly?n.id:null},[n?.id,n?.readOnly]),(0,i.useEffect)(()=>{var e,t;e={sessionId:nm,newSessionPromoted:nB,promptSubmitted:nO,ensuringNewSession:nN},t=n?.id??null,e.sessionId.current=t,e.newSessionPromoted.current=!1,e.promptSubmitted.current=!1,e.ensuringNewSession.current=null,nF(),W([]),nb.current=[],P([]),H([]),b(null),A(null),J.current=!1,_(!1),V.current=!1,R(!1),X({type:"reset"}),ee({}),en(!1),eF(null),e5(!1),eq(null),eD(null),eY(null),ey(null),e1((n?.id?e2.current.get(n.id):void 0)??null),eL.current+=1,ez.current=!1,eC(null),eE.current=null,eR(!1),n?.id||eR(!0);let r=n?.id??null;t7.current=r,t3({steering:[],followUp:aa(al(t9.current,r??"")),followUpRows:ad(al(t9.current,r??"")),followUpRevision:r?al(t9.current,r).serverRevision:null}),ir.current=null;let i=nz(),l=n?.id??(f&&o?ne(o):null),s=null;if(l?(n?.readOnly!==!0&&(ng.current=i.attach(l,e=>{nI.current?.(e)})),s=i.subscribe(l,e=>{if(!nm.current||e.sessionId===nm.current||e.sessionId===l){if(W(e.messages),P(e.entryIds),H(e.messageKeys),ee(e.turnMetrics),nb.current=e.entryIds,n?.readOnly===!0){Z(!1),ei(!1),nj.current=!1,el(null),X({type:"end"}),nf.current=null;return}Z(e.agentRunning),e.streamState.isStreaming?X({type:"update",message:e.streamState.streamingMessage??null}):X({type:"end"}),ei(e.bashRunning),nj.current=e.bashRunning,el(e.pendingBash),nf.current=i.getEventSource(e.sessionId)}})):(Z(!1),ei(!1),nj.current=!1,el(null)),n)if(!0===n.readOnly)nX(n.id,!0,!1);else{let e=null!=l&&(i.getSnapshot(l)?.messages.length??0)>0,t=l?i.getRunState(l):null;nX(n.id,!e,!0).then(e=>{if(!0===e)return;let r=i.getRunState(n.id);if(e?.activeRun===!1&&!0!==e.lockedByOther&&t?.agentRunning&&!t.sendInFlight&&r?.agentRunning&&r.promptRunId===t.promptRunId&&(i.completeRun(n.id,r.promptRunId),tn(null),eF(null)),(e?.running||e?.live)&&(n5(n.id),(e.state?.isStreaming||e.state?.isPromptRunning)&&(nz().importRunningRun(n.id),tn(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),!e.state.isStreaming&&e.state.isPromptRunning&&rC(n.id)),e.state?.isBashRunning&&(nz().setBashRunning(n.id,!0,e.state.pendingBash??null),r_(n.id))),e?.lockedByOther!==void 0&&en(e.lockedByOther),e?.state){let t=af({sessionId:n.id},{sessionId:nm.current});t&&void 0!==e.state.isCompacting&&e5(e.state.isCompacting),t&&void 0!==e.state.contextUsage&&eD(e.state.contextUsage??null),rk(n.id,e.state),t&&void 0!==e.state.systemPrompt&&eq(e.state.systemPrompt??null),t&&s1(e.state.thinkingLevel)&&eW({targetSessionId:n.id,capturedGeneration:eL.current,remoteLevel:e.state.thinkingLevel,source:"live-hydrate"}),void 0!==e.state.queuedMessages&&na(n.id,e.state.queuedMessages),t&&t6(e.state)}})}return()=>{n_.current+=1,N.current?.abort(),N.current=null,s?.();let e=l??nm.current??n?.id;e&&ng.current&&(nz().detach(e,ng.current),ng.current=null)}},[n?.id,n?.readOnly,o,f,nF,tJ,t6]),(0,i.useEffect)(()=>{p?.(eO)},[eO,p]),(0,i.useEffect)(()=>{u&&u(y?.tree??[],M,ru,rv)},[y?.tree,M,ru,rv,u]),(0,i.useEffect)(()=>{let e=new AbortController;return rH(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rH,c]),(0,i.useEffect)(()=>{let e=!1;return fetch("/api/agent-settings").then(e=>e.json()).then(t=>{!e&&s1(t.defaultThinkingLevel)&&ej(t.defaultThinkingLevel)}).catch(()=>void 0),()=>{e=!0}},[]),(0,i.useEffect)(()=>{if(!e3)return;let e=setTimeout(()=>e9(null),3e3);return()=>clearTimeout(e)},[e3]),(0,i.useEffect)(()=>{if(!e7)return;let e=setTimeout(()=>te(null),6e3);return()=>clearTimeout(e)},[e7]),(0,i.useEffect)(()=>{tx(null)},[z.length,eH?.tokens,eH?.percent,eH?.contextWindow]),{data:y,loading:w,historyLoading:j,hasMoreBefore:C,error:T,activeLeafId:M,messages:z,entryIds:$,messageKeys:F,streamState:Y,agentRunning:G,turnMetrics:Q,lockedByOther:et,modelNames:es,modelList:ed,modelAuthConfigured:em,modelThinkingLevels:ep,modelThinkingLevelMaps:ef,newSessionModel:ev,thinkingLevel:e$,thinkingReady:eI,defaultThinkingLevel:f?ek:null,retryInfo:eP,contextUsage:eH,systemPrompt:eO,forkingEntryId:eK,isCompacting:e6,compactError:e3,compactResult:e7,currentModel:nK,displayModel:nJ,sessionStats:nY,slashCommands:to,slashCommandsLoading:ts,queuedMessages:t8,notices:td,liveNoticeActivities:tc,dismissNotice:tf,toggleNoticePin:tg,extensionDialog:tv,extensionCustomUi:ty,extensionEditorTakeover:tb,extensionStatuses:tw,extensionWidgets:tk,extensionHeader:tj,extensionFooter:t_,extensionTerminalInputListenerCount:tI,extensionShortcuts:tR,extensionWorkingMessage:tM,extensionWorkingVisible:tA,extensionWorkingIndicator:tL,hiddenThinkingLabel:tz,extensionToolsExpandedRequest:tW,respondToExtensionUi:rr,dismissExtensionUiRequest:tH,sendExtensionCustomInput:ri,sendExtensionCustomMouse:ro,sendExtensionCustomBounds:rl,sendExtensionWidgetMouse:rs,sendExtensionEditorInput:r0,runExtensionShortcut:ra,todos:nq,isAutoModelSelection:f&&null===ev,agentPhase:tt,toolExecutionSnapshots:tr,isNew:f,sessionIdRef:nm,eventSourceRef:nf,scrollContainerRef:nL,jumpButtonVisible:nW,jumpToBottom:n$,loadOlderHistory:n0,retryLoadSession:nG,loadNewerHistory:n6,hasMoreAfter:I,jumpToEntry:n4,notifyBrowsingHistory:nD,handleSend:rL,handleAbort:rz,handleFork:rd,handleNavigate:rc,handleModelChange:rP,handleCompact:rF,handleSteer:rV,handleFollowUp:r2,handlePromptWithStreamingBehavior:r1,handleAbortCompaction:r4,handleRecallQueue:r6,handleSendQueueAsSteer:r5,handleBuiltinSlashCommand:rN,dismissEditorTakeover:rG,reenterEditorTakeover:rZ,reportEditorTakeoverView:rQ,handleThinkingLevelChange:r8,loadTools:n5,loadSlashCommands:n9,loadCommandArgumentCompletions:n7,setActiveLeafId:A,setData:b,setMessages:W,loadCompletionSuggestions:re,applyCompletionSuggestion:rt,extensionAutocompleteProviderCount:tT,extensionAutocompleteTriggerCharacters:tE,dispatch:X,setAgentRunning:Z,setForkingEntryId:eJ,bashRunning:er,pendingBash:eo,handleWorkspaceUndo:r9,handleWorkspaceRedo:r7,handleWorkspaceCheckpoint:ie,handleBranchHere:rp,handleBranchFromAssistant:rh,handleNewSessionFromHere:rf,handleNewSessionFromAnswer:rg,branchBusy:np,branchActions:rv,navigateBranch:rm,setBranchLabel:rx,handleAgentEventRef:nI}}({session:e,newSessionCwd:D,newSessionIntentId:n,onAgentEnd:O,onAgentRunningChange:c,onSessionCreated:u,onSessionForked:p,modelsRefreshKey:h,chatInputRef:f,onBranchDataChange:g,onSystemPromptChange:m,onSessionStatsPanelOpen:v,isMobile:W,editorTakeoverDisplayedRef:U}),tL=!!eL||!!(ez&&!ez.hidden),[tz,tW]=(0,i.useState)(!0),[t$,tP]=(0,i.useState)(!1),[tF,tH]=(0,i.useState)(!1);(0,i.useEffect)(()=>{tW(ed()),tH(!0);let e=()=>tW(ed());return window.addEventListener(es,e),window.addEventListener("storage",e),()=>{window.removeEventListener(es,e),window.removeEventListener("storage",e)}},[]);let tD=eW?.id??null;(0,i.useEffect)(()=>{tP(!1)},[tD]);let tN={hasTakeover:!!eW,enabled:tF&&tz,dismissed:t$,isMobile:W,isReadOnly:$,lockedByOther:to,hasDialog:!!eL},tB=!!tN.hasTakeover&&!!tN.enabled&&!tN.dismissed&&!tN.isMobile&&!tN.isReadOnly&&!tN.lockedByOther&&!tN.hasDialog,tO=!!tN.hasTakeover&&!!tN.dismissed&&!!tN.enabled&&!tN.isMobile&&!tN.isReadOnly&&!tN.lockedByOther&&!tN.hasDialog,tU=(0,i.useCallback)(()=>q.current,[]),tq=(0,i.useCallback)(e=>{q.current=e},[]);U.current=tB;let tK=(0,i.useRef)(null);(0,i.useEffect)(()=>{var t;let n=e?.id??null,r=n&&tD?{sessionId:n,requestId:tD}:null,i=(t=tK.current,!t||r&&r.sessionId===t.sessionId&&r.requestId===t.requestId?null:t);tK.current=r,i&&tR?.(i.requestId,!1,i.sessionId),r&&tR?.(r.requestId,tB,r.sessionId)},[tD,tB,e?.id,tR]),(0,i.useEffect)(()=>()=>{let e=tK.current;e&&tR?.(e.requestId,!1,e.sessionId)},[tR]),(0,i.useEffect)(()=>{let t=e?.id??null;if(tD&&t){var n;let e,r,i;return e=(n={readShown:()=>!0===U.current,report:e=>tR?.(tD,e,t),intervalMs:1e4}).setIntervalFn??((e,t)=>setInterval(e,t)),r=n.clearIntervalFn??(e=>clearInterval(e)),i=e(()=>n.report(!0===n.readShown()),n.intervalMs),()=>r(i)}},[tD,e?.id,tR]);let tJ=tB&&!tL;!function(e){let{shortcuts:t,enabled:n,onRun:r}=e;(0,i.useEffect)(()=>{if(!n)return;let e=t.filter(e=>e.available);if(0===e.length)return;let i=t=>{let n=function(e,t){if(t.defaultPrevented||t.repeat||t.isComposing)return null;for(let n of e)if(n.available&&function(e,t){let n=sy(e);if(!n)return!1;let r=function(e){let t="string"==typeof e.key?e.key:"";if(0===t.length)return null;let n=null;if(1===t.length)n=t.toLowerCase(),e.shiftKey&&sw[t]&&(n=sw[t]);else{let e=t.toLowerCase();n=sb[e]??(sv.test(e)?e:null)}if(!n)return null;let r=[];return e.ctrlKey&&r.push("ctrl"),e.altKey&&r.push("alt"),e.shiftKey&&r.push("shift"),e.metaKey&&r.push("super"),r.push(n),r.join("+")}(t);return null!==r&&r===n}(n.key,t))return n;return null}(e,t);n&&(t.preventDefault(),r(n.key))};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[n,r,t])}({shortcuts:eN,enabled:!$&&!tL&&!tB&&!!e8.current,onRun:e0}),function(e){let{sessionId:t,hiddenPanelRouting:n,surfaceRouting:r,takeoverKeytrap:o}=e,l=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!t||!n&&!r)return;let e=()=>{l.current=Date.now()+80},i=e=>{var i;if(e.defaultPrevented)return;let s=Date.now(),a=lh(e,l.current,s);if(a)return;if(n&&!e.metaKey&&("Escape"===e.key||/^F([1-9]|1[0-2])$/.test(e.key)||(e.altKey?1===e.key.length:!!e.ctrlKey&&1===e.key.length&&!ld(e)&&!la(e)))&&!o?.()?.contains(e.target)){let n=lx(e);if(!n)return;e.preventDefault(),e.stopPropagation(),(0,li.$J)(t,{type:"terminal_input",data:n}).catch(()=>{});return}if(!r||"route"!=((i={key:e.key,ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey,composing:a,domOwned:function(e,t){if(!e&&!t)return!1;if(t&&!lf(t)&&e&&function(e,t){if(e===t)return!0;if("function"!=typeof t.contains)return!1;try{return!0===t.contains(e)}catch{return!0}}(e,t))return!0;if(e&&"function"==typeof e.closest)try{return null!==e.closest('[data-pidance-modal="true"]')}catch{return!0}return!1}(e.target,document.activeElement)}).composing||i.domOwned||i.metaKey||"Tab"===i.key||ld(i)||la(i)?"ignore":"route"))return;let d=lx(e)??(lc(e)?e.key:null);d&&(e.preventDefault(),e.stopPropagation(),(0,li.$J)(t,{type:"terminal_input",data:d}).catch(()=>{}))};return window.addEventListener("keydown",i,!0),window.addEventListener("compositionend",e,!0),()=>{window.removeEventListener("keydown",i,!0),window.removeEventListener("compositionend",e,!0)}},[t,n,r,o])}({sessionId:e8.current,hiddenPanelRouting:!!ez?.hidden&&eD>0,takeoverKeytrap:tU,surfaceRouting:tL&&eD>0&&!$});let tV=(0,i.useRef)(!1);(0,i.useLayoutEffect)(()=>{var e;let t=tV.current;tV.current=tL,(e={wasSurfaceActive:t,surfaceActive:tL,activeElement:document.activeElement}).wasSurfaceActive&&!e.surfaceActive&&(!e.activeElement||lf(e.activeElement))&&f?.current?.focus()},[tL,f]),function(e){let{sessionId:t,containerRef:n,enabled:r=!0}=e,o=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(!r||!t)return;o.current=null;let e=!1,i=0,l=0,s=null,a=null,d=null,c=null,u=r=>{var i;let s=function(e){var t;let n=window.getComputedStyle(e),r=(Number.parseFloat(n.paddingLeft)||0)+(Number.parseFloat(n.paddingRight)||0),i=n2(e);return null===i?null:(t=e.clientWidth-r,t>0&&i>0?Math.min(240,Math.max(40,Math.floor(t/i))):null)}(r),d=function(e){var t;let n=window.getComputedStyle(e),r=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0),i=n4(e);return null===i?null:(t=e.clientHeight-r,t>0&&i>0?Math.min(200,Math.max(10,Math.floor(t/i))):null)}(r);if(null===s||null===d)return;let c={sessionId:t,width:s,rows:d};i=o.current,(!i||i.sessionId!==c.sessionId||i.width!==c.width||Math.abs(i.rows-c.rows)>1)&&(o.current=c,(0,li.$J)(t,{type:"set_render_size",width:s,rows:d}).catch(()=>{o.current=null,e||l>=3||(l+=1,a&&clearTimeout(a),a=setTimeout(()=>{a=null;let t=n.current;!e&&t&&u(t)},2e3))}))};return!function t(){if(e)return;let r=n.current;if(!r){if(i>=40)return;i+=1,s=setTimeout(()=>{s=null,t()},250);return}c!==r&&(d?.disconnect(),c=r,u(r),(d=new ResizeObserver(()=>u(r))).observe(r))}(),()=>{e=!0,s&&clearTimeout(s),a&&clearTimeout(a),d?.disconnect(),d=null,c=null}},[n,r,t])}({sessionId:e?.id??e8.current,containerRef:e3,enabled:!$});let[tY,tX]=(0,i.useState)(null),tG=(0,i.useRef)(null),t0=(0,i.useRef)(null),t6=function({scrollContainer:e,resolveMessageElementRef:t,jumpToEntry:n,railHandleRef:r,notifyBrowsingHistory:o}){let[l,s]=(0,i.useState)(null),a=(0,i.useRef)(null),d=(0,i.useRef)(0);return{jumpTo:(0,i.useCallback)(async i=>{let l=e.current;if(!l)return!1;r.current?.setActive(i),a.current=i,window.setTimeout(()=>{a.current===i&&(a.current=null)},5e3);let c=++d.current,u=()=>d.current===c,p=()=>t.current?.(i)??null,h=e=>{var n,r,i,o;let s;return n=l,r=e,i=e=>t.current?.(e)??null,!!(s=i?.(r.entryId)??function(e,t){let n=aC(t),r=e.querySelector(`[data-chat-anchor="${n}"]`);if(r)return r;let i=t.indexOf(":"),o=i>=0?aC(t.slice(i+1)):n;return e.querySelector(`[data-message-entry-id="${o}"]`)}(n,r.entryId))&&!!s.isConnected&&(n.scrollTop=(o={elementTop:s.getBoundingClientRect().top,containerTop:n.getBoundingClientRect().top,scrollTop:n.scrollTop,offset:r.offset}).elementTop-o.containerTop+o.scrollTop-o.offset,!0)},f=(e,t)=>{let n=()=>e.getBoundingClientRect().top-l.getBoundingClientRect().top+l.scrollTop,o=!1,s=()=>{o=!0},d=()=>{l.removeEventListener("wheel",s),l.removeEventListener("pointerdown",s),l.removeEventListener("keydown",s),a.current===i&&(a.current=null)},c=(t,i)=>{if(o||!u()||!e.isConnected){d(),r.current?.syncActive();return}if(Math.abs(e.getBoundingClientRect().top-l.getBoundingClientRect().top)>2){if(i>=12){d(),r.current?.syncActive();return}l.scrollTo({top:n(),behavior:"auto"}),window.setTimeout(()=>c(0,i+1),100);return}if(t>=3){d(),r.current?.syncActive();return}window.setTimeout(()=>c(t+1,i+1),100)},p=(r=0,i=NaN,s=0)=>{if(!u()||!e.isConnected||o)return void d();t?.anchor&&h(t.anchor);let a=n(),f=2>Math.abs(a-i)?s+1:0;if(f>=2||r>20){l.scrollTo({top:a,behavior:"smooth"});let t=(n,r)=>{if(o||!u()||!e.isConnected)return void d();let i=l.scrollTop;r>=3?c(0,0):window.setTimeout(()=>t(i,1>Math.abs(i-n)?r+1:0),60)};window.setTimeout(()=>t(l.scrollTop,0),60);return}requestAnimationFrame(()=>p(r+1,a,f))};if(l.addEventListener("wheel",s,{passive:!0}),l.addEventListener("pointerdown",s,{passive:!0}),l.addEventListener("keydown",s),t?.instantAtTarget){l.scrollTop=n(),c(0,0);return}requestAnimationFrame(()=>p())},g=async()=>{for(let e=0;e<10&&u();e+=1){let e=p();if(e)return e;await new Promise(e=>requestAnimationFrame(()=>e(null)))}return null},m=!1,x=await g();if(x)return o(),m=!0,f(x),!0;s(i);let v=function(e){let t=e.getBoundingClientRect().top,n=null,r=null;for(let i of e.querySelectorAll("[data-chat-anchor], [data-message-entry-id]")){let e=i.getAttribute("data-chat-anchor")||i.getAttribute("data-message-entry-id");if(!e)continue;let o=i.getBoundingClientRect().top-t;if(n??={entryId:e,offset:o},o>1)break;r={entryId:e,offset:o}}return r??n}(l);try{if(!await n(i)||!u())return!1;let e=await g();if(e&&u()){m=!0;let t=null!==v&&h(v);f(e,t&&v?{anchor:v}:{instantAtTarget:!0})}}finally{u()&&s(null),m||a.current!==i||(a.current=null)}return m},[n,t,e,r,o]),jumpingTo:l,jumpPinRef:a}}({scrollContainer:e3,resolveMessageElementRef:tG,jumpToEntry:tn,railHandleRef:t0,notifyBrowsingHistory:tr}),t5=(0,i.useRef)(t6.jumpTo),t8=(0,i.useRef)(S);(0,i.useEffect)(()=>{t5.current=t6.jumpTo,t8.current=S}),(0,i.useEffect)(()=>{if(!j||j.sessionId!==e?.id||K)return;let t=j.entryId,n=!1,r=0,i=async()=>{if(n)return;let e=await t5.current(t);if(!n){if(e||(r+=1)>=8)return void(n||t8.current?.());window.setTimeout(()=>void i(),250)}};return i(),()=>{n=!0}},[j,e?.id,K]);let t3=e?.id??null,t9=function(e,t){for(let n=Math.min(e.length,t.length)-1;n>=0;n-=1){if(e[n]?.role!=="user")continue;let r=t[n];if(r)return r}return null}(G,Z);(0,i.useEffect)(()=>{if(!t3)return void tX(null);let e=new AbortController;return fetch(`/api/sessions/${encodeURIComponent(t3)}/outline`,{signal:e.signal,cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{!e.signal.aborted&&t&&tX({sessionId:t3,items:Array.isArray(t.userMessages)?t.userMessages:[]})}).catch(()=>{}),()=>e.abort()},[t3,G.length,t9,et]);let t7=(0,i.useMemo)(()=>(function(e){let{outline:t,loadedUsers:n,isAtLiveTail:r}=e;if(!r||0===n.length)return t.slice();let i=new Set(t.map(e=>e.entryId)),o=n.filter(e=>e.entryId);if(0===t.length)return o.map((e,t)=>({...e,ordinal:t}));let l=-1;for(let e=o.length-1;e>=0;e-=1)if(i.has(o[e].entryId)){l=e;break}let s=(l>=0?o.slice(l+1):o).filter(e=>!i.has(e.entryId));return 0===s.length?t.slice():[...t,...s.map((e,n)=>({...e,ordinal:t.length+n}))]})({outline:function(e){let{sessionId:t,ownerId:n,items:r}=e;return t&&t===n?r.slice():[]}({sessionId:t3,ownerId:tY?.sessionId??null,items:tY?.items??[]}),loadedUsers:function(e,t){let n=[],r=Math.min(e.length,t.length);for(let o=0;o<r;o+=1){let r=e[o],l=t[o];if(r?.role==="user"&&l){var i;n.push({entryId:l,ordinal:n.length,text:"string"==typeof(i=r.content)?i:Array.isArray(i)?i.filter(e=>e?.type==="text"&&"string"==typeof e.text).map(e=>e.text).join("\n"):"",..."number"==typeof r.timestamp?{timestamp:r.timestamp}:{}})}}return n}(G,Z),isAtLiveTail:!ti}),[t3,tY,G,Z,ti]),nt=$||to,ni=!eL&&!($&&e)&&!to,no=et||er||ev,nl=ee.isStreaming&&ee.streamingMessage?{message:ee.streamingMessage,isActive:!0}:void 0,na=function(e){let{messages:t,isStreaming:n,liveSlot:r}=e,i=rn(t,!!(r?.isActive&&r.message)),o=[];for(let e=0;e<i;e++)o.push(rt(t,e,n));r?.isActive&&r.message&&o.push({kind:"message",source:"live",messageIndex:null,messageOverride:r.message,keyPrefix:"live",attachRef:!1,showTimestamp:!1});for(let e=i;e<t.length;e++)o.push(rt(t,e,n));return o}({messages:G,isStreaming:ee.isStreaming,liveSlot:nl}),nd=na.some(e=>"live"===e.source&&e.messageOverride?.role==="assistant"),nc=(()=>{if(!eO)return null;if(er&&!ei)return`${E("chat_runningCommand")}...`;if(!et||ee.streamingMessage)return null;let e=e4?.kind;return"running_tools"===e||"running_command"===e?null:eB??function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?`${t("chat_runningTool")}...`:1===n.length?`${t("chat_runningNamed",{name:n[0]})}...`:n.length<=3?`${t("chat_runningNamed",{name:n.join(", ")})}...`:`${t("chat_runningNamed",{name:`${n.slice(0,2).join(", ")} (+${n.length-2})`})}...`}return e?.kind==="waiting_model"?`${t("chat_waitingModel")}...`:e?.kind==="running_command"?`${t("chat_runningCommand")}...`:`${t("chat_thinking")}...`}(e4,E)})(),nu=eq?.frames??null,[np,nh]=(0,i.useState)(0);(0,i.useEffect)(()=>{if(!nu||nu.length<=1)return;let e=Math.max(16,eq?.intervalMs??120),t=window.setInterval(()=>{nh(e=>(e+1)%nu.length)},e);return()=>window.clearInterval(t)},[nu,eq?.intervalMs]);let[nf,ng]=(0,i.useState)(!0),nm=e?.id??(D?`new:${D}`:"new-session");(0,i.useEffect)(()=>{ng(!0)},[nm]),(0,i.useEffect)(()=>{l=no?ts:null},[no,ts]);let nx=(0,i.useRef)(null),nv=(0,i.useRef)(null);(0,i.useEffect)(()=>{nv.current=null},[e?.id]),(0,i.useEffect)(()=>{let e=nx.current,t=e3.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&!J&&V&&(nv.current=t.scrollHeight-t.scrollTop,te().then(e=>{e||(nv.current=null)}))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[e3,V,J,te]),(0,i.useLayoutEffect)(()=>{let e=nv.current;if(null===e)return;let t=e3.current;if(!t)return;nv.current=null;let n=Math.max(0,t.scrollHeight-e);Math.abs(n-t.scrollTop)>1&&(t.scrollTop=n)},[G.length,na.length,e3]);let ny=ek?[ek.sessionId,ek.sessionFile??"",ek.sessionName??"",ek.userMessages,ek.assistantMessages,ek.toolCalls,ek.toolResults,ek.totalMessages,ek.tokens.input,ek.tokens.output,ek.tokens.cacheRead,ek.tokens.cacheWrite,ek.tokens.total,ek.cost??0].join("|"):null,nb=(0,i.useRef)(ek);nb.current=ek,(0,i.useEffect)(()=>{x?.(nb.current)},[ny,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]);let nw=ek?.contextUsage??em??null,nk=em?`${em.percent??"null"}|${em.contextWindow}|${em.tokens??"null"}`:null,nj=(0,i.useRef)(em);nj.current=em,(0,i.useEffect)(()=>{y?.(nj.current)},[nk,y]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let nS=`${en.ttftMs??""}|${en.tokensPerSecond??""}`,nC=(0,i.useRef)(en);nC.current=en,(0,i.useEffect)(()=>{b?.(nC.current)},[nS,b]),(0,i.useEffect)(()=>()=>{b?.({})},[b]);let{isDragOver:n_,handleDragEnter:nI,handleDragOver:nR,handleDragLeave:nT,handleDrop:nE}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),o=e=>Array.from(e.dataTransfer.types).includes("Files"),l=(0,i.useCallback)(e=>{o(e)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{o(e)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:l,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{nt||f?.current?.addFiles(e)},[nt,f])),nM=(R=G.filter(e=>"user"===e.role||"assistant"===e.role).length,(T=(0,i.useRef)([])).current=Array(R).fill(null).map((e,t)=>T.current[t]??null),T),nA=e5&&0===G.length&&!ee.isStreaming&&!no,nL=e?.cwd??D??void 0,nW=ew?eu[`${ew.provider}:${ew.modelId}`]??null:null,n$=ew?ep[`${ew.provider}:${ew.modelId}`]??null:null,nP=(0,r.jsxs)(r.Fragment,{children:[tO?(0,r.jsx)(lB,{onReenter:()=>{tI(),tP(!1)}}):null,eL?(0,r.jsx)("div",{style:{flexShrink:0,padding:`0 ${W?16:18}px 8px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsx)(l0,{request:eL,disabled:nt||!e8.current,onRespond:e=>{eV(eL,e)}})})}):$&&e?(0,r.jsx)(aT,{session:e,isMobile:W}):to?(0,r.jsx)(aR,{isMobile:W}):tB&&eW?(0,r.jsx)(lN,{request:eW,onKeytrapElement:tq,queuedCount:e_.followUpRows.length||e_.followUp.length,onInput:eQ,onExit:()=>{t_(),tP(!0)},autoFocus:tJ}):(0,r.jsx)(lH,{ref:f,onSend:tl,onAbort:ts,onSteer:no?tc:void 0,onFollowUp:no?tu:void 0,onPromptWithStreamingBehavior:no?tp:void 0,isStreaming:no,model:ew,isAutoModelSelection:e2,modelNames:eo,modelList:el,sessionTokens:nw?.tokens??null,modelAuthConfigured:ea,onModelChange:ta,onCompact:e||e5?td:void 0,onAbortCompaction:th,isCompacting:ev,compactError:ey,compactResult:eb,thinkingLevel:eh,thinkingReady:ef,defaultThinkingLevel:ej,onThinkingLevelChange:e||e5?tx:void 0,availableThinkingLevels:nW,thinkingLevelMap:n$,thinkingLevelMaps:ep,retryInfo:eg,queuedMessages:e_,onRecallQueue:tf,onSendQueueAsSteer:tg,slashCommands:eS,slashCommandsLoading:eC,onLoadSlashCommands:tv,onLoadCommandArgumentCompletions:ty,autocompleteProviderCount:tk,autocompleteTriggerCharacters:tj,onLoadCompletionSuggestions:tb,onApplyCompletionSuggestion:tw,onBuiltinCommand:tm,soundEnabled:M,onSoundToggle:A,footerCollapsed:C,onFooterToggle:nA?void 0:_,onAudioUnlock:z,draftKey:e?.id??(D?`new:${D}`:void 0),cwd:e?.cwd??D,sessionId:e8.current,extensionWidgetKeysEnabled:!$&&!ez&&eP.length>0&&eD>0,blocked:!!eL})]}),nF=eP.some(e=>/todo/i.test(e.key)),nH=0===e1.length||nF?null:(0,r.jsx)("div",{style:{flexShrink:0,padding:`0 ${W?16:18}px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsx)(sc,{todos:e1,collapsed:nf,onToggle:()=>ng(e=>!e)})})}),nD=eP.filter(e=>"belowEditor"!==e.placement),nN=eP.filter(e=>"belowEditor"===e.placement),nB=G.flatMap((e,t)=>{if("custom"!==e.role||"pidance.activity"!==e.customType||!e.details)return[];let n=e.details;return 1!==n.version||"string"!=typeof n.title||"string"!=typeof n.content?[]:[{key:Z[t]??`${n.requestId??"activity"}-${t}`,activity:n,timestamp:e.timestamp}]}),nO=new Set(nB.map(e=>e.activity.requestId).filter(Boolean)),nU=[...nB,...eR.filter(e=>!e.activity.requestId||!nO.has(e.activity.requestId)).map(e=>({key:`live-${e.activity.requestId??e.timestamp}`,...e}))];return K?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-text-muted",children:E("chat_loadingSession")}):Y?(0,r.jsxs)("div",{role:"alert",className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-center",children:[(0,r.jsx)("div",{className:"text-[var(--error-text)]",children:Y}),(0,r.jsx)("div",{className:"text-[12px] text-[var(--text-muted)]",children:E("chat_loadFailedHint")}),(0,r.jsx)("button",{type:"button",onClick:X,className:"mt-1",children:E("app_retry")})]}):(0,r.jsxs)("div",{"data-pidance-chat":"true","data-chat-message-count":G.length,"data-chat-entry-count":Z.length,"data-chat-entry-ids":Z.join(","),className:"relative flex h-full min-h-0 flex-col overflow-hidden",onDragEnter:nI,onDragOver:nR,onDragLeave:nT,onDrop:nE,children:[(0,r.jsx)(ia,{}),n_&&!nt&&(0,r.jsxs)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center bg-[color-mix(in_srgb,var(--accent)_6%,transparent)] backdrop-blur-[1px]",children:[(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:[0,.8,1.6].map(e=>(0,r.jsx)("div",{className:"absolute h-[720px] w-[720px] rounded-full border-[1.5px] border-solid border-[color-mix(in_srgb,var(--accent)_50%,transparent)] animate-[drop-ripple_2.4s_ease-out_infinite_backwards]",style:{transformOrigin:"center",animationDelay:`${e}s`}},e))}),(0,r.jsxs)("svg",{width:"280",height:"280",viewBox:"0 0 140 140",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{filter:"drop-shadow(0 6px 18px color-mix(in srgb, var(--accent) 18%, transparent))"},children:[(0,r.jsx)("rect",{x:"28",y:"44",width:"84",height:"60",rx:"8",fill:"color-mix(in srgb, var(--accent) 8%, transparent)",stroke:"color-mix(in srgb, var(--accent) 50%, transparent)",strokeWidth:"1.8"}),(0,r.jsx)("path",{d:"M36 100 L54 72 L68 88 L80 74 L104 100Z",fill:"color-mix(in srgb, var(--accent) 16%, transparent)",stroke:"color-mix(in srgb, var(--accent) 40%, transparent)",strokeWidth:"1.4",strokeLinejoin:"round"}),(0,r.jsx)("circle",{cx:"96",cy:"58",r:"8",fill:"color-mix(in srgb, var(--accent) 22%, transparent)",stroke:"color-mix(in srgb, var(--accent) 55%, transparent)",strokeWidth:"1.6"}),(0,r.jsxs)("g",{stroke:"color-mix(in srgb, var(--accent) 45%, transparent)",strokeWidth:"1.4",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"96",y1:"46",x2:"96",y2:"43"}),(0,r.jsx)("line",{x1:"96",y1:"70",x2:"96",y2:"73"}),(0,r.jsx)("line",{x1:"84",y1:"58",x2:"81",y2:"58"}),(0,r.jsx)("line",{x1:"108",y1:"58",x2:"111",y2:"58"}),(0,r.jsx)("line",{x1:"87.5",y1:"49.5",x2:"85.4",y2:"47.4"}),(0,r.jsx)("line",{x1:"104.5",y1:"66.5",x2:"106.6",y2:"68.6"}),(0,r.jsx)("line",{x1:"104.5",y1:"49.5",x2:"106.6",y2:"47.4"}),(0,r.jsx)("line",{x1:"87.5",y1:"66.5",x2:"85.4",y2:"68.6"})]})]})]}),ez&&(0,r.jsx)(l4,{request:ez,onInput:eY,onMouse:eX,onBounds:eG}),eF&&eF.length>0?(0,r.jsx)("div",{style:{flexShrink:0,padding:`0 ${W?16:18}px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsx)(aE,{lines:eF,kind:"header"})})}):null,nA?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center overflow-y-auto px-4 py-8",children:(0,r.jsxs)("div",{className:"w-full max-w-[760px]",children:[(0,r.jsx)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0,flex:1,lineHeight:1.4,overflow:"hidden"},children:[(0,r.jsx)("span",{style:{fontSize:28,fontWeight:700,letterSpacing:0,color:"var(--text)",flexShrink:0,whiteSpace:"nowrap"},children:"π"}),(0,r.jsx)("span",{style:{fontSize:22,color:"var(--text)",fontWeight:700,letterSpacing:0,flexShrink:0,whiteSpace:"nowrap"},children:"Pidance"})]})}),(0,r.jsx)(a$,{notices:eI,activities:nU,onDismiss:eT,onTogglePin:eE,align:"right"}),(0,r.jsx)("div",{className:"mb-4",children:(0,r.jsx)(so,{targetCwd:D,projectRoots:s??[],onTargetChange:H})}),nH,nP]})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"relative flex min-h-0 flex-col flex-1 overflow-hidden",children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:18*!W,right:18*!W,zIndex:40,pointerEvents:"none"},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsx)(a$,{notices:eI,activities:nU,onDismiss:eT,onTogglePin:eE,floating:!0,align:"right"})})}),W?null:(0,r.jsx)("div",{style:{position:"absolute",top:0,bottom:0,left:0,width:18,zIndex:30},children:(0,r.jsx)(lY,{renderKey:`${G.length}|${Z.length}`,scrollContainer:e3,outline:t7,entryIds:Z,jumpTo:t6.jumpTo,jumpingTo:t6.jumpingTo,jumpPinRef:t6.jumpPinRef,railHandleRef:t0,isAtLiveTail:!ti})}),(0,r.jsx)("div",{ref:e3,"data-chat-scroller":"true",className:"min-h-0 flex-1 overflow-y-auto py-4 [scrollbar-width:none]",style:{overscrollBehavior:"auto",padding:`0 ${W?16:18}px`},children:(0,r.jsx)(i3,{value:eJ,children:(0,r.jsxs)("div",{style:{maxWidth:I,margin:"0 auto"},children:[(()=>{let t=new Map;for(let e of G)"toolResult"===e.role&&t.set(e.toolCallId,e);let n=new Map,i=0;G.forEach((e,t)=>{("user"===e.role||"assistant"===e.role)&&n.set(t,i++)}),tG.current=e=>{let t=Z.indexOf(e);if(t<0)return null;for(let e=t;e>=0;e--){let t=n.get(e);if(void 0!==t)return nM.current[t]??null}return null};let o=i=>{let o="live"===i.source,l=o?-1:i.messageIndex,s=i.messageOverride??G[l],a="assistant"===s.role&&function(e){let{messages:t,index:n,liveAssistantActive:r}=e;if(null===n)return!0;if(!function(e,t){if(e[t]?.role!=="assistant")return!1;for(let n=t+1;n<e.length;n+=1){let t=e[n]?.role;if("user"===t)break;if("assistant"===t)return!1}return!0}(t,n))return!1;if(!r)return!0;for(let e=n+1;e<t.length;e+=1)if(t[e]?.role==="user")return!0;return!1}({messages:G,index:o?null:l,liveAssistantActive:nd})?(function(e){let{messages:t,index:n,liveMessage:r=null,toolResults:i,cwd:o}=e,l=n??t.length-1,s=0;for(let e=l;e>=0;e-=1)if(t[e]?.role==="user"){s=e+1;break}let a=[];for(let e=s;e<=l&&e<t.length;e+=1){let n=t[e];n&&a.push(n)}r&&a.push(r);let d=new Set,c=[];for(let e of a)if("assistant"===e.role){for(let t of e.content)if("toolCall"===t.type)for(let e of function(e,t,n){if(!function(e){let t;return iP(e)||"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||t.includes("write_file")||t.includes("create_file")||iF(e)}(e)||!n||!0===n.isError)return[];if(iF(e))return function(e,t){let n=function(e,t){let n=new Set;if(o_(t)&&o_(t.preview)&&Array.isArray(t.preview.files))for(let e of t.preview.files)o_(e)&&"delete"===e.operation&&"string"==typeof e.filePath&&e.filePath.length>0&&n.add(e.filePath);for(let t of iE(e).matchAll(/^\*\*\* Delete File: (.+)$/gm)){let e=(t[1]??"").trim();e&&n.add(e)}return n}(e,t),r=iz(t);if(r.length>0)return r.filter(e=>!n.has(e));if(iA(t))return[];if(o_(t)){var i;return(i=i$(t.preview))?i.map(e=>e.newPath).filter(e=>"string"==typeof e&&e.length>0):[]}return[]}(t,n.details);let r=function(e){if(!e)return null;let t=e.path??e.file_path;return"string"==typeof t&&""!==t.trim()?t.trim():null}(t);return r?[r]:[]}(t.toolName,t.input,i.get(t.toolCallId))){let t=function(e,t){let n=(0,rH.A0)(e.trim());return n?n.startsWith("/")||n.startsWith("//")||/^[a-zA-Z]:\//.test(n)||!t?n:(0,rH.e_)(t,n.replace(/^(\.\/)+/,"")):""}(e,o);!t||d.has(t)||(d.add(t),c.push({filePath:t}))}}return c})({messages:G,index:o?null:l,liveMessage:o?s:null,toolResults:t,cwd:nL}).map(e=>e.filePath):a_,d="user"===s.role||"assistant"===s.role,c=o?void 0:n.get(l),u=o?"live":Q[l]??`idx:${l}`,p=(0,r.jsx)(iQ,{message:s,toolResults:t,toolExecutionSnapshots:e6,modelNames:eo,cwd:nL,onOpenFile:w,onReferenceFile:ni?k:void 0,writtenFiles:a,isStreaming:o,toolsActive:no,entryId:o?void 0:Z[l],onBranchHere:o||no||e5||nt?void 0:tT,onNewSessionFromHere:o||no||e5||nt?void 0:tM,onBranchFromAssistant:o||no||e5||nt?void 0:tE,onNewSessionFromAnswer:o||no||e5||nt?void 0:tA,forking:!o&&ex===Z[l],showTimestamp:i.showTimestamp,prevTimestamp:!o&&l>0?G[l-1].timestamp:void 0,sessionId:e?.id??e8.current??void 0,contextUsage:nw,onCompactContext:o||no||nt?void 0:td,hiddenThinkingLabel:eK??void 0},`${i.keyPrefix}-view-${u}`),h=o||!Z[l]?void 0:`${i.keyPrefix}:${Z[l]}`;return h||d&&i.attachRef&&void 0!==c?(0,r.jsx)("div",{ref:d&&i.attachRef&&void 0!==c?e=>{nM.current[c]=e}:void 0,"data-message-entry-id":!o&&i.attachRef?Z[l]:void 0,"data-chat-anchor":h,children:p},`${i.keyPrefix}-${u}`):p},l=[];for(let e of na)l.push(o(e));return(0,r.jsxs)(r.Fragment,{children:[V&&(0,r.jsx)("div",{ref:nx,className:"py-3 text-center text-xs text-text-muted",children:J?E("chat_loadingSession"):E("chat_loadEarlier",{count:100})}),l]})})(),nc&&(0,r.jsxs)("div",{className:"flex items-center gap-2 py-2 text-[13px] text-text-muted",children:[null===nu?(0,r.jsx)("span",{className:"size-1.5 rounded-full bg-status-running","aria-hidden":"true"}):nu.length>0?(0,r.jsx)("span",{"aria-hidden":"true",children:aP(nu[np%nu.length],"working-frame")}):null,(0,r.jsx)("span",{children:nc})]}),ti&&(0,r.jsx)("div",{className:"py-3 text-center",children:(0,r.jsx)("button",{type:"button",onClick:()=>void tt(),disabled:J,style:{border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:J?"default":"pointer",fontSize:12,padding:"4px 10px"},children:J?E("chat_loadingSession"):E("chat_loadNewer")})}),ei&&(0,r.jsx)(iQ,{message:{role:"bashExecution",command:ei.command,output:"",excludeFromContext:ei.excludeFromContext,timestamp:ei.startedAt},sessionId:e?.id??e8.current??void 0}),(0,r.jsx)("div",{"aria-hidden":"true",style:{height:W?40:"10vh"}})]})})}),(0,r.jsx)("button",{type:"button",className:`chat-jump-bottom${e9?" is-visible":""}`,"aria-label":E("chat_backToBottom"),"aria-hidden":!e9,tabIndex:e9?0:-1,onClick:e7,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})}),W?null:(0,r.jsx)("div",{style:{position:"absolute",top:0,bottom:0,right:0,width:18,zIndex:30},children:(0,r.jsx)(lU,{messages:G,plan:na,scrollContainer:e3,messageRefs:nM})})]}),(0,r.jsxs)("div",{className:"relative",children:[(0,r.jsx)("div",{style:{padding:`0 ${W?16:18}px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsx)(aL,{widgets:nD,onWidgetMouse:eZ})})}),nH,ev&&(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{display:"flex",alignItems:"center",gap:7,padding:"4px 16px 6px",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{className:"size-1.5 rounded-full bg-status-running","aria-hidden":"true"}),(0,r.jsx)("span",{children:E("input_compacting")})]}),nP,!eL&&(0,r.jsx)("div",{style:{padding:`0 ${W?16:18}px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:!C&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(aL,{widgets:nN,onWidgetMouse:eZ})," ",eH&&eH.length>0?(0,r.jsx)(aE,{lines:eH,kind:"footer"}):null," ",(0,r.jsx)(aM,{statuses:e$})]})})})]})]})]})}function aR({isMobile:e}){let{t}=(0,eU.s9)();return(0,r.jsx)("div",{style:{flexShrink:0,padding:`0 ${e?16:18}px 8px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsxs)("div",{role:"status","aria-label":t("chat_sessionWriteLocked"),style:{display:"flex",alignItems:"flex-start",gap:8,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",padding:"8px 12px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2,color:"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{color:"var(--text)",fontWeight:600},children:t("chat_sessionWriteLocked")}),`. ${t("chat_sessionWriteLockedDescription")}`]})]})})})}function aT({session:e,isMobile:t}){let{t:n}=(0,eU.s9)(),i=e.subagent,o=i?`${i.agent?n("chat_agentNamed",{name:i.agent}):n("chat_subagent")} \xb7 ${n("chat_subagentRun",{count:i.runIndex})}`:null;return(0,r.jsx)("div",{style:{flexShrink:0,padding:`0 ${t?16:18}px 8px`},children:(0,r.jsx)("div",{style:{maxWidth:I,margin:"0 auto"},children:(0,r.jsxs)("div",{role:"note","aria-label":n("chat_readOnlySession"),style:{display:"flex",alignItems:"flex-start",gap:8,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",padding:"8px 12px",fontSize:12,lineHeight:1.5,color:"var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:2,color:"var(--text-dim)"},"aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{color:"var(--text)",fontWeight:600},children:n("chat_readOnlySession")}),o?` — ${o}`:` — ${n("chat_subagentSessionFallback")}`,`. ${n("chat_readOnlySessionDescription")}`]})]})})})}function aE({lines:e,kind:t}){let n=ra();return 0===e.length?null:(0,r.jsx)("pre",{"data-extension-slot":t,style:{margin:0,marginBottom:"footer"===t?8:6,padding:"4px 2px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre",fontFamily:"var(--font-mono)",maxHeight:n?"min(88px, 20vh)":"min(124px, 26vh)",overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y"},children:e.map((e,n,o)=>(0,r.jsxs)(i.Fragment,{children:[aP(e,`slot-${t}-line-${n}`),n<o.length-1?"\n":null]},n))})}function aM({statuses:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",border:"1px solid color-mix(in srgb, var(--accent) 24%, var(--border))",borderRadius:6,background:"color-mix(in srgb, var(--accent) 7%, var(--bg))",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:11},children:e.key}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:aP(e.text,`status-${e.key}`)})]},e.key))})}function aA({widgetKey:e,lines:t,images:n,imageFallbacks:o,bodyMaxHeight:l,onWidgetMouse:s}){let{t:a}=(0,eU.s9)(),d=(0,i.useRef)(n3),c=(0,i.useRef)(null),u=(0,i.useRef)(null),p=(0,i.useCallback)(()=>{null!==c.current&&(clearTimeout(c.current),c.current=null)},[]);(0,i.useEffect)(()=>p,[p]);let h=(0,i.useCallback)((e,t,n)=>{let r=e.getBoundingClientRect(),i=window.getComputedStyle(e),o=Number.parseFloat(i.paddingLeft)||0,l=Number.parseFloat(i.paddingTop)||0,s=Number.parseFloat(i.paddingRight)||0,a=Number.parseFloat(i.paddingBottom)||0;return function(e){let{offsetX:t,offsetY:n,charWidth:r,lineHeight:i,bodyWidth:o,bodyHeight:l}=e;return"number"==typeof r&&r>0&&"number"==typeof i&&i>0&&Number.isFinite(t)&&Number.isFinite(n)?{x:Math.max(0,Math.floor(t/r)),y:Math.max(0,Math.floor(n/i)),width:Math.max(1,Math.floor(o/r)),height:Math.max(1,Math.floor(l/i))}:null}({offsetX:t-r.left-o+e.scrollLeft,offsetY:n-r.top-l+e.scrollTop,charWidth:n2(e),lineHeight:n4(e),bodyWidth:e.clientWidth-o-s,bodyHeight:e.clientHeight-l-a})},[]),f=(0,i.useCallback)((t,n,r,i)=>{if(!s)return;let o=h(t,n,r);o&&s(e,{type:"click",button:i.button,x:o.x,y:o.y,screenX:o.x,screenY:o.y,width:o.width,height:o.height,shift:i.shift,alt:i.alt,ctrl:i.ctrl,clickCount:i.clickCount})},[s,h,e]);return(0,r.jsx)("pre",{onClick:e=>{var t,n;let r=(t=d.current).longPressFired||t.scrolled?{state:n3,send:!1}:{state:t,send:!0};(d.current=r.state,r.send)?f(e.currentTarget,e.clientX,e.clientY,{button:0===(n=e.button)?"left":1===n?"middle":"right",clickCount:e.detail,shift:e.shiftKey,alt:e.altKey,ctrl:e.ctrlKey}):e.preventDefault()},onTouchStart:e=>{let t=e.touches[0];if(!t)return;d.current={pressing:!0,longPressFired:!1,scrolled:!1},u.current={x:t.clientX,y:t.clientY},p();let n=e.currentTarget;c.current=setTimeout(()=>{var e,t;if(c.current=null,!((e=d.current).pressing&&!e.longPressFired&&1))return;d.current={pressing:(t=d.current).pressing,longPressFired:!0,scrolled:t.scrolled};let r=u.current;r&&f(n,r.x,r.y,{button:"right",clickCount:1,shift:!1,alt:!1,ctrl:!1})},500)},onTouchMove:e=>{let t=e.touches[0],n=u.current;if(!t||!n)return;let r=t.clientX-n.x,i=t.clientY-n.y;if(n7(r,i)){var o;o=d.current,d.current=o.pressing&&n7(r,i)?{pressing:!1,longPressFired:!1,scrolled:!0}:o,p()}},onTouchEnd:()=>{p(),d.current=n9(d.current),u.current=null},onTouchCancel:()=>{p(),d.current=n9(d.current),u.current=null},style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre",fontFamily:"var(--font-mono)",maxHeight:l,overflow:"auto",overscrollBehavior:"auto",touchAction:"pan-y",cursor:s?"pointer":void 0},children:(0,r.jsx)(n8,{lines:Array.isArray(t)?t:[],images:n,imageFallbacks:o,keyPrefix:`widget-${e}-line`,renderLine:aP,imageAlt:a("message_imageAlt"),fallbackLabel:e=>{let t=nH(e);return a("message_imageUnavailable",{reason:t?a(t):e})}})})}function aL({widgets:e,onWidgetMouse:t}){let n=e.map(e=>{let t=e.lines.some(e=>"string"==typeof e&&e.startsWith(l6)),n=function(e){if(!e||0===e.length)return null;let t=!1,n=[];for(let r of e){if("string"!=typeof r)continue;let e=r.replace(l5,"").split("\xb7").map(e=>e.trim()).filter(Boolean).filter(e=>!l8.test(e)||(t=!0,!1));e.length>0&&n.push(e.join(" \xb7 "))}return t?n:null}(e.lines);return{widget:n?{...e,lines:n}:e,snapshot:t?function(e){for(let t of e??[]){let e;if("string"!=typeof t||!t.startsWith(l6))continue;try{e=JSON.parse(t.slice(l6.length))}catch{break}let n=l9(e);if(!n||!Array.isArray(n.runs))break;let r=se(n.kind);if("pi-subagents.async-status-snapshot"!==r)break;let i=[];for(let e of n.runs){let t=function e(t,n){let r=l9(t);if(!r)return null;let i=se(r.state),o=se(r.id),l=se(r.label);if(!i||!l3.has(i)||!o||!l)return null;let s=[];if(n<2&&Array.isArray(r.children))for(let t of r.children){let r=e(t,n+1);r&&s.push(r)}let a={id:o,kind:se(r.kind)??"subagent",label:l,state:i},d=l7(r.startedAt),c=l7(r.updatedAt),u=l7(r.endedAt);void 0!==d&&(a.startedAt=d),void 0!==c&&(a.updatedAt=c),void 0!==u&&(a.endedAt=u);let p=function(e){let t=l9(e);if(!t)return;let n={},r=se(t.state),i=se(t.currentTool),o=l7(t.lastActivityAt),l=l7(t.currentToolStartedAt),s=l7(t.turnCount),a=l7(t.toolCount);return r&&(n.state=r),i&&(n.currentTool=i),void 0!==o&&(n.lastActivityAt=o),void 0!==l&&(n.currentToolStartedAt=l),void 0!==s&&(n.turnCount=s),void 0!==a&&(n.toolCount=a),n}(r.activity);return p&&(a.activity=p),s.length>0&&(a.children=s),a}(e,0);t&&i.push(t)}let o=l9(n.omitted);return{kind:r,version:l7(n.version)??0,generatedAt:l7(n.generatedAt)??0,runs:i,omittedRuns:l7(o?.runs)??0,byteLimitExceeded:o?.byteLimitExceeded===!0}}return null}(e.lines):null,machinePayload:t,drop:null!==n&&0===n.length}}),{t:o}=(0,eU.s9)(),l=ra()?T:R,[s,a]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(az),t=e?JSON.parse(e):null;if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e))}catch{}return new Set})()),d=(0,i.useCallback)(e=>{a(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),function(e){try{window.localStorage.setItem(az,JSON.stringify([...e]))}catch{}}(n),n})},[]);return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:n.map(({widget:e,snapshot:n,machinePayload:i,drop:a})=>{let c,u;if(a||i&&!n)return null;let p=s.has(e.key),h=n?(c=st(n),{singleLabel:1===(u=Array.isArray(n.runs)?n.runs:[]).length?u[0]?.label??null:null,running:c.running,queued:c.queued,hidden:c.hidden,byteLimitExceeded:c.byteLimitExceeded}):null,f=h?h.singleLabel?o("subagent_widgetSingle",{name:h.singleLabel}):o("subagent_widgetTitle"):re(e.key),g=h?[o("subagent_widgetBackground"),h.queued>0?o("subagent_widgetQueued",{count:h.queued}):"",h.hidden>0?o("subagent_widgetMore",{count:h.hidden}):"",h.byteLimitExceeded?o("subagent_widgetTruncated"):""].filter(Boolean).join(" \xb7 "):null;return(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>d(e.key),"aria-expanded":!p,"aria-label":p?o("extension_widgetExpand",{name:f}):o("extension_widgetCollapse",{name:f}),title:p?o("extension_widgetExpand",{name:f}):o("extension_widgetCollapse",{name:f}),style:{display:"flex",width:"100%",minHeight:36,alignItems:"center",gap:8,padding:"8px 12px",border:"none",borderBottom:p?"none":"1px solid var(--border)",background:"transparent",color:"var(--text)",fontSize:13,fontFamily:"inherit",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:p?"none":"rotate(90deg)",transition:"transform 0.15s ease"},children:(0,r.jsx)("polyline",{points:"4 2.5 7.5 6 4 9.5"})}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),g?(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g}):null]}),!p&&(n?(0,r.jsx)(sr,{snapshot:n}):(0,r.jsx)(aA,{widgetKey:e.key,lines:e.lines,images:e.images,imageFallbacks:e.imageFallbacks,bodyMaxHeight:l,onWidgetMouse:!0===e.interactive?t:void 0}))]},e.key)})})}let az="pidance.collapsedWidgetKeys.v1";function aW({label:e,active:t=!1,onClick:n,children:i}){return(0,r.jsx)("button",{type:"button","aria-label":e,title:e,onClick:n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,flexShrink:0,border:"none",borderRadius:7,background:t?"var(--bg-selected)":"transparent",color:t?"var(--text)":"var(--text-dim)",cursor:"pointer"},children:i})}function a$({notices:e,activities:t,onDismiss:n,onTogglePin:o,floating:l=!1,align:s="left"}){let{t:a}=(0,eU.s9)(),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)({}),[g,m]=(0,i.useState)(null),x=(0,i.useRef)(0);if(0===e.length&&0===t.length)return null;let v=[...e].sort((e,t)=>Number(t.pinned)-Number(e.pinned)),y=u?t.filter(e=>e.activity.requestId===u):t,b=async e=>{let t=x.current+=1,n=!0;try{await tC(e.message)}catch{n=!1}m({id:e.id,ok:n,attempt:t}),window.setTimeout(()=>{m(n=>n&&n.id===e.id&&n.attempt===t?null:n)},n?1200:2600)};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===s?"flex-end":"stretch",gap:7,width:"100%",marginBottom:10*!l,pointerEvents:"auto"},children:[t.length>0&&(0,r.jsxs)("button",{type:"button",onClick:()=>{p(null),c(e=>!e)},"aria-expanded":d,style:{display:"flex",alignItems:"center",gap:7,padding:"5px 9px",border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v6h6"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]}),a("notice_activityHistory",{count:t.length})]}),d&&(0,r.jsxs)("section",{"aria-label":a("notice_activityHistoryTitle"),style:{width:"min(100%, 620px)",maxHeight:360,overflow:"auto",border:"1px solid var(--border)",borderRadius:12,background:"var(--bg)",boxShadow:"0 16px 40px color-mix(in srgb, var(--text) 14%, transparent)"},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:0,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"9px 10px 9px 12px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:12,fontWeight:650},children:a("notice_activityHistoryTitle")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10},children:a("notice_activityHistoryDescription")})]}),(0,r.jsx)(aW,{label:a("notice_close"),onClick:()=>c(!1),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]}),y.length>0?(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:10},children:[...y].reverse().map(({key:e,activity:t,timestamp:n})=>(0,r.jsxs)("article",{style:{border:"1px solid var(--border)",borderLeft:`3px solid ${"warning"===t.kind||"error"===t.kind?"var(--warning)":"var(--accent)"}`,borderRadius:10,background:"var(--bg-panel)",padding:"9px 10px"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:5},children:[(0,r.jsx)("span",{style:{color:"var(--text)",fontSize:12,fontWeight:650},children:t.title}),n?(0,r.jsx)("time",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}):null]}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:t.content})]},e))}):(0,r.jsx)("div",{style:{padding:16,color:"var(--text-muted)",fontSize:12},children:a("notice_activityPending")})]}),v.map(e=>{let t="important"===e.tier,i=function(e){switch(e){case"error":return"var(--error-text)";case"warning":return"var(--warning)";case"success":return"var(--success)";default:return"var(--accent)"}}(e.type),s=!0===h[e.id],d=a(function(e){switch(e){case"error":return"notice_error";case"warning":return"notice_warning";case"success":return"notice_success";default:return"notice_info"}}(e.type));return(0,r.jsxs)("div",{className:"notice-shelf-item",role:"error"===e.type?"alert":"status",style:{display:"flex",alignItems:s?"flex-start":"center",gap:6,minHeight:s?t?64:40:36,borderRadius:10,border:`1px solid color-mix(in srgb, ${i} 42%, var(--border))`,borderLeft:`3px solid ${i}`,background:`color-mix(in srgb, ${i} ${t?12:8}%, var(--bg-panel))`,color:"var(--text-muted)",width:"min(100%, 620px)",maxWidth:"min(100%, 620px)",boxShadow:l?"0 12px 32px color-mix(in srgb, var(--text) 13%, transparent)":"0 8px 24px color-mix(in srgb, var(--text) 8%, transparent)",fontSize:t?13:12,lineHeight:1.45,transformOrigin:"top right",animation:e.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"5px 6px 5px 6px"},children:[(0,r.jsx)(aW,{label:s?a("notice_collapse"):a("notice_expand"),active:s,onClick:()=>{var t;return t=e.id,void f(e=>({...e,[t]:!e[t]}))},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:s?(0,r.jsx)("path",{d:"m6 9 6 6 6-6"}):(0,r.jsx)("path",{d:"m9 6 6 6-6 6"})})}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1,paddingTop:4*!!s},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsxs)("span",{style:{color:i,fontFamily:"var(--font-mono)",fontSize:10,fontWeight:700,letterSpacing:.6,textTransform:"uppercase",flexShrink:0},children:[d,e.pinned?` \xb7 ${a("notice_pinned")}`:""]}),!s&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:e.message.replace(/\s+/g," ").trim()})]}),s&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{marginTop:4,color:t?"var(--text)":"var(--text-muted)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.message}),t&&e.activityRecord&&(0,r.jsxs)("button",{type:"button",onClick:()=>{p(e.id),c(!0)},style:{marginTop:7,padding:0,border:"none",background:"transparent",color:"var(--accent)",cursor:"pointer",fontSize:11,fontWeight:600},children:[a("notice_viewActivity")," →"]})]})]}),(0,r.jsx)(aW,{label:g?.id===e.id?a(g.ok?"notice_copied":"notice_copyFailed"):a("notice_copy"),active:g?.id===e.id&&g.ok,onClick:()=>{b(e)},children:g?.id!==e.id||g.ok?g?.id===e.id?(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"})}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),(0,r.jsx)("path",{d:"M5 15V5a2 2 0 0 1 2-2h10"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--status-danger)",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 8v5m0 3h.01"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"})]})}),t&&(0,r.jsx)(aW,{label:e.pinned?a("notice_unpin"):a("notice_pin"),active:e.pinned,onClick:()=>o(e.id),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:e.pinned?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m15 4 5 5-4 2-3 5-2 4-1-6-6-6 4-1 5-3 2-4Z"}),(0,r.jsx)("path",{d:"m4 20 5-5"})]})}),(0,r.jsx)(aW,{label:a("notice_close"),onClick:()=>n(e.id),children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.id)})]})}function aP(e,t){return nG(e).map((e,n)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${t}-${n}`):e.text)}var aF=n(50640);function aH(){let e=0;return{next:()=>++e,isCurrent:t=>t===e,invalidate:()=>{e+=1}}}var aD=n(79617),aN=n.n(aD);function aB(e){let t=e.replace(/[\\/]+$/,"");return t.length>0?t:aN().sep}function aO(e,t){return e.some(e=>(function(e,t){let n=aB(e),r=aB(t);if(n===r)return!0;let i=`${n}${aN().sep}`,o=`${n}/`;return r.startsWith(i)||r.startsWith(o)})(e,t))}let aU={buffers:{}};function aq(e,t){return JSON.stringify([e,t??null])}function aK(e,t){let n={...e,...t};return{...n,dirty:n.content!==n.savedContent}}function aJ(e,t){return{...e,buffers:{...e.buffers,[t.key]:t}}}function aV(e=aU,t){var n;if("initialize"===t.type){let n=aq(t.filePath,t.sourceSessionId),r=e.buffers[n];return r?.dirty?aJ(e,aK(r,{externalChange:{content:t.content,baseline:t.baseline}})):r?aJ(e,aK(r,{savedContent:t.content,content:t.content,baseline:t.baseline,language:t.language,past:[],future:[],lastEditAt:null,saveState:"idle",saveRequestId:null,saveRequestRevision:null,error:null,externalChange:null})):aJ(e,{key:n,filePath:t.filePath,sourceSessionId:t.sourceSessionId??null,savedContent:t.content,content:t.content,baseline:t.baseline,language:t.language,dirty:!1,past:[],future:[],lastEditAt:null,revision:0,saveState:"idle",saveRequestId:null,saveRequestRevision:null,error:null,externalChange:null})}let r=(n=t.key,e.buffers[n]);if(!r)return e;if("edit"===t.type){if(t.content===r.content)return e;let n=t.at??Date.now(),i=!t.forceBoundary&&null!==r.lastEditAt&&n-r.lastEditAt<=500&&n>=r.lastEditAt?r.past:[...r.past,r.content].slice(-50);return aJ(e,aK(r,{content:t.content,past:i,future:[],lastEditAt:n,revision:r.revision+1,saveState:"error"===r.saveState?"idle":r.saveState,error:null}))}if("undo"===t.type){if(!r.past.length)return e;let t=r.past[r.past.length-1];return aJ(e,aK(r,{content:t,past:r.past.slice(0,-1),future:[r.content,...r.future].slice(0,50),revision:r.revision+1}))}if("redo"===t.type){if(!r.future.length)return e;let t=r.future[0];return aJ(e,aK(r,{content:t,past:[...r.past,r.content].slice(-50),future:r.future.slice(1),revision:r.revision+1}))}if("discard"===t.type)return aJ(e,aK(r,{content:r.savedContent,past:[],future:[],lastEditAt:null,revision:r.revision+1,saveState:"idle",saveRequestId:null,saveRequestRevision:null,error:null,externalChange:null}));if("remove"===t.type){let n={...e.buffers};return delete n[t.key],{...e,buffers:n}}if("markSaving"===t.type){let n=t.requestRevision??r.revision;return aJ(e,aK(r,{saveState:"saving",saveRequestId:t.requestId,saveRequestRevision:n,error:null}))}return("saveSuccess"===t.type||"saveConflict"===t.type||"saveError"===t.type)&&t.requestId&&r.saveRequestId!==t.requestId?e:"saveSuccess"===t.type?r.saveRequestRevision!==t.requestRevision?e:aJ(e,aK(r,{savedContent:t.savedContent,baseline:t.baseline,saveState:"idle",saveRequestId:null,saveRequestRevision:null,error:null,externalChange:null})):"saveConflict"===t.type?aJ(e,aK(r,{saveState:"conflict",baseline:t.baseline??r.baseline,error:t.message??"文件已被外部修改"})):"saveError"===t.type?aJ(e,aK(r,{saveState:"error",error:t.message})):e}function aY(e,t){return e.buffers[t]}function aX(e){return!!e?.past.length}function aG(e){return!!e?.future.length}function aZ(){let[e,t]=(0,i.useState)(0);return(0,i.useEffect)(()=>(0,t4.DF)(()=>t(e=>e+1)),[]),e}let aQ={source:"viewer_source",preview:"viewer_preview",diff:"viewer_diff"},a0={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},a1={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function a2({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,o)=>{let l=e.children??[],s=l[0]?.properties?.className,a=Array.isArray(s)&&s.includes("react-syntax-highlighter-line-number"),d=a?l[0]:null,c=a?l.slice(1):l;return(0,r.jsxs)("span",{className:"file-source-line",style:{display:"flex",minWidth:"100%"},children:[d&&(0,aF.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${o}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,aF.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${o}-${r}`}))})]},`source-line-${o}`)})}function a4(e,t,n,r={}){let i=(0,rH.HG)(e),o=new URLSearchParams({type:t});for(let[e,t]of(n&&o.set("sessionId",n),Object.entries(r)))void 0!==t&&o.set(e,String(t));return`/api/files/${i}?${o.toString()}`}function a6({filePath:e,sourceSessionId:t}){let{t:n}=(0,eU.s9)();return(0,r.jsx)("a",{href:a4(e,"download",t),download:(0,rH.WP)(e),title:n("viewer_download"),"aria-label":n("viewer_download"),className:"file-viewer-icon-button",children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})})}function a5(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function a8({patch:e}){let t,{t:n}=(0,eU.s9)(),i=(t=iR(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("viewer_noChanges")});let o=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),l=new Set;for(let e of o)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)l.add(t);let s=[],a=0;for(;a<i.length;)if(l.has(a)){let e=[];for(;a<i.length&&l.has(a);)e.push(i[a]),a++;s.push({hidden:!1,lines:e})}else{let e=0;for(;a<i.length&&!l.has(a);)e++,a++;s.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...a0},children:s.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"var(--diff-added-bg)":"removed"===e.type?"var(--diff-removed-bg)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",o="added"===e.type?"var(--diff-added-text)":"removed"===e.type?"var(--diff-removed-text)":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid var(--diff-added-border)":"removed"===e.type?"3px solid var(--diff-removed-border)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:a1,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:o,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function a3({filePath:e,cwd:t,sourceSessionId:n}){let{t:o}=(0,eU.s9)(),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),m=(0,i.useRef)(null),x=aZ(),v=(0,rH.WP)(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),g(null),s(!1),m.current&&((0,t4.qE)(m.current),m.current=null);let t=new EventSource(a4(e,"watch",n));return m.current=t,(0,t4.D)(t),t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}d(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{(0,t4.qE)(t),m.current=null}},[e,n,x]);let y=a4(e,"read",n,a?{v:a}:void 0),b=null!=c?a5(c):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:(0,rH.qP)(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:v||"image"}),p&&(0,r.jsxs)("span",{children:[p.w," \xd7 ",p.h]}),b&&(0,r.jsx)("span",{children:b}),(0,r.jsxs)("span",{title:l?o("viewer_liveSyncOn"):o("viewer_liveSyncOff"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--status-success)":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--status-success)":"var(--border)",display:"inline-block",boxShadow:l?"var(--live-indicator-glow)":"none"}}),l?o("viewer_live"):o("viewer_static")]}),(0,r.jsx)(a6,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:f?(0,r.jsx)("div",{style:{color:"var(--error-text)",fontSize:13},children:f}):(0,r.jsx)("img",{src:y,alt:e,onLoad:e=>{let t=e.currentTarget;h({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>g(o("viewer_loadFailed")),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function a9(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}function a7({filePath:e,cwd:t,sourceSessionId:n}){let{t:o}=(0,eU.s9)(),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),m=(0,i.useRef)(null),x=aZ(),v=(0,rH.WP)(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),g(null),s(!1),m.current&&((0,t4.qE)(m.current),m.current=null);let t=new EventSource(a4(e,"watch",n));return m.current=t,(0,t4.D)(t),t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),g(null),d(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{(0,t4.qE)(t),m.current=null}},[e,n,x]);let y=a4(e,"read",n,a?{v:a}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:(0,rH.qP)(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:v||"video"}),null!=p&&(0,r.jsx)("span",{children:a9(p)}),null!=c&&(0,r.jsx)("span",{children:a5(c)}),(0,r.jsxs)("span",{title:l?o("viewer_liveSyncOn"):o("viewer_liveSyncOff"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--status-success)":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--status-success)":"var(--border)",display:"inline-block",boxShadow:l?"var(--live-indicator-glow)":"none"}}),l?o("viewer_live"):o("viewer_static")]}),(0,r.jsx)(a6,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[f&&(0,r.jsx)("div",{style:{color:"var(--error-text)",fontSize:13,marginBottom:12,textAlign:"center"},children:f}),(0,r.jsx)("video",{controls:!0,playsInline:!0,preload:"metadata",src:y,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>g(o("viewer_loadFailed")),style:{width:"100%",maxHeight:"min(480px, 60vh)",background:"var(--media-canvas)"}},y)]})})]})}function de({filePath:e,cwd:t,sourceSessionId:n}){let{t:o}=(0,eU.s9)(),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),m=(0,i.useRef)(null),x=aZ(),v=(0,rH.WP)(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{d(0),u(null),h(null),g(null),s(!1),m.current&&((0,t4.qE)(m.current),m.current=null);let t=new EventSource(a4(e,"watch",n));return m.current=t,(0,t4.D)(t),t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&u(t.size)}catch{}h(null),g(null),d(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{(0,t4.qE)(t),m.current=null}},[e,n,x]);let y=a4(e,"read",n,a?{v:a}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},title:e,children:(0,rH.qP)(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:v||"audio"}),null!=p&&(0,r.jsx)("span",{children:a9(p)}),null!=c&&(0,r.jsx)("span",{children:a5(c)}),(0,r.jsxs)("span",{title:l?o("viewer_liveSyncOn"):o("viewer_liveSyncOff"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--status-success)":"var(--text-dim)"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--status-success)":"var(--border)",display:"inline-block",boxShadow:l?"var(--live-indicator-glow)":"none"}}),l?o("viewer_live"):o("viewer_static")]}),(0,r.jsx)(a6,{filePath:e,sourceSessionId:n})]}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[f&&(0,r.jsx)("div",{style:{color:"var(--error-text)",fontSize:13,marginBottom:12,textAlign:"center"},children:f}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:y,onLoadedMetadata:e=>h(e.currentTarget.duration),onError:()=>g(o("viewer_loadFailed")),style:{width:"100%"}},y)]})})]})}function dt({filePath:e,cwd:t,sourceSessionId:n}){let{t:o}=(0,eU.s9)(),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),f=(0,i.useRef)(null),g=aZ(),m=iB(e),x="pdf"===m,v=x?a4(e,"read",n,a?{v:a}:void 0):a4(e,"preview",n,a?{v:a}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),s(!1),f.current&&((0,t4.qE)(f.current),f.current=null),fetch(a4(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!x&&e.size>0xa00000&&h(o("viewer_docxTooLarge")))}).catch(e=>h(String(e)));let t=new EventSource(a4(e,"watch",n));return f.current=t,(0,t4.D)(t),t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!x&&t.size>0xa00000))return void h(o("viewer_docxTooLarge"))}catch{}h(null),d(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{(0,t4.qE)(t),f.current=null}},[e,x,n,o,g]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"4px 16px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e,children:(0,rH.qP)(e,t)}),(0,r.jsx)("span",{style:{marginLeft:"auto"},children:"docx"===m?"docx preview":"pdf"}),null!=c&&(0,r.jsx)("span",{children:a5(c)}),(0,r.jsx)(a6,{filePath:e,sourceSessionId:n}),(0,r.jsxs)("span",{title:l?o("viewer_liveSyncOn"):o("viewer_liveSyncOff"),style:{display:"flex",alignItems:"center",gap:4,color:l?"var(--status-success)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:l?"var(--status-success)":"var(--border)",display:"inline-block",boxShadow:l?"var(--live-indicator-glow)":"none"}}),l?o("viewer_live"):o("viewer_static")]})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"var(--error-text)",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:v,sandbox:x?void 0:"",title:`${o("viewer_preview")} ${(0,rH.WP)(e)}`,style:{width:"100%",height:"100%",border:"none",background:x?"var(--bg)":"#eef1f5"}},v)})]})}function dn({filePath:e,cwd:t,sourceSessionId:n,writable:i,buffer:o,dispatchBuffer:l,onSave:s,onOpenFile:a,gitAffectedPaths:d}){let c;return iO(e)?(0,r.jsx)(a3,{filePath:e,cwd:t,sourceSessionId:n}):iq(e)?(0,r.jsx)(a7,{filePath:e,cwd:t,sourceSessionId:n}):iU(e)?(0,r.jsx)(de,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(c=iB(e))||"docx"===c?c:null)?(0,r.jsx)(dt,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(dr,{filePath:e,cwd:t,sourceSessionId:n,writable:i,buffer:o,dispatchBuffer:l,onSave:s,onOpenFile:a,gitAffectedPaths:d})}function dr({filePath:e,cwd:t,sourceSessionId:n,writable:o=!1,buffer:l,dispatchBuffer:s,onSave:a,onOpenFile:d,gitAffectedPaths:c}){let{isDark:u}=rF(),{t:p}=(0,eU.s9)(),[h,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(!0),[y,b]=(0,i.useState)(null),[w,k]=(0,i.useState)("source"),[j,S]=(0,i.useState)(!1),[C,_]=(0,i.useState)(!1),I=(0,i.useRef)(null),R=aZ(),T=(0,i.useRef)(null);T.current||(T.current=aH());let E=T.current,M=(0,i.useRef)(null),A=(0,i.useRef)(null),L=(0,i.useRef)(l);L.current=l;let z=(0,i.useRef)(!1),[W,$]=(0,i.useState)(!1),[P,F]=(0,i.useState)(null),H=(0,i.useRef)(null),D=(0,i.useCallback)(e=>fetch(a4(e,"read",n)).then(e=>e.json()).then(t=>{if(t.error)return b(t.error),null;b(null),f(t);let r=L.current;return r?.dirty&&r.savedContent===t.content&&r.baseline.size===t.size&&r.baseline.mtimeMs===t.mtimeMs||s?.({type:"initialize",filePath:e,sourceSessionId:n,content:t.content,baseline:{size:t.size,mtimeMs:t.mtimeMs},language:t.language}),t}).catch(e=>(b(String(e)),null)),[s,n]),N=(0,i.useCallback)(async e=>{let n=E.next();if(!t)return void m(null);try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),o=await i.json();if(!E.isCurrent(n))return;m(i.ok&&o.supported&&"string"==typeof o.patch?o:null)}catch{E.isCurrent(n)&&m(null)}},[t,E]);(0,i.useEffect)(()=>{v(!0),b(null),f(null),m(null),k("source"),S(!1),_(!1),I.current&&((0,t4.qE)(I.current),I.current=null),N(e),D(e).then(e=>{e?.language==="markdown"&&k("preview")}).finally(()=>v(!1));let t=new EventSource(a4(e,"watch",n));return I.current=t,(0,t4.D)(t),t.addEventListener("connected",()=>{_(!0)}),t.addEventListener("change",()=>{D(e),N(e)}),t.addEventListener("error",()=>{_(!1)}),t.onerror=()=>{_(!1)},()=>{(0,t4.qE)(t),I.current=null}},[e,D,N,n,R]),(0,i.useEffect)(()=>{c&&aO(c,e)&&N(e)},[N,e,c]),(0,i.useEffect)(()=>()=>{H.current&&clearTimeout(H.current)},[]);let B=(0,i.useCallback)(async()=>{if(!a||!l?.dirty||"saving"===l.saveState)return!1;let e=await a();return e&&(H.current&&clearTimeout(H.current),$(!0),H.current=setTimeout(()=>$(!1),1600)),e},[l?.dirty,l?.saveState,a]),O=(0,i.useCallback)(()=>{l&&s&&aX(l)&&s({type:"undo",key:l.key})},[l,s]),U=(0,i.useCallback)(()=>{l&&s&&aG(l)&&s({type:"redo",key:l.key})},[l,s]);(0,i.useEffect)(()=>{let e=e=>{if(!o||!l||!(e.ctrlKey||e.metaKey)||e.altKey)return;let t=document.activeElement;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLElement&&t.isContentEditable)&&!M.current?.contains(t))return;let n=e.key.toLowerCase();"s"!==n||e.shiftKey?"z"===n&&e.shiftKey?(e.preventDefault(),U()):"z"!==n||e.shiftKey||(e.preventDefault(),O()):(e.preventDefault(),B())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[l,U,B,O,o]);let q=g?.supported===!0&&"string"==typeof g.patch,K=l?.externalChange?`${l.externalChange.baseline.mtimeMs}:${l.externalChange.baseline.size}`:l?.saveState==="conflict"?`conflict:${l.baseline.mtimeMs}:${l.baseline.size}`:null,J=null!==K&&P!==K;if((0,i.useEffect)(()=>{F(null)},[K]),(0,i.useEffect)(()=>{q||"diff"!==w||k("source")},[w,q]),x)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:p("common_loading")});if(y)return(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--error-text)",fontSize:13},children:y});if(!h)return null;let V=l?.content??h.content,Y=l?.language??h.language,X="html"===Y,G="markdown"===Y,Z=(0,rH.gX)(e),Q=V.split("\n"),ee=["source",...X||G?["preview"]:[],...q?["diff"]:[]],et=`${Y} \xb7 ${p("viewer_linesCount",{count:Q.length})} \xb7 ${a5(h.size)}`,en=n?o?null:p("viewer_readOnlySession"):p("viewer_readOnlyNoSession"),er=e=>{l&&s&&(s({type:"edit",key:l.key,content:e,forceBoundary:z.current}),z.current=!1)};return(0,r.jsxs)("div",{ref:M,className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,minWidth:0,overflow:"hidden"},children:[(0,r.jsxs)("div",{className:"file-viewer-toolbar",style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderBottom:"1px solid var(--border)",fontSize:11,color:"var(--text-dim)",background:"var(--bg)",flexShrink:0},children:[(0,r.jsx)("span",{className:"file-viewer-path",style:{fontFamily:"var(--font-mono)"},title:e,children:(0,rH.qP)(e,t)}),(0,r.jsx)("span",{className:"file-viewer-meta",title:et,children:et}),(0,r.jsx)("span",{title:C?p("viewer_liveSyncOn"):p("viewer_liveSyncOff"),"aria-label":C?p("viewer_liveSyncOn"):p("viewer_liveSyncOff"),className:"file-viewer-live-indicator",style:{background:C?"var(--status-success)":"var(--border)",boxShadow:C?"var(--live-indicator-glow)":"none"}}),(0,r.jsxs)("div",{className:"file-viewer-controls",role:"toolbar","aria-label":p("viewer_fileEditAria"),children:[ee.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>k(e),title:"diff"===e?p("viewer_gitDiff"):p(aQ[e]),"aria-label":"diff"===e?p("viewer_gitDiff"):p(aQ[e]),"aria-pressed":w===e,className:"file-viewer-icon-button","data-active":w===e,children:"source"===e?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"16 18 22 12 16 6"}),(0,r.jsx)("polyline",{points:"8 6 2 12 8 18"})]}):"preview"===e?(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M8 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3"}),(0,r.jsx)("path",{d:"M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3"}),(0,r.jsx)("path",{d:"M12 2v20"})]})},e)),"source"===w&&(0,r.jsx)("button",{type:"button",onClick:()=>S(e=>!e),title:j?p("viewer_disableWrap"):p("viewer_enableWrap"),"aria-label":j?p("viewer_disableWrap"):p("viewer_enableWrap"),"aria-pressed":j,className:"file-viewer-icon-button","data-active":j,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]})}),(0,r.jsx)("span",{className:"file-viewer-toolbar-separator","aria-hidden":"true"}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",onClick:O,disabled:!o||!aX(l),title:`${p("viewer_undo")} (Ctrl/Cmd+Z)`,"aria-label":p("viewer_undo"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9 14 4 9l5-5"}),(0,r.jsx)("path",{d:"M4 9h10a6 6 0 0 1 6 6v1"})]})}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button",onClick:U,disabled:!o||!aG(l),title:`${p("viewer_redo")} (Ctrl/Cmd+Shift+Z)`,"aria-label":p("viewer_redo"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m15 14 5-5-5-5"}),(0,r.jsx)("path",{d:"M20 9H10a6 6 0 0 0-6 6v1"})]})}),(0,r.jsx)("button",{type:"button",className:"file-viewer-icon-button is-save",onClick:()=>void B(),disabled:!o||!l?.dirty||"saving"===l.saveState,title:`${p("viewer_save")} (Ctrl/Cmd+S)`,"aria-label":p("viewer_save"),children:l?.saveState==="saving"?(0,r.jsx)("span",{className:"file-save-spinner","aria-hidden":"true"}):(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"}),(0,r.jsx)("polyline",{points:"17 21 17 13 7 13 7 21"}),(0,r.jsx)("polyline",{points:"7 3 7 8 15 8"})]})}),(0,r.jsx)(a6,{filePath:e,sourceSessionId:n})]})]}),(J||l?.saveState==="error"||en||W)&&(0,r.jsxs)("div",{className:`file-editor-notice${J?" is-warning":l?.saveState==="error"?" is-error":W?" is-success":""}`,role:l?.saveState==="error"?"alert":"status",children:[(0,r.jsx)("span",{children:l?.externalChange?p("viewer_externalChangeDraftKept"):l?.saveState==="conflict"?l.error??p("viewer_externalSaveConflict"):l?.saveState==="error"?l.error:W?p("common_saved"):en}),J&&(0,r.jsxs)("span",{className:"file-editor-notice__actions",children:[(0,r.jsx)("button",{type:"button",onClick:()=>{F(K),k("source"),requestAnimationFrame(()=>A.current?.focus())},title:p("viewer_keepLocalDraft"),"aria-label":p("viewer_keepLocalDraft"),children:p("viewer_keepLocalDraft")}),(0,r.jsx)("button",{type:"button",className:"is-danger",onClick:()=>{l&&s&&(s({type:"discard",key:l.key}),v(!0),D(e).finally(()=>v(!1)))},title:p("viewer_discardLocalDraftReload"),"aria-label":p("viewer_discardLocalDraftReload"),children:p("viewer_discardLocalDraftReload")})]})]}),(0,r.jsx)("div",{className:"file-viewer-content",style:{flex:"1 1 auto",minHeight:0,minWidth:0,display:"flex",flexDirection:"column",overflow:"auto",background:"var(--bg)"},children:"diff"===w&&q?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"file-viewer-context-label",children:p("viewer_gitDiffSavedWorktree")}),(0,r.jsx)(a8,{patch:g.patch})]}):X&&"preview"===w?(0,r.jsx)("iframe",{srcDoc:V,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:p("viewer_htmlPreview")}):G&&"preview"===w?(0,r.jsx)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:(0,r.jsx)(rb.oz,{remarkPlugins:rX,rehypePlugins:rZ,components:{a({href:e,children:n,...i}){delete i.node;let o=d?rN(e,Z,t??Z):null;return o&&d?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),d(o))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})}},children:V})}):o&&l&&s?(0,r.jsx)("textarea",{ref:A,className:j?"file-source-editor is-wrapped":"file-source-editor",value:V,onChange:e=>er(e.target.value),onKeyDown:e=>{if("Tab"!==e.key||e.ctrlKey||e.metaKey||e.altKey)return;e.preventDefault();let t=e.currentTarget,n=t.selectionStart,r=t.selectionEnd,i=`${V.slice(0,n)} ${V.slice(r)}`;z.current=!0,er(i),requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(n+2,n+2)})},onPaste:()=>{z.current=!0},onCut:()=>{z.current=!0},wrap:j?"soft":"off",spellCheck:!1,"aria-label":`${p("viewer_fileEditAria")}: ${(0,rH.WP)(e)}`}):(0,r.jsx)(rw.A,{className:j?"file-source-view is-wrapped":"file-source-view",language:"text"===Y?"plaintext":Y,style:u?rk.xJ:rk.vs,showLineNumbers:!0,lineNumberStyle:{...a1},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...a0,width:j?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:j?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(a2,{...e,wrapLines:j}),wrapLongLines:j,children:V})})]})}function di({open:e,title:t,initialPath:n,onSelect:o,onClose:l}){let{t:s}=(0,eU.s9)(),[a,d]=(0,i.useState)(n),[c,u]=(0,i.useState)([]),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),[m,x]=(0,i.useState)(null),v=(0,i.useRef)(0),y=(0,i.useCallback)(e=>{let t=++v.current;g(!0),x(null),fetch(`/api/cwd/browse?path=${encodeURIComponent(e)}`).then(async n=>{let r=await n.json().catch(()=>({}));if(t===v.current){if(!n.ok)return void x(r.error??`HTTP ${n.status}`);d(r.path??e),h(r.parentPath??null),u(r.entries??[])}}).catch(()=>{t===v.current&&x(s("files_pickerBrowseFailed"))}).finally(()=>{t===v.current&&g(!1)})},[s]);return(0,i.useEffect)(()=>{e&&(d(n),n?y(n):u([]))},[e,n,y]),(0,r.jsx)(tw,{open:e,onClose:l,title:t,width:440,closeLabel:s("dialog_close"),children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,minHeight:260},children:[(0,r.jsx)("div",{style:{padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:12,fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:a??"…"}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)"},children:m}),(0,r.jsxs)("div",{role:"list","aria-label":s("files_pickerDirectories"),style:{flex:1,minHeight:180,maxHeight:300,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:4},children:[p&&(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:()=>y(p),style:dl,children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:16,color:"var(--text-dim)"},children:"↰"}),s("files_pickerUp")]}),f&&0===c.length&&(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-dim)"},children:s("common_loading")}),!f&&0===c.length&&(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-dim)"},children:s("files_pickerEmpty")}),c.map(e=>(0,r.jsxs)("button",{type:"button",role:"listitem",onClick:()=>y(e.path),style:dl,title:e.path,children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:16,color:"var(--accent)"},children:"\uD83D\uDCC1"}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path))]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",disabled:!a,onClick:()=>a&&o(a),style:{minHeight:32,padding:"0 14px",borderRadius:7,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",fontSize:12,fontWeight:600,cursor:a?"pointer":"not-allowed",opacity:a?1:.5},children:s("files_pickerSelect")}),(0,r.jsx)("button",{type:"button",onClick:l,style:{minHeight:32,padding:"0 14px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("extension_cancel")}),(0,r.jsx)("span",{style:{marginLeft:"auto",fontSize:11,color:"var(--text-dim)"},children:s("files_pickerHint")})]})]})})}let dl={display:"flex",width:"100%",alignItems:"center",gap:6,minHeight:30,padding:"4px 8px",border:"none",borderRadius:5,background:"transparent",color:"var(--text)",fontSize:12,textAlign:"left",cursor:"pointer"};function ds(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):t}async function da(e,t){let n=(0,rH.HG)(e),r=await fetch(`/api/files/${n}?type=list`);if(!r.ok){let e=t("files_loadFailed",{status:r.status});try{let t=await r.json();t.error&&(e=t.error)}catch{}throw Error(e)}return((await r.json()).entries??[]).map(t=>({name:t.name,fullPath:(0,rH.e_)(e,t.name),isDir:t.isDir,size:t.size,children:t.isDir?[]:void 0,loaded:!t.isDir}))}async function dd(e,t){let n=new URLSearchParams({cwd:e}),r=await fetch(`/api/git/status?${n.toString()}`);if(!r.ok)throw Error(t("files_gitStatusLoadFailed",{status:r.status}));return r.json()}let dc={modified:"files_modified",added:"files_added",deleted:"files_deleted",renamed:"files_renamed",untracked:"files_untracked",conflict:"files_conflict"},du={modified:"files_modified",added:"files_added",deleted:"files_deleted",renamed:"files_renamed",untracked:"files_untracked",conflict:"files_conflict"},dp={modified:"var(--status-warning)",added:"var(--status-success)",deleted:"var(--status-danger)",renamed:"var(--status-unread)",untracked:"var(--status-success)",conflict:"var(--status-danger)"};function dh({size:e=11}){return(0,r.jsxs)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function df({onClick:e,title:t}){return(0,r.jsx)("button",{type:"button",onClick:e,title:t,"aria-label":t,style:{width:24,height:24,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"none",borderRadius:4,background:"none",color:"var(--text-dim)",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m6 6 12 12"}),(0,r.jsx)("path",{d:"m18 6-12 12"})]})})}async function dg(e,t,n){let r=await fetch(`/api/files/${(0,rH.HG)(e)}?type=${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);return{path:i.path??e,name:i.name??""}}function dm({targetPath:e,type:t,defaultName:n,placeholder:o,paddingLeft:l,onDone:s,t:a}){let[d,c]=(0,i.useState)(n??""),[u,p]=(0,i.useState)(!1),h=(0,i.useRef)(null),f=(0,i.useRef)(s);f.current=s,(0,i.useEffect)(()=>{h.current?.focus(),h.current?.select()},[]);let g=(0,i.useCallback)(async()=>{let n=d.trim();if(n&&!u){p(!0);try{"rename"===t?await dg(e,"rename",{newName:n}):await dg(e,t,{name:n}),f.current(!0)}catch(n){let e=n instanceof Error?n.message:String(n);window.alert(`${"rename"===t?a("files_renameFailed"):a("files_createFailed")}: ${e}`),p(!1)}}},[u,a,e,t,d]);return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,paddingLeft:l,paddingRight:8,height:24},onClick:e=>e.stopPropagation(),children:[(0,r.jsx)("input",{ref:h,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),g()):"Escape"===e.key&&(e.stopPropagation(),f.current(!1))},onBlur:()=>{u||f.current(!1)},placeholder:o,disabled:u,"aria-label":o,style:{flex:1,minWidth:0,height:20,padding:"0 6px",fontSize:12,border:"1px solid var(--accent)",borderRadius:4,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"inherit"}}),u&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),!u&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",disabled:!d.trim(),onMouseDown:e=>e.preventDefault(),onClick:()=>void g(),"aria-label":a("files_confirmRename"),title:a("files_confirmRename"),style:dx,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})})}),(0,r.jsx)("button",{type:"button",onMouseDown:e=>e.preventDefault(),onClick:()=>f.current(!1),"aria-label":a("files_cancelRename"),title:a("files_cancelRename"),style:dx,children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})]})}let dx={flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,border:"none",borderRadius:4,background:"transparent",color:"var(--text-dim)",cursor:"pointer"};function dv({entryPath:e,name:t,isDir:n,cwd:o,onRename:l,onCreate:a,onMove:d,onCopy:c,onDelete:u,t:p}){let[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=p("files_rowMenuLabel",{name:t}),b=(0,i.useCallback)((e=!1)=>{f(!1),e&&x.current?.focus()},[]);(0,i.useEffect)(()=>{if(!h)return;let e=e=>{let t=e.target;v.current?.contains(t)||x.current?.contains(t)||b()},t=()=>b();document.addEventListener("mousedown",e),window.addEventListener("resize",t),window.addEventListener("scroll",t);let n=requestAnimationFrame(()=>v.current?.querySelector("[role='menuitem']")?.focus());return()=>{cancelAnimationFrame(n),document.removeEventListener("mousedown",e),window.removeEventListener("resize",t),window.removeEventListener("scroll",t)}},[b,h]);let w={display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:32,padding:"6px 11px",boxSizing:"border-box",background:"var(--bg-elevated)",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",textDecoration:"none",fontSize:12,whiteSpace:"nowrap"},k={onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-elevated)",e.currentTarget.style.color="var(--text-muted)"}},j=e=>(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"flex",color:"var(--text-dim)"},children:e});return(0,r.jsxs)("div",{style:{display:"flex",flexShrink:0},onClick:e=>e.stopPropagation(),onKeyDown:e=>{"Escape"===e.key&&h&&(e.preventDefault(),e.stopPropagation(),b(!0))},children:[(0,r.jsx)("button",{ref:x,type:"button",className:"file-row-action-btn","data-menu-open":h?"true":void 0,onClick:e=>{e.stopPropagation(),(()=>{if(h)return b();let e=x.current?.getBoundingClientRect();if(e){let t=n?280:212,r=e.bottom+4+t<=window.innerHeight?e.bottom+4:Math.max(8,e.top-t-4),i=e.right-200;m({top:r,left:i=Math.max(8,Math.min(i,window.innerWidth-200-8))})}f(!0)})()},"aria-haspopup":"menu","aria-expanded":h,"aria-label":y,title:y,children:(0,r.jsx)(tn,{size:12})}),h&&g&&(0,s.createPortal)((0,r.jsxs)("div",{ref:v,role:"menu","aria-label":y,style:{position:"fixed",top:g.top,left:g.left,zIndex:10060,minWidth:190,padding:4,background:"var(--bg-elevated)",border:"1px solid var(--border)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-float)"},children:[(0,r.jsxs)("a",{role:"menuitem",href:`/api/files/${(0,rH.HG)(e)}?type=download`,download:!0,style:w,...k,onClick:()=>b(),children:[j((0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})),p(n?"files_downloadFolder":"viewer_download",n?{name:t}:void 0)]}),n&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",role:"menuitem",style:w,...k,onClick:()=>{b(),a("create-file")},children:[j((0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"}),(0,r.jsx)("path",{d:"M14 2v6h6"}),(0,r.jsx)("path",{d:"M12 18v-6"}),(0,r.jsx)("path",{d:"M9 15h6"})]})),p("files_newFile")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:w,...k,onClick:()=>{b(),a("create-dir")},children:[j((0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9l-.8-1.2A2 2 0 0 0 8 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),(0,r.jsx)("path",{d:"M12 11v6"}),(0,r.jsx)("path",{d:"M9 14h6"})]})),p("files_newFolder")]})]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:w,...k,onClick:()=>{b(),tC((0,rH.qP)(e,o)).catch(()=>window.alert(p("files_copyPathFailed")))},children:[j((0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})),p("files_copyPath")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:w,...k,onClick:()=>{b(),l()},children:[j((0,r.jsx)(te,{size:13})),p("files_rename")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:w,...k,onClick:()=>{b(),d()},children:[j((0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 4h4l3 3h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z"})})),p("files_move")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:w,...k,onClick:()=>{b(),c()},children:[j((0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})),p("files_copy")]}),(0,r.jsxs)("button",{type:"button",role:"menuitem",style:{...w,color:"var(--status-danger)"},...k,onClick:()=>{b(),u()},children:[j((0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}),(0,r.jsx)("path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})),p("files_delete")]})]}),document.body)]})}function dy({node:e,depth:t,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:p,onMutated:h,onMoveEntry:f,onCopyEntry:g,onDeleteEntry:m,t:x}){let v=s.has(e.fullPath),y=c.has(e.fullPath),b=(0,rH.A0)(e.fullPath),w=u.get(b),k=e.isDir&&(void 0!==w||p.has(b)),[j,S]=(0,i.useState)(e.children??[]),[C,_]=(0,i.useState)(e.loaded??!1),[I,R]=(0,i.useState)(!1),[T,E]=(0,i.useState)(!1),[M,A]=(0,i.useState)(null),L=(0,i.useCallback)(async(t=!1)=>{if(!C||t){R(!0);try{let t=await da(e.fullPath,x);S(t),_(!0)}catch{}finally{R(!1)}}},[C,e.fullPath,x]);(0,i.useEffect)(()=>{v&&C&&L(!0)},[d]);let z=(0,i.useCallback)(()=>{e.isDir?a(e.fullPath,!v):o(e.fullPath,e.name)},[e.isDir,e.fullPath,e.name,v,o,a]);(0,i.useEffect)(()=>{v&&!C&&L()},[v,C,L]);let W=(0,i.useCallback)(e=>{e.target===e.currentTarget&&("Enter"===e.key||" "===e.key)&&(e.preventDefault(),z())},[z]);return(0,r.jsxs)("div",{role:"none",children:[M?.kind==="rename"?(0,r.jsx)(dm,{targetPath:e.fullPath,type:"rename",defaultName:e.name,placeholder:x("files_namePlaceholder"),paddingLeft:8+14*t,onDone:e=>{A(null),e&&h()},t:x}):(0,r.jsxs)("div",{className:"file-row",role:"treeitem",tabIndex:0,"aria-expanded":e.isDir?v:void 0,"aria-selected":!1,draggable:!0,onClick:z,onKeyDown:W,onDragStart:t=>{t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.fullPath)},onDragOver:t=>{e.isDir&&(t.preventDefault(),t.dataTransfer.dropEffect="move",E(!0))},onDragLeave:()=>E(!1),onDrop:t=>{if(!e.isDir)return;t.preventDefault(),E(!1);let n=t.dataTransfer.getData("text/plain");n&&n!==e.fullPath&&(async()=>{try{await dg(n,"move",{targetDirectory:e.fullPath}),h()}catch(e){window.alert(`${x("files_moveFailed")}: ${e instanceof Error?e.message:String(e)}`)}})()},style:{position:"relative",display:"flex",alignItems:"center",gap:4,paddingLeft:8+14*t,paddingRight:8,height:24,cursor:"pointer",userSelect:"none",outline:T?"1px solid var(--accent)":void 0,borderRadius:T?5:void 0,background:T?"var(--bg-selected)":void 0},children:[e.isDir&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,transform:v?"rotate(90deg)":"none",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"3 2 7 5 3 8"})}),!e.isDir&&(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{className:"file-row-icon",style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(oz,{size:14,open:v}):o9(e.name,14)}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},title:e.fullPath,children:e.name}),y&&(0,r.jsx)("span",{className:"file-row-badge",title:x("files_uploaded"),"aria-label":x("files_uploaded"),style:{width:6,height:6,flexShrink:0,borderRadius:"50%",background:"var(--status-unread)"}}),!e.isDir&&w&&(0,r.jsx)("span",{className:"file-row-badge",title:x(du[w.status]),"aria-label":x(du[w.status]),style:{width:14,flexShrink:0,color:dp[w.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,textAlign:"center"},children:w.code}),k&&(0,r.jsx)("span",{className:"file-row-badge",title:x("files_containsChanges"),"aria-label":x("files_containsChanges"),style:{width:6,height:6,flexShrink:0,borderRadius:"50%",background:"var(--status-warning)"}}),I&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",children:(0,r.jsx)("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4"})}),(0,r.jsxs)("div",{className:"file-row-actions",children:[l&&(0,r.jsx)("button",{type:"button",className:"file-row-action-btn",onClick:t=>{t.stopPropagation(),l((0,rH.qP)(e.fullPath,n),e.isDir)},title:x("files_insertIntoChat",{name:e.name}),"aria-label":x("files_insertIntoChat",{name:e.name}),style:{color:"var(--accent)"},children:(0,r.jsx)(dh,{})}),(0,r.jsx)(dv,{entryPath:e.fullPath,name:e.name,isDir:e.isDir,cwd:n,onRename:()=>A({kind:"rename"}),onCreate:e=>A({kind:e}),onMove:()=>f(e.fullPath,e.name),onCopy:()=>g(e.fullPath,e.name),onDelete:()=>m(e.fullPath,e.name,e.isDir),t:x})]})]}),M&&"rename"!==M.kind&&(0,r.jsx)(dm,{targetPath:e.fullPath,type:M.kind,placeholder:x("files_namePlaceholder"),paddingLeft:8+(t+1)*14,onDone:e=>{A(null),e&&h()},t:x}),e.isDir&&v&&(0,r.jsxs)("div",{role:"group",children:[j.map(e=>(0,r.jsx)(dy,{node:e,depth:t+1,cwd:n,onOpenFile:o,onAtMention:l,expandedPaths:s,onToggleExpanded:a,refreshToken:d,highlightedPaths:c,gitStatusByPath:u,changedDirectoryPaths:p,onMutated:h,onMoveEntry:f,onCopyEntry:g,onDeleteEntry:m,t:x},e.fullPath)),0===j.length&&C&&(0,r.jsx)("div",{style:{paddingLeft:8+(t+1)*14,fontSize:11,color:"var(--text-dim)",height:22,display:"flex",alignItems:"center"},children:x("files_noFiles")})]})]})}let db=(0,i.forwardRef)(function({cwd:e,onOpenFile:t,refreshKey:n,onAtMention:o,onAtMentions:l,onUploadBusyChange:s},a){let{t:d}=(0,eU.s9)(),c=(0,eA.Fd)(),[u,p]=(0,i.useState)(!1),[h,f]=(0,i.useState)(null),g=(0,i.useMemo)(()=>{var e;let t;return{indexMaxFiles:ds((t="object"!=typeof(e=c.fileConfig)||null===e||Array.isArray(e)?{}:e).indexMaxFiles,5e3),indexGitHardCap:ds(t.indexGitHardCap,2e5),indexWalkHardCap:ds(t.indexWalkHardCap,5e4),indexMaxWalkDepth:ds(t.indexMaxWalkDepth,8),atResultLimit:ds(t.atResultLimit,20),textPreviewMaxBytes:ds(t.textPreviewMaxBytes,0xa00000),imagePreviewMaxBytes:ds(t.imagePreviewMaxBytes,0x3200000),docxPreviewMaxBytes:ds(t.docxPreviewMaxBytes,0xa00000),browseMaxEntries:ds(t.browseMaxEntries,400)}},[c.fileConfig]);(0,i.useCallback)(e=>{(0,eA.dM)("fileConfig",{...g,...e})},[g]);let m=(0,i.useCallback)(()=>{u?(p(!1),f(null)):(f(g),p(!0))},[u,g]),[x,v]=(0,i.useState)([]),[y,b]=(0,i.useState)(!0),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(()=>new Set),C=(0,i.useRef)(null),_=(0,i.useRef)(null),I=(0,i.useRef)(j);I.current=j;let R=(0,i.useRef)(null),[T,E]=(0,i.useState)(0),[M,A]=(0,i.useState)(null),[L,z]=(0,i.useState)(new Set),[W,$]=(0,i.useState)([]),[P,F]=(0,i.useState)("idle"),[H,D]=(0,i.useState)(0),[N,B]=(0,i.useState)(null),[O,U]=(0,i.useState)(null),[K,J]=(0,i.useState)(null),V=(0,i.useRef)(null),Y=(0,i.useRef)(null),G=(0,i.useRef)(e),[Z,Q]=(0,i.useState)(null),ee=`${n??0}:${T}`,et="idle"!==P,en=(0,i.useCallback)(()=>"function"==typeof requestIdleCallback?new Promise(e=>requestIdleCallback(()=>e(),{timeout:800})):new Promise(e=>setTimeout(e,250)),[]),er=(0,i.useMemo)(()=>new Map(W.map(e=>[(0,rH.A0)(e.filePath),e])),[W]),ei=(0,i.useMemo)(()=>{let t=new Set,n=(0,rH.A0)(e).replace(/\/$/,"");for(let e of W){let r=(0,rH.gX)((0,rH.A0)(e.filePath));for(;(r===n||r.startsWith(`${n}/`))&&(t.add(r),r!==n);){let e=(0,rH.gX)(r);if(e===r)break;r=e}}return t},[e,W]),eo=(0,i.useCallback)((t,n)=>{X(e,{expanded:[...t],scrollTop:n})},[e]),el=(0,i.useCallback)((e,t)=>{let n=new Set(j);t?n.add(e):n.delete(e),S(n),eo(n,C.current?.scrollTop??0)},[j,eo]),es=(0,i.useCallback)(()=>{E(e=>e+1)},[]),ea=(0,i.useCallback)(async(e,t)=>{if(window.confirm(d("files_deleteConfirm",{name:t})))try{let t=await fetch(`/api/files/${(0,rH.HG)(e)}`,{method:"DELETE"});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??d("files_deleteFailed"))}es()}catch(e){window.alert(`${d("files_deleteFailed")}: ${e instanceof Error?e.message:String(e)}`)}},[d,es]),ed=(0,i.useCallback)(()=>{null!==_.current&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{eo(I.current,C.current?.scrollTop??0)},200)},[eo]),ec=(0,i.useCallback)(()=>{if(null==R.current)return;let e=R.current;R.current=null,requestAnimationFrame(()=>{C.current&&(C.current.scrollTop=e)})},[]),eu=(0,i.useCallback)(e=>{let t=e.uploaded??[];if(U({uploaded:t,skipped:e.skipped??[],errors:e.errors??[]}),t.length>0){let e=G.current;z(new Set(t.map(t=>(0,rH.e_)(e,t)))),E(e=>e+1)}},[]),ep=(0,i.useCallback)(async(e,t)=>{J(null),B(null),D(0),F("uploading");try{let n=G.current,{status:r,data:i}=await new Promise((r,i)=>{let o=new FormData;e.forEach(e=>o.append("files",e,e.name));let l=new XMLHttpRequest;l.open("POST",`/api/files/${(0,rH.HG)(n)}?type=upload&conflict=${t}`),l.upload.onprogress=e=>{e.lengthComputable&&e.total>0&&D(Math.round(e.loaded/e.total*100))},l.onerror=()=>i(Error(d("files_uploadNetworkError"))),l.onabort=()=>i(Error(d("files_uploadCancelled"))),l.onload=()=>{let e={};try{e=JSON.parse(l.responseText)}catch{l.responseText&&(e.error=l.responseText)}r({status:l.status,data:e})},l.send(o)});if(409===r&&i.conflicts?.length)return void J({files:e,conflicts:i.conflicts,nonReplaceable:i.nonReplaceable??[]});if(r<200||r>=300)throw Error(i.error??d("files_uploadFailed",{status:r}));D(100),eu(i)}catch(e){B(e instanceof Error?e.message:String(e))}finally{F("idle")}},[eu,d]),eh=(0,i.useCallback)(async e=>{if(0!==e.length&&!et){U(null),z(new Set),J(null),B(null),D(0),F("checking");try{let t=G.current,n=await fetch(`/api/files/${(0,rH.HG)(t)}?type=upload-check`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fileNames:e.map(e=>e.name)})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??d("files_uploadCheckFailed",{status:n.status}));if(r.conflicts?.length)return void J({files:e,conflicts:r.conflicts,nonReplaceable:r.nonReplaceable??[]});await ep(e,"error")}catch(e){B(e instanceof Error?e.message:String(e))}finally{F("idle")}}},[ep,d,et]),ef=(0,i.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value="",eh(t)},[eh]);(0,i.useImperativeHandle)(a,()=>({openUploadPicker(){et||Q({mode:"upload",initialPath:e})},startCreateFile(){A("create-file")},startCreateDir(){A("create-dir")},toggleConfig(){m()}}),[et,e,m]);let eg=(0,i.useCallback)(async e=>{if(Q(null),Z){if("upload"===Z.mode){G.current=e,Y.current?.click();return}if(Z.sourcePath)try{await dg(Z.sourcePath,Z.mode,{targetDirectory:e}),es()}catch(t){let e=t instanceof Error?t.message:String(t);window.alert(`${"move"===Z.mode?d("files_moveFailed"):d("files_copyFailed")}: ${e}`)}}},[Z,es,d]),em=(0,i.useCallback)((e,t)=>{Q({mode:e,sourcePath:t,initialPath:(0,rH.gX)(t)})},[]);(0,i.useEffect)(()=>{s?.(et)},[s,et]),(0,i.useEffect)(()=>()=>s?.(!1),[s]),(0,i.useEffect)(()=>{(0,eA.zo)()},[]),(0,i.useEffect)(()=>{let t=V.current!==e,n=V.current;if(V.current=e,t){null!==n&&X(n,{expanded:[...I.current],scrollTop:C.current?.scrollTop??0});let t=q().fileExplorerState[e]??{expanded:[],scrollTop:0};S(new Set(t.expanded)),R.current=t.scrollTop,z(new Set),U(null),J(null),B(null),A(null)}b(t),k(null);let r=!1;return en().then(()=>{r||da(e,d).then(e=>{r||(v(e),ec())}).catch(e=>{r||k(e instanceof Error?e.message:String(e))}).finally(()=>{r||b(!1)})}),()=>{r=!0}},[e,n,d,T,en,ec]),(0,i.useEffect)(()=>{let t=!1;return en().then(()=>{t||dd(e,d).then(e=>{t||$(e.isGitRepository?e.files:[])}).catch(()=>{t||$([])})}),()=>{t=!0}},[e,n,d,T,en]);let ex=et||null!==K||null!==N||null!==O,ev=(0,i.useCallback)(()=>{O&&0!==O.uploaded.length&&l?.(O.uploaded.map(t=>(0,rH.qP)((0,rH.e_)(e,t),e)))},[e,l,O]);return(0,r.jsxs)("div",{ref:C,onScroll:ed,style:{height:"100%",overflowY:"auto",overflowX:"hidden"},children:[(0,r.jsx)("input",{ref:Y,type:"file",multiple:!0,hidden:!0,onChange:ef}),u&&h&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 10px"},children:[["indexMaxFiles",d("files_configIndexMaxFiles"),1],["indexGitHardCap",d("files_configGitHardCap"),1],["indexWalkHardCap",d("files_configWalkHardCap"),1],["indexMaxWalkDepth",d("files_configMaxWalkDepth"),1],["atResultLimit",d("files_configAtResultLimit"),1],["textPreviewMaxBytes",d("files_configTextPreview"),1048576],["imagePreviewMaxBytes",d("files_configImagePreview"),1048576],["docxPreviewMaxBytes",d("files_configDocxPreview"),1048576],["browseMaxEntries",d("files_configBrowseMaxEntries"),1]].map(([e,t,n])=>(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:4,fontSize:10,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:t}),(0,r.jsx)("input",{type:"number",min:1,value:Math.round((h[e]??g[e])/n),onChange:t=>{let r=Number(t.target.value);Number.isFinite(r)&&!(r<=0)&&f(t=>({...t??g,[e]:Math.round(r*n)}))},style:{width:70,height:20,border:"1px solid var(--border)",borderRadius:4,background:"var(--bg)",color:"var(--text)",fontSize:10,padding:"0 4px"}})]},e))}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{(0,eA.dM)("fileConfig",h),p(!1),f(null)},style:{height:22,padding:"0 10px",border:"1px solid var(--accent)",borderRadius:4,background:"var(--accent)",color:"#fff",cursor:"pointer",fontSize:10},children:d("files_configSave")}),(0,r.jsx)("button",{type:"button",onClick:()=>{p(!1),f(null)},style:{height:22,padding:"0 10px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:d("files_configCancel")}),(0,r.jsx)("span",{style:{marginLeft:4,fontSize:10,color:"var(--text-dim)"},children:d("files_configHint")})]})]}),Z&&(0,r.jsx)(di,{open:!0,title:"upload"===Z.mode?d("files_pickerUploadTitle"):"move"===Z.mode?d("files_pickerMoveTitle"):d("files_pickerCopyTitle"),initialPath:Z.initialPath,onSelect:eg,onClose:()=>Q(null)}),ex&&(0,r.jsxs)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:[et&&(0,r.jsxs)("div",{role:"status","aria-live":"polite","aria-label":"checking"===P?d("files_loadingList"):`${d("files_uploading")} ${H}%`,children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,minHeight:14,color:"var(--text-muted)"},children:["checking"===P?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-5.7-8.4"})}):(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 16V4"}),(0,r.jsx)("path",{d:"m7 9 5-5 5 5"}),(0,r.jsx)("path",{d:"M5 20h14"})]}),"uploading"===P&&(0,r.jsxs)("span",{style:{fontSize:10},children:[H,"%"]})]}),"uploading"===P&&(0,r.jsx)("div",{style:{height:3,marginTop:4,overflow:"hidden",borderRadius:2,background:"var(--border)"},children:(0,r.jsx)("div",{style:{width:`${H}%`,height:"100%",background:"var(--text-muted)",transition:"width 120ms ease"}})})]}),K&&(0,r.jsxs)("div",{role:"alert",style:{padding:7,border:"1px solid color-mix(in srgb, var(--status-warning) 55%, var(--border))",borderRadius:4,background:"color-mix(in srgb, var(--status-warning) 9%, var(--bg-panel))"},children:[(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text)",lineHeight:1.35,overflowWrap:"anywhere"},children:[d(1===K.conflicts.length?"files_existingFilesCount_one":"files_existingFilesCount",{count:K.conflicts.length}),": ",K.conflicts.join(", ")]}),K.nonReplaceable.length>0&&(0,r.jsx)("div",{style:{marginTop:3,fontSize:10,color:"var(--status-warning)",lineHeight:1.35,overflowWrap:"anywhere"},children:d("files_cannotReplace",{names:K.nonReplaceable.join(", ")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:7},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void ep(K.files,"overwrite"),style:{height:22,padding:"0 7px",border:"1px solid var(--status-danger)",borderRadius:4,background:"transparent",color:"var(--status-danger)",cursor:"pointer",fontSize:10},children:d("files_replace")}),(0,r.jsx)("button",{type:"button",onClick:()=>void ep(K.files,"skip"),style:{height:22,padding:"0 7px",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:10},children:d("files_skip")}),(0,r.jsx)("button",{type:"button",onClick:()=>J(null),style:{height:22,padding:"0 7px",border:"none",borderRadius:4,background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:10},children:d("files_cancel")})]})]}),N&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:6,fontSize:11,lineHeight:1.35,color:"var(--status-danger)"},children:[(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflowWrap:"anywhere"},children:N}),(0,r.jsx)(df,{onClick:()=>B(null),title:d("files_closeError")})]}),O&&(0,r.jsxs)("div",{"aria-live":"polite",children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minHeight:22,fontSize:11},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8},children:[O.uploaded.length>0&&(0,r.jsxs)("span",{title:d("files_uploadedCount",{count:O.uploaded.length}),"aria-label":d("files_uploadedCount",{count:O.uploaded.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--status-success)"},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m5 12 4 4L19 6"})}),(0,r.jsx)("span",{children:O.uploaded.length})]}),O.skipped.length>0&&(0,r.jsxs)("span",{title:d("files_skippedCount",{count:O.skipped.length}),"aria-label":d("files_skippedCount",{count:O.skipped.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--text-dim)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M8 12h8"})]}),(0,r.jsx)("span",{children:O.skipped.length})]}),O.errors.length>0&&(0,r.jsxs)("span",{title:d("files_failedCount",{count:O.errors.length}),"aria-label":d("files_failedCount",{count:O.errors.length}),style:{display:"flex",alignItems:"center",gap:3,color:"var(--status-danger)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 3 2.5 20h19L12 3Z"}),(0,r.jsx)("path",{d:"M12 9v4"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{children:O.errors.length})]})]}),O.uploaded.length>0&&l&&(0,r.jsx)("button",{type:"button",onClick:ev,title:1===O.uploaded.length?d("files_addFileToChat"):d("files_addAllFilesToChat"),"aria-label":1===O.uploaded.length?d("files_addFileToChat"):d("files_addAllFilesToChat"),className:"file-row-action-btn",style:{color:"var(--accent)"},children:(0,r.jsx)(dh,{})}),(0,r.jsx)(df,{onClick:()=>U(null),title:d("files_closeUploadResults")})]}),O.errors.map(e=>(0,r.jsxs)("div",{title:e.error,style:{display:"flex",alignItems:"center",gap:4,marginTop:3,minWidth:0,fontSize:10,color:"var(--status-danger)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 8v5"}),(0,r.jsx)("path",{d:"M12 17h.01"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.name))]})]}),(0,r.jsxs)("div",{style:{padding:"2px 4px"},children:[y?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:d("files_loading")}):w?(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--status-danger)"},children:w}):(0,r.jsxs)(r.Fragment,{children:[M&&(0,r.jsx)(dm,{targetPath:e,type:M,placeholder:d("files_namePlaceholder"),paddingLeft:12,onDone:e=>{A(null),e&&es()},t:d}),(0,r.jsx)("div",{role:"tree",children:x.map(n=>(0,r.jsx)(dy,{node:n,depth:0,cwd:e,onOpenFile:t,onAtMention:o,expandedPaths:j,onToggleExpanded:el,refreshToken:ee,highlightedPaths:L,gitStatusByPath:er,changedDirectoryPaths:ei,onMutated:es,onMoveEntry:e=>em("move",e),onCopyEntry:e=>em("copy",e),onDeleteEntry:(e,t)=>void ea(e,t),t:d},n.fullPath))})]}),!y&&!w&&0===x.length&&(0,r.jsx)("div",{style:{padding:"8px 12px",fontSize:11,color:"var(--text-dim)"},children:d("files_noFiles")})]})]})}),dw={conflict:0,modified:1,added:2,deleted:3,renamed:4,untracked:5};function dk({cwd:e,status:t,loading:n,error:o,onOpenFile:l,selectedFilePath:s}){let{t:a}=(0,eU.s9)(),d=(0,i.useMemo)(()=>t?[...t.files].sort((e,t)=>{let n=dw[e.status]-dw[t.status];return 0!==n?n:e.filePath.localeCompare(t.filePath)}):[],[t]);return n&&!t?(0,r.jsx)(dS,{children:a("git_loading")}):o?(0,r.jsx)(dS,{tone:"error",children:o}):t&&t.isGitRepository?0===d.length?(0,r.jsxs)("div",{style:{padding:"18px 12px",display:"flex",flexDirection:"column",alignItems:"center",gap:6,color:"var(--text-dim)"},children:[(0,r.jsx)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"var(--status-success)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{style:{fontSize:12},children:a("git_clean")})]}):(0,r.jsxs)("div",{style:{padding:"4px 0"},children:[(0,r.jsxs)("div",{style:{padding:"4px 10px 6px",fontSize:10.5,color:"var(--text-dim)",lineHeight:1.4},title:t.repositoryRoot??e,children:[a(1===d.length?"git_changesCount_one":"git_changesCount",{count:d.length})," \xb7 ",t.repositoryRoot??e]}),d.map(t=>(0,r.jsx)(dj,{file:t,cwd:e,onOpenFile:l,selected:t.filePath===s},t.filePath))]}):(0,r.jsx)(dS,{children:a("git_notRepo")})}function dj({file:e,cwd:t,onOpenFile:n,selected:i}){let{t:o}=(0,eU.s9)(),l=(0,rH.WP)(e.filePath)||e.filePath,s=(0,rH.qP)(e.filePath,t),a=o(dc[e.status]);return(0,r.jsxs)("button",{type:"button",className:`git-file-row${i?" is-selected":""}`,onClick:()=>n(e.filePath,l),title:`${e.filePath} — ${a}`,"aria-label":o("git_openFile",{path:s,status:a}),"aria-pressed":i,children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:14,flexShrink:0,color:dp[e.status],fontFamily:"var(--font-mono)",fontSize:11,fontWeight:700,textAlign:"center"},children:e.code}),(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:o9(l,13)}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),(0,r.jsx)("span",{style:{flexShrink:0,fontSize:10,color:"var(--text-dim)"},children:a})]})}function dS({children:e,tone:t="dim"}){return(0,r.jsx)("div",{style:{padding:"14px 12px",fontSize:11.5,lineHeight:1.5,color:"error"===t?"var(--status-danger)":"var(--text-dim)"},children:e})}var dC=n(48368),d_=n(12612),dI=n(42804);function dR({kind:e}){let t={width:17,height:17,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"info"===e?(0,r.jsx)(dC.A,{size:17,strokeWidth:1.8,"aria-hidden":"true"}):"files"===e?(0,r.jsx)("svg",{...t,children:(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}):"git"===e?(0,r.jsx)(d_.A,{size:17,strokeWidth:1.8,"aria-hidden":"true"}):"terminal"===e?(0,r.jsx)(dI.A,{size:17,strokeWidth:1.8,"aria-hidden":"true"}):(0,r.jsxs)("svg",{...t,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function dT({open:e,width:t,onWidthChange:n,onClose:o,cwd:l,isMobile:s,mobileReady:a,tabs:d,activeTabId:c,onSelectTab:u,sessionInfoContent:p,branchContent:h,terminalContent:f,fileRefreshKey:g,gitRefreshKey:m,onOpenFile:x,onAtMention:v,onAtMentions:y}){let{t:b}=(0,eU.s9)(),w=(0,i.useRef)(null),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(0),[_,I]=(0,i.useState)(null),[R,T]=(0,i.useState)(!1),[E,M]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),z=(0,i.useRef)(null),[W,$]=(0,i.useState)(e);(0,i.useEffect)(()=>{e&&$(!0)},[e]);let P=(0,i.useCallback)(async()=>{if(!l){I(null),M(null);return}T(!0);try{let e=await fetch(`/api/git/status?${new URLSearchParams({cwd:l}).toString()}`),t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??b("workspace_gitStatusLoadFailed",{status:e.status}));I(t),M(null)}catch(e){M(e instanceof Error?e.message:String(e)),I(null)}finally{T(!1)}},[l,b]);(0,i.useEffect)(()=>{e&&P()},[e,P,m]);let F=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=F.current;F.current=k,e&&!k&&P()},[k,P]);let H=(0,i.useCallback)(e=>{s||(e.preventDefault(),z.current={startX:e.clientX,startWidth:t},L(!0),e.currentTarget.setPointerCapture(e.pointerId))},[s,t]),D=(0,i.useCallback)(e=>{let t=z.current;t&&n(Math.min(Math.max(320,Math.min(720,.42*window.innerWidth)),Math.max(320,t.startWidth+t.startX-e.clientX)))},[n]),N=(0,i.useCallback)(e=>{z.current&&(z.current=null,L(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),B=d.filter(e=>e.kind&&"file"!==e.kind&&"chat"!==e.kind),O=_?.isGitRepository?_.files.length:0,U=44+(e?t:0),q=s?"calc(100% - 44px)":e?t:0;return(0,r.jsxs)("div",{className:`workspace-container${e?" workspace-open":" workspace-closed"}${A?" workspace-dragging":""}${a?"":" workspace-mobile-pending"}`,style:{width:U,minWidth:U,display:"flex",borderLeft:e?"1px solid var(--border)":"none",background:"var(--bg-panel)",position:"relative",flexShrink:0,zIndex:200},role:"complementary","aria-label":b("panel_ariaLabel"),onKeyDownCapture:t=>{e&&"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),o())},children:[e&&(0,r.jsx)("div",{className:`workspace-resize-handle${A?" dragging":""}`,onPointerDown:H,onPointerMove:D,onPointerUp:N,onPointerCancel:N,onDoubleClick:()=>n(400),title:b("workspace_resizeHandle"),"aria-hidden":"true"}),(0,r.jsxs)("div",{className:"workspace-inner",style:{width:U,minWidth:U,height:"100%",display:"flex"},children:[(0,r.jsx)("div",{"aria-hidden":!e,inert:!e,style:{width:q,minWidth:q,overflow:"hidden",height:"100%",display:"flex",flexDirection:"column",opacity:+!!e,transition:A?"none":"width 0.2s ease, min-width 0.2s ease, opacity 0.12s ease"},children:(0,r.jsx)("div",{style:{flex:1,overflow:"hidden",position:"relative",background:"var(--bg-panel)"},children:W?"terminal"===c?(0,r.jsx)("div",{style:{height:"100%",overflow:"hidden"},children:f}):l?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{display:"files"===c?"flex":"none",height:"100%",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>w.current?.openUploadPicker(),disabled:k||!l,"data-tooltip":b("workspace_upload"),"aria-label":b("workspace_upload"),className:"sidebar-icon-btn",children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("path",{d:"m17 8-5-5-5 5"}),(0,r.jsx)("path",{d:"M12 3v12"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>w.current?.startCreateFile(),disabled:!l,"data-tooltip":b("files_newFile"),"aria-label":b("files_newFile"),className:"sidebar-icon-btn",children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"}),(0,r.jsx)("path",{d:"M14 2v6h6"}),(0,r.jsx)("path",{d:"M12 18v-6"}),(0,r.jsx)("path",{d:"M9 15h6"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>w.current?.startCreateDir(),disabled:!l,"data-tooltip":b("files_newFolder"),"aria-label":b("files_newFolder"),className:"sidebar-icon-btn",children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9l-.8-1.2A2 2 0 0 0 8 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),(0,r.jsx)("path",{d:"M12 11v6"}),(0,r.jsx)("path",{d:"M9 14h6"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(e=>e+1),"data-tooltip":b("workspace_refreshFiles"),"aria-label":b("workspace_refreshFiles"),className:"sidebar-icon-btn",children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>w.current?.toggleConfig(),"data-tooltip":b("files_config"),"aria-label":b("files_config"),className:"sidebar-icon-btn",style:{marginLeft:"auto"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.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 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.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 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 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 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 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-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"})]})})]}),(0,r.jsx)("div",{style:{flex:1,minHeight:0},children:(0,r.jsx)(db,{ref:w,cwd:l,onOpenFile:(e,t)=>x(e,t,"content"),refreshKey:(g??0)+S,onAtMention:v,onAtMentions:y,onUploadBusyChange:j})})]}),(0,r.jsxs)("div",{style:{display:"git"===c?"flex":"none",height:"100%",flexDirection:"column"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("button",{type:"button",onClick:()=>void P(),disabled:!l,"data-tooltip":b("workspace_refreshGitStatus"),"aria-label":b("workspace_refreshGitStatus"),className:"sidebar-icon-btn",children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(dk,{cwd:l,status:_,loading:R,error:E,onOpenFile:(e,t)=>x(e,t,"diff")})})]}),"branch"===c&&(0,r.jsx)("div",{style:{height:"100%",overflow:"hidden"},children:h}),"info"===c&&(0,r.jsx)("div",{style:{height:"100%",overflow:"hidden"},children:p})]}):(0,r.jsx)("div",{style:{padding:"16px 12px",fontSize:11.5,color:"var(--text-dim)",lineHeight:1.6},children:b("workspace_selectProject")}):null})}),(0,r.jsx)("nav",{className:"workspace-navigation-rail","aria-label":b("panel_ariaLabel"),style:{width:44,flex:"0 0 44px"},children:B.map(t=>{let n=e&&t.id===c,i="git"===t.kind&&O>0?`${t.label} (${O>99?"99+":O})`:t.label;return(0,r.jsxs)("button",{type:"button",className:"sidebar-icon-btn","aria-label":i,"data-tooltip":i,"aria-pressed":n,onClick:()=>u(t.id),style:{width:34,height:34,color:n?"var(--accent)":"var(--text-muted)",background:n?"var(--bg-selected)":"transparent",border:n?"1px solid color-mix(in srgb, var(--accent) 30%, var(--border))":"1px solid transparent",position:"relative"},children:[(0,r.jsx)(dR,{kind:t.kind}),"git"===t.kind&&O>0&&(0,r.jsx)("span",{"aria-hidden":"true",style:{position:"absolute",right:3,top:3,width:6,height:6,borderRadius:"50%",background:"var(--accent)",boxShadow:"0 0 0 2px var(--bg)"}})]},t.id)})})]})]})}function dE({kind:e}){let t={width:13,height:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"files"===e?(0,r.jsx)("svg",{...t,children:(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}):"git"===e||"branch"===e?(0,r.jsxs)("svg",{...t,children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}):(0,r.jsxs)("svg",{...t,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function dM({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:o}){let{t:l}=(0,eU.s9)(),[s,a]=(0,i.useState)(null);return(0,r.jsx)("div",{style:{display:"flex",alignItems:"flex-end",background:"var(--bg-panel)",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t,d=void 0!==e.kind&&"file"!==e.kind;return(0,r.jsxs)("div",{role:"tab",tabIndex:0,"aria-selected":i,onClick:()=>n(e.id),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),n(e.id))},onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1!==t.button||d||(t.preventDefault(),t.stopPropagation(),o(e.id))},style:{display:"flex",alignItems:"center",gap:6,height:36,paddingLeft:12,paddingRight:d?12:6,borderRight:"1px solid var(--border)",background:i?"var(--bg)":"var(--bg-panel)",cursor:"pointer",fontSize:12,color:i?"var(--text)":"var(--text-muted)",whiteSpace:"nowrap",maxWidth:180,minWidth:80*!d,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:"chat"===e.kind?(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}):d?(0,r.jsx)(dE,{kind:e.kind}):o9(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},title:"chat"===e.kind?l("tabs_backToChat"):e.filePath||e.label,children:e.label}),!d&&(0,r.jsx)("button",{onClick:t=>{t.stopPropagation(),o(e.id)},onMouseEnter:()=>a(e.id),onMouseLeave:()=>a(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:s===e.id?"var(--bg-hover)":"transparent",border:"none",borderRadius:4,color:s===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:e.dirty?l("tabs_closeUnsaved"):l("tabs_close"),"aria-label":l("tabs_closeNamed",{label:e.label}),children:e.dirty?(0,r.jsx)("span",{className:e.saving?"file-tab-dirty-dot is-saving":"file-tab-dirty-dot","aria-hidden":"true"}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}function dA({open:e,width:t,onWidthChange:n,cwd:o,isMobile:l,mobileReady:s,tabs:a,activeTabId:d,onSelectTab:c,onCloseTab:u,onCloseAllTabs:p,pendingCloseTabLabel:h,onSaveAndClose:f,onDiscardAndClose:g,onCancelClose:m,fileViewerContent:x,activeMode:v,gitAffectedPaths:y}){let{t:b}=(0,eU.s9)(),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!1),[C,_]=(0,i.useState)(null),[I,R]=(0,i.useState)(!1),T=(0,i.useRef)(null),E=a.find(e=>e.id===d),M=(0,i.useRef)(null);M.current||(M.current=aH());let A=M.current;(0,i.useEffect)(()=>()=>A.invalidate(),[A]);let L=(0,i.useCallback)(async()=>{let e=A.next();if(!o||"diff"!==v||!E?.filePath){k(null),_(null),S(!1);return}S(!0),_(null);try{let t=new URLSearchParams({cwd:o,path:E.filePath}),n=await fetch(`/api/git/diff?${t.toString()}`),r=await n.json().catch(()=>({}));if(!A.isCurrent(e))return;if(!n.ok)throw Error(r.error??b("changes_diffError",{status:n.status}));k(r.supported&&"string"==typeof r.patch?r:null)}catch(t){if(!A.isCurrent(e))return;k(null),_(t instanceof Error?t.message:String(t))}finally{A.isCurrent(e)&&S(!1)}},[v,E?.filePath,o,b,A]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{"diff"===v&&E?.filePath&&y?.some(e=>aO(y,e))&&L()},[v,E?.filePath,L,y]);let z=(0,i.useCallback)(e=>{l||(e.preventDefault(),T.current={startX:e.clientX,startWidth:t},R(!0),e.currentTarget.setPointerCapture(e.pointerId))},[l,t]),W=(0,i.useCallback)(e=>{let t=T.current;t&&n(t.startWidth+t.startX-e.clientX)},[n]),$=(0,i.useCallback)(e=>{T.current&&(T.current=null,R(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),P=E?"content"===v?x:j?(0,r.jsx)("div",{className:"changes-panel-hint",children:b("changes_diffLoading")}):C?(0,r.jsx)("div",{className:"changes-panel-hint is-error",children:C}):w?.patch?(0,r.jsx)(a8,{patch:w.patch}):(0,r.jsx)("div",{className:"changes-panel-hint",children:b("changes_diffUnavailable")}):(0,r.jsx)("div",{className:"changes-panel-hint",children:b("secondary_empty")});return(0,r.jsxs)("aside",{className:`changes-panel${e?" changes-panel-open":" changes-panel-closed"}${I?" changes-panel-dragging":""}${s?"":" workspace-mobile-pending"}`,style:{width:e?t:0,minWidth:e?t:0,height:"100%",minHeight:0,flex:"1 1 auto",display:"flex",flexDirection:"column"},"aria-label":b("secondary_title"),children:[e&&(0,r.jsx)("div",{className:`changes-panel-resize-handle${I?" dragging":""}`,role:"separator","aria-orientation":"vertical",tabIndex:0,title:b("changes_resizeHandle"),"aria-label":b("changes_resizeHandle"),onPointerDown:z,onPointerMove:W,onPointerUp:$,onPointerCancel:$}),(0,r.jsxs)("div",{className:"secondary-panel-inner",children:[a.length>0&&(0,r.jsxs)("div",{className:"secondary-panel-tabs",style:{display:"flex",alignItems:"stretch",flexShrink:0},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,overflow:"hidden"},children:(0,r.jsx)(dM,{tabs:a,activeTabId:d,onSelectTab:c,onCloseTab:u})}),(0,r.jsx)("button",{type:"button",className:"sidebar-icon-btn",onClick:p,title:b("secondary_closeAll"),"aria-label":b("secondary_closeAll"),style:{flexShrink:0,borderRadius:0,borderLeft:"1px solid var(--border)"},children:(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})})]}),null!==h&&(0,r.jsxs)("div",{className:"file-close-confirm",role:"alert",children:[(0,r.jsx)("span",{className:"file-close-confirm__message",children:b("app_unsavedChangesIn",{name:h})}),(0,r.jsx)("button",{type:"button",className:"file-close-confirm__button",onClick:f,children:b("app_saveAndClose")}),(0,r.jsx)("button",{type:"button",className:"file-close-confirm__button is-danger",onClick:g,children:b("app_discardChanges")}),(0,r.jsx)("button",{type:"button",className:"file-close-confirm__button",onClick:m,children:b("common_cancel")})]}),(0,r.jsx)("div",{className:"secondary-panel-body",children:P})]})]})}function dL({session:e,sessionStats:t,contextUsage:n,systemPrompt:o}){let l,s,{t:a}=(0,eU.s9)(),[d,c]=(0,i.useState)(null),u=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>{u.current&&clearTimeout(u.current)},[]);let p=(0,i.useCallback)((e,t)=>{tC(t).then(()=>{u.current&&clearTimeout(u.current),c(e),u.current=setTimeout(()=>c(null),1400)})},[]),h=e=>(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),f=(e,t)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[h(e),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr)",columnGap:12,rowGap:4},children:t.map(([t,n])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",textAlign:"right",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:n})]},`${e}:${t}`))})]}),g=e=>(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:e});return(0,r.jsx)("div",{style:{height:"100%",overflowY:"auto",overflowX:"hidden",padding:"12px 16px 20px",display:"flex",flexDirection:"column",gap:18,fontSize:12,lineHeight:1.5},children:e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[h(a("app_sessionInfo")),t?(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:[...t.sessionName?[{label:a("app_name"),value:t.sessionName,copyField:null}]:[],{label:a("app_file"),value:t.sessionFile??a("app_inMemory"),copyField:"file"},{label:a("app_id"),value:t.sessionId,copyField:"id"}].map(e=>{var t,n;let i;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal",fontFamily:"var(--font-mono)",fontSize:11.5},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,n=e.value,i=d===t,(0,r.jsx)("button",{type:"button",title:i?a("app_copied"):"file"===t?a("app_copyFilePath"):a("app_copySessionId"),"aria-label":i?a("app_copied"):"file"===t?a("app_copyFilePath"):a("app_copySessionId"),onClick:()=>p(t,n),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:i?"var(--accent)":"var(--text-dim)",background:"transparent",border:"1px solid var(--border)",borderRadius:4,cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, border-color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=i?"var(--accent)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="transparent"},children:i?(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})):null})]},`session-info:${e.label}`)})}):g(a("app_sessionInfoAfterMessageHint"))]}),t&&(0,r.jsxs)(r.Fragment,{children:[f(a("app_messages"),[[a("app_user"),t.userMessages.toLocaleString()],[a("app_assistant"),t.assistantMessages.toLocaleString()],[a("app_toolCalls"),t.toolCalls.toLocaleString()],[a("app_toolResults"),t.toolResults.toLocaleString()],[a("app_total"),t.totalMessages.toLocaleString()]]),(l=n??t.contextUsage,f(a("app_tokens"),[[a("app_input"),t.tokens.input.toLocaleString()],[a("app_output"),t.tokens.output.toLocaleString()],...t.tokens.cacheRead>0?[[a("app_cacheRead"),t.tokens.cacheRead.toLocaleString()]]:[],...t.tokens.cacheWrite>0?[[a("app_cacheWrite"),t.tokens.cacheWrite.toLocaleString()]]:[],[a("app_total"),t.tokens.total.toLocaleString()],...t.cost>0?[[a("app_cost"),`$${t.cost.toFixed(4)}`]]:[],...l?.contextWindow?[[a("app_context"),`${null!==l.percent?`${l.percent.toFixed(1)}%`:"?"} / ${(s=l.contextWindow)>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}k`:String(s)}`]]:[]]))]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[h(a("app_systemPrompt")),!0===e.readOnly?g(a("app_systemPromptReadOnlyHint")):o?(0,r.jsx)("div",{style:{maxHeight:"min(480px, 60vh)",overflowY:"auto",padding:"10px 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontFamily:"var(--font-mono)"},children:o}):g(""===o?a("app_systemPromptEmptyHint"):a("app_systemPromptAfterMessageHint"))]})]}):g(a("panel_selectSessionHint"))})}var dz=n(6296),dW=n(53961),d$=n(28538),dP=n(91958);function dF({onModelsChanged:e,cwd:t}){let{t:n}=(0,eU.s9)(),o=ra(),l=t&&""!==t.trim()?`?cwd=${encodeURIComponent(t)}`:"",[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),y=(0,i.useCallback)(async()=>{try{let e=await fetch(`/api/models/enabled${l}`,{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok){v("string"==typeof t.error&&t.error?t.error:`HTTP ${e.status}`),a(null);return}v(null),a({enabledModels:t.enabledModels??null,projectOverride:!0===t.projectOverride,unreadable:!0===t.unreadable,models:Array.isArray(t.models)?t.models:[]})}catch(e){v(e instanceof Error?e.message:String(e)),a(null)}finally{c(!1)}},[l]);(0,i.useEffect)(()=>{y()},[y]);let b=s?.projectOverride===!0||s?.unreadable===!0,w=(0,i.useCallback)(async(t,r)=>{p(t.ref),m(null);try{let i=await fetch(`/api/models/enabled${l}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ref:t.ref,enabled:r})}),o=await i.json().catch(()=>({}));if(!i.ok)return void m({kind:"error",text:"last-model"===o.code?n("models_lastModelHint"):o.error??`HTTP ${i.status}`});await y(),e?.()}catch(e){m({kind:"error",text:e instanceof Error?e.message:String(e)})}finally{p(null)}},[l,y,e,n]),k=(0,i.useCallback)(async()=>{f(!0),m(null);try{let t=await fetch("/api/models/refresh",{method:"POST"}),r=await t.json().catch(()=>({}));if(!t.ok)return void m({kind:"error",text:n("models_refreshFailed",{error:r.error??`HTTP ${t.status}`})});await y(),e?.(),m({kind:"ok",text:n("models_refreshDone")})}catch(e){m({kind:"error",text:n("models_refreshFailed",{error:e instanceof Error?e.message:String(e)})})}finally{f(!1)}},[y,e,n]),j=s?.models.filter(e=>e.enabled).length??0;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"12px 16px 16px",minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:12,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{flex:"1 1 200px",minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:n("models_availableTitle")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:4,lineHeight:1.5},children:n("models_availableHint")})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>void k(),disabled:h,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"7px 12px",borderRadius:"var(--radius-md)",border:"1px solid var(--border)",background:"var(--bg-panel)",color:h?"var(--text-dim)":"var(--text)",fontSize:12,cursor:h?"default":"pointer",minHeight:o?44:36},children:[h?(0,r.jsx)(dz.A,{size:13,className:"animate-spin","aria-hidden":!0}):(0,r.jsx)(dP.A,{size:13}),h?n("models_refreshing"):n("models_refreshCatalog")]})]}),b&&(0,r.jsx)("div",{role:"status",style:{fontSize:11,lineHeight:1.5,padding:"8px 10px",borderRadius:"var(--radius-md)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--text-muted)"},children:s?.unreadable?n("models_availableReadOnlyUnreadable"):n("models_availableReadOnlyProject")}),g&&(0,r.jsx)("div",{role:"error"===g.kind?"alert":"status",style:{fontSize:11,lineHeight:1.5,padding:"8px 10px",borderRadius:"var(--radius-md)",border:`1px solid ${"error"===g.kind?"var(--status-danger-border)":"var(--border)"}`,color:"error"===g.kind?"var(--status-danger)":"var(--text-muted)"},children:g.text}),d?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 0"},children:n("models_loading")}):x?(0,r.jsx)("div",{role:"alert",style:{fontSize:12,color:"var(--status-danger)"},children:x}):s&&0!==s.models.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)"},children:n("models_availableCount",{enabled:j,total:s.models.length})}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",border:"1px solid var(--border)",borderRadius:"var(--radius-md)",overflow:"hidden"},children:s.models.map(e=>{let t=u===e.ref;return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:10,padding:o?"10px 12px":"8px 12px",minHeight:44,borderTop:"1px solid var(--border)",cursor:b||t?"default":"pointer",opacity:t?.6:1,minWidth:0},children:[(0,r.jsx)("input",{type:"checkbox",role:"switch",checked:e.enabled,disabled:b||t,"aria-label":n("models_toggleModelAria",{name:e.name}),onChange:t=>void w(e,t.target.checked),style:{width:15,height:15,flexShrink:0,accentColor:"var(--accent)",cursor:b?"default":"pointer"}}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12.5,color:"var(--text)"},children:e.name||e.id}),(0,r.jsx)("span",{style:{flexShrink:0,fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",maxWidth:o?90:220,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.provider})]},e.ref)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",padding:"12px 0"},children:n("models_availableEmpty")})]})}function dH(e){return{minHeight:32,padding:"0 14px",borderRadius:7,border:`1px solid ${e?"var(--accent)":"var(--border)"}`,background:e?"var(--accent)":"var(--bg-panel)",color:e?"var(--accent-foreground)":"var(--text-muted)",cursor:e?"pointer":"not-allowed",fontSize:12,fontWeight:600,opacity:e?1:.65}}function dD(e=!0){return{minHeight:32,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:e?"pointer":"not-allowed",fontSize:12,opacity:e?1:.65}}function dN(e=!0){return{display:"inline-flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--status-danger)",cursor:e?"pointer":"not-allowed",opacity:e?1:.55}}function dB({fixedHint:e,dynamicHint:t,children:n,onClose:i,closeLabel:o}){let{t:l}=(0,eU.s9)();return(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 20px 14px",borderTop:"1px solid var(--border)",background:"var(--bg)",display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{flex:"1 1 160px",minWidth:0,display:"flex",flexDirection:"column",gap:2,justifyContent:"center",minHeight:36},children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"var(--font-mono)",lineHeight:1.4,minHeight:16,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:"string"==typeof e?e:void 0,children:null!=e&&""!==e?e:"\xa0"}),(0,r.jsx)("div",{style:{fontSize:12,lineHeight:1.4,minHeight:16},children:null!=t&&""!==t?t:"\xa0"})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginLeft:"auto",flexShrink:0},children:[n,i&&(0,r.jsx)("button",{type:"button",onClick:i,style:dD(!0),children:o??l("dialog_close")})]})]})}function dO({stickyFooter:e=!1,onClose:t,apiPath:n="/api/settings/raw",fixedHint:o="~/.pi/agent/settings.json",titleLabel:l,fileLabel:s="settings.json"}={}){let{t:a}=(0,eU.s9)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(0),w=i.useRef(null),[k,j]=(0,i.useState)(0),[S,C]=(0,i.useState)(null),_=(0,i.useCallback)(async()=>{p(!0),m(null);try{let e=await fetch(n,{cache:"no-store"});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`HTTP ${e.status}`)}let t=await e.json();c("string"==typeof t.json?t.json:"{}\n")}catch(e){m(e instanceof Error?e.message:String(e)),c(null)}finally{p(!1)}},[n]);(0,i.useEffect)(()=>{_()},[_,y]);let I=(0,i.useCallback)(()=>{if(null===d)return null;try{let e=JSON.parse(d);if("object"!=typeof e||null===e||Array.isArray(e))return a("settingsJson_mustBeObject");return null}catch(n){let e=n instanceof Error?n.message:String(n),t=/position (\d+)/.exec(e);if(t){let e=Number(t[1]),n=d.slice(0,e),r=n.split("\n").length,i=e-n.lastIndexOf("\n");return a("settingsJson_invalidAt",{line:String(r),col:String(i)})}return a("settingsJson_invalid",{message:e})}},[d,a]),R=(0,i.useCallback)(()=>{if(null===d)return;let e=I();if(null!==e)return void C(e);try{let e=JSON.parse(d);c(JSON.stringify(e,null,2)),C(!0),m(null),v(!1)}catch{}},[d,I]),T=(0,i.useCallback)(()=>{if(null===d)return C(null),!1;let e=I();return C(null===e||e),null===e},[d,I]),E=(0,i.useCallback)(async()=>{if(T()){f(!0),m(null),v(!1);try{let e=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({json:d})});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`HTTP ${e.status}`)}v(!0),window.setTimeout(()=>v(!1),2e3)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}},[d,I,a,n]);return u&&null===d?(0,r.jsx)("div",{style:{padding:"12px 0",fontSize:12,color:"var(--text-muted)"},children:a("common_loading")}):e?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"12px 20px 12px",display:"flex",flexDirection:"column"},children:[(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)"},children:l??a("defaults_jsonTab")}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:s})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:200,display:"flex",alignItems:"stretch",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{"aria-hidden":"true",style:{flexShrink:0,padding:"10px 6px 10px 10px",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",color:"var(--text-dim)",fontSize:12,lineHeight:1.55,fontFamily:"var(--font-mono)",textAlign:"right",userSelect:"none",overflow:"hidden",minHeight:0},children:(d??"").split("\n").map((e,t)=>(0,r.jsx)("div",{style:{transform:`translateY(-${k}px)`},children:t+1},t))}),(0,r.jsx)("textarea",{ref:w,value:d??"",onChange:e=>{c(e.target.value),m(null),v(!1),C(null)},onScroll:e=>j(e.currentTarget.scrollTop),spellCheck:!1,"aria-label":a("settingsJson_editorLabel"),style:{flex:1,minHeight:0,width:"100%",padding:"10px 12px",border:"none",borderRadius:0,background:"var(--bg)",color:"var(--text)",fontSize:12,lineHeight:1.55,outline:"none",fontFamily:"var(--font-mono)",whiteSpace:"pre",overflow:"auto",boxSizing:"border-box",resize:"none"}})]})]}),(0,r.jsxs)(dB,{fixedHint:o,dynamicHint:"string"==typeof S||g?(0,r.jsx)("span",{style:{color:"var(--status-danger)",fontFamily:"var(--font-mono)"},children:"string"==typeof S?S:g}):!0===S?(0,r.jsx)("span",{style:{color:"var(--status-ok, var(--accent))",fontFamily:"var(--font-mono)"},children:a("settingsJson_valid")}):x?(0,r.jsx)("span",{style:{color:"var(--accent)"},children:a("common_saved")}):null,onClose:t,children:[(0,r.jsx)("button",{type:"button",onClick:()=>void R(),disabled:null===d,style:dD(null!==d),children:a("settingsJson_format")}),(0,r.jsx)("button",{type:"button",onClick:()=>void T(),disabled:null===d,style:dD(null!==d),children:a("settingsJson_validate")}),(0,r.jsx)("button",{type:"button",onClick:()=>b(e=>e+1),disabled:h,style:dD(!h),children:a("common_reload")}),(0,r.jsx)("button",{type:"button",onClick:()=>void E(),disabled:null===d||h||!0!==S,style:dH(null!==d&&!h&&!0===S),children:h?a("common_saving"):a("common_save")})]})]}):(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.6,marginBottom:12,maxWidth:560},children:a("settingsJson_hint")}),(g||"string"==typeof S)&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)",marginBottom:10,fontFamily:"var(--font-mono)"},children:"string"==typeof S?S:g}),!0===S&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-ok, var(--accent))",marginBottom:10,fontFamily:"var(--font-mono)"},children:a("settingsJson_valid")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"stretch",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden"},children:[(0,r.jsx)("div",{"aria-hidden":"true",style:{flexShrink:0,padding:"10px 6px 10px 10px",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",color:"var(--text-dim)",fontSize:12,lineHeight:1.55,fontFamily:"var(--font-mono)",textAlign:"right",userSelect:"none",overflow:"hidden",maxHeight:"60vh"},children:(d??"").split("\n").map((e,t)=>(0,r.jsx)("div",{style:{transform:`translateY(-${k}px)`},children:t+1},t))}),(0,r.jsx)("textarea",{ref:w,value:d??"",onChange:e=>{c(e.target.value),m(null),v(!1),C(null)},onScroll:e=>j(e.currentTarget.scrollTop),spellCheck:!1,"aria-label":a("settingsJson_editorLabel"),style:{width:"100%",minHeight:320*!e,maxHeight:e?"none":"60vh",padding:"10px 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:12,lineHeight:1.55,outline:"none",fontFamily:"var(--font-mono)",whiteSpace:"pre",overflow:"auto",boxSizing:"border-box",resize:e?"none":"vertical",border:"none",borderRadius:0,minHeight:320,maxHeight:"60vh"}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginTop:12,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void R(),disabled:null===d,style:{minHeight:30,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:null===d?"not-allowed":"pointer",fontSize:12},children:a("settingsJson_format")}),(0,r.jsx)("button",{type:"button",onClick:()=>void T(),disabled:null===d,style:{minHeight:30,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:null===d?"not-allowed":"pointer",fontSize:12},children:a("settingsJson_validate")}),(0,r.jsx)("button",{type:"button",onClick:()=>void E(),disabled:null===d||h||!0!==S,style:{minHeight:30,padding:"0 14px",borderRadius:7,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",cursor:null===d||h||!0!==S?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:null===d||h||!0!==S?.65:1},children:h?a("common_saving"):a("common_save")}),(0,r.jsx)("button",{type:"button",onClick:()=>b(e=>e+1),disabled:h,style:{minHeight:30,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:h?"not-allowed":"pointer",fontSize:12},children:a("common_reload")}),x&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--accent)"},children:a("common_saved")})]})]})}var dU=n(67381),dq=n(64433),dK=n(70350),dJ=n(88195),dV=n(9312),dY=n(87275),dX=n(22008),dG=n(95476),dZ=n(35029),dQ=n(14489),d0=n(78728),d1=n(19872),d2=n(7751),d4=n(92526),d6=n(48238),d5=n(57794),d8=n(41098),d3=n(84604),d9=n(15315),d7=n(74278),ce=n(55457),ct=n(71437),cn=n(29167),cr=n(97283),ci=n(34166),co=n(33889),cl=n(85486),cs=n(74068),ca=n(83546),cd=n(83709);let cc={anthropic:{Icon:dU.A,hasColor:!1},openai:{Icon:dq.A,hasColor:!1},"openai-codex":{Icon:dq.A,hasColor:!1},google:{Icon:dK.A,hasColor:!0},"google-vertex":{Icon:dK.A,hasColor:!0},"ant-ling":{Icon:co.A,hasColor:!0},deepseek:{Icon:dJ.A,hasColor:!0},groq:{Icon:dV.A,hasColor:!1},mistral:{Icon:dY.A,hasColor:!0},moonshotai:{Icon:dX.A,hasColor:!1},"moonshotai-cn":{Icon:dX.A,hasColor:!1},moonshot:{Icon:dX.A,hasColor:!1},minimax:{Icon:dG.A,hasColor:!0},"minimax-cn":{Icon:dG.A,hasColor:!0},fireworks:{Icon:dZ.A,hasColor:!0},huggingface:{Icon:dQ.A,hasColor:!0},cerebras:{Icon:d0.A,hasColor:!0},openrouter:{Icon:d1.A,hasColor:!1},xai:{Icon:d2.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:d4.A,hasColor:!0},"cloudflare-workers-ai":{Icon:d4.A,hasColor:!0},"vercel-ai-gateway":{Icon:d6.A,hasColor:!1},"github-copilot":{Icon:d5.A,hasColor:!1},"amazon-bedrock":{Icon:d8.A,hasColor:!0},"azure-openai-responses":{Icon:d3.A,hasColor:!0},"kimi-coding":{Icon:d9.A,hasColor:!0},nvidia:{Icon:cl.A,hasColor:!0},opencode:{Icon:cs.A,hasColor:!1},"opencode-go":{Icon:cs.A,hasColor:!1},qwen:{Icon:d7.A,hasColor:!0},xiaomi:{Icon:ca.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:ca.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:ca.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:ca.A,hasColor:!1},zai:{Icon:cd.A,hasColor:!1},"zai-coding-cn":{Icon:cd.A,hasColor:!1},zhipu:{Icon:ce.A,hasColor:!0},cohere:{Icon:ct.A,hasColor:!0},perplexity:{Icon:cn.A,hasColor:!0},together:{Icon:cr.A,hasColor:!0},grok:{Icon:ci.A,hasColor:!1}},cu=["openai-completions","openai-responses","openai-codex-responses","anthropic-messages","google-generative-ai"];function cp({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let ch={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 cf({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...ch,fontFamily:i?"var(--font-mono)":"inherit"}})}function cg({value:e,onChange:t,placeholder:n,mono:o,onKeyDown:l,autoComplete:s="off",spellCheck:a=!1,style:d}){let{t:c}=(0,eU.s9)(),[u,p]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{e||p(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:u?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:l,placeholder:n,style:{...ch,paddingRight:34,fontFamily:o?"var(--font-mono)":"inherit"},autoComplete:s,spellCheck:a}),(0,r.jsx)("button",{type:"button",onClick:()=>p(e=>!e),"aria-label":c(u?"models_hideApiKey":"models_showApiKey"),title:c(u?"models_hideApiKey":"models_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:u?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function cm({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:ch})}function cx({value:e,onChange:t,options:n,required:i}){let{t:o}=(0,eU.s9)();return(0,r.jsxs)("select",{value:e,onChange:e=>t(e.target.value),style:{...ch,color:e?"var(--text)":"var(--text-dim)"},children:[!i&&(0,r.jsx)("option",{value:"",children:o("models_inheritNone")}),n.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})}function cv({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function cy({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function cb({label:e,onClick:t,disabled:n=!1,success:i=!1,error:o=!1,children:l}){return(0,r.jsx)("button",{type:"button",onClick:t,disabled:n,title:e,"aria-label":e,style:{width:24,height:24,padding:0,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",background:i?"var(--status-success)":"none",border:`1px solid ${i?"var(--status-success)":o?"var(--status-danger)":"var(--border)"}`,borderRadius:5,color:i?"#fff":o?"var(--status-danger)":n?"var(--text-dim)":"var(--text-muted)",cursor:n?"not-allowed":"pointer",opacity:n?.55:1,boxSizing:"border-box"},children:l})}function cw({value:e,onChange:t}){let{t:n}=(0,eU.s9)(),i=Object.entries(e??{}),o=(e,n,r)=>{let o=i.map(([t,i],o)=>o===e?[n,r]:[t,i]),l={};for(let[e,t]of o)e.trim()&&(l[e.trim()]=t);t(Object.keys(l).length?l:void 0)};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.map(([e,l],s)=>(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr auto",gap:6},children:[(0,r.jsx)(cf,{value:e,onChange:e=>o(s,e,l),placeholder:n("models_headerKey"),mono:!0}),(0,r.jsx)(cf,{value:l,onChange:t=>o(s,e,t),placeholder:n("models_headerValue"),mono:!0}),(0,r.jsx)("button",{type:"button",onClick:()=>{let e;return e={},void(i.forEach(([t,n],r)=>{r!==s&&(e[t]=n)}),t(Object.keys(e).length?e:void 0))},style:{minHeight:30,padding:"0 8px",borderRadius:5,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--status-danger)",cursor:"pointer",fontSize:11},children:n("common_remove")})]},s)),(0,r.jsxs)("button",{type:"button",onClick:()=>{let n={...e??{}},r=1,i="X-Custom-Header";for(;i in n;)i=`X-Custom-Header-${r++}`;n[i]="",t(n)},style:{alignSelf:"flex-start",minHeight:28,padding:"0 10px",borderRadius:5,border:"1px dashed var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:["+ ",n("models_addHeader")]})]})}let ck=["supportsDeveloperRole","supportsReasoningEffort","supportsStore","supportsUsageInStreaming","supportsStrictMode","sendSessionAffinityHeaders","supportsLongCacheRetention"],cj=["supportsDeveloperRole","supportsReasoningEffort","requiresReasoningContentOnAssistantMessages","requiresThinkingAsText","supportsLongCacheRetention","supportsStore","supportsUsageInStreaming","supportsStrictMode","sendSessionAffinityHeaders"],cS={supportsDeveloperRole:"models_compatDeveloperRole",supportsReasoningEffort:"models_compatReasoningEffort",supportsStore:"models_compatStore",supportsUsageInStreaming:"models_compatUsageInStreaming",supportsStrictMode:"models_compatStrictMode",sendSessionAffinityHeaders:"models_compatSessionAffinityHeaders",supportsLongCacheRetention:"models_compatLongCacheRetention",requiresReasoningContentOnAssistantMessages:"models_compatReasoningContentOnAssistant",requiresThinkingAsText:"models_compatThinkingAsText"},cC={input:"models_costInput",output:"models_costOutput",cacheRead:"models_costCacheRead",cacheWrite:"models_costCacheWrite"},c_=["","openai","openrouter","together","baseten","deepseek","zai","qwen","chat-template","qwen-chat-template","string-thinking","ant-ling"],cI=["","openai","openai-nosession","openrouter"],cR=["","max_tokens","max_completion_tokens"];function cT(e,t,n){let r={...e??{}};return n?r[t]=n:delete r[t],Object.keys(r).length?r:void 0}function cE({keys:e,compat:t,onChange:n}){let{t:i}=(0,eU.s9)();return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.map(e=>(0,r.jsx)(cv,{label:i(cS[e]),checked:t?.[e]===!0,onChange:r=>{let i;return n((i={...t??{}},r?i[e]=!0:delete i[e],Object.keys(i).length?i:void 0))}},e))})}function cM({name:e,provider:t,onChange:n,onRename:o,onDelete:l}){let{t:s}=(0,eU.s9)(),[a,d]=(0,i.useState)(e);(0,i.useEffect)(()=>d(e),[e]);let c=(e,r)=>n({...t,[e]:r});return(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(cy,{children:s("models_provider")}),(0,r.jsx)("button",{onClick:l,style:{padding:"3px 8px",background:"none",border:"1px solid var(--status-danger-border)",borderRadius:4,color:"var(--status-danger)",cursor:"pointer",fontSize:11},children:s("models_delete")})]}),(0,r.jsxs)(cp,{label:s("models_providerName"),children:[(0,r.jsx)(cf,{value:a,onChange:d,placeholder:"provider-name",mono:!0}),a!==e&&a.trim()&&(0,r.jsx)("button",{onClick:()=>o(a.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--accent)",border:"none",borderRadius:4,color:"#fff",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:s("models_rename")})]}),(0,r.jsx)(cp,{label:s("models_baseUrl"),children:(0,r.jsx)(cf,{value:t.baseUrl??"",onChange:e=>c("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(cp,{label:s("models_apiKey"),children:[(0,r.jsx)(cg,{value:t.apiKey??"",onChange:e=>c("apiKey",e||void 0),placeholder:s("models_apiKeyPlaceholder"),mono:!0}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:s("models_apiKeyHint")})]}),(0,r.jsx)(cp,{label:s("models_apiLabel"),children:(0,r.jsx)(cx,{value:t.api??"openai-completions",onChange:e=>c("api",e),options:cu,required:!0})}),(0,r.jsx)(cv,{label:s("models_authHeader"),checked:!0===t.authHeader,onChange:e=>c("authHeader",e||void 0)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:-8},children:s("models_authHeaderHint")}),(0,r.jsxs)("div",{children:[(0,r.jsx)(cy,{children:s("models_headers")}),(0,r.jsx)("div",{style:{marginTop:8},children:(0,r.jsx)(cw,{value:t.headers,onChange:e=>c("headers",e)})}),t.headersConfigured&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:4},children:s("models_headersHint")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(cy,{children:s("models_compat")}),(0,r.jsxs)("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)(cp,{label:s("models_sessionAffinityFormat"),children:(0,r.jsx)(cx,{value:"string"==typeof t.compat?.sessionAffinityFormat?String(t.compat.sessionAffinityFormat):"",onChange:e=>c("compat",cT(t.compat,"sessionAffinityFormat",e)),options:cI})}),(0,r.jsx)(cE,{keys:ck,compat:t.compat,onChange:e=>c("compat",e)})]})]})]})}let cA=["off","minimal","low","medium","high","xhigh","max"],cL={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"var(--status-danger)"};function cz({value:e,onChange:t}){let{t:n}=(0,eU.s9)(),i=e??{},o=(e,n)=>{let r={...i};"omit"===n?delete r[e]:r[e]=n,t(Object.keys(r).length?r:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:cA.map(e=>{let t=i[e],l=e in i?null===t?"null":"string":"omit",s="string"==typeof t?t:"",a=cL[e],d={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)"},c={background:"var(--accent)",color:"#fff",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:a,flexShrink:0,opacity:"null"===l?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===l?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===l?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>o(e,"omit"),style:{...d,..."omit"===l?c:{}},children:n("models_default")}),(0,r.jsx)("button",{onClick:()=>o(e,null),style:{...d,borderLeft:"1px solid var(--border)",..."null"===l?{background:"var(--status-danger)",color:"#fff",fontWeight:600}:{}},children:n("models_disabled")})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===l?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>o(e,s||e),style:{...d,..."string"===l?c:{},borderRight:"1px solid var(--border)",flexShrink:0},children:n("models_custom")}),(0,r.jsx)("input",{value:s,onChange:t=>o(e,t.target.value),onFocus:()=>{"string"!==l&&o(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===l?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===l?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let cW={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function c$({providerName:e,provider:t,model:n,onChange:o,onDelete:l}){let{t:s}=(0,eU.s9)(),[a,d]=(0,i.useState)({phase:"idle"}),c=(e,t)=>o({...n,[e]:t}),u=(()=>{if("idle"===a.phase)return null;if("testing"===a.phase)return s("models_testing");let e=[void 0!==a.latencyMs?`${a.latencyMs}ms`:null,void 0!==a.status?`HTTP ${a.status}`:null].filter(Boolean);return"success"===a.phase?[s("models_connected"),...e,a.responseText||null].filter(Boolean).join(" \xb7 "):[s("models_failed"),...e,a.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{d({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]);let p=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==a.phase){d({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.text(),o={};try{o=JSON.parse(i)}catch{o={}}if(!r.ok||!o.ok){let e=i.trim().slice(0,200),t="string"==typeof o.error&&o.error.trim()?o.error:null;d({phase:"error",message:t??(e||`HTTP ${r.status}`),latencyMs:o.latencyMs,status:o.status??(r.ok?void 0:r.status)});return}d({phase:"success",latencyMs:o.latencyMs,status:o.status,responseText:o.responseText})}catch(e){d({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,a.phase]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(cy,{children:s("models_model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[u&&(0,r.jsx)("span",{title:u,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===a.phase?"#fecaca":"success"===a.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===a.phase?"#fee2e2":"success"===a.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:u}),(0,r.jsx)(cb,{onClick:p,disabled:!n.id.trim()||"testing"===a.phase,success:"success"===a.phase,error:"error"===a.phase,label:"testing"===a.phase?s("models_testing"):"success"===a.phase?s("models_testAgain"):"error"===a.phase?s("models_testFailedAgain"):s("models_test"),children:"testing"===a.phase?(0,r.jsx)(dz.A,{size:12,className:"animate-spin","aria-hidden":!0}):"success"===a.phase?(0,r.jsx)(rd.A,{size:12,"aria-hidden":!0}):(0,r.jsx)(dW.A,{size:12,"aria-hidden":!0})}),(0,r.jsx)("button",{onClick:l,style:{height:24,padding:"0 8px",background:"none",border:"1px solid var(--status-danger-border)",borderRadius:4,color:"var(--status-danger)",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:s("common_remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(cp,{label:s("models_id"),children:(0,r.jsx)(cf,{value:n.id,onChange:e=>c("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(cp,{label:s("models_nameLabel"),children:(0,r.jsx)(cf,{value:n.name??"",onChange:e=>c("name",e||void 0),placeholder:s("models_displayName")})})]}),(0,r.jsx)(cp,{label:s("models_apiOverride"),children:(0,r.jsx)(cx,{value:n.api??"",onChange:e=>c("api",e||void 0),options:cu})}),(0,r.jsx)(cp,{label:s("models_baseUrlOverride"),children:(0,r.jsx)(cf,{value:n.baseUrl??"",onChange:e=>c("baseUrl",e||void 0),placeholder:s("models_baseUrlOverrideHint"),mono:!0})}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(cv,{label:s("models_reasoning"),checked:n.reasoning??!1,onChange:e=>c("reasoning",e||void 0)}),(0,r.jsx)(cv,{label:s("models_imageInput"),checked:n.input?.includes("image")??!1,onChange:e=>c("input",e?["text","image"]:["text"])})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(cv,{label:s("models_thinkingCompat"),checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>o(function(e,t){if(t)return{...e,compat:{...e.compat??{},...cW}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(cy,{children:s("models_thinkingMap")}),n.thinkingLevelMap&&(0,r.jsx)(cb,{label:s("models_clearThinkingMap"),onClick:()=>c("thinkingLevelMap",void 0),children:(0,r.jsx)(d$.A,{size:12,"aria-hidden":!0})})]}),(0,r.jsx)(cz,{value:n.thinkingLevelMap,onChange:e=>c("thinkingLevelMap",e)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:6},children:s("models_thinkingMapHint")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(cp,{label:s("models_contextWindow"),children:(0,r.jsx)(cm,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>c("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(cp,{label:s("models_maxOutput"),children:(0,r.jsx)(cm,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>c("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(cy,{children:s("models_cost")}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(cp,{label:s(cC[e]),children:(0,r.jsx)(cm,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void o({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(cy,{children:s("models_headers")}),(0,r.jsx)("div",{style:{marginTop:8},children:(0,r.jsx)(cw,{value:n.headers,onChange:e=>c("headers",e)})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(cy,{children:s("models_compat")}),(0,r.jsxs)("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(cp,{label:s("models_thinkingFormat"),children:(0,r.jsx)(cx,{value:"string"==typeof n.compat?.thinkingFormat?String(n.compat.thinkingFormat):"",onChange:e=>c("compat",cT(n.compat,"thinkingFormat",e)),options:c_})}),(0,r.jsx)(cp,{label:s("models_maxTokensField"),children:(0,r.jsx)(cx,{value:"string"==typeof n.compat?.maxTokensField?String(n.compat.maxTokensField):"",onChange:e=>c("compat",cT(n.compat,"maxTokensField",e)),options:cR})})]}),(0,r.jsx)(cp,{label:s("models_sessionAffinityFormat"),children:(0,r.jsx)(cx,{value:"string"==typeof n.compat?.sessionAffinityFormat?String(n.compat.sessionAffinityFormat):"",onChange:e=>c("compat",cT(n.compat,"sessionAffinityFormat",e)),options:cI})}),(0,r.jsx)(cE,{keys:cj,compat:n.compat,onChange:e=>c("compat",e)})]})]})]})}function cP({provider:e,onRefresh:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)({phase:"idle"}),[s,a]=(0,i.useState)(""),d=(0,i.useRef)(null),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{("auth"===o.phase||"prompt"===o.phase)&&setTimeout(()=>c.current?.focus(),50)},[o.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),a(""),d.current?.close(),d.current=null},[e.id]),(0,i.useEffect)(()=>()=>{d.current?.close()},[]);let u=(0,i.useCallback)(()=>{d.current?.close(),l({phase:"connecting"}),a("");let r=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);d.current=r,r.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),window.open(n.url,"_blank","noopener,noreferrer")):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),window.open(n.verificationUri,"_blank","noopener,noreferrer")):"prompt_request"===n.type?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?(r.close(),l({phase:"success"}),t()):"error"===n.type?(r.close(),l({phase:"error",message:n.message})):"cancelled"===n.type&&(r.close(),l({phase:"idle"}))},r.onerror=()=>{r.close(),l(e=>"success"===e.phase?e:{phase:"error",message:n("oauth_connectionLost")})}},[e.id,t,n]),p=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),l({phase:"idle"}),t()},[e.id,t]),h=(0,i.useCallback)(async(t,r)=>{if(r.trim()){l({phase:"progress",message:n("oauth_verifying")});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r.trim()})});if(!n.ok){let e=await n.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${n.status}`});return}a("")}catch(e){l({phase:"error",message:e instanceof Error?e.message:n("oauth_networkError")})}}},[e.id,n]),f=(0,i.useCallback)(async(t,r)=>{l({phase:"progress",message:n("oauth_continuing")});try{let n=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:r})});if(!n.ok){let e=await n.json().catch(()=>({}));l({phase:"error",message:e.error??`Server error ${n.status}`})}}catch(e){l({phase:"error",message:e instanceof Error?e.message:n("oauth_networkError")})}},[e.id,n]),g="connecting"===o.phase||"progress"===o.phase||"auth"===o.phase||"device_code"===o.phase||"prompt"===o.phase||"select"===o.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(cy,{children:n("models_subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"var(--status-success)":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"var(--status-success)":"var(--text-dim)"},children:e.loggedIn?n("models_subscriptionStatus"):n("models_subscriptionNotConnected")})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.loggedIn?n("models_alreadyConnected"):n("models_connectAccount",{provider:e.name})}),"connecting"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:n("models_openingBrowser")}),"select"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:o.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:o.options.map(e=>(0,r.jsx)("button",{onClick:()=>f(o.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===o.phase||"prompt"===o.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===o.phase?n("models_redirectInstructions"):o.message}),"auth"===o.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[n("models_browserNotOpened")," ",(0,r.jsx)("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:n("models_openLoginPage")}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:c,value:s,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&h(o.token,s)},placeholder:"auth"===o.phase?"http://localhost:1455/auth/callback?code=…":o.placeholder??n("models_enterValue"),style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>h(o.token,s),disabled:!s.trim(),style:{padding:"6px 12px",background:s.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:s.trim()?"#fff":"var(--text-dim)",cursor:s.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:n("models_submit")})]})]}),"device_code"===o.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("models_verifyPage")}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:o.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:o.verificationUri}),o.expiresInSeconds?` ${n("models_expiresIn",{minutes:Math.ceil(o.expiresInSeconds/60)})}`:""]})]}),"progress"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o.message}),"success"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--status-success)"},children:n("models_connectedSuccessfully")}),"error"===o.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--status-danger)"},children:o.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:g?(0,r.jsx)("button",{onClick:()=>{d.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:n("models_cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{onClick:u,style:{padding:"5px 14px",background:"var(--accent)",border:"none",borderRadius:5,color:"#fff",cursor:"pointer",fontSize:12,fontWeight:600},children:e.loggedIn?n("models_relogin"):n("models_login")}),e.loggedIn&&(0,r.jsx)("button",{onClick:p,style:{padding:"5px 12px",background:"none",border:"1px solid var(--status-danger-border)",borderRadius:5,color:"var(--status-danger)",cursor:"pointer",fontSize:12},children:n("models_disconnect")})]})})]})}function cF({provider:e,onRefresh:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(""),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1);(0,i.useEffect)(()=>{l(""),p(null),f(!1)},[e.id]);let g=(0,i.useCallback)(async()=>{if(o.trim()){a(!0),p(null),f(!1);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:o.trim()})}),r=await n.json();!n.ok||r.error?p(r.error??`HTTP ${n.status}`):(l(""),f(!0),setTimeout(()=>f(!1),2e3),t())}catch(e){p(String(e))}finally{a(!1)}}},[o,e.id,t]),m=(0,i.useCallback)(async()=>{c(!0),p(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?p(r.error??`HTTP ${n.status}`):t()}catch(e){p(String(e))}finally{c(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(cy,{children:n("models_apiKey")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"var(--status-success)":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"var(--status-success)":"var(--text-dim)"},children:n(e.configured?"models_configured":"models_notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?n("models_keyStored"):n("models_enableModels",{provider:e.displayName,count:e.modelCount})}),(0,r.jsx)(cp,{label:n("models_apiKey"),children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(cg,{value:o,onChange:l,onKeyDown:e=>{"Enter"===e.key&&o.trim()&&g()},placeholder:e.configured?n("models_enterNewKey"):"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:g,disabled:s||!o.trim()||h,style:{padding:"6px 12px",background:h?"var(--status-success)":o.trim()?"var(--accent)":"var(--bg-panel)",border:"none",borderRadius:5,color:o.trim()||h?"#fff":"var(--text-dim)",cursor:s||!o.trim()||h?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[h&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),n(h?"common_saved":s?"models_saving":"common_save")]})]})}),u&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--status-danger)"},children:u}),e.configured&&(0,r.jsx)("button",{onClick:m,disabled:d,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid var(--status-danger-border)",borderRadius:5,color:"var(--status-danger)",cursor:d?"not-allowed":"pointer",fontSize:12},children:n(d?"models_removing":"models_disconnect")})]})}function cH({id:e,size:t}){let n=cc[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}function cD({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:o,onAddCustom:l,onClose:s,loading:a=!1,extensionProvidersError:d=null,embedded:c=!1}){let{t:u}=(0,eU.s9)(),[p,h]=(0,i.useState)(""),f=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>f.current?.focus(),30)},[]);let g=p.trim().toLowerCase(),m=e.filter(e=>!e.loggedIn&&(!g||e.name.toLowerCase().includes(g))),x=t.filter(e=>!e.configured&&(!g||e.displayName.toLowerCase().includes(g)||e.id.toLowerCase().includes(g))),v=!g||"custom".includes(g)||"openai-compatible".includes(g)||"anthropic-compatible".includes(g),y=m.length+x.length+ +!!v,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,r.jsx)("div",{style:c?{position:"absolute",inset:0,zIndex:10,padding:12,boxSizing:"border-box",background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"}:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&s()},children:(0,r.jsxs)("div",{style:{width:c?"100%":820,maxWidth:c?"100%":"calc(100vw - 32px)",maxHeight:c?"100%":"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("button",{type:"button",onClick:s,"aria-label":u("common_cancel"),style:{display:"inline-flex",alignItems:"center",gap:4,flexShrink:0,minHeight:28,padding:"0 8px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}),u("common_cancel")]}),(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:f,value:p,onChange:e=>h(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),s())},placeholder:u("models_searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:14},children:[d&&(0,r.jsx)("div",{role:"status",style:{marginBottom:10,padding:"8px 10px",borderRadius:"var(--radius-md)",border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:u("models_extensionProvidersFailed",{error:d})}),a?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-muted)",textAlign:"center"},children:u("common_loading")}):0===y?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:u("models_noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[v&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("models_custom")}),v&&(0,r.jsxs)("button",{onClick:()=>{l(),s()},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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u("models_compatible")}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("models_customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!v,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("models_subscriptions")}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),s()},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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(cH,{id:e.id,size:28})]},e.id)),x.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(m.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:u("models_apiKey")}),x.map(e=>(0,r.jsxs)("button",{onClick:()=>{o(e.id),s()},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,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:u("models_authRequiredToViewModels")})]}),(0,r.jsx)(cH,{id:e.id,size:28})]},e.id))]})]})]})})}function cN({onClose:e,embedded:t=!1,onAuthStateChange:n,cwd:o}){let{t:l}=(0,eU.s9)(),s=ra(),[a,d]=(0,i.useState)("basic"),[c,u]=(0,i.useState)({providers:{}}),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(!0),[m,x]=(0,i.useState)(!1),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(null),[_,I]=(0,i.useState)([]),[R,T]=(0,i.useState)([]),[E,M]=(0,i.useState)(null),[A,L]=(0,i.useState)(!1),[z,W]=(0,i.useState)(!0),[$,P]=(0,i.useState)(!0),F=(0,i.useCallback)(()=>{W(!0),fetch("/api/auth/providers").then(e=>e.json()).then(e=>I(e.providers)).catch(()=>{}).finally(()=>W(!1))},[]),H=(0,i.useCallback)(()=>{P(!0);let e=o&&""!==o.trim()?`?cwd=${encodeURIComponent(o)}`:"";fetch(`/api/auth/all-providers${e}`).then(e=>e.json()).then(e=>{T(e.providers),M("string"==typeof e.extensionProvidersError&&e.extensionProvidersError?e.extensionProvidersError:null)}).catch(()=>{}).finally(()=>P(!1))},[o]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok){w("string"==typeof t.error&&t.error.trim()?t.error:`HTTP ${e.status}`),u({providers:{}}),h(null);return}w(null);let{baseline:n,...r}=t,i=r.providers?r:{...r,providers:{}};u(i),h(n??null);let o=Object.keys(i.providers??{});o.length>0&&!s&&C({type:"provider",name:o[0]})}).catch(()=>{u({providers:{}}),h(null)}).finally(()=>g(!1)),F(),H()},[F,H]),(0,i.useEffect)(()=>{if("basic"!==a)return;let e=!1;return fetch("/api/models-config").then(e=>e.json()).then(t=>{if(e)return;let{baseline:n,...r}=t;u(r.providers?r:{...r,providers:{}}),n&&h(n)}).catch(()=>void 0),()=>{e=!0}},[a]);let D=(0,i.useCallback)(()=>{F(),H(),n?.()},[F,H,n]),N=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;c.providers?.[e];)e=`new-provider-${t++}`;u(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),C({type:"provider",name:e})},[c.providers]),B=(0,i.useCallback)((e,t)=>{u(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),O=(0,i.useCallback)((e,t)=>{u(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),C(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),U=(0,i.useCallback)(e=>{u(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),u(e=>{let t=Object.keys(e.providers??{});return s?C(null):C(t.length>0?{type:"provider",name:t[0]}:null),e})},[s]),q=(0,i.useCallback)(e=>{u(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),u(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return C({type:"model",providerName:e,index:n}),t})},[]),K=(0,i.useCallback)((e,t,n)=>{u(r=>{let i=r.providers?.[e]??{},o=[...i.models??[]];return o[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:o}}}})},[]),J=(0,i.useCallback)((e,t)=>{u(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),C({type:"provider",name:e})},[]),V=(0,i.useCallback)(async()=>{if(b)return void y(b);x(!0),y(null),j(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...c,baseline:p})}),t=await e.json();!e.ok||t.error?y(t.error??`HTTP ${e.status}`):(j(!0),t.baseline&&h(t.baseline),setTimeout(()=>j(!1),2e3))}catch(e){y(String(e))}finally{x(!1)}},[c,p,b]),Y=Object.entries(c.providers??{}),X=_.filter(e=>e.loggedIn),G=R.filter(e=>e.configured),Z=(()=>{if(!S)return null;if("oauth"===S.type){if(z)return(0,r.jsx)("div",{style:{padding:20,fontSize:12,color:"var(--text-muted)"},children:l("common_loading")});let e=_.find(e=>e.id===S.providerId);return e?(0,r.jsx)(cP,{provider:e,onRefresh:D},e.id):null}if("apikey"===S.type){if($)return(0,r.jsx)("div",{style:{padding:20,fontSize:12,color:"var(--text-muted)"},children:l("common_loading")});let e=R.find(e=>e.id===S.providerId);return e?(0,r.jsx)(cF,{provider:e,onRefresh:D},e.id):null}if("provider"===S.type){let e=c.providers?.[S.name];return e?(0,r.jsx)(cM,{name:S.name,provider:e,onChange:e=>B(S.name,e),onRename:e=>O(S.name,e),onDelete:()=>U(S.name)},S.name):null}let e=c.providers?.[S.providerName],t=e?.models?.[S.index];return t?(0,r.jsx)(c$,{providerName:S.providerName,provider:e,model:t,onChange:e=>K(S.providerName,S.index,e),onDelete:()=>J(S.providerName,S.index)},`${S.providerName}-${S.index}`):null})();return(0,r.jsxs)("div",{style:t?{position:"relative",display:"flex",flexDirection:"column",height:"100%",minHeight:0,overflow:"hidden"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:t?void 0:t=>{t.target===t.currentTarget&&e()},children:[(0,r.jsxs)("div",{style:t?{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:"var(--bg)",overflow:"hidden"}:{width:s?"calc(100vw - 16px)":860,maxWidth:"calc(100vw - 16px)",height:s?"calc(100dvh - 16px)":"78vh",maxHeight:"calc(100dvh - 16px)",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:[!t&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("models_modelsTitle")}),(0,r.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,r.jsxs)("div",{style:{flexShrink:0,padding:"12px 16px 0",display:"flex",gap:8,flexWrap:"wrap",borderBottom:"basic"===a?void 0:"none"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>d("basic"),style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:"basic"===a?"var(--bg-selected)":"var(--bg-panel)",color:"basic"===a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:"basic"===a?600:400},"aria-current":"basic"===a?"page":void 0,children:l("defaults_basicTab")}),(0,r.jsx)("button",{type:"button",onClick:()=>d("json"),style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:"json"===a?"var(--bg-selected)":"var(--bg-panel)",color:"json"===a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:"json"===a?600:400},"aria-current":"json"===a?"page":void 0,children:l("defaults_jsonTab")}),(0,r.jsx)("button",{type:"button",onClick:()=>d("available"),style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:"available"===a?"var(--bg-selected)":"var(--bg-panel)",color:"available"===a?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:"available"===a?600:400},"aria-current":"available"===a?"page":void 0,children:l("models_availableTab")})]}),"json"===a?(0,r.jsx)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:(0,r.jsx)(dO,{stickyFooter:!0,onClose:e,apiPath:"/api/models-config/raw",fixedHint:"~/.pi/agent/models.json",titleLabel:l("defaults_jsonTab"),fileLabel:"models.json"})}):"available"===a?(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto"},children:(0,r.jsx)(dF,{onModelsChanged:n,cwd:o})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":210,borderRight:s?"none":"1px solid var(--border)",borderBottom:s?"1px solid var(--border)":"none",flexDirection:"column",background:"var(--bg-panel)",...s?{display:S?"none":"flex",flex:1,minHeight:0}:{display:"flex",flexShrink:0}},children:[(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(z||$)&&(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("common_loading")}),X.map(e=>{let t=S?.type==="oauth"&&S.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>C({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,r.jsx)(cH,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),G.map(e=>{let t=S?.type==="apikey"&&S.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>C({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,r.jsx)(cH,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(X.length>0||G.length>0)&&Y.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),f?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("common_loading")}):Y.map(([e,t])=>{let n=S?.type==="provider"&&S.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>C({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{var i;let o=S?.type==="model"&&S.providerName===e&&S.index===n;return(0,r.jsxs)("div",{onClick:()=>C({type:"model",providerName:e,index:n}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",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,r.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||l("models_newModel")}),"number"==typeof t.contextWindow&&Number.isFinite(t.contextWindow)?(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",flexShrink:0},children:(i=t.contextWindow)>=1e6?`${(i/1e6).toFixed(+(i%1e6!=0))}M`:i>=1e3?`${Math.round(i/1e3)}k`:String(i)}):null]},n)}),(0,r.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),q(e)},"aria-label":l("models_addModel",{provider:e}),title:l("models_addModel",{provider:e}),style:{display:"flex",alignItems:"center",width:"100%",padding:"4px 8px 4px 26px",borderRadius:5,border:"none",background:"none",cursor:"pointer",color:"var(--text-dim)",boxSizing:"border-box"},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,r.jsx)(r0.A,{size:13,"aria-hidden":!0})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.jsx)("button",{type:"button",onClick:()=>L(!0),"aria-label":l("models_addProvider"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",minHeight:30,padding:"0 8px",borderRadius:7,border:"1px solid var(--border)",background:A?"var(--bg-selected)":"var(--bg-panel)",color:A?"var(--accent)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500},children:l("models_addProvider")})})]}),(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:20,display:s&&!S?"none":void 0},children:[s&&S&&(0,r.jsxs)("button",{type:"button",onClick:()=>C(null),style:{display:"flex",alignItems:"center",gap:5,minHeight:32,padding:"0 10px",marginBottom:12,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"15 18 9 12 15 6"})}),l("common_back")]}),f?null:Z??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("models_selectDetail")})]})]}),(0,r.jsx)(dB,{fixedHint:"~/.pi/agent/models.json",dynamicHint:b?(0,r.jsx)("span",{style:{color:"var(--status-danger)"},children:l("models_configUnreadable")}):v?(0,r.jsx)("span",{style:{color:"var(--status-danger)"},children:v}):k?(0,r.jsx)("span",{style:{color:"var(--accent)"},children:l("common_saved")}):null,onClose:e,children:(0,r.jsx)("button",{type:"button",onClick:V,disabled:m||k,style:dH(!(m||k)),children:k?l("common_saved"):m?l("models_saving"):l("common_save")})})]})]}),A&&(0,r.jsx)(cD,{oauthProviders:_,apiKeyProviders:R,onSelectOAuth:e=>C({type:"oauth",providerId:e}),onSelectApiKey:e=>C({type:"apikey",providerId:e}),onAddCustom:N,onClose:()=>L(!1),loading:z||$,extensionProvidersError:E,embedded:t})]})}var cB=n(25344),cO=n(68459);function cU(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function cq(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function cK(e){return e?e.slice(0,8):null}function cJ({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,eU.s9)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:i(e?"skills_visible":"skills_hidden"),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,r.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 cV({skill:e,cwd:t,onToggle:n,toggling:i,saveError:o,updateStatus:l,updating:s,updateError:a,onUpdate:d,onRemove:c,locked:u,onToggleLock:p}){let{t:h}=(0,eU.s9)(),f=cU(e),g=!e.disableModelInvocation,m=!!e.install?.canCheckForUpdates,x=l?.state==="update-available",v=(()=>{let t=cK(l?.currentVersion??e.install?.versionHash)??h("skills_unknownVersion");if(x){let e=cK(l?.latestVersion)??"?";return`${t} → ${e}`}return t})();return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0,flex:1},children:[(0,r.jsx)(cJ,{enabled:g,loading:i,onToggle:()=>n(e)}),(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===f?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===f?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:"global"===f?h("common_global"):"project"===f?h("common_project"):h("skills_path")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:13,color:"var(--text)",fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[m&&(0,r.jsxs)("label",{title:h("skills_lockVersionHint"),style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-muted)",cursor:"pointer",padding:"4px 6px",borderRadius:6,border:"1px solid var(--border)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:u,onChange:p}),h("skills_lockVersion")]}),x&&!u&&(0,r.jsx)("button",{type:"button",onClick:d,disabled:s,title:s?h("skills_updating"):h("skills_update"),"aria-label":s?h("skills_updating"):h("skills_update"),style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:32,height:32,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--accent)",cursor:s?"not-allowed":"pointer"},children:s?(0,r.jsx)(dz.A,{size:13,className:"animate-spin","aria-hidden":!0}):(0,r.jsx)(cB.A,{size:13,"aria-hidden":!0})}),(0,r.jsx)("button",{type:"button",onClick:()=>{window.confirm(h("skills_confirmRemove",{name:e.name}))&&c()},disabled:i||s,title:h("common_remove"),"aria-label":h("common_remove"),style:dN(!(i||s)),children:(0,r.jsx)(cO.A,{size:13,"aria-hidden":!0})})]})]}),e.description&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.description}),e.install&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(72px, 100px) minmax(0, 1fr)",gap:"8px 12px",fontSize:12},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:h("common_version")}),(0,r.jsx)("div",{style:{color:x?"var(--status-warning)":"var(--text-muted)",fontFamily:"var(--font-mono)"},children:v}),e.install.package&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:h("plugins_package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.install.package})]})]}),(o||a)&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)"},children:o||a})]})}function cY({cwd:e,installedPackages:t,onInstalled:n}){let{t:o}=(0,eU.s9)(),[l,s]=(0,i.useState)(""),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[m,x]=(0,i.useState)(null),[v,y]=(0,i.useState)(new Set),[b,w]=(0,i.useState)("global"),k=(0,i.useRef)(null);(0,i.useEffect)(()=>{k.current?.focus()},[]);let j=(0,i.useCallback)(async e=>{if(e.trim()){u(!0),h(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 h(n.error);d(n.results??[]),0===(n.results??[]).length&&h(o("skills_noResults"))}catch(e){h(String(e))}finally{u(!1)}}},[o]),S=(0,i.useCallback)(async t=>{g(t),x(null);try{let r=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:b,cwd:e})}),i=await r.json();if(!r.ok||i.error)return void x(i.error??`HTTP ${r.status}`);y(e=>new Set(e).add(`${b}:${t}`)),n()}catch(e){x(String(e))}finally{g(null)}},[n,b,e]),C="global"===b?"~/.pi/agent/skills/":`${(0,rH.nf)(e)}/.pi/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:o("skills_add")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:k,value:l,onChange:e=>s(e.target.value),onKeyDown:e=>{"Enter"===e.key&&j(l)},placeholder:o("skills_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,r.jsx)("button",{onClick:()=>j(l),disabled:c||!l.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--accent)",color:"#fff",cursor:c||!l.trim()?"not-allowed":"pointer",opacity:c||!l.trim()?.5:1,flexShrink:0},children:c?o("skills_searching"):o("common_search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>w(e),style:{padding:"3px 10px",border:"none",cursor:"pointer",background:b===e?"var(--bg-selected)":"none",color:b===e?"var(--text)":"var(--text-dim)",fontWeight:b===e?600:400,borderRight:"global"===e?"1px solid var(--border)":"none"},children:"global"===e?o("common_global"):o("common_project")},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",C]})]}),p&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)"},children:p}),m&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)",wordBreak:"break-word"},children:m})]}),a.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:a.map(e=>{let n=t[b].has(e.package)||v.has(`${b}:${e.package}`),i=f===e.package,l=e.package.indexOf("@"),s=l>-1?e.package.slice(0,l):e.package,a=l>-1?e.package.slice(l+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:a??s}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:s}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&S(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"var(--status-success-bg)":"none",color:n?"var(--status-success)":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${o("skills_installed")}`:i?o("skills_installing"):o("common_install")})]},e.package)})}):!p&&!c&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:[o("skills_discoverPrefix")," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ",o("skills_discoverSuffix")]})]})}function cX({cwd:e,onClose:t,embedded:n=!1,globalOnly:o=!1}){let{t:l}=(0,eU.s9)(),s=ra(),[a,d]=(0,i.useState)([]),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[m,x]=(0,i.useState)(new Set),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(!1),k=b||null!==f,[j,S]=(0,i.useState)({}),[C,_]=(0,i.useState)(new Set),[I,R]=(0,i.useState)(!1),[T,E]=(0,i.useState)(null),[M,A]=(0,i.useState)(null),[L,z]=(0,i.useState)(()=>{let e=(0,eA.b3)("skillLocks");return e&&"object"==typeof e?{...e}:{}}),W=(0,i.useCallback)(e=>{z(t=>{let n=!t[e];return(0,eA.dM)(`skillLocks.${e}`,n),{...t,[e]:n}})},[]),$=(0,i.useCallback)(async()=>{u(!0),h(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=(n.skills??[]).filter(e=>!o||e.sourceInfo?.scope!=="project");return d(r),!(r.length>0)||f||s||g(r[0].filePath),r}catch(e){return h(String(e)),[]}finally{u(!1)}},[e,f]);(0,i.useEffect)(()=>{S({}),A(null),$()},[e]);let P=(0,i.useCallback)(async t=>{let n=(t?[t]:a.filter(e=>{if(!e.install)return!1;let t=cq(e);return!!t&&!L[t]})).map(cq).filter(e=>!!e);if(0!==n.length){A(null),_(e=>new Set([...e,...n])),t||R(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);S(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){A(e instanceof Error?e.message:String(e))}finally{_(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||R(!1)}}},[e,a,L]),F=(0,i.useCallback)(async t=>{if(!t.install)return;let n=cq(t);E(n),A(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await $();let o=i.skill?.install?.versionHash;S(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:o,latestVersion:o}}))}catch(e){A(e instanceof Error?e.message:String(e))}finally{E(null)}},[e,$]),H=(0,i.useCallback)(async t=>{y(null);try{let n=await fetch("/api/skills",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);g(null),await $()}catch(e){y(e instanceof Error?e.message:String(e))}},[e,$]),D=(0,i.useCallback)(async t=>{let n=!t.disableModelInvocation;x(e=>new Set(e).add(t.filePath)),y(null);try{let r=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,filePath:t.filePath,disableModelInvocation:n})}),i=await r.json();if(!r.ok||i.error)return void y(i.error??`HTTP ${r.status}`);d(e=>e.map(e=>e.filePath===t.filePath?{...e,disableModelInvocation:n}:e))}catch(e){y(String(e))}finally{x(e=>{let n=new Set(e);return n.delete(t.filePath),n})}},[]),N=a.find(e=>e.filePath===f)??null;return(0,r.jsx)("div",{style:n?{position:"relative",display:"flex",flexDirection:"column",height:"100%",minHeight:0,overflow:"hidden"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:n?void 0:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsxs)("div",{style:n?{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:"var(--bg)",overflow:"hidden"}:{width:s?"calc(100vw - 16px)":860,maxWidth:"calc(100vw - 16px)",height:s?"calc(100dvh - 16px)":"78vh",maxHeight:"calc(100dvh - 16px)",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:[!n&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:l("common_skills")}),(0,r.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,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:s?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:s?"100%":245,borderRight:s?"none":"1px solid var(--border)",display:s&&k?"none":"flex",flexDirection:"column",...s?{flex:1,minHeight:0}:{flexShrink:0},background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:c?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:l("skills_loading")}):p?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--status-danger)"},children:p}):0===a.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:l("skills_noResults")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===cU(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===cU(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===cU(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===cU(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===cU(e)}]){let r=a.filter(n);r.length>0&&e.push({label:t,skills:r})}return e.map(({label:e,skills:t})=>{let n;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:(n=e.startsWith("project")?l("common_project"):e.startsWith("global")?l("common_global"):l("skills_path"),e.endsWith("skills.sh")?`${n} / skills.sh`:n)}),t.map(e=>{let t=!b&&f===e.filePath,n=e.disableModelInvocation,i=cq(e),o=i?j[i]:void 0,l=o?.state==="update-available",s=cK(e.install?.versionHash);return(0,r.jsx)("div",{onClick:()=>{g(e.filePath),w(!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,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:t?600:400,color:n?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),l&&(0,r.jsx)("span",{style:{display:"inline-block",fontSize:9,marginTop:2,padding:"1px 6px",borderRadius:999,background:"color-mix(in srgb, var(--status-warning) 18%, transparent)",color:"var(--status-warning)",fontWeight:600,fontFamily:"var(--font-mono)"},children:`${cK(o?.currentVersion??e.install?.versionHash)??"?"} → ${cK(o?.latestVersion)??"?"}`}),e.description&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},title:e.description,children:e.description}),s&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2,fontFamily:"var(--font-mono)"},children:s})]})},e.filePath)})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void P(),disabled:I||null!==T||a.every(e=>!e.install),style:{...dD(!(I||null!==T||a.every(e=>!e.install))),flex:1,minHeight:30,padding:"0 6px",fontSize:11},children:I?l("common_loading"):l("skills_checkUpdates")}),(0,r.jsx)("button",{type:"button",onClick:async()=>{for(let e of a.filter(e=>{let t=cq(e);return t&&!L[t]&&j[t]?.state==="update-available"}))await F(e)},disabled:null!==T||!a.some(e=>{let t=cq(e);return t&&!L[t]&&j[t]?.state==="update-available"}),style:{flex:1,minHeight:30,padding:"0 6px",borderRadius:7,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",fontSize:11,fontWeight:600,cursor:null!==T?"not-allowed":"pointer",opacity:null!==T?.5:1},children:l("skills_upgradeAll")}),(0,r.jsx)("button",{type:"button",onClick:()=>w(!0),style:{...dD(!0),flex:1,minHeight:30,padding:"0 6px",fontSize:11,background:b?"var(--bg-selected)":"var(--bg-panel)",color:b?"var(--accent)":"var(--text-muted)"},children:l("skills_add")})]})})]}),(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:20,display:s&&!k?"none":void 0},children:[s&&k&&(0,r.jsxs)("button",{type:"button",onClick:()=>{g(null),w(!1),y(null)},style:{display:"flex",alignItems:"center",gap:5,minHeight:32,padding:"0 10px",marginBottom:12,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"15 18 9 12 15 6"})}),l("common_back")]}),b?(0,r.jsx)(cY,{cwd:e,installedPackages:{global:new Set(a.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(a.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{$()}}):c?null:N?(0,r.jsx)(cV,{skill:N,cwd:e,onToggle:D,toggling:m.has(N.filePath),saveError:v,updateStatus:cq(N)?j[cq(N)]:void 0,updating:T===cq(N),updateError:M,onUpdate:()=>void F(N),onRemove:()=>void H(N),locked:!!(cq(N)&&L[cq(N)]),onToggleLock:()=>{let e=cq(N);e&&W(e)}},N.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:l("skills_select")})]})]}),(0,r.jsx)(dB,{fixedHint:l("skills_countHint",{count:String(a.length)}),dynamicHint:Object.values(j).filter(e=>"update-available"===e.state).length>0?(0,r.jsxs)("span",{style:{color:"var(--status-warning)"},children:[Object.values(j).filter(e=>"update-available"===e.state).length," ",1===Object.values(j).filter(e=>"update-available"===e.state).length?l("skills_updateSingle"):l("skills_updatePlural")]}):v?(0,r.jsx)("span",{style:{color:"var(--status-danger)"},children:v}):M?(0,r.jsx)("span",{style:{color:"var(--status-danger)"},children:M}):null,onClose:t})]})})}function cG({sessionId:e,refreshKey:t=0}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)({kind:"no-session"});(0,i.useEffect)(()=>{if(!e)return void l({kind:"no-session"});let t=!1;return l({kind:"no-session"}),(async()=>{try{let n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(String(n.status));let r=await n.json();if(t)return;l(sj({sessionId:e,payload:r}))}catch{t||l(sj({sessionId:e,failed:!0}))}})(),()=>{t=!0}},[e,t]);let s=(e,t="var(--text-dim)")=>(0,r.jsx)("div",{style:{padding:"2px 8px",fontSize:11,color:t},children:n(e)});return(0,r.jsxs)("div",{style:{padding:"8px 6px 0"},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:n("plugins_shortcuts")}),"no-session"===o.kind?s("plugins_shortcutsNeedsSession"):"failed"===o.kind?s("plugins_shortcutsLoadFailed","var(--status-danger)"):"no-state"===o.kind?s("plugins_shortcutsNoState"):0===o.entries.length?s("plugins_shortcutsEmpty"):o.entries.map(e=>{var t;return(0,r.jsxs)("div",{style:{padding:"4px 8px",fontSize:11,color:"var(--text-muted)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:6,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono, monospace)",color:"var(--text)"},children:sk(e.key)}),e.available?null:(0,r.jsxs)("span",{style:{color:"var(--status-warning)",fontSize:10},children:[n("plugins_shortcutsUnavailable"),"\xb7","browser-reserved"===(t=e.reason)?n("plugins_shortcutsReasonBrowser"):"shell-reserved"===t?n("plugins_shortcutsReasonShell"):"sdk-conflict"===t?n("plugins_shortcutsReasonSdkConflict"):n("plugins_shortcutsReasonTyping")]})]}),e.description?(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:e.description}):null]},`${e.extensionPath}:${e.key}`)}),"ready"===o.kind&&o.entries.length>0?(0,r.jsx)("div",{style:{padding:"6px 8px 0",fontSize:10,color:"var(--text-dim)",lineHeight:1.5},children:n("plugins_shortcutsPanelWindowHint")}):null,"ready"===o.kind&&o.diagnostics.length>0?(0,r.jsxs)("div",{style:{padding:"6px 8px 0"},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:n("plugins_shortcutsDiagnostics")}),o.diagnostics.map((e,t)=>(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.5},children:e.message},`${e.path??""}:${t}`))]}):null]})}function cZ(e){return`${e.scope}\0${e.source}`}function cQ(e){return e.packageName?.trim()||e.source}function c0(e,t){if(e.disabled)return t("plugins_disabled");let n=[e.counts.extensions?t("plugins_countExtensions",{count:e.counts.extensions}):"",e.counts.skills?t("plugins_countSkills",{count:e.counts.skills}):"",e.counts.prompts?t("plugins_countPrompts",{count:e.counts.prompts}):"",e.counts.themes?t("plugins_countThemes",{count:e.counts.themes}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("plugins_noResources")}function c1(e,t){let n=e.version??"",r=t?.latest;return!!(t?.hasUpdate&&r&&r!==n)}function c2(e,t){let n=e.version??"?";return c1(e,t)&&t?.latest?`${n} → ${t.latest}`:n}function c4({pkg:e}){let{t}=(0,eU.s9)(),n=[["extension",t("plugins_extensions")],["skill",t("plugins_skills")],["prompt",t("plugins_prompts")],["theme",t("plugins_themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"plugins_packageDisabled":"plugins_noResolved")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function c6({scope:e}){let{t}=(0,eU.s9)();return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:t("project"===e?"common_project":"common_global")})}function c5({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:i,"aria-label":i,"aria-pressed":e,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",opacity:t?.65:1},children:(0,r.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 c8({value:e,onChange:t}){let{t:n}=(0,eU.s9)();return(0,r.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:7,overflow:"hidden",height:30},children:["global","project"].map(i=>{let o=e===i;return(0,r.jsx)("button",{onClick:()=>t(i),style:{width:76,border:"none",borderRight:"global"===i?"1px solid var(--border)":"none",background:o?"var(--bg-selected)":"none",color:o?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12},children:"project"===i?n("common_project"):n("common_global")},i)})})}function c3({cwd:e,source:t,scope:n,busy:o,actionError:l,onSourceChange:s,onScopeChange:a,onInstall:d}){var c;let{t:u}=(0,eU.s9)(),p=(0,i.useRef)(null);return(0,i.useEffect)(()=>{p.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:u("plugins_add")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:"project"===n?`${(0,rH.nf)(e)}/.pi/agent/{npm,git}`:"~/.pi/agent/{npm,git}"})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:u("common_source")}),(0,r.jsx)("input",{id:"plugin-source",ref:p,value:t,onChange:e=>s(e.target.value),placeholder:"npm:@scope/package",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!o&&d()}})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)(c8,{value:n,onChange:a}),(0,r.jsx)("button",{type:"button",onClick:d,disabled:o||!t.trim(),style:{...{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:(c=o||!t.trim())?"not-allowed":"pointer",fontSize:12,opacity:c?.5:1},background:"var(--accent)",color:"white",borderColor:"var(--accent)"},children:u(o?"plugins_installing":"common_install")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:u("plugins_examples")}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["npm:@scope/pi-plugin","git:https://github.com/user/repo","/absolute/path/to/plugin"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),l&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)",whiteSpace:"pre-wrap"},children:l}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,marginTop:4},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:8},children:u("plugins_searchLibrary")}),(0,r.jsx)(c9,{onPick:e=>s(`npm:${e}`)})]})]})}function c9({onPick:e}){let{t}=(0,eU.s9)(),[n,o]=(0,i.useState)(""),[l,s]=(0,i.useState)(null),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),p=(0,i.useCallback)(async()=>{let e=n.trim();if(e){d(!0),u(null);try{let t=await fetch("/api/plugins/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`HTTP ${t.status}`)}let n=await t.json();s(n.results??[])}catch(e){u(e instanceof Error?e.message:String(e)),s(null)}finally{d(!1)}}},[n]);return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{type:"text",value:n,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p()},placeholder:t("plugins_searchLibraryPlaceholder"),"aria-label":t("plugins_searchLibrary"),style:{flex:1,height:30,padding:"0 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:12,outline:"none"}}),(0,r.jsx)("button",{type:"button",onClick:()=>void p(),disabled:a||!n.trim(),style:{minHeight:30,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:a||!n.trim()?"not-allowed":"pointer",fontSize:12,opacity:a||!n.trim()?.5:1},children:t(a?"common_loading":"common_search")})]}),c&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--status-danger)",marginTop:6},children:c}),l&&0===l.length&&!c&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",marginTop:6},children:t("plugins_searchEmpty")}),l&&l.length>0&&(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginTop:8,maxHeight:240,overflowY:"auto"},children:l.map(t=>(0,r.jsxs)("button",{type:"button",onClick:()=>e(t.name),style:{textAlign:"left",padding:"7px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:600,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.name}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",flexShrink:0},children:["v",t.version]})]}),t.description&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.description})]},t.name))})]})}function c7({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:o,sessionId:l,updateInfo:s,locked:a,onToggleLock:d,onAction:c}){var u;let{t:p}=(0,eU.s9)(),h=cZ(e),f=n?.endsWith(h)??!1,g=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(c5,{enabled:g,loading:f,onToggle:()=>c(e.disabled?"enable":"disable",e),label:e.disabled?p("plugins_enable"):p("plugins_disable")}),(0,r.jsx)(c6,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:p("plugins_disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"color-mix(in srgb, var(--status-warning) 12%, transparent)",color:"var(--status-warning)"},children:p("plugins_filtered")}),(0,r.jsx)("span",{style:{fontFamily:e.packageName?void 0:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:cQ(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[(0,r.jsxs)("label",{title:p("plugins_lockVersionHint"),style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,color:"var(--text-muted)",cursor:"pointer",padding:"4px 6px",borderRadius:6,border:"1px solid var(--border)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:a,onChange:d}),p("plugins_lockVersion")]}),c1(e,s)&&(0,r.jsx)("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)",fontWeight:600,fontFamily:"var(--font-mono)"},children:c2(e,s)}),!a&&(0,r.jsx)("button",{type:"button",onClick:()=>c("update",e),disabled:f,style:{width:26,height:26,padding:0,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",background:"none",border:"1px solid var(--border)",borderRadius:6,color:f?"var(--text-dim)":"var(--text-muted)",cursor:f?"not-allowed":"pointer",opacity:f?.5:1,boxSizing:"border-box"},title:n===`update:${h}`?p("plugins_updating",{source:e.source}):p("plugins_update",{source:e.source}),"aria-label":n===`update:${h}`?p("plugins_updating",{source:e.source}):p("plugins_update",{source:e.source}),children:n===`update:${h}`?(0,r.jsx)(dz.A,{size:13,className:"animate-spin","aria-hidden":!0}):(0,r.jsx)(cB.A,{size:13,"aria-hidden":!0})}),(0,r.jsx)("button",{type:"button",onClick:()=>{window.confirm(p("plugins_confirmRemove",{source:e.source}))&&c("remove",e)},disabled:f,style:dN(!f),title:n===`remove:${h}`?p("plugins_removing"):p("common_remove"),"aria-label":n===`remove:${h}`?p("plugins_removing"):p("common_remove"),children:n===`remove:${h}`?(0,r.jsx)(dz.A,{size:13,className:"animate-spin","aria-hidden":!0}):(0,r.jsx)(cO.A,{size:13,"aria-hidden":!0})})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("common_status")}),(0,r.jsx)("div",{style:{color:"loaded"===(u=e.status)?"var(--accent)":"installed"===u?"var(--status-warning)":"disabled"===u?"var(--text-dim)":"var(--status-danger)",textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("common_version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:c2(e,s)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("plugins_package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??p("common_unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("plugins_source")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.source}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("common_resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:c0(e,p)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("plugins_installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"var(--status-danger)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?(0,rH.nf)(e.installedPath):p("plugins_notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:p("plugins_cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:(0,rH.nf)(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:p("plugins_resolvedResources")}),(0,r.jsx)(c4,{pkg:e})]}),o&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-success)"},children:o}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--status-danger)",whiteSpace:"pre-wrap"},children:i})]})}function ue({cwd:e,sessionId:t,onClose:n,onReloaded:o,embedded:l=!1}){let{t:s}=(0,eU.s9)(),a=ra(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(0),[h,f]=(0,i.useState)(!0),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[y,b]=(0,i.useState)(!1),w=y||null!==x,[k,j]=(0,i.useState)({}),[S,C]=(0,i.useState)(!1),[_,I]=(0,i.useState)(!1),[R,T]=(0,i.useState)(()=>{let e=(0,eA.b3)("pluginLocks");return e&&"object"==typeof e?e:{}}),E=(0,i.useCallback)(e=>{T(t=>{let n=!t[e];return(0,eA.dM)(`pluginLocks.${e}`,n),{...t,[e]:n}})},[]),M=(0,i.useCallback)(async()=>{if(!d)return;let e=d.packages.filter(e=>!R[cZ(e)]);if(0!==e.length){C(!0);try{let t=await fetch("/api/plugins/updates",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({packages:e.map(e=>({source:e.source,installed:e.version??e.configuredVersion??null}))})});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.error??`HTTP ${t.status}`)}let n=await t.json(),r={};for(let t of n.updates??[]){let n=e.find(e=>e.source===t.source);n&&(r[cZ(n)]={latest:t.latest,hasUpdate:t.hasUpdate})}j(r)}catch(e){H(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[d,R]),[A,L]=(0,i.useState)(""),[z,W]=(0,i.useState)("global"),[$,P]=(0,i.useState)(null),[F,H]=(0,i.useState)(null),[D,N]=(0,i.useState)(null),B=(0,i.useMemo)(()=>d?.packages??[],[d?.packages]),O=B.find(e=>cZ(e)===x)??null,U=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:B.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[B]),q=(0,i.useCallback)(async()=>{f(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);c(n),b(e=>0===n.packages.length||e),v(e=>e&&n.packages.some(t=>cZ(t)===e)?e:a?null:n.packages[0]?cZ(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}},[e,a]);(0,i.useEffect)(()=>{q()},[q]);let K=(0,i.useCallback)(async(t,n)=>{let r=cZ(n);P(`${t}:${r}`),H(null),N(null);try{let i=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),o=await i.json();if(!i.ok||o.error)throw Error(o.error??`HTTP ${i.status}`);if(c(o),"update"===t&&j(e=>{let t=e[r];return t?{...e,[r]:{...t,hasUpdate:!1}}:e}),"remove"===t)v(o.packages[0]?cZ(o.packages[0]):null),0===o.packages.length&&b(!0),N(s("plugins_removed")),p(e=>e+1);else{let e={install:s("plugins_installed"),update:s("plugins_updated"),disable:s("plugins_disabledMessage"),enable:s("plugins_enabled")};N(e[t])}}catch(e){H(e instanceof Error?e.message:String(e))}finally{P(null)}},[e,s]),J=(0,i.useCallback)(async()=>{if(!d)return;let e=d.packages.filter(e=>{let t=cZ(e);return!R[t]&&c1(e,k[t])});if(0!==e.length){I(!0);try{for(let t of e)await K("update",t)}finally{I(!1),M()}}},[d,R,k,K,M]),V=(0,i.useCallback)(async()=>{let t=A.trim();if(!t)return;let n=`${z}\0${t}`;P(`install:${n}`),H(null),N(null);try{var r;let i,o,l=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:z,cwd:e})}),a=await l.json();if(!l.ok||a.error)throw Error(a.error??`HTTP ${l.status}`);c(a);let d=(r=a.packages,o=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===z&&e.source===i)??r.find(e=>e.scope===z&&e.source===`npm:${o}`)??r.find(e=>e.scope===z&&e.source.endsWith(i)));v(d?cZ(d):n),b(!1),L(""),N(s("plugins_installed")),p(e=>e+1)}catch(e){H(e instanceof Error?e.message:String(e))}finally{P(null)}},[e,z,A,s]);(0,i.useCallback)(async()=>{if(t){P("reload"),H(null),N(null);try{await (0,li.$J)(t,{type:"reload"}),o?.(),await q(),N(s("plugins_reloaded")),p(e=>e+1)}catch(e){H(e instanceof Error?e.message:String(e))}finally{P(null)}}},[q,o,t,s]);let Y=$?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:l?{position:"relative",display:"flex",flexDirection:"column",height:"100%",minHeight:0,overflow:"hidden"}:{position:"fixed",inset:0,zIndex:1e3,background:"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:l?void 0:e=>{e.target===e.currentTarget&&n()},children:(0,r.jsxs)("div",{style:l?{display:"flex",flexDirection:"column",height:"100%",minHeight:0,background:"var(--bg)",overflow:"hidden"}:{width:a?"calc(100vw - 16px)":860,maxWidth:"calc(100vw - 16px)",height:a?"calc(100dvh - 16px)":"76vh",maxHeight:"calc(100dvh - 16px)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[!l&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common_plugins")}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":245,borderRight:a?"none":"1px solid var(--border)",display:a&&w?"none":"flex",flexDirection:"column",...a?{flex:1,minHeight:0}:{flexShrink:0},background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("common_loading")}):g?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--status-danger)"},children:g}):0===B.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("plugins_noConfigured")}):U.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:"project"===e.scope?s("common_project"):s("common_global")}),e.packages.map(e=>{let t=cZ(e),n=!y&&x===t;return(0,r.jsx)("div",{onClick:()=>{v(t),b(!1),H(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:e.packageName?void 0:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:cQ(e)}),c1(e,k[cZ(e)])&&(0,r.jsx)("span",{style:{display:"inline-block",fontSize:9,marginTop:2,padding:"1px 6px",borderRadius:999,background:"color-mix(in srgb, var(--status-warning) 18%, transparent)",color:"var(--status-warning)",fontWeight:600,fontFamily:"var(--font-mono)"},children:c2(e,k[cZ(e)])}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:c0(e,s)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:c2(e,k[cZ(e)])})]})},t)})]},e.scope))}),(0,r.jsx)(cG,{sessionId:t,refreshKey:u}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void M(),disabled:S||!d,style:{...dD(!(S||!d)),flex:1,minHeight:30,padding:"0 6px",fontSize:11},children:S?s("common_loading"):s("plugins_checkUpdates")}),(0,r.jsx)("button",{type:"button",onClick:()=>void J(),disabled:_||B.every(e=>R[cZ(e)]||!c1(e,k[cZ(e)])),style:{flex:1,minHeight:30,padding:"0 6px",borderRadius:7,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",fontSize:11,fontWeight:600,cursor:_||B.every(e=>R[cZ(e)]||!c1(e,k[cZ(e)]))?"not-allowed":"pointer",opacity:_||B.every(e=>R[cZ(e)]||!c1(e,k[cZ(e)]))?.5:1},children:_?s("common_loading"):s("plugins_upgradeAll")}),(0,r.jsx)("button",{type:"button",onClick:()=>{b(!0),H(null),N(null)},style:{...dD(!0),flex:1,minHeight:30,padding:"0 6px",fontSize:11,background:y?"var(--bg-selected)":"var(--bg-panel)",color:y?"var(--accent)":"var(--text-muted)"},children:s("plugins_add")})]})})]}),(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:20,display:a&&!w?"none":void 0},children:[a&&w&&(0,r.jsxs)("button",{type:"button",onClick:()=>{v(null),b(!1),H(null),N(null)},style:{display:"flex",alignItems:"center",gap:5,minHeight:32,padding:"0 10px",marginBottom:12,borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"15 18 9 12 15 6"})}),s("common_back")]}),y?(0,r.jsx)(c3,{cwd:e,source:A,scope:z,busy:Y,actionError:F,onSourceChange:L,onScopeChange:W,onInstall:V}):h?null:O?(0,r.jsx)(c7,{pkg:O,cwd:e,busyKey:$,actionError:F,actionMessage:D,sessionId:t,updateInfo:k[cZ(O)]??null,locked:!!R[cZ(O)],onToggleLock:()=>E(cZ(O)),onAction:K},cZ(O)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("plugins_select")})]})]}),(0,r.jsx)(dB,{fixedHint:d?s("plugins_totals",{extensions:d.totals.extensions,skills:d.totals.skills,prompts:d.totals.prompts,themes:d.totals.themes}):null,dynamicHint:F?(0,r.jsx)("span",{style:{color:"var(--status-danger)"},children:F}):D?(0,r.jsx)("span",{style:{color:"var(--accent)"},children:D}):d?.diagnostics.length?(0,r.jsx)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"var(--status-danger)":"var(--status-warning)"},children:s(1===d.diagnostics.length?"plugins_diagnostics_one":"plugins_diagnostics_other",{count:d.diagnostics.length})}):null,onClose:n,children:(0,r.jsx)("button",{type:"button",onClick:()=>void q(),disabled:h||null!==$,style:dD(!(h||null!==$)),children:h?s("plugins_refreshing"):s("plugins_refresh")})})]})})}let ut={fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:8},un={fontSize:12,color:"var(--text-muted)",marginBottom:4},ur={width:"100%",maxWidth:420,padding:"7px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,outline:"none",fontFamily:"var(--font-mono)"},ui={...ur,fontFamily:"inherit",cursor:"pointer"};function uo({label:e,value:t,placeholder:n,onChange:i,mono:o=!0}){return(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:e}),(0,r.jsx)("input",{type:"text",value:t,placeholder:n,onChange:e=>i(e.target.value),style:o?ur:{...ur,fontFamily:"inherit"}})]})}function ul({label:e,value:t,min:n,max:i,onChange:o}){return(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:e}),(0,r.jsx)("input",{type:"number",value:t,min:n,max:i,onChange:e=>o(e.target.value),style:{...ur,maxWidth:220}})]})}function us({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked)}),e]})}let ua={off:"input_thinkingOff",minimal:"input_thinkingMinimal",low:"input_thinkingLow",medium:"input_thinkingMedium",high:"input_thinkingHigh",xhigh:"input_thinkingXhigh",max:"input_thinkingMax"},ud={off:"defaults_cacheWarmingOff",streaming:"defaults_cacheWarmingStreaming",idle:"defaults_cacheWarmingIdle"};function uc(e){return"string"==typeof e?e:""}function uu(e){return"number"==typeof e&&Number.isFinite(e)?String(e):""}function up(e){return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function uh(e){var t;let n=up(e.compaction),r=up(e.retry);return{defaultProvider:uc(e.defaultProvider),defaultModel:uc(e.defaultModel),defaultThinkingLevel:e.defaultThinkingLevel??"",cacheWarming:"string"==typeof(t=e.cacheWarming)&&s0.includes(t)?e.cacheWarming:"streaming",compactionEnabled:!0===n.enabled,compactionReserve:uu(n.reserveTokens),compactionKeep:uu(n.keepRecentTokens),retryEnabled:!0===r.enabled,retryMaxRetries:uu(r.maxRetries),retryBaseDelayMs:uu(r.baseDelayMs),hideThinkingBlock:!0===e.hideThinkingBlock,showCacheMissNotices:!0===e.showCacheMissNotices,httpProxy:uc(e.httpProxy),httpIdleTimeoutMs:uu(e.httpIdleTimeoutMs),sessionDir:uc(e.sessionDir),shellPath:uc(e.shellPath),quietStartup:!0===e.quietStartup,externalEditor:uc(e.externalEditor),defaultProjectTrust:uc(e.defaultProjectTrust),doubleEscapeAction:uc(e.doubleEscapeAction),transport:uc(e.transport)||"auto"}}function uf({cwd:e,onClose:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(null),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!0),[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(0),[w,k]=(0,i.useState)("basic"),j=(0,i.useCallback)(async()=>{p(!0),m(null);try{let t,n=new URLSearchParams;e&&n.set("cwd",e);let r=n.toString(),[i,o]=await Promise.all([fetch("/api/settings/raw",{cache:"no-store"}),fetch(`/api/models${r?`?${r}`:""}`)]);if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let s=await i.json();try{t=JSON.parse("string"==typeof s.json?s.json:"{}")}catch{t={}}if(l(t),a(uh(t)),o.ok){let e=await o.json();c(Array.isArray(e.modelList)?e.modelList:[])}else c([])}catch(e){m(e instanceof Error?e.message:String(e)),l(null),a(null)}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{j()},[j,y]);let S=(0,i.useCallback)(async()=>{if(s&&o){f(!0),m(null),v(!1);try{let e=await fetch("/api/settings/raw",{cache:"no-store"});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`HTTP ${e.status}`)}let t=await e.json(),n={...(()=>{try{return JSON.parse("string"==typeof t.json?t.json:"{}")}catch{return{}}})()};n.defaultProvider=s.defaultProvider||void 0,n.defaultModel=s.defaultModel||void 0,n.defaultThinkingLevel=""===s.defaultThinkingLevel?void 0:s.defaultThinkingLevel,n.hideThinkingBlock=s.hideThinkingBlock||void 0,n.showCacheMissNotices=s.showCacheMissNotices||void 0,n.quietStartup=s.quietStartup||void 0,n.cacheWarming=s.cacheWarming;let r={...up(n.compaction)};r.enabled=s.compactionEnabled;let i=Number(s.compactionReserve),o=Number(s.compactionKeep);Number.isFinite(i)&&i>0&&(r.reserveTokens=i),Number.isFinite(o)&&o>0&&(r.keepRecentTokens=o),n.compaction=r;let d={...up(n.retry)};d.enabled=s.retryEnabled;let c=Number(s.retryMaxRetries),u=Number(s.retryBaseDelayMs);for(let e of(Number.isFinite(c)&&c>=0&&(d.maxRetries=c),Number.isFinite(u)&&u>=0&&(d.baseDelayMs=u),n.retry=d,["httpProxy","sessionDir","shellPath","externalEditor","defaultProjectTrust","doubleEscapeAction","transport"])){let t=s[e].trim();t?n[e]=t:delete n[e]}let p=Number(s.httpIdleTimeoutMs);Number.isFinite(p)&&p>0?n.httpIdleTimeoutMs=p:delete n.httpIdleTimeoutMs;let h=await fetch("/api/settings/raw",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({json:JSON.stringify(n,null,2)})});if(!h.ok){let e=await h.json().catch(()=>({}));throw Error(e.error??`HTTP ${h.status}`)}l(n),a(uh(n)),v(!0),window.setTimeout(()=>v(!1),2e3)}catch(e){m(e instanceof Error?e.message:String(e))}finally{f(!1)}}},[s,o]);if(u&&!o)return(0,r.jsx)("div",{style:{padding:"18px 20px",fontSize:12,color:"var(--text-muted)"},children:n("common_loading")});if(g&&!o)return(0,r.jsxs)("div",{style:{padding:"18px 20px"},children:[(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--status-danger)",marginBottom:10},children:[n("defaults_loadFailed"),": ",g]}),(0,r.jsx)("button",{type:"button",onClick:()=>b(e=>e+1),style:{minHeight:30,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:"pointer",fontSize:12},children:n("defaults_retry")})]});if(!o||!s)return null;let C=uh(o),_=s.defaultProvider!==C.defaultProvider||s.defaultModel!==C.defaultModel||s.defaultThinkingLevel!==C.defaultThinkingLevel||s.cacheWarming!==C.cacheWarming||s.compactionEnabled!==C.compactionEnabled||s.compactionReserve!==C.compactionReserve||s.compactionKeep!==C.compactionKeep||s.retryEnabled!==C.retryEnabled||s.retryMaxRetries!==C.retryMaxRetries||s.retryBaseDelayMs!==C.retryBaseDelayMs||s.hideThinkingBlock!==C.hideThinkingBlock||s.showCacheMissNotices!==C.showCacheMissNotices||s.httpProxy!==C.httpProxy||s.httpIdleTimeoutMs!==C.httpIdleTimeoutMs||s.sessionDir!==C.sessionDir||s.shellPath!==C.shellPath||s.quietStartup!==C.quietStartup||s.externalEditor!==C.externalEditor||s.defaultProjectTrust!==C.defaultProjectTrust||s.doubleEscapeAction!==C.doubleEscapeAction||s.transport!==C.transport,I=[];for(let e of d)I.includes(e.provider)||I.push(e.provider);let R=s.defaultProvider?d.filter(e=>e.provider===s.defaultProvider):[],T=e=>({minHeight:30,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:e?"var(--bg-selected)":"var(--bg-panel)",color:e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:e?600:400}),E={marginBottom:22};return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{flexShrink:0,padding:"16px 20px 0",display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>k("basic"),style:T("basic"===w),"aria-current":"basic"===w?"page":void 0,children:n("defaults_basicTab")}),(0,r.jsx)("button",{type:"button",onClick:()=>k("json"),style:T("json"===w),"aria-current":"json"===w?"page":void 0,children:n("defaults_jsonTab")})]}),"json"===w?(0,r.jsx)("div",{style:{flex:1,minHeight:0,display:"flex",flexDirection:"column"},children:(0,r.jsx)(dO,{stickyFooter:!0,onClose:t})}):(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"16px 20px 20px"},children:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.6,marginBottom:16},children:n("defaults_hint")}),g&&(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--status-danger)",marginBottom:12},children:[n("defaults_saveFailed"),": ",g]}),(0,r.jsxs)("div",{style:E,children:[(0,r.jsx)("div",{style:ut,children:n("defaults_modelSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_provider")}),(0,r.jsxs)("select",{value:s.defaultProvider,onChange:e=>{let t=e.target.value,n=d.filter(e=>e.provider===t).some(e=>e.id===s.defaultModel);a({...s,defaultProvider:t,defaultModel:n?s.defaultModel:""})},style:ui,children:[(0,r.jsx)("option",{value:"",children:n("defaults_providerUnset")}),s.defaultProvider&&!I.includes(s.defaultProvider)&&(0,r.jsx)("option",{value:s.defaultProvider,children:s.defaultProvider}),I.map(e=>(0,r.jsx)("option",{value:e,children:e},e))]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_model")}),(0,r.jsxs)("select",{value:s.defaultModel,onChange:e=>a({...s,defaultModel:e.target.value}),style:ui,disabled:!s.defaultProvider,children:[(0,r.jsx)("option",{value:"",children:s.defaultProvider?0!==R.length||s.defaultModel?n("defaults_modelUnset"):n("defaults_modelEmpty"):n("defaults_modelUnset")}),s.defaultModel&&!R.some(e=>e.id===s.defaultModel)&&(0,r.jsx)("option",{value:s.defaultModel,children:s.defaultModel}),R.map(e=>(0,r.jsx)("option",{value:e.id,children:e.name&&e.name!==e.id?`${e.name} (${e.id})`:e.id},`${e.provider}:${e.id}`))]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_thinking")}),(0,r.jsxs)("select",{value:s.defaultThinkingLevel,onChange:e=>a({...s,defaultThinkingLevel:e.target.value}),style:ui,children:[(0,r.jsx)("option",{value:"",children:n("defaults_thinkingUnset")}),sQ.map(e=>(0,r.jsxs)("option",{value:e,children:[e," \xb7 ",n(ua[e])]},e))]}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:4},children:n("defaults_thinkingHint")})]})]})]}),(0,r.jsxs)("div",{style:E,children:[(0,r.jsx)("div",{style:ut,children:n("defaults_compactionSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(us,{label:n("defaults_compactionEnabled"),checked:s.compactionEnabled,onChange:e=>a({...s,compactionEnabled:e})}),(0,r.jsx)(ul,{label:n("defaults_reserveTokens"),value:s.compactionReserve,min:1,onChange:e=>a({...s,compactionReserve:e})}),(0,r.jsx)(ul,{label:n("defaults_keepRecentTokens"),value:s.compactionKeep,min:1,onChange:e=>a({...s,compactionKeep:e})})]})]}),(0,r.jsxs)("div",{style:E,children:[(0,r.jsx)("div",{style:ut,children:n("defaults_retrySection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(us,{label:n("defaults_retryEnabled"),checked:s.retryEnabled,onChange:e=>a({...s,retryEnabled:e})}),(0,r.jsx)(ul,{label:n("defaults_maxRetries"),value:s.retryMaxRetries,min:0,onChange:e=>a({...s,retryMaxRetries:e})}),(0,r.jsx)(ul,{label:n("defaults_baseDelayMs"),value:s.retryBaseDelayMs,min:0,onChange:e=>a({...s,retryBaseDelayMs:e})})]})]}),(0,r.jsxs)("div",{style:E,children:[(0,r.jsx)("div",{style:ut,children:n("defaults_cacheWarmingSection")}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_cacheWarming")}),(0,r.jsx)("select",{value:s.cacheWarming,onChange:e=>a({...s,cacheWarming:e.target.value}),style:ui,children:s0.map(e=>(0,r.jsxs)("option",{value:e,children:[e," \xb7 ",n(ud[e])]},e))}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:4},children:n("defaults_cacheWarmingHint")})]})]}),(0,r.jsxs)("div",{style:E,children:[(0,r.jsx)("div",{style:ut,children:n("defaults_appearanceSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(us,{label:n("defaults_hideThinkingBlock"),checked:s.hideThinkingBlock,onChange:e=>a({...s,hideThinkingBlock:e})}),(0,r.jsx)(us,{label:n("defaults_showCacheMissNotices"),checked:s.showCacheMissNotices,onChange:e=>a({...s,showCacheMissNotices:e})})]})]}),(0,r.jsxs)("div",{style:E,children:[(0,r.jsx)("div",{style:ut,children:n("defaults_advancedSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[(0,r.jsx)(uo,{label:n("defaults_httpProxy"),value:s.httpProxy,onChange:e=>a({...s,httpProxy:e})}),(0,r.jsx)(ul,{label:n("defaults_httpIdleTimeoutMs"),value:s.httpIdleTimeoutMs,min:1,onChange:e=>a({...s,httpIdleTimeoutMs:e})}),(0,r.jsx)(uo,{label:n("defaults_sessionDir"),value:s.sessionDir,onChange:e=>a({...s,sessionDir:e})}),(0,r.jsx)(uo,{label:n("defaults_shellPath"),value:s.shellPath,onChange:e=>a({...s,shellPath:e})}),(0,r.jsx)(uo,{label:n("defaults_externalEditor"),value:s.externalEditor,onChange:e=>a({...s,externalEditor:e})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_defaultProjectTrust")}),(0,r.jsx)("input",{type:"text",value:s.defaultProjectTrust,placeholder:n("defaults_defaultProjectTrustPlaceholder"),onChange:e=>a({...s,defaultProjectTrust:e.target.value}),style:{...ur,fontFamily:"inherit"}})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_doubleEscapeAction")}),(0,r.jsxs)("select",{value:s.doubleEscapeAction,onChange:e=>a({...s,doubleEscapeAction:e.target.value}),style:ui,children:[(0,r.jsx)("option",{value:"",children:n("defaults_unset")}),(0,r.jsx)("option",{value:"fork",children:n("defaults_doubleEscapeFork")}),(0,r.jsx)("option",{value:"tree",children:n("defaults_doubleEscapeTree")}),(0,r.jsx)("option",{value:"none",children:n("defaults_doubleEscapeNone")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:un,children:n("defaults_transport")}),(0,r.jsxs)("select",{value:s.transport,onChange:e=>a({...s,transport:e.target.value}),style:ui,children:[(0,r.jsx)("option",{value:"auto",children:n("defaults_transportAuto")}),(0,r.jsx)("option",{value:"sse",children:n("defaults_transportSse")}),(0,r.jsx)("option",{value:"websocket",children:n("defaults_transportWebsocket")})]})]}),(0,r.jsx)(us,{label:n("defaults_quietStartup"),checked:s.quietStartup,onChange:e=>a({...s,quietStartup:e})})]})]})]})}),"basic"===w&&(0,r.jsxs)(dB,{fixedHint:"~/.pi/agent/settings.json",dynamicHint:g?(0,r.jsxs)("span",{style:{color:"var(--status-danger)"},children:[n("defaults_saveFailed"),": ",g]}):x?(0,r.jsx)("span",{style:{color:"var(--accent)"},children:n("common_saved")}):null,onClose:t,children:[(0,r.jsx)("button",{type:"button",onClick:()=>b(e=>e+1),disabled:u||h,style:dD(!(u||h)),children:n("common_reload")}),(0,r.jsx)("button",{type:"button",onClick:()=>void S(),disabled:!_||h,style:dH(!!(_&&!h)),children:h?n("common_saving"):n("common_save")})]})]})}let ug={fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:8};function um({onClose:e}={}){let t,{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)({system:"",systemAppend:"",agents:""}),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(null),[g,m]=(0,i.useState)(null),[x,v]=(0,i.useState)("system"),y=(0,i.useCallback)(async()=>{c(!0),f(null);try{let e=await fetch("/api/prompts",{cache:"no-store"});if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error??`HTTP ${e.status}`)}let t=await e.json(),n={system:{key:"system",enabled:!1,content:""},systemAppend:{key:"systemAppend",enabled:!1,content:""},agents:{key:"agents",enabled:!1,content:""}};for(let e of t.entries??[])e&&e.key in n&&(n[e.key]=e);l(n),a({system:n.system.content,systemAppend:n.systemAppend.content,agents:n.agents.content})}catch(e){f(e instanceof Error?e.message:String(e)),l(null)}finally{c(!1)}},[]);(0,i.useEffect)(()=>{y()},[y]);let b=(0,i.useCallback)(async(e,t)=>{p(e),f(null),m(null);try{let n=await fetch("/api/prompts",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e,...t})});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??`HTTP ${n.status}`)}void 0!==t.enabled&&o&&l({...o,[e]:{...o[e],enabled:t.enabled}}),m(e),window.setTimeout(()=>m(null),2e3)}catch(e){f(e instanceof Error?e.message:String(e))}finally{p(null)}},[o]);if(d&&!o)return(0,r.jsx)("div",{style:{padding:"18px 20px",fontSize:12,color:"var(--text-muted)"},children:n("common_loading")});if(!o)return(0,r.jsx)("div",{style:{padding:"18px 20px"},children:(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--status-danger)",marginBottom:10},children:[n("prompts_loadFailed"),": ",h]})});let w={system:"SYSTEM.md",systemAppend:"APPEND_SYSTEM.md",agents:"AGENTS.md"},k={system:n("prompts_systemTitle"),systemAppend:n("prompts_systemAppendTitle"),agents:n("prompts_agentsTitle")};return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{flexShrink:0,padding:"16px 20px 0",display:"flex",gap:8,flexWrap:"wrap"},children:["system","systemAppend","agents"].map(e=>{let t;return(0,r.jsx)("button",{type:"button",onClick:()=>v(e),style:{minHeight:28,padding:"0 12px",borderRadius:6,border:"1px solid var(--border)",background:(t=x===e)?"var(--bg-selected)":"var(--bg-panel)",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:t?600:400},"aria-current":x===e?"page":void 0,children:k[e]},e)})}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"12px 20px 20px",display:"flex",flexDirection:"column"},children:[h&&(0,r.jsxs)("div",{style:{flexShrink:0,fontSize:12,color:"var(--status-danger)",marginBottom:12},children:[n("prompts_saveFailed"),": ",h]}),(t=o[x],s[x],t.content,(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[(0,r.jsx)("div",{style:ug,children:k[x]}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:w[x]}),(0,r.jsxs)("label",{style:{display:"inline-flex",alignItems:"center",gap:6,marginLeft:"auto",fontSize:12,color:"var(--text-muted)",cursor:"pointer"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t.enabled,disabled:u===x,onChange:e=>void b(x,{enabled:e.target.checked})}),n("prompts_enabled")]})]}),(0,r.jsx)("textarea",{value:s[x],onChange:e=>{a(t=>({...t,[x]:e.target.value})),f(null),m(null)},spellCheck:!1,disabled:u===x,"aria-label":k[x],style:{width:"100%",flex:1,minHeight:0,padding:"10px 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:12,lineHeight:1.55,outline:"none",fontFamily:"var(--font-mono)",whiteSpace:"pre",overflow:"auto",boxSizing:"border-box",resize:"vertical",resize:"none",flex:1,minHeight:200}})]}))]}),(0,r.jsx)(dB,{fixedHint:w[x],dynamicHint:h?(0,r.jsxs)("span",{style:{color:"var(--status-danger)"},children:[n("prompts_saveFailed"),": ",h]}):o[x].enabled?g===x?(0,r.jsx)("span",{style:{color:"var(--accent)"},children:n("common_saved")}):null:(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:n("prompts_disabledDraftHint")}),onClose:e,children:(0,r.jsx)("button",{type:"button",onClick:()=>void b(x,{content:s[x]}),disabled:u===x||s[x]===o[x].content,style:dH(u!==x&&s[x]!==o[x].content),children:n(u===x?"common_saving":"common_save")})})]})}var ux=n(84747);let uv={openAtLogin:"desktop_openAtLogin",minimizeToTray:"desktop_minimizeToTray",notificationsEnabled:"desktop_notifications"},uy={fontSize:12,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:.5,marginBottom:10};function ub({bridge:e,onClose:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(null),[s,a]=(0,i.useState)(null);(0,i.useEffect)(()=>{let t=!1;return e.getSettings().then(e=>{t||l(eg(e))}).catch(e=>{t||a(n("desktop_settingsLoadFailed",{error:e instanceof Error?e.message:String(e)}))}),()=>{t=!0}},[e,n]);let d=(0,i.useCallback)(t=>{l(r=>{if(!r)return r;let i=!r[t],o={...r,[t]:i};return a(null),e.setSetting(t,i).then(e=>{l(eg(e))}).catch(e=>{l(r),a(n("desktop_settingSaveFailed",{error:e instanceof Error?e.message:String(e)}))}),o})},[e,n]);return(0,r.jsxs)("div",{style:{padding:"4px 2px"},children:[(0,r.jsx)("div",{style:uy,children:n("desktop_pageTitle")}),(0,r.jsx)("p",{style:{margin:"0 0 14px",fontSize:13,color:"var(--text-muted)",lineHeight:1.6},children:n("desktop_pageHint")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[ef.map(e=>(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:10,fontSize:14},children:[(0,r.jsx)("input",{type:"checkbox",checked:o?.[e]??!1,disabled:null===o,"aria-label":n(uv[e]),onChange:()=>d(e)}),(0,r.jsx)("span",{children:n(uv[e])})]},e)),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:n("desktop_notificationsHint")})]}),s?(0,r.jsx)("div",{role:"alert",style:{marginTop:12,fontSize:13,color:"var(--status-danger)"},children:s}):null,t?(0,r.jsx)("div",{style:{marginTop:18},children:(0,r.jsx)("button",{type:"button",className:"extension-card-btn",onClick:t,"aria-label":n("chat_close"),children:n("chat_close")})}):null]})}let uw=["general","appearance","models","defaults","prompts","skills","plugins","desktop"],uk=new Set(["desktop"]),uj={skills:"skills",plugins:"plugins"},uS="pidance:settings:page:v1",uC="appearance";function u_(e){try{let r=e.getItem(uS);if(null===r)return uC;var t,n=r;if("string"!=typeof n||!n)return uC;let i=n;try{i=JSON.parse(n)}catch{i=n}return i&&"object"==typeof i&&!Array.isArray(i)&&(i=i.page),"string"==typeof(t=i)&&uw.includes(t)?i:uC}catch{return uC}}function uI(e,t){return"back"===t.type?{page:null}:e.page===t.page?e:{page:t.page}}function uR(e){switch(e){case"general":return"common_general";case"appearance":return"common_appearance";case"models":return"common_models";case"defaults":return"common_defaults";case"prompts":return"common_prompts";case"skills":return"common_skills";case"plugins":return"common_plugins";case"desktop":return"common_desktop"}}function uT(){try{return u_(window.localStorage)}catch{return u_({getItem:()=>null,setItem:()=>{},removeItem:()=>{}})}}function uE({hint:e}){let{t}=(0,eU.s9)();return(0,r.jsxs)("div",{className:"settings-empty-state",children:[(0,r.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"})}),(0,r.jsx)("div",{style:{fontSize:13,color:"var(--text)",fontWeight:600},children:t("common_selectProject")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.6,maxWidth:380},children:t("common_selectProjectHint")})]})}function uM({label:e,options:t,value:n,onChange:i}){return(0,r.jsxs)("div",{className:"settings-choice",children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:8},children:e}),(0,r.jsx)("div",{className:"settings-segmented-control",role:"group","aria-label":e,children:t.map(e=>{let t=e.value===n;return(0,r.jsx)("button",{type:"button",className:`settings-segmented-option${t?" is-active":""}`,"aria-pressed":t,onClick:()=>i(e.value),children:e.label},e.value)})})]})}let uA={password_too_short:"general_passwordTooShort",remote_requires_password:"general_remoteRequiresPassword",port_invalid:"general_portInvalid",bad_request:"general_badRequest"};function uL({onClose:e}){let{t}=(0,eU.s9)(),[n,o]=(0,i.useState)(null),[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),[m,x]=(0,i.useState)(""),[v,y]=(0,i.useState)(""),[b,w]=(0,i.useState)(!1),[k,j]=(0,i.useState)(null),[S,C]=(0,i.useState)(!1),[_,I]=(0,i.useState)(null),[R,T]=(0,i.useState)(!1),[E,M]=(0,i.useState)(null);(0,i.useEffect)(()=>{u(ei())},[]);let A=(0,i.useCallback)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/auth/ui-session",{method:"GET",credentials:"same-origin",cache:"no-store"}),n=await t.json().catch(()=>({}));if(e)return;o({passwordRequired:!!n.passwordRequired,authenticated:!!n.authenticated}),s(!1)}catch{e||(s(!0),o(null))}})(),()=>{e=!0}},[]);(0,i.useEffect)(()=>A(),[A]);let L=(0,i.useCallback)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/settings/remote",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(e)return;h({passwordSet:!!n.passwordSet,remoteEnabled:!!n.remoteEnabled,port:"number"==typeof n.port?n.port:null}),g(!1)}catch{e||g(!0)}})(),()=>{e=!0}},[]);(0,i.useEffect)(()=>L(),[L]);let z=(0,i.useCallback)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/auth/ui-sessions",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(e)return;I(Array.isArray(n.devices)?n.devices:[]),T(!1)}catch{e||T(!0)}})(),()=>{e=!0}},[]);(0,i.useEffect)(()=>z(),[z]);let W=(0,i.useCallback)(async e=>{M(e.id);try{let t=await fetch(`/api/auth/ui-sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"});if(!t.ok)throw Error(`HTTP ${t.status}`);e.current&&await (0,ux.b)(),z(),A()}catch{j(t("general_deviceRemoveFailed"))}finally{M(null)}},[z,A,t]);(0,i.useEffect)(()=>{p&&y(null===p.port?"":String(p.port))},[p]);let $=(0,i.useCallback)(async e=>{w(!0),j(null),C(!1);try{let n=await fetch("/api/settings/remote",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await n.json().catch(()=>({}));if(!n.ok){let e=r.error&&uA[r.error]||"general_badRequest";return j(t(e)),!1}return h({passwordSet:!!r.passwordSet,remoteEnabled:!!r.remoteEnabled,port:"number"==typeof r.port?r.port:null}),C(!0),x(""),A(),!0}catch{return j(t("general_serverCheckFailed")),!1}finally{w(!1)}},[A,t]),P={fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:8},[F,H]=(0,i.useState)("followUp");(0,i.useEffect)(()=>{H(ee())},[]);let[D,N]=(0,i.useState)(!0);(0,i.useEffect)(()=>{N(aj())},[]);let[B,O]=(0,i.useState)(!0);(0,i.useEffect)(()=>{O(ed())},[]);let U=(0,eA.Fd)(),[q,K]=(0,i.useState)(()=>!0===U.queueFlushAsOne);(0,i.useEffect)(()=>{K(!0===U.queueFlushAsOne);let e=(0,eA.b3)("streamingEnter");("steer"===e||"followUp"===e)&&(H(e),et(e));let t=(0,eA.b3)("autoUpdateCheck");"boolean"==typeof t&&(u(t),eo(t))},[U]);let J=t("common_loading");l?J=t("general_loginCheckFailed"):n&&(J=n.passwordRequired?n.authenticated?t("general_loginAuthenticated"):t("general_loginNotAuthenticated"):t("general_loginNotRequired"));let V=!!(n?.passwordRequired&&n.authenticated);return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{className:"settings-page-content",style:{flex:1,minHeight:0,overflowY:"auto"},children:[(0,r.jsxs)("div",{style:{marginBottom:22},children:[(0,r.jsx)("div",{style:P,children:t("general_loginSection")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.6,marginBottom:12,maxWidth:480},children:t("general_loginHint")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:t("general_loginStatus")}),(0,r.jsx)("div",{style:{fontSize:13,color:"var(--text)",marginBottom:14,lineHeight:1.5},children:J}),V&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",disabled:a,onClick:()=>{d(!0),(0,ux.b)()},style:{minHeight:32,padding:"0 14px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:a?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:a?.65:1},children:t("auth_logout")}),(0,r.jsx)("div",{style:{marginTop:8,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("general_logoutHint")}),(0,r.jsx)("div",{style:{marginTop:4,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("general_trustedDeviceHint")})]}),(0,r.jsxs)("div",{style:{marginTop:14},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",marginBottom:8},children:t("general_connectedDevices")}),R?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:t("general_serverCheckFailed")}):null===_?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:t("common_loading")}):0===_.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:t("general_noDevices")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,maxWidth:480,maxHeight:320,overflowY:"auto",overscrollBehavior:"contain"},children:_.map(e=>(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12,color:"var(--text)",border:"1px solid var(--border)",borderRadius:8,padding:"8px 10px",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsxs)("div",{style:{fontWeight:600,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.label,e.current&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:10,color:"var(--accent)"},children:t("general_thisDevice")})]}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:new Date(e.createdAt).toLocaleString()})]}),(0,r.jsx)("button",{type:"button",disabled:null!==E,onClick:()=>void W(e),style:{flexShrink:0,minHeight:28,padding:"0 10px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",cursor:null!==E?"not-allowed":"pointer",fontSize:11,fontWeight:600,opacity:null!==E&&E!==e.id?.5:1},children:t("general_deleteDevice")})]},e.id))})]})]}),(0,r.jsxs)("div",{style:{marginBottom:22},children:[(0,r.jsx)("div",{style:P,children:t("general_serverSection")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.6,marginBottom:12,maxWidth:480},children:t("general_serverHint")}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:p?.remoteEnabled===!0,disabled:b||null===p,onChange:e=>{let n=e.target.checked;n&&p&&!p.passwordSet?j(t("general_remoteNeedsPassword")):$({remoteEnabled:n})},style:{width:16,height:16,accentColor:"var(--accent)"}}),(0,r.jsx)("span",{children:t("general_remoteEnabled")})]}),(0,r.jsx)("div",{style:{marginTop:6,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("general_remoteHint")}),(0,r.jsxs)("div",{style:{marginTop:14},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:t("general_port")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[(0,r.jsx)("input",{type:"number",min:1,max:65535,placeholder:t("general_portPlaceholder"),value:v,disabled:b,onChange:e=>y(e.target.value),style:{width:130,padding:"7px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,outline:"none"}}),(0,r.jsx)("button",{type:"button",disabled:b,onClick:()=>{let e=v.trim(),n=""===e?null:Number(e);null!==n&&(!Number.isInteger(n)||n<1||n>65535)?j(t("general_portInvalid")):$({port:n})},style:{minHeight:32,padding:"0 14px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:b?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:b?.65:1},children:t("general_savePort")})]}),(0,r.jsx)("div",{style:{marginTop:6,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("general_portHint")})]}),(0,r.jsx)("div",{style:{marginTop:14,fontSize:12,color:"var(--text-muted)",marginBottom:4},children:f?t("general_serverCheckFailed"):p?p.passwordSet?t("general_passwordSet"):t("general_passwordNotSet"):t("common_loading")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[(0,r.jsx)("input",{type:"password",placeholder:t("general_newPassword"),value:m,disabled:b,onChange:e=>x(e.target.value),style:{width:170,padding:"7px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,outline:"none"}}),p?.passwordSet&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)"},children:t("general_newPasswordHint")}),(0,r.jsx)("button",{type:"button",disabled:b,onClick:()=>{m.length<6?j(t("general_passwordTooShort")):$({password:m})},style:{minHeight:32,padding:"0 14px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:b?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:b?.65:1},children:t("general_setPassword")}),p?.passwordSet&&(0,r.jsx)("button",{type:"button",disabled:b,onClick:()=>void $({clearPassword:!0}),style:{minHeight:32,padding:"0 14px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",cursor:b?"not-allowed":"pointer",fontSize:12,fontWeight:600,opacity:b?.65:1},children:t("general_clearPassword")})]}),k&&(0,r.jsx)("div",{style:{marginTop:8,fontSize:12,color:"var(--error-text)",maxWidth:420,lineHeight:1.45},children:k}),S&&(0,r.jsx)("div",{style:{marginTop:8,fontSize:12,color:"var(--text-muted)"},children:t("general_saved")}),(0,r.jsx)("div",{style:{marginTop:8,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("general_serverRestartHint")})]}),(0,r.jsxs)("div",{style:{marginBottom:22},children:[(0,r.jsx)("div",{style:P,children:t("general_updateSection")}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.6,marginBottom:12,maxWidth:480},children:t("general_updateHint")}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:10,fontSize:13,color:"var(--text)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:c,onChange:e=>{let t=e.target.checked;u(t),eo(t),(0,eA.dM)("autoUpdateCheck",t)},style:{width:16,height:16,accentColor:"var(--accent)"}}),(0,r.jsx)("span",{children:t("general_autoUpdateCheck")})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:P,children:t("general_interactionSection")}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:t("defaults_streamingEnter")}),(0,r.jsxs)("select",{value:F,onChange:e=>{let t="steer"===e.target.value?"steer":"followUp";H(t),et(t),(0,eA.dM)("streamingEnter",t),window.dispatchEvent(new Event("pidance:streaming-enter-changed"))},style:{width:"100%",maxWidth:420,padding:"7px 10px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:13,outline:"none",cursor:"pointer"},children:[(0,r.jsx)("option",{value:"followUp",children:t("defaults_streamingEnterQueue")}),(0,r.jsx)("option",{value:"steer",children:t("defaults_streamingEnterSteer")})]}),(0,r.jsx)("div",{style:{marginTop:6,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("defaults_streamingEnterHint")})]}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:D,onChange:e=>{let t=e.target.checked;N(t),aS(t)},style:{width:16,height:16,accentColor:"var(--accent)"}}),t("defaults_completionSound")]}),(0,r.jsx)("div",{style:{marginTop:-6,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("defaults_completionSoundHint")}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:B,onChange:e=>{let t=e.target.checked;O(t);var n=window.localStorage;try{n.setItem(el,JSON.stringify(ea(t)))}catch{}window.dispatchEvent(new Event(es))},style:{width:16,height:16,accentColor:"var(--accent)"}}),t("defaults_editorTakeover")]}),(0,r.jsx)("div",{style:{marginTop:-6,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("defaults_editorTakeoverHint")}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:q,onChange:e=>{let t=e.target.checked;K(t),(0,eA.dM)("queueFlushAsOne",t)},style:{width:16,height:16,accentColor:"var(--accent)"}}),t("defaults_queueFlushAsOne")]}),(0,r.jsx)("div",{style:{marginTop:-6,fontSize:11,color:"var(--text-dim)",maxWidth:420,lineHeight:1.45},children:t("defaults_queueFlushAsOneHint")})]})]})]}),(0,r.jsx)(dB,{onClose:e})]})}function uz({onClose:e}){let{mode:t,themeStyle:n,setTheme:i,setThemeStyle:o}=rF(),{locale:l,setLocale:s,t:a}=(0,eU.s9)();return(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{className:"settings-page-content",style:{flex:1,minHeight:0,overflowY:"auto"},children:[(0,r.jsx)(uM,{label:a("appearance_colorMode"),options:[{value:"light",label:a("appearance_light")},{value:"dark",label:a("appearance_dark")},{value:"system",label:a("appearance_system")}],value:t,onChange:e=>i(e)}),(0,r.jsx)(uM,{label:a("appearance_themeStyle"),options:[{value:"chamber",label:a("appearance_chamber")},{value:"fusion",label:a("appearance_fusion")}],value:n,onChange:e=>o(e)}),(0,r.jsx)(uM,{label:a("appearance_language"),options:[{value:"en",label:"English"},{value:"zh-CN",label:"简体中文"}],value:l,onChange:e=>s(e)}),(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.6,maxWidth:420},children:a("appearance_coverage")})]}),(0,r.jsx)(dB,{onClose:e})]})}function uW({cwd:e,sessionId:t,onClose:n,onModelsChanged:o,onAuthStateChange:l,onPluginsReloaded:s,initialPage:a}){let{t:d}=(0,eU.s9)(),c=ra(),[u,p]=(0,i.useState)(uT);(0,i.useEffect)(()=>{a&&p(a)},[a]);let[h,f]=(0,i.useState)({page:null});(0,i.useEffect)(()=>{try{window.localStorage.setItem(uS,JSON.stringify(u))}catch{}},[u]);let g=!!e,m=em(),x=(0,i.useMemo)(()=>(function(e,t={}){return uw.filter(e=>!uk.has(e)||!0===t.hasDesktop).map(t=>{let n="skills"===t||"plugins"===t,r=!n||e;return{id:t,label:t,requiresCwd:n,available:r,...r?{}:{unavailableHint:uj[t]}}})})(g,{hasDesktop:!!m}),[g,m]),v=x.find(e=>e.id===u)??x[0],y=(0,i.useCallback)(e=>{p(e),f(t=>uI(t,{type:"select",page:e}))},[]),b=(0,i.useCallback)(()=>{f(e=>uI(e,{type:"back"}))},[]),w=()=>{if(!v.available)return(0,r.jsx)(uE,{hint:v.unavailableHint});switch(v.id){case"general":return(0,r.jsx)(uL,{onClose:n});case"appearance":return(0,r.jsx)(uz,{onClose:n});case"models":return(0,r.jsx)(cN,{embedded:!0,onClose:o??n,onAuthStateChange:l,cwd:e??void 0});case"defaults":return(0,r.jsx)(uf,{cwd:e,onClose:n});case"prompts":return(0,r.jsx)(um,{onClose:n});case"skills":return(0,r.jsx)(cX,{embedded:!0,globalOnly:!0,cwd:e,onClose:n});case"plugins":return(0,r.jsx)(ue,{embedded:!0,cwd:e,sessionId:t,onClose:n,onReloaded:s});case"desktop":return m?(0,r.jsx)(ub,{bridge:m,onClose:n}):null}},k=(0,r.jsx)("div",{className:"settings-nav-list",children:x.map(e=>{let t=e.id===v.id;return(0,r.jsxs)("button",{type:"button",className:`settings-nav-item${!c&&t?" is-active":""}`,"aria-current":!c&&t?"page":void 0,onClick:()=>y(e.id),style:{minHeight:c?44:34,padding:c?"0 12px":"0 10px 0 12px"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d(uR(e.id))}),!e.available&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0},children:d("common_needsProject")}),c&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"9 18 15 12 9 6"})})]},e.id)})}),j=c&&null!==h.page?(0,r.jsxs)("button",{type:"button",onClick:b,"aria-label":d("common_back"),style:{flexShrink:0,display:"flex",alignItems:"center",gap:4,minHeight:32,padding:"0 8px",background:"none",border:"none",borderRadius:7,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"15 18 9 12 15 6"})}),d("common_back")]}):void 0;return(0,r.jsx)(tw,{open:!0,onClose:n,closeLabel:d("dialog_close"),title:c&&null!==h.page?d(uR(v.id)):d("common_settings"),width:920,zIndex:1e3,headerActions:j,contentPadding:"0",children:(0,r.jsx)("div",{className:"settings-layout",children:c?null===h.page?(0,r.jsx)("nav",{"aria-label":d("common_settings"),style:{flex:1,overflowY:"auto"},children:k}):(0,r.jsx)("section",{"aria-label":d(uR(v.id)),className:"settings-content-pane",children:(0,r.jsx)("div",{className:"settings-scroll-region",children:w()})}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("nav",{"aria-label":d("common_settings"),style:{width:190,flexShrink:0,borderRight:"1px solid var(--border)",background:"var(--bg-panel)",overflowY:"auto"},children:k}),(0,r.jsx)("section",{"aria-label":d(uR(v.id)),className:"settings-content-pane",children:(0,r.jsx)("div",{className:"settings-scroll-region",children:w()})})]})})})}function u$(e,...t){let n=e.toLowerCase();if(!n)return 0;let r=-1;for(let e of t){let t=e.toLowerCase(),i=t.indexOf(n);if(-1===i)continue;let o=1e3-2*i-(t.length>n.length);o>r&&(r=o)}if(r>=0)return r;for(let e of n)if(!t.some(t=>t.toLowerCase().indexOf(e,0)>=0))return -1;return 1}function uP({open:e,onClose:t,onSelectSession:n,onNewSession:o,onOpenFile:l,onOpenSettings:s,onToggleTheme:a,cwd:d}){let{t:c}=(0,eU.s9)(),[u,p]=(0,i.useState)(""),[h,f]=(0,i.useState)([]),[g,m]=(0,i.useState)([]),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(0),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{if(!e)return;p(""),b(0),w.current?.focus();let t=!1;return(async()=>{try{let e=await fetch("/api/sessions"),n=((await e.json()).sessions??[]).map(e=>({id:e.id,title:e.name||e.firstMessage||e.id.slice(0,12),cwd:e.cwd??"",session:e}));t||f(n)}catch{}})(),()=>{t=!0}},[e]),(0,i.useEffect)(()=>{if(!e||!d||u.trim().length<2)return void m([]);let t=++k.current,n=setTimeout(()=>{(async()=>{v(!0);try{let e=new URLSearchParams({cwd:d,q:u.trim()}),n=await fetch(`/api/file-index?${e.toString()}`),r=((await n.json()).files??[]).slice(0,12).map(e=>({path:e,name:e.split("/").pop()??e}));t===k.current&&m(r)}catch{t===k.current&&m([])}finally{t===k.current&&v(!1)}})()},180);return()=>clearTimeout(n)},[e,d,u]);let j=(0,i.useMemo)(()=>{let e=u.trim();return e?h.map(t=>({s:t,score:u$(e,t.title,t.cwd)})).filter(e=>e.score>=0).sort((e,t)=>t.score-e.score).slice(0,8).map(e=>e.s):h.slice(0,8)},[h,u]),S=(0,i.useMemo)(()=>{let e=u.trim(),t=[],r=[{key:"new",kind:"action",title:c("palette_newSession"),run:o},{key:"theme",kind:"action",title:c("palette_toggleTheme"),run:a},{key:"set-models",kind:"action",title:c("palette_settingsModels"),run:()=>s("models")},{key:"set-skills",kind:"action",title:c("palette_settingsSkills"),run:()=>s("skills")},{key:"set-plugins",kind:"action",title:c("palette_settingsPlugins"),run:()=>s("plugins")}];for(let i of(e?t.push(...r.filter(t=>u$(e,t.title)>=0)):t.push(...r),j))t.push({key:`s:${i.id}`,kind:"session",title:i.title,subtitle:i.cwd,run:()=>n(i.session)});for(let e of g)t.push({key:`f:${e.path}`,kind:"file",title:e.name,subtitle:e.path,run:()=>l(e.path,e.name)});return t},[j,g,u,c,o,n,l,s,a]);return((0,i.useEffect)(()=>{if(!e)return;let n=e=>{if("ArrowDown"===e.key)e.preventDefault(),b(e=>Math.min(e+1,S.length-1));else if("ArrowUp"===e.key)e.preventDefault(),b(e=>Math.max(e-1,0));else if("Enter"===e.key){e.preventDefault();let n=S[Math.min(y,S.length-1)];n&&(t(),n.run())}else"Escape"===e.key&&(e.preventDefault(),t())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[e,S,y,t]),(0,i.useEffect)(()=>{b(0)},[u]),e)?(0,r.jsx)("div",{role:"dialog","aria-modal":"true","aria-label":c("palette_title"),style:{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:"12vh",padding:"12vh 20px 20px",background:"rgba(0,0,0,0.28)"},onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsxs)("div",{style:{width:"min(620px, 100%)",maxHeight:"70vh",display:"flex",flexDirection:"column",borderRadius:12,border:"1px solid var(--border)",background:"var(--bg)",boxShadow:"0 24px 70px rgba(0,0,0,0.3)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("path",{d:"m21 21-4.3-4.3"})]}),(0,r.jsx)("input",{ref:w,value:u,onChange:e=>p(e.target.value),placeholder:c("palette_placeholder"),"aria-label":c("palette_title"),style:{flex:1,minWidth:0,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:14,fontFamily:"inherit"}}),x&&(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)"},children:c("palette_searching")})]}),(0,r.jsxs)("div",{style:{overflowY:"auto",padding:6,flex:1},children:[0===S.length&&(0,r.jsx)("div",{style:{padding:"14px 12px",fontSize:12,color:"var(--text-dim)"},children:c("palette_noResults")}),S.map((e,n)=>{let i=n===y;return(0,r.jsxs)("button",{type:"button",onMouseEnter:()=>b(n),onClick:()=>{t(),e.run()},style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:2,width:"100%",padding:"7px 10px",borderRadius:8,border:"none",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:"100%"},children:["session"===e.kind&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),"file"===e.kind&&(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),(0,r.jsx)("polyline",{points:"14 2 14 8 20 8"})]}),"action"===e.kind&&(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("polyline",{points:"9 10 4 15 9 20"}),(0,r.jsx)("path",{d:"M20 4v7a4 4 0 0 1-4 4H4"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title})]}),e.subtitle&&(0,r.jsx)("span",{style:{fontSize:10.5,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%",paddingLeft:18},children:e.subtitle})]},e.key)})]})]})}):null}async function uF(e,t){let n=await fetch("/api/update/apply?stream=1",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({version:e,stream:!0})});if(!n.ok||!n.body){let t=await n.json().catch(()=>null);return{ok:!1,status:t?.status||"error",message:t?.message||`HTTP ${n.status}`,targetVersion:t?.targetVersion??e}}let r=n.body.getReader(),i=new TextDecoder,o="",l=null;for(;;){let{done:e,value:n}=await r.read();if(e)break;let s=(o+=i.decode(n,{stream:!0})).split("\n\n");for(let e of(o=s.pop()??"",s)){let n=e.split("\n").find(e=>e.startsWith("data: "));if(n)try{let e=JSON.parse(n.slice(6));"progress"===e.type&&e.phase?t({phase:e.phase,percent:"number"==typeof e.percent?e.percent:0,message:e.message||""}):"result"===e.type&&e.result&&(l=e.result)}catch{}}}return l??{ok:!1,status:"error",message:"升级未返回结果",targetVersion:e}}function uH(e){return new Promise(t=>{setTimeout(t,e)})}async function uD(e={}){let t=e.timeoutMs??18e4,n=e.intervalMs??1500,r=e.fetchImpl??globalThis.fetch.bind(globalThis),i=e.now??Date.now,o=e.sleepImpl??uH,l=i();for(;i()-l<t;){e.onTick?.(i()-l);try{let t=await r("/api/about",{cache:"no-store",credentials:"same-origin"});if(401===t.status||403===t.status)return!0;if(t.ok){let n=await t.json();if(!e.expectedVersion||"string"==typeof n.version&&n.version===e.expectedVersion)return!0}}catch{}await o(n)}return!1}async function uN(e,t,n){var r,i;let o,l="preparing",s=n?.wait??uD,a=e=>{l=e.phase,t(e)};try{o=await uF(e,a)}catch(t){o={ok:!1,status:"error",message:t instanceof Error?t.message:String(t),targetVersion:e}}if(!(o.ok&&("upgraded"===o.status||"already_latest"===o.status)||(r=l,!(i=o).ok&&(i.message.includes("升级未返回结果")||/network|fetch|abort|failed/i.test(i.message))&&("restarting"===r||"linking"===r||"done"===r))))return o;let d=o.targetVersion??e;return(a({phase:"waiting",percent:97,message:"等待服务就绪…"}),await s({expectedVersion:"already_latest"===o.status?void 0:d,fetchImpl:n?.fetchImpl,onTick:e=>{a({phase:"waiting",percent:Math.min(99,97+Math.floor(e/3e4)),message:"等待服务就绪…"})}}))?{ok:!0,status:o.ok?o.status:"upgraded",message:o.ok?o.message:`已升级到 ${d}`,targetVersion:d}:{ok:!1,status:"error",message:"已切换版本,但等待服务就绪超时,请手动刷新",targetVersion:d}}function uB(){let{t:e}=(0,eU.s9)(),[t,n]=(0,i.useState)(!1),[r,o]=(0,i.useState)(null),[l,s]=(0,i.useState)(null),[a,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),p=(0,i.useCallback)(()=>{n(!1),o(null),s(null),d(null)},[]);return{overlay:t,progress:r,resultMsg:l,doneOk:a,busy:c,run:(0,i.useCallback)(async t=>{u(!0),n(!0),d(null),s(null),o({phase:"preparing",percent:3,message:e("update_phasePreparing")});try{let n=await uN(t,o),r=!!(n.ok&&("upgraded"===n.status||"already_latest"===n.status));if(d(r),r){let r=e("about_upgradeDone",{version:n.targetVersion??t});return o({phase:"done",percent:100,message:r}),s(r),window.location.reload(),{ok:!0,message:r}}let i="not_supported"===n.status?e("about_upgradeNotSupported"):e("about_upgradeFailed",{message:n.message});return o({phase:"error",percent:100,message:n.message}),s(i),{ok:!1,message:i,status:n.status}}catch(r){let t=r instanceof Error?r.message:String(r),n=e("about_upgradeFailed",{message:t});return d(!1),o({phase:"error",percent:100,message:t}),s(n),{ok:!1,message:n}}finally{u(!1)}},[e]),close:p}}function uO({currentVersion:e,latestVersion:t,progress:n,resultMsg:i,doneOk:o,onReload:l,onClose:s}){let{t:a}=(0,eU.s9)(),d=null===o;return(0,r.jsx)("div",{role:"alertdialog","aria-modal":"true","aria-busy":d,"aria-label":a("update_overlayTitle"),style:{position:"fixed",inset:0,zIndex:400,background:"color-mix(in srgb, var(--bg) 72%, #000)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:(0,r.jsxs)("div",{style:{width:"min(100%, 420px)",borderRadius:14,border:"1px solid var(--border)",background:"var(--bg-panel)",boxShadow:"0 20px 48px color-mix(in srgb, var(--text) 18%, transparent)",padding:"28px 24px 22px",display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsx)("div",{style:{fontSize:16,fontWeight:700,color:"var(--text)",textAlign:"center"},children:a("update_overlayTitle")}),(e||t)&&(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",textAlign:"center",fontVariantNumeric:"tabular-nums"},children:[e," → ",t]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10,alignItems:"center",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:650,color:"var(--text)"},children:a(n?function(e){switch(e){case"preparing":return"update_phasePreparing";case"downloading":return"update_phaseDownloading";case"installing":return"update_phaseInstalling";case"linking":return"update_phaseLinking";case"restarting":return"update_phaseRestarting";case"waiting":return"update_phaseWaiting";case"done":return"update_phaseDone";default:return"update_phaseError"}}(n.phase):"update_phasePreparing")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.55,minHeight:36,maxWidth:320},children:n?.message||a("update_phasePreparing")}),d&&(0,r.jsx)("div",{"aria-hidden":"true",style:{width:28,height:28,borderRadius:"50%",border:"2px solid var(--border)",borderTopColor:"var(--accent)",animation:"sidebar-running-spin 0.9s linear infinite"}})]}),i&&null!==o&&(0,r.jsxs)("div",{style:{fontSize:12,color:o?"var(--status-success)":"var(--status-danger)",textAlign:"center",whiteSpace:"pre-wrap"},children:[i,o&&(0,r.jsx)("div",{style:{marginTop:6,color:"var(--text-dim)",fontSize:11},children:a("update_reloadHint")})]}),null!==o&&(0,r.jsx)("div",{style:{display:"flex",justifyContent:"center",gap:8},children:o?(0,r.jsx)("button",{type:"button",onClick:l,style:{padding:"8px 16px",borderRadius:8,border:"none",background:"var(--accent)",color:"#fff",fontWeight:600,fontSize:12,cursor:"pointer"},children:a("update_reload")}):(0,r.jsx)("button",{type:"button",onClick:s,style:{padding:"8px 16px",borderRadius:8,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontWeight:600,fontSize:12,cursor:"pointer"},children:a("close")})})]})})}var uU=n(41463);function uq(e){let t=uU.env[e];if("string"!=typeof t)return;let n=t.trim();return n&&"unknown"!==n?n:void 0}function uK(...e){for(let t of e)if("string"==typeof t){let e=t.trim();if(e)return e}return"—"}function uJ({open:e,onClose:t}){let{t:n}=(0,eU.s9)(),[o,l]=(0,i.useState)(()=>({name:"Pidance",version:uq("NEXT_PUBLIC_APP_VERSION"),piSdkVersion:uq("NEXT_PUBLIC_PI_VERSION"),homepage:"https://github.com/henlii/pidance#readme",repository:"https://github.com/henlii/pidance"})),[s,a]=(0,i.useState)(!1),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),{overlay:h,progress:f,resultMsg:g,doneOk:m,busy:x,run:v,close:y}=uB();(0,i.useEffect)(()=>{if(!e)return;let t=!1;return(async()=>{try{let e=await fetch("/api/about",{cache:"no-store"});if(!e.ok)return;let n=await e.json();if(t)return;l(e=>({name:n.name||e.name||"Pidance",version:n.version||e.version||uq("NEXT_PUBLIC_APP_VERSION"),piSdkVersion:n.piSdkVersion||e.piSdkVersion||uq("NEXT_PUBLIC_PI_VERSION"),homepage:n.homepage||e.homepage,repository:n.repository||e.repository}))}catch{}})(),()=>{t=!0}},[e]);let b=(0,i.useCallback)(async()=>{a(!0),p(null);try{let e=await fetch("/api/update/check",{cache:"no-store"});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();c(t),t.updateAvailable?p(n("about_updateAvailable",{current:t.currentVersion,latest:t.latestVersion??"?"})):p(n("about_upToDate",{version:t.currentVersion}))}catch(e){p(n("about_upgradeFailed",{message:e instanceof Error?e.message:String(e)}))}finally{a(!1)}},[n]),w=(0,i.useCallback)(async()=>{d?.updateAvailable&&d.latestVersion&&(p(null),p((await v(d.latestVersion)).message))},[d,v]),k=o.repository??o.homepage??"https://github.com/henlii/pidance",j=uK(o.version,uq("NEXT_PUBLIC_APP_VERSION")),S=uK(o.piSdkVersion,uq("NEXT_PUBLIC_PI_VERSION"));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(tw,{open:e,onClose:t,title:n("about_title"),width:360,closeLabel:n("close"),contentPadding:"20px 22px 22px",children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",textAlign:"center",gap:14},children:[(0,r.jsx)("img",{src:"/brand/pidance-logo.png",alt:"",width:64,height:64,style:{width:64,height:64,borderRadius:14,objectFit:"contain",flexShrink:0}}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,width:"100%"},children:[(0,r.jsx)("div",{style:{fontSize:17,fontWeight:650,color:"var(--text)",letterSpacing:"-0.01em"},children:"Pidance"}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.65,fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)("div",{children:n("about_version",{version:j})}),(0,r.jsx)("div",{children:n("about_piSdkVersion",{version:S})})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,width:"100%",alignItems:"center"},children:[(0,r.jsx)("button",{type:"button",disabled:s||x,onClick:()=>{b()},style:{padding:"6px 14px",borderRadius:8,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text)",fontSize:12,fontWeight:600,cursor:s||x?"wait":"pointer"},children:s?n("about_checkingUpdate"):n("about_checkUpdate")}),u&&(0,r.jsxs)("div",{style:{fontSize:11,color:"var(--text-muted)",lineHeight:1.5,maxWidth:280},children:[u,d&&!d.upgradeSupported&&d.updateAvailable&&(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)"},children:n("update_bannerWorkspace")})]}),d?.updateAvailable&&d.upgradeSupported&&(0,r.jsx)("button",{type:"button",disabled:x,onClick:()=>{w()},style:{padding:"6px 14px",borderRadius:8,border:"none",background:"var(--accent)",color:"#fff",fontSize:12,fontWeight:600,cursor:x?"wait":"pointer",opacity:x?.7:1},children:x?n("about_upgrading"):n("about_upgradeNow")})]}),(0,r.jsxs)("a",{href:k,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,color:"var(--text-muted)",textDecoration:"none",padding:"4px 8px",borderRadius:6,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.background="transparent"},children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 2C6.477 2 2 6.477 2 12c0 4.418 2.865 8.166 6.839 9.489.5.092.682-.217.682-.482 0-.237-.009-.866-.013-1.7-2.782.604-3.369-1.341-3.369-1.341-.454-1.155-1.11-1.463-1.11-1.463-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.564 9.564 0 0 1 12 6.844c.85.004 1.705.115 2.504.337 1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.203 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.936.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.749 0 .267.18.579.688.481C19.138 20.163 22 16.416 22 12c0-5.523-4.477-10-10-10Z"})}),(0,r.jsx)("span",{children:n("about_github")})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5,maxWidth:260},children:n("about_footerNote")})]})}),h&&(0,r.jsx)(uO,{currentVersion:d?.currentVersion,latestVersion:d?.latestVersion,progress:f,resultMsg:g,doneOk:m,onReload:()=>{window.location.reload()},onClose:y})]})}function uV(e){let t=e;for(;t&&t!==document.body;){if(t instanceof HTMLElement&&t.hasAttribute("data-tooltip")){let e=t.getAttribute("data-tooltip");if(e&&e.trim())return t}t=t.parentElement}return null}function uY(){let[e,t]=(0,i.useState)(null),[n,o]=(0,i.useState)(!1);return((0,i.useEffect)(()=>{o(!0)},[]),(0,i.useEffect)(()=>{if(!n)return;let e=null,r=null,i=()=>{e=null,t(null)},o=n=>{let o,l,s=n.getAttribute("data-tooltip")?.trim();if(!s)return void i();e=n;let a=n.getBoundingClientRect();r||((r=document.createElement("div")).setAttribute("aria-hidden","true"),r.style.cssText="position:fixed;left:-9999px;top:0;visibility:hidden;pointer-events:none;max-width:min(280px,calc(100vw - 16px));padding:5px 8px;font-size:11px;font-weight:400;line-height:1.35;white-space:pre-line;overflow-wrap:anywhere;word-break:break-word;border:1px solid transparent;box-sizing:border-box;",document.body.appendChild(r)),r.textContent=s;let d=Math.ceil(r.getBoundingClientRect().width)||80,c=Math.ceil(r.getBoundingClientRect().height)||28;t({text:s,...(o="down",(l=a.bottom+6)+c>window.innerHeight-8&&a.top-6-c>=8&&(o="up",l=a.top-6-c),l=Math.max(8,Math.min(l,window.innerHeight-c-8)),{left:Math.max(8,Math.min(a.left+a.width/2-d/2,window.innerWidth-d-8)),top:l,placement:o})})},l=t=>{let n=uV(t.target);if(!n){e&&i();return}n!==e&&o(n)},s=()=>{e&&document.contains(e)?o(e):i()},a=t=>{let n=t.relatedTarget;e&&n&&e.contains(n)||e&&!uV(n)&&i()},d=t=>{let n=t.relatedTarget;e&&n&&uV(n)||i()};document.addEventListener("mouseover",l,!0),document.addEventListener("focusin",l,!0),document.addEventListener("mouseout",a,!0),document.addEventListener("focusout",d,!0),window.addEventListener("scroll",s,!0),window.addEventListener("resize",s);let c=new MutationObserver(t=>{e&&document.contains(e)&&t.some(t=>t.target===e)&&o(e)});return c.observe(document.body,{attributes:!0,attributeFilter:["data-tooltip"],subtree:!0}),()=>{c.disconnect(),document.removeEventListener("mouseover",l,!0),document.removeEventListener("focusin",l,!0),document.removeEventListener("mouseout",a,!0),document.removeEventListener("focusout",d,!0),window.removeEventListener("scroll",s,!0),window.removeEventListener("resize",s),r?.remove()}},[n]),n&&e)?(0,s.createPortal)((0,r.jsx)("div",{role:"tooltip",className:"instant-tooltip-layer",style:{position:"fixed",left:e.left,top:e.top,zIndex:10050,maxWidth:"min(280px, calc(100vw - 16px))",padding:"5px 8px",border:"1px solid var(--border-strong)",borderRadius:"var(--radius-sm)",background:"var(--bg-elevated)",color:"var(--text)",boxShadow:"var(--shadow-float)",fontSize:11,fontWeight:400,lineHeight:1.35,whiteSpace:"pre-line",overflowWrap:"anywhere",wordBreak:"break-word",pointerEvents:"none"},children:e.text}),document.body):null}function uX(e){return`pidance.update.dismissed.${e}`}function uG(e){try{sessionStorage.setItem(uX(e),"1")}catch{}}function uZ(){let{t:e}=(0,eU.s9)(),[t,n]=(0,i.useState)(null),[o,l]=(0,i.useState)(!1),{overlay:s,progress:a,resultMsg:d,doneOk:c,run:u,close:p}=uB();(0,i.useEffect)(()=>{if(!ei())return;let e=!1;return(async()=>{try{let t=await fetch("/api/update/check",{cache:"no-store"});if(!t.ok)return;let r=await t.json();if(e)return;n(r),r.updateAvailable&&r.latestVersion&&!function(e){try{return"1"===sessionStorage.getItem(uX(e))}catch{return!1}}(r.latestVersion)&&l(!0)}catch{}})(),()=>{e=!0}},[]);let h=async()=>{t?.updateAvailable&&t.latestVersion&&(l(!1),(await u(t.latestVersion)).ok?uG(t.latestVersion):l(!0))},f="var(--accent)";return(0,r.jsxs)(r.Fragment,{children:[o&&t?.updateAvailable&&t.latestVersion&&!s&&(0,r.jsxs)("div",{role:"status",className:"notice-shelf-item",style:{position:"fixed",bottom:16,right:16,zIndex:260,display:"flex",flexDirection:"column",gap:8,width:"min(100% - 24px, 360px)",padding:"10px 12px",borderRadius:10,border:`1px solid color-mix(in srgb, ${f} 42%, var(--border))`,borderLeft:`3px solid ${f}`,background:`color-mix(in srgb, ${f} 10%, var(--bg-panel))`,boxShadow:"0 12px 32px color-mix(in srgb, var(--text) 16%, transparent)",fontSize:12,color:"var(--text)",pointerEvents:"auto"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)("span",{style:{fontWeight:650,fontSize:13},children:e("update_bannerTitle")}),(0,r.jsx)("button",{type:"button",onClick:()=>{t?.latestVersion&&uG(t.latestVersion),l(!1)},"aria-label":e("update_bannerDismiss"),style:{border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:11,padding:"2px 4px"},children:e("update_bannerDismiss")})]}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontVariantNumeric:"tabular-nums"},children:e("update_bannerBody",{current:t.currentVersion,latest:t.latestVersion})}),!t.upgradeSupported&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:11},children:e("update_bannerWorkspace")}),(0,r.jsx)("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:t.upgradeSupported&&(0,r.jsx)("button",{type:"button",onClick:()=>{h()},style:{padding:"6px 12px",borderRadius:8,border:"none",background:"var(--accent)",color:"#fff",fontSize:12,fontWeight:600,cursor:"pointer"},children:e("about_upgradeNow")})})]}),s&&(0,r.jsx)(uO,{currentVersion:t?.currentVersion,latestVersion:t?.latestVersion,progress:a,resultMsg:d,doneOk:c,onReload:()=>{window.location.reload()},onClose:()=>{p(),l(!0)}})]})}function uQ({size:e=10}){return(0,r.jsx)("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0},children:(0,r.jsx)("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}function u0({node:e,activePathIds:t,activeLeafId:n,depth:i,isLast:o,parentLines:l,onActivate:s,assistantLabel:a,bookmarkAria:d,switchable:c,switchTargetId:u,chooserFor:p,disabled:h,preserveRoot:f=!1}){let{node:g,skipped:m}=function(e,t=!1){let n=e,r=n.compressedEntryIds?.length??0;for(;!t&&1===n.children.length&&null===ib(n.label);)n=n.children[0],r+=1+(n.compressedEntryIds?.length??0);return{node:n,skipped:r}}(e,f),x=t.has(g.entry.id),v=t.has(e.entry.id)||t.has(g.entry.id),y=g.entry.id===n,b=ib(g.label),w=function(e){if("message"===e.type&&"message"in e){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(g.entry),k="[assistant]"===w?a:w,j=b??k,S="message"===g.entry.type&&"message"in g.entry?g.entry.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("button",{type:"button",disabled:h,onClick:()=>s(g),"aria-current":y?"true":void 0,"aria-expanded":c&&!y?u===g.entry.id:void 0,"aria-label":b?`${b} — ${d}`:void 0,title:b?`${b} — ${k}`:k,style:{display:"flex",alignItems:"center",width:"100%",height:24,padding:0,background:"none",border:"none",font:"inherit",textAlign:"left",cursor:h?"default":"pointer"},children:[l.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:e&&(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:0,width:1,background:"var(--border)"}})},t)),(0,r.jsxs)("div",{style:{width:16,flexShrink:0,position:"relative",height:"100%",alignSelf:"stretch"},children:[(0,r.jsx)("div",{style:{position:"absolute",left:7,top:0,bottom:o?"50%":0,width:1,background:"var(--border)"}}),(0,r.jsx)("div",{style:{position:"absolute",left:7,top:"50%",width:9,height:1,background:"var(--border)"}})]}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:x?"var(--accent)":v?"var(--text-muted)":"var(--border)",border:x?"none":"1px solid var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),b?(0,r.jsx)("span",{style:{display:"flex",color:"var(--accent)",marginRight:5,flexShrink:0},children:(0,r.jsx)(uQ,{size:9})}):S?(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===S?"var(--accent)":"var(--text-dim)",background:"user"===S?"rgba(37,99,235,0.08)":"var(--bg-hover)",border:`1px solid ${"user"===S?"rgba(37,99,235,0.2)":"var(--border)"}`,borderRadius:3,padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===S?"U":"A"}):null,m>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",m]}),(0,r.jsx)("span",{style:{fontSize:11,color:x||b?"var(--text)":v?"var(--text-muted)":"var(--text-dim)",fontWeight:x?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:j})]}),p(g.entry.id,(l.length+1)*16+4),g.children.map((e,f)=>(0,r.jsx)(u0,{node:e,activePathIds:t,activeLeafId:n,depth:i+1,isLast:f===g.children.length-1,parentLines:[...l,!o],onActivate:s,assistantLabel:a,bookmarkAria:d,switchable:c,switchTargetId:u,chooserFor:p,disabled:h,preserveRoot:!1},e.entry.id))]})}function u1({title:e,desc:t,onClick:n}){return(0,r.jsxs)("button",{type:"button",onClick:n,style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:1,width:"100%",minHeight:34,padding:"5px 8px",background:"none",border:"none",borderRadius:5,cursor:"pointer",textAlign:"left",font:"inherit"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="none"},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",lineHeight:1.4},children:e}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",lineHeight:1.3},children:t})]})}function u2({indent:e,mode:t,busy:n,pendingLabel:i,error:o,customFocus:l,onModeChange:s,onFocusChange:a,onChoose:d,onCancel:c,t:u}){return(0,r.jsxs)("div",{role:"group","aria-label":u("branches_switchPrompt"),onKeyDown:e=>{"Escape"!==e.key||n||(e.stopPropagation(),c())},style:{margin:"1px 0 4px",marginLeft:Math.min(e,64),border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",padding:4},children:[n?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"8px 10px",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsxs)("svg",{className:"animate-spin",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),i]}):"options"===t?(0,r.jsxs)("div",{children:[(0,r.jsx)(u1,{title:u("branches_switchDirect"),desc:u("branches_switchDirectHint"),onClick:()=>d({mode:"direct"})}),(0,r.jsx)(u1,{title:u("branches_switchSummary"),desc:u("branches_switchSummaryHint"),onClick:()=>d({mode:"summary"})}),(0,r.jsx)(u1,{title:u("branches_switchCustom"),desc:u("branches_switchCustomHint"),onClick:()=>s("custom")})]}):(0,r.jsxs)("div",{style:{padding:4},children:[(0,r.jsx)("input",{autoFocus:!0,value:l,onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&l.trim()&&d({mode:"custom",focus:l}),"Escape"===e.key&&(e.stopPropagation(),s("options"))},placeholder:u("branches_switchCustomPlaceholder"),"aria-label":u("branches_switchCustom"),style:{width:"100%",height:28,padding:"0 8px",fontSize:12,color:"var(--text)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:6,marginTop:6},children:[(0,r.jsx)("button",{type:"button",disabled:!l.trim(),onClick:()=>d({mode:"custom",focus:l}),style:{minHeight:28,padding:"0 10px",fontSize:11,borderRadius:5,border:"1px solid var(--accent)",background:l.trim()?"var(--accent)":"transparent",color:l.trim()?"#fff":"var(--text-dim)",cursor:l.trim()?"pointer":"not-allowed"},children:u("branches_switchCustomSubmit")}),(0,r.jsx)("button",{type:"button",onClick:()=>s("options"),style:{minHeight:28,padding:"0 10px",fontSize:11,borderRadius:5,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:"pointer"},children:u("branches_switchBack")})]})]}),o&&(0,r.jsx)("div",{role:"alert",style:{padding:"4px 8px 2px",fontSize:11,color:"var(--status-danger)",lineHeight:1.4},children:o})]})}function u4({currentLabel:e,disabled:t,onSubmit:n,t:o}){let[l,s]=(0,i.useState)(!1),[a,d]=(0,i.useState)(""),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),f=(0,i.useRef)(null);(0,i.useEffect)(()=>{l&&f.current?.focus()},[l]);let g=t||c,m=a.trim(),x=m===(e??""),v=async e=>{if(g)return;let t=e.trim();if(t.length>120)return void h(o("branches_bookmarkTooLong",{max:120}));u(!0),h(null);let r=await n(t);(u(!1),"ok"===r.kind)?s(!1):"busy"===r.kind?h(o("branches_waitForRun")):h("error"===r.kind&&r.message?`${o("branches_bookmarkFailed")}: ${r.message}`:o("branches_bookmarkFailed"))},y=e=>{d(e),h(null),s(!0)},b={display:"inline-flex",alignItems:"center",gap:4,minHeight:28,padding:"0 8px",fontSize:11,borderRadius:5,border:"1px solid var(--border)",background:"none",color:"var(--text-muted)",cursor:g?"not-allowed":"pointer",flexShrink:0,opacity:g?.55:1};return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"6px 12px 8px",flexShrink:0},children:l?(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:f,value:a,maxLength:120,disabled:c,onChange:e=>{d(e.target.value),h(null)},onKeyDown:e=>{"Enter"===e.key&&m&&!x&&v(m),"Escape"===e.key&&(s(!1),h(null))},placeholder:o("branches_bookmarkPlaceholder"),"aria-label":o("branches_bookmarkPlaceholder"),style:{flex:1,minWidth:0,height:28,padding:"0 8px",fontSize:12,color:"var(--text)",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5}}),(0,r.jsx)("button",{type:"button",disabled:g||!m||x,onClick:()=>void v(m),style:{...b,border:"1px solid var(--accent)",background:!m||x?"transparent":"var(--accent)",color:!m||x?"var(--text-dim)":"#fff",cursor:g||!m||x?"not-allowed":"pointer",opacity:1},children:o("branches_bookmarkSave")}),(0,r.jsx)("button",{type:"button",disabled:c,onClick:()=>{s(!1),h(null)},style:b,children:o("branches_bookmarkCancel")})]}),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:4,minHeight:14},children:[p?(0,r.jsx)("span",{role:"alert",style:{fontSize:10,color:"var(--status-danger)",lineHeight:1.4},children:p}):(0,r.jsx)("span",{}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",flexShrink:0},children:[a.length,"/",120]})]})]}):(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,minHeight:28},children:[(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",letterSpacing:"0.04em",textTransform:"uppercase",flexShrink:0},children:o("branches_currentPoint")}),e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{title:e,style:{display:"inline-flex",alignItems:"center",gap:4,minWidth:0,flex:1,fontSize:11,color:"var(--text)"},children:[(0,r.jsx)("span",{style:{color:"var(--accent)",display:"flex",flexShrink:0},children:(0,r.jsx)(uQ,{size:10})}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),(0,r.jsx)("button",{type:"button",disabled:g,onClick:()=>y(e),title:o("branches_editBookmark"),style:b,children:o("branches_editBookmark")}),(0,r.jsx)("button",{type:"button",disabled:g,onClick:()=>void v(""),title:o("branches_removeBookmark"),style:b,children:o("branches_removeBookmark")})]}):(0,r.jsxs)("button",{type:"button",disabled:g,onClick:()=>y(""),style:{...b,gap:5},children:[(0,r.jsx)(uQ,{size:10}),o("branches_addBookmark")]})]}),p&&(0,r.jsx)("div",{role:"alert",style:{marginTop:4,fontSize:10,color:"var(--status-danger)",lineHeight:1.4},children:p})]})})}function u6({tree:e,activeLeafId:t,onLeafChange:n,inline:o,containerRef:l,open:s,onToggle:a,hasSession:d,compact:c,branchActions:u,panel:p}){let{t:h}=(0,eU.s9)(),[f,g]=(0,i.useState)(!1),m=void 0!==s?s:f,x=(0,i.useRef)(null),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(null),[k,j]=(0,i.useState)("options"),[S,C]=(0,i.useState)(""),[_,I]=(0,i.useState)(null),[R,T]=(0,i.useState)(null),E=u?.canWrite===!0,M=u?.busy===!0;(0,i.useEffect)(()=>{if(!m||!o)return;let e=l?.current??x.current;if(!e)return;let t=()=>{let t=e.getBoundingClientRect();y({top:t.bottom,left:t.left,width:t.width})};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[m,o,l]),(0,i.useEffect)(()=>{m||(w(null),I(null),j("options"),C(""),T(null))},[m]),(0,i.useEffect)(()=>{w(null),I(null)},[e]);let A=(0,i.useMemo)(()=>t?new Set(function e(n,r){for(let i of n){let n=[...r,i.entry.id];if(i.entry.id===t||i.compressedEntryIds?.includes(t))return n;let o=e(i.children,n);if(o)return o}return null}(e,[])??[]):new Set,[e,t]),L=(0,i.useMemo)(()=>(function(e){let t=[...e];for(;t.length>0;){let e=t.pop();if(null!==ib(e.label))return!0;t.push(...e.children)}return!1})(e),[e]),z=(0,i.useMemo)(()=>(function(e,t){if(!t)return null;let n=[...e];for(;n.length>0;){let e=n.pop();if(e.entry.id===t||e.compressedEntryIds?.includes(t))return ib(e.label);n.push(...e.children)}return null})(e,t),[e,t]),W=(0,i.useCallback)(()=>{if(void 0!==s){s&&a?.();return}g(!1)},[s,a]),$=(0,i.useCallback)(e=>{if(M)return;let r=e.entry.id;if(r===t)return void w(null);if(E){I(null),j("options"),C(""),w(e=>e===r?null:r);return}n(r)},[M,t,E,n]),P=(0,i.useCallback)(async e=>{if(!u||!b||u.busy)return;I(null),T(e.mode);let t=await u.navigate(b,e);if(T(null),"ok"===t.kind){w(null),W();return}"cancelled"===t.kind?w(null):"busy"===t.kind?I(h("branches_waitForRun")):I(t.message?`${h("branches_switchFailed")}: ${t.message}`:h("branches_switchFailed"))},[u,b,W,h]),F=(0,i.useCallback)((e,t)=>b===e&&E?(0,r.jsx)(u2,{indent:t,mode:k,busy:null!==R||M,pendingLabel:"direct"===R?h("branches_switching"):h("branches_summarizing"),error:_,customFocus:S,onModeChange:e=>{j(e),I(null)},onFocusChange:C,onChoose:e=>void P(e),onCancel:()=>w(null),t:h}):null,[b,E,k,R,M,_,S,P,h]),H=!t||(function e(t,n){for(let r of t){if(r.entry.id===n)return 0===r.children.length;if(r.compressedEntryIds?.includes(n))return!1;let t=e(r.children,n);if(null!==t)return t}return null}(e,t)??!0),D=d?function e(t){for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)||L||!H?null:h("branches_empty"):h("branches_noSession"),N=e.length>0?[e[0]]:[],B=!D&&N.length>0,O=p&&!H&&!D,U=h("branches_assistant"),q=h("branches_bookmarkAria"),K=O?(0,r.jsx)("div",{style:{padding:"4px 12px 2px 12px",fontSize:11,color:"var(--text-dim)"},children:h("branches_currentPosition")}):null,J=(0,r.jsxs)(r.Fragment,{children:[K,B?(0,r.jsx)("div",{style:{padding:"4px 12px 8px 12px",maxHeight:260,overflowY:"auto"},children:N.map((e,n)=>(0,r.jsx)(u0,{node:e,activePathIds:A,activeLeafId:t,depth:0,isLast:n===N.length-1,parentLines:[],onActivate:$,assistantLabel:U,bookmarkAria:q,switchable:E,switchTargetId:b,chooserFor:F,disabled:M,preserveRoot:!0},e.entry.id))}):(0,r.jsx)("div",{style:{padding:"10px 16px",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:D})]}),V=E&&t?(0,r.jsx)(u4,{currentLabel:z,disabled:M,onSubmit:e=>u.setLabel(t,e),t:h},t):null,Y=M?(0,r.jsxs)("svg",{className:"animate-spin",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{color:"var(--accent)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2",opacity:"0.25"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:B?"var(--accent)":"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),X=(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",style:{marginLeft:2,transform:m?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})});return o?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",alignItems:"stretch"},children:[(0,r.jsxs)("button",{ref:x,onClick:()=>a?a():g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",background:m?"var(--bg-selected)":"none",border:"none",borderTop:m?"2px solid var(--accent)":"2px solid transparent",borderRight:"1px solid var(--border)",cursor:"pointer",color:m?"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=m?"var(--text)":"var(--text-muted)"},title:h("branches"),"aria-label":h("branches"),"aria-pressed":m,children:[Y,!c&&(0,r.jsx)("span",{children:h("branches")})]}),m&&v&&(0,r.jsxs)("div",{style:{position:"fixed",top:v.top,left:v.left,width:v.width,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)",zIndex:500},children:[J,V]})]}):p?(0,r.jsxs)("div",{style:{height:"100%",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,minHeight:0,overflowY:"auto",paddingTop:8},children:J}),V]}):(0,r.jsxs)("div",{style:{borderBottom:"1px solid var(--border)",background:"var(--bg)",flexShrink:0,position:"relative"},children:[(0,r.jsxs)("button",{onClick:()=>g(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"5px 12px",background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:11,textAlign:"left"},children:[Y,(0,r.jsx)("span",{style:{color:"var(--text-muted)"},children:h("branches")}),X]}),m&&(0,r.jsxs)("div",{style:{position:"absolute",top:"100%",left:0,right:0,background:"var(--bg)",borderBottom:"1px solid var(--border)",boxShadow:"0 4px 12px rgba(0,0,0,0.1)",zIndex:100},children:[J,V]})]})}function u5(e){return e.subagent?.parentSessionId??null}function u8(e,t){return e.length<=t?e:`${e.slice(0,Math.max(1,t-1))}…`}function u3(e,t=32){let n=e.subagent?"":e.firstMessage;return u8((e.name?.trim()||("(no messages)"===n.trim()?"":n)||e.id).split(/\r?\n/).map(e=>e.trim()).find(e=>e.length>0)||e.id,t)}function u9({open:e}){return(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:e?{transform:"rotate(180deg)"}:void 0,children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})}function u7(e){return e?Array.from(e.querySelectorAll('[role="treeitem"]')):[]}function pe(e,t){let n=u7(e);0!==n.length&&n[Math.max(0,Math.min(n.length-1,t))]?.focus()}function pt({catalogStore:e,session:t,onSelectSession:n}){let{t:o}=(0,eU.s9)(),l=ra(),a=eT(),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(()=>new Set),g=(0,i.useRef)(null),m=(0,i.useRef)(null),x=(0,i.useRef)(null),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useId)(),w=null!==u;(0,i.useEffect)(()=>e.subscribe(()=>c(e=>e+1)),[e]);let k=(0,i.useMemo)(()=>e.getSnapshot(t.id).sessions,[e,d,t.id]),j=(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=u5(n);if(!e||e===n.id)continue;let r=t.get(e);r?r.push(n):t.set(e,[n])}for(let e of t.values())e.sort((e,t)=>t.modified.localeCompare(e.modified)||e.id.localeCompare(t.id));return t})(k),[k]),S=(0,i.useMemo)(()=>{let e=function(e,t){let n=new Map(e.map(e=>[e.id,e])),r=[],i=new Set,o=n.get(t);for(;o&&!i.has(o.id);){i.add(o.id),r.push(o);let e=u5(o);o=e?n.get(e):void 0}return r.reverse()}(k,t.id);return e.length>0?e:[t]},[k,t]),C=S[0],_=t.subagent?.parentSessionId??C.id,I=(0,i.useMemo)(()=>{var e;let n,r,i;return e="switcher"===u?_:t.id,n=[],r=new Set([e]),(i=(e,t)=>{for(let o of j.get(e)??[]){if(n.length>=512)return;!r.has(o.id)&&(r.add(o.id),n.push({session:o,depth:t}),h.has(o.id)||i(o.id,t+1))}})(e,1),n},[j,u,_,t.id,h]),R=a.runningChildIds,T=(0,i.useMemo)(()=>(function(e,t){let n=[],r=new Set([t]),i=[],o=(t,n)=>{let r=e.get(t)??[];for(let e=r.length-1;e>=0;e-=1)i.push({session:r[e],depth:n})};for(o(t,1);i.length>0&&n.length<512;){let e=i.pop();r.has(e.session.id)||(r.add(e.session.id),n.push(e),o(e.session.id,e.depth+1))}return n})(j,t.id),[j,t.id]),E=(0,i.useMemo)(()=>T.filter(e=>R.has(e.session.id)).length,[T,R]),M=R.has(t.id),[A,L]=(0,i.useState)(()=>Date.now()),z=I.some(e=>R.has(e.session.id));(0,i.useEffect)(()=>{if(!w||!z)return;L(Date.now());let e=setInterval(()=>L(Date.now()),1e3);return()=>clearInterval(e)},[w,z]);let W=(0,i.useMemo)(()=>({overlayRef:v,preferredPlacement:"below",gap:4,margin:8,minHeight:120,maxHeight:420,minWidth:l?void 0:280,maxWidth:420,width:l?"max":void 0,align:"start"}),[l]),$=lr({open:"switcher"===u,anchorRef:m,...W}),P=lr({open:"directory"===u,anchorRef:x,...W}),F="switcher"===u?$:P;(0,i.useEffect)(()=>{g.current=null,p(null),f(new Set)},[t.id]);let H=(0,i.useCallback)(e=>{g.current=e,p(e)},[]),D=(0,i.useCallback)(e=>{let t=g.current;g.current=null,p(null),e&&t&&("switcher"===t?m:x).current?.focus()},[]);(0,i.useEffect)(()=>{if(!w)return;let e=e=>{let t=e.target;!t||v.current?.contains(t)||m.current?.contains(t)||x.current?.contains(t)||D(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[w,D]),(0,i.useEffect)(()=>{if(!w)return;let e=e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),D(!0))};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[w,D]),(0,i.useEffect)(()=>{if(!w||!F.ready)return;if(0===I.length)return void D(!1);let e=I.findIndex(e=>e.session.id===t.id);pe(v.current,e>=0?e:0)},[w,F.ready]),(0,i.useEffect)(()=>{let e=y.current;if(e&&w){var t;let n,r;y.current=null,t=v.current,(r=(n=u7(t)).findIndex(t=>t.dataset.sessionId===e))>=0&&n[r].focus()}},[h,w]);let N=(0,i.useCallback)(e=>{f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),B=(0,i.useCallback)(e=>{D(!0),e.id!==t.id&&n(e)},[D,n,t.id]),O=(0,i.useCallback)(e=>{let t=document.activeElement,n=u7(v.current),r=t?n.indexOf(t):-1,i=r>=0?I[r]:void 0,o=i?.session,l=!!o&&(j.get(o.id)?.length??0)>0,s=!!o&&h.has(o.id);switch(e.key){case"ArrowDown":e.preventDefault(),pe(v.current,r+1);return;case"ArrowUp":e.preventDefault(),pe(v.current,r-1);return;case"Home":e.preventDefault(),pe(v.current,0);return;case"End":e.preventDefault(),pe(v.current,n.length-1);return;case"ArrowRight":if(!i)return;e.preventDefault(),l&&s?(y.current=i.session.id,N(i.session.id)):pe(v.current,r+1);return;case"ArrowLeft":if(!i)return;if(e.preventDefault(),l&&!s){y.current=i.session.id,N(i.session.id);return}for(let e=r-1;e>=0;e-=1)if(I[e].depth<i.depth)return void pe(v.current,e);return;case"Enter":case" ":if(!o)return;e.preventDefault(),B(o);return}},[h,j,B,I,N]),U=(0,i.useCallback)(e=>{let t=a.bySessionId.get(e.id);return t?.step.label?.trim()||t?.step.agent||e.subagent?.agent||u3(e,48)},[a.bySessionId]),q=(0,i.useCallback)(e=>{if(!e)return null;let t=[];if(e.active)e.step.currentTool&&t.push(e.step.currentTool);else{let n=function(e,t){if(!e||!t||t<e)return null;let n=Math.round((t-e)/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60);return r<60?`${r}m${String(n%60).padStart(2,"0")}s`:`${Math.floor(r/60)}h${String(r%60).padStart(2,"0")}m`}(e.step.startedAt,e.step.endedAt);n&&t.push(n)}let n=e.step.tokens?.total;return"number"==typeof n&&n>0&&t.push(n>=1e6?`${(n/1e6).toFixed(1)}M`:n>=1e3?`${Math.round(n/1e3)}k`:String(n)),t.length>0?t.join(" \xb7 "):null},[]),K=!l||S.length<=2?[...S]:[S[0],"gap",S[S.length-1]],J=U(t),V=!!t.subagent;return(0,r.jsxs)("div",{className:"session-lineage",children:[(0,r.jsx)("nav",{className:"session-lineage-crumbs","aria-label":o("lineage_listLabel"),children:K.map((e,s)=>(0,r.jsxs)(i.Fragment,{children:[s>0&&(0,r.jsx)("span",{className:"session-lineage-sep","aria-hidden":"true",children:"/"}),"gap"===e?(0,r.jsx)("span",{className:"session-lineage-gap","aria-hidden":"true",children:"…"}):e.id!==t.id?(0,r.jsx)("button",{type:"button",className:"session-lineage-crumb instant-tooltip","data-tooltip":o("lineage_switchTo",{title:U(e)}),onClick:()=>n(e),children:u8(U(e),l?16:30)}):V?(0,r.jsxs)("button",{ref:m,type:"button",className:"session-lineage-title instant-tooltip","aria-haspopup":"tree","aria-expanded":"switcher"===u,"aria-controls":"switcher"===u?b:void 0,"aria-label":o("lineage_switcherLabel",{title:J}),"data-tooltip":o("lineage_switcherLabel",{title:J}),onClick:()=>"switcher"===u?D(!0):H("switcher"),onKeyDown:e=>{"ArrowDown"===e.key&&"switcher"!==u&&(e.preventDefault(),H("switcher"))},children:[M&&(0,r.jsx)("span",{className:"session-lineage-dot","aria-hidden":"true"}),(0,r.jsx)("span",{className:"session-lineage-trigger-label",children:u8(J,l?20:36)}),(0,r.jsx)(u9,{open:"switcher"===u})]}):(0,r.jsxs)("span",{className:"session-lineage-current","aria-current":"page",title:o("lineage_current"),children:[M&&(0,r.jsx)("span",{className:"session-lineage-dot","aria-hidden":"true"}),u3(e,l?16:30)]})]},"gap"===e?"gap":e.id))}),T.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"session-lineage-sep","aria-hidden":"true",children:"/"}),(0,r.jsxs)("button",{ref:x,type:"button",className:"session-lineage-trigger instant-tooltip","aria-haspopup":"tree","aria-expanded":"directory"===u,"aria-controls":"directory"===u?b:void 0,"data-tooltip":o("lineage_listLabel"),onClick:()=>"directory"===u?D(!0):H("directory"),onKeyDown:e=>{"ArrowDown"===e.key&&"directory"!==u&&(e.preventDefault(),H("directory"))},children:[E>0&&(0,r.jsx)("span",{className:"session-lineage-dot","aria-hidden":"true"}),(0,r.jsx)("span",{className:"session-lineage-trigger-label",children:o("lineage_subagentCount",{count:T.length})}),E>0&&(0,r.jsx)("span",{className:"session-lineage-trigger-running",children:o("lineage_runningCount",{count:E})}),(0,r.jsx)(u9,{open:"directory"===u})]})]}),w&&(0,s.createPortal)((0,r.jsxs)("div",{ref:v,id:b,role:"tree","aria-label":o("lineage_listLabel"),className:"session-lineage-panel",onKeyDown:O,style:{...F.style,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"0 6px 18px rgba(0,0,0,0.12)",overflowY:"auto"},children:[a.stale&&(0,r.jsx)("div",{className:"session-lineage-note",children:o("lineage_stale")}),I.map(e=>{let n=e.session,i=a.bySessionId.get(n.id),l=j.get(n.id)?.length??0,s=h.has(n.id),d=n.id===t.id,c=R.has(n.id),u=i?.step.activityState==="needs_attention",p=q(i),f=U(n);return(0,r.jsxs)("div",{role:"treeitem",tabIndex:-1,"aria-level":e.depth,"aria-expanded":l>0?!s:void 0,"aria-selected":d,"data-session-id":n.id,className:`session-lineage-row${d?" is-current":""}${u?" needs-attention":""}`,style:{paddingLeft:8+(e.depth-1)*14},title:[d?o("lineage_current"):o("lineage_switchTo",{title:f}),o("sidebar_subagentReadOnly"),...n.subagent&&n.subagent.runIndex>0?[o("sidebar_runCount",{count:n.subagent.runIndex})]:[]].join(" \xb7 "),onClick:()=>B(n),children:[l>0?(0,r.jsx)("button",{type:"button",tabIndex:-1,className:"session-lineage-row-toggle","aria-label":s?o("sidebar_expandChild"):o("sidebar_collapseChild"),onClick:e=>{e.stopPropagation(),N(n.id)},children:(0,r.jsx)("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:s?"rotate(-90deg)":"none"},children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})}):(0,r.jsx)("span",{className:"session-lineage-row-toggle","aria-hidden":"true"}),u?(0,r.jsx)(td,{size:12}):c?(0,r.jsx)(ta,{size:12}):null,(0,r.jsx)("span",{className:"session-lineage-row-label",children:f}),i?.mode&&"single"!==i.mode&&(0,r.jsx)("span",{className:"session-lineage-row-tag",children:i.mode}),u&&(0,r.jsx)("span",{className:"session-lineage-row-attention",children:o("lineage_needsAttention")}),p&&(0,r.jsx)("span",{className:"session-lineage-row-meta",children:p}),c&&!u&&(0,r.jsx)(tc,{startedAt:i?.step.startedAt,now:A,running:!0})]},n.id)})]}),document.body)]})}var pn=n(8422),pr=n(63606);n(82407);var pi=n(1164);let po="pidance.terminalPad",pl=[{id:"esc",label:"Esc",send:"\\e"},{id:"tab",label:"Tab",send:"\\t"},{id:"ctrl-c",label:"Ctrl-C",send:"\\x03"},{id:"ctrl-d",label:"Ctrl-D",send:"\\x04"},{id:"ctrl-z",label:"Ctrl-Z",send:"\\x1a"},{id:"ctrl-l",label:"Ctrl-L",send:"\\x0c"},{id:"up",label:"↑",send:"\\e[A"},{id:"down",label:"↓",send:"\\e[B"},{id:"right",label:"→",send:"\\e[C"},{id:"left",label:"←",send:"\\e[D"},{id:"home",label:"Home",send:"\\e[H"},{id:"end",label:"End",send:"\\e[F"}];function ps(e){return e.replace(/\\e/g,"\x1b").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\x([0-9a-fA-F]{2})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}function pa(e){return!!e&&"object"==typeof e&&"string"==typeof e.id&&e.id.length>0&&"string"==typeof e.label&&"string"==typeof e.send}let pd=[{kind:"special",label:"Esc",send:"\\e"},{kind:"special",label:"Tab",send:"\\t",shiftSend:"\\e[Z"},{kind:"special",label:"Enter",send:"\\r"},{kind:"special",label:"Bksp",send:"\\x7f"},{kind:"special",label:"Space",send:" "},{kind:"special",label:"↑",send:"\\e[A"},{kind:"special",label:"↓",send:"\\e[B"},{kind:"special",label:"→",send:"\\e[C"},{kind:"special",label:"←",send:"\\e[D"},{kind:"special",label:"Home",send:"\\e[H"},{kind:"special",label:"End",send:"\\e[F"}],pc=["1234567890","qwertyuiop","asdfghjkl","zxcvbnm"];function pu(e){return`\\x${e.toString(16).padStart(2,"0")}`}function pp(e,t){let n=[];return e.ctrl&&n.push("Ctrl"),e.alt&&n.push("Alt"),e.shift&&n.push("Shift"),n.push(t),n.join("-")}function ph(){let{t:e}=(0,eU.s9)(),t=ra(),{isDark:n}=rF(),o=(0,i.useRef)(null),l=(0,i.useRef)(null),s=(0,i.useRef)(null),a=(0,i.useRef)(()=>!1),[d,c]=(0,i.useState)("idle"),[u,p]=(0,i.useState)(null),[h,f]=(0,i.useState)(!1),[g,m]=(0,i.useState)(()=>(function(){if("u"<typeof localStorage)return{keys:pl.map(e=>({...e})),commands:[]};try{let t=localStorage.getItem(po);var e=t?JSON.parse(t):null;if(!e||"object"!=typeof e)return{keys:pl.map(e=>({...e})),commands:[]};let n=Array.isArray(e.keys)?e.keys.filter(pa):[],r=Array.isArray(e.commands)?e.commands.filter(pa):[];return{keys:n.length>0?n:pl.map(e=>({...e})),commands:r}}catch{return{keys:pl.map(e=>({...e})),commands:[]}}})()),[x,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(0),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(""),C=(0,i.useRef)(!1),_=(0,i.useRef)(e);_.current=e;let I=(0,i.useCallback)(e=>{a.current(e),k("\r"===e?"Enter":1===e.length&&32>e.charCodeAt(0)?`^${String.fromCharCode(64+e.charCodeAt(0))}`:e.slice(0,24))},[]),R=(0,i.useCallback)(()=>{j&&I(j),I("\r"),S("")},[j,I]),T=(0,i.useCallback)(e=>{e.nativeEvent.isComposing||C.current||"Enter"===e.key&&(e.preventDefault(),R())},[R]);return(0,i.useEffect)(()=>{let e=window.visualViewport;if(!e||!t)return void b(0);let n=()=>{b(Math.max(0,window.innerHeight-e.height-e.offsetTop))};return n(),e.addEventListener("resize",n),e.addEventListener("scroll",n),()=>{e.removeEventListener("resize",n),e.removeEventListener("scroll",n)}},[t]),(0,i.useEffect)(()=>{let e=o.current;if(!e)return;let t=!1,n=null,r=null,i=[],d={current:!1};e.innerHTML="";let u=new pn.B({allowProposedApi:!0,allowTransparency:!0,cursorBlink:!0,cursorStyle:"block",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.4,scrollback:8e3,convertEol:!1,macOptionIsMeta:!0,theme:{background:"transparent",foreground:"#fff"}}),h=new pr.Y;u.loadAddon(h),u.open(e);try{h.fit()}catch{}l.current=u,s.current=h;let g=u.textarea;g&&(g.setAttribute("autocapitalize","off"),g.setAttribute("autocorrect","off"),g.setAttribute("autocomplete","off"),g.setAttribute("spellcheck","false"),g.setAttribute("inputmode","text"),g.setAttribute("enterkeyhint","send"),g.style.fontSize="16px");let m=e=>(n&&n.readyState===WebSocket.OPEN?n.send(JSON.stringify({type:"in",d:e})):(i.push(e),f(!0),n&&n.readyState!==WebSocket.CLOSED||w()),!0);a.current=m;let x=u.onData(e=>{m(e)}),v=u.onResize(({cols:e,rows:t})=>{n&&n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({type:"rs",cols:e,rows:t}))}),y=()=>{try{h.fit()}catch{}},b=new ResizeObserver(()=>{window.requestAnimationFrame(y)});b.observe(e);let w=()=>{if(t)return;null!==r&&(window.clearTimeout(r),r=null);let e="https:"===window.location.protocol?"wss:":"ws:";c("connecting"),p(null);let o=new WebSocket(`${e}//${window.location.host}/api/pty`);n=o,o.onopen=()=>{if(!t&&n===o&&(d.current=!0,c("open"),o.send(JSON.stringify({type:"rs",cols:u.cols,rows:u.rows})),n&&n.readyState===WebSocket.OPEN)){for(;i.length>0;){let e=i.shift();e&&n.send(JSON.stringify({type:"in",d:e}))}f(!1)}},o.onmessage=e=>{Promise.resolve(e.data).then(e=>"string"!=typeof e?e instanceof Blob?e.text():e instanceof ArrayBuffer?new TextDecoder().decode(e):"":e).then(e=>{if(!t&&n===o&&e){try{let t=JSON.parse(e);if(t&&"string"==typeof t.type){if("error"===t.type&&t.message){p(t.message),c("error");return}if("exit"===t.type)return void c("closed");if("out"===t.type&&"string"==typeof t.d)return void u.write(t.d)}}catch{}u.write(e)}})},o.onclose=e=>{t||n!==o||(d.current?c("connecting"):(c("error"),p(1006===e.code?_.current("terminal_wsRefused"):_.current("terminal_wsFailed"))),r=window.setTimeout(w,600))},o.onerror=()=>{t||n!==o||(c("error"),p(_.current("terminal_wsFailed")))}};return w(),()=>{t=!0,a.current=()=>!1,x.dispose(),v.dispose(),b.disconnect(),null!==r&&window.clearTimeout(r),n?.close(),u.dispose(),l.current=null,s.current=null}},[]),(0,i.useEffect)(()=>{let e=l.current;if(!e)return;let t=getComputedStyle(document.documentElement),r=(e,n)=>t.getPropertyValue(e).trim()||n;e.options.theme={background:r("--bg",n?"#101719":"#fbfcfd"),foreground:r("--text",n?"#ced8d8":"#263439"),cursor:r("--accent",n?"#69a7ca":"#286e98"),cursorAccent:r("--bg",n?"#101719":"#fbfcfd"),selectionBackground:r("--bg-selected",n?"#6ba7c426":"#2e6f9520")}},[n]),(0,i.useEffect)(()=>{let e=l.current;if(e){e.options.fontSize=t?14:13;try{s.current?.fit()}catch{}}},[t]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",minHeight:0,paddingBottom:y},children:[(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,color:"var(--text-dim)",borderBottom:"1px solid var(--border)",flexShrink:0},children:["connecting"===d&&e("terminal_connecting"),"open"===d&&e("terminal_connected"),"closed"===d&&e("terminal_disconnected"),"error"===d&&(u??e("terminal_unavailable")),h&&"open"!==d&&(0,r.jsx)("span",{style:{marginLeft:8,color:"var(--status-warning)"},children:e("terminal_queuedOffline")}),w&&"open"===d&&(0,r.jsxs)("span",{style:{marginLeft:8},children:["\xb7 ",e("terminal_sent",{value:w})]})]}),(0,r.jsx)("div",{className:"pidance-terminal-surface",style:{flex:1,minHeight:80,position:"relative",overflow:"hidden"},children:(0,r.jsx)("div",{ref:o,className:"pidance-terminal-xterm",style:{position:"absolute",inset:0,padding:"6px 8px 8px"}})}),t&&(0,r.jsxs)("div",{style:{flexShrink:0,borderTop:"1px solid var(--border)",background:"var(--bg)",padding:"6px 8px",display:"flex",gap:6},children:[(0,r.jsx)("input",{value:j,onChange:e=>S(e.target.value),onKeyDown:T,onCompositionStart:()=>{C.current=!0},onCompositionEnd:()=>{C.current=!1},placeholder:e("terminal_inputPlaceholder"),enterKeyHint:"send",autoCapitalize:"off",autoCorrect:"off",autoComplete:"off",spellCheck:!1,"aria-label":e("workspace_terminal"),style:{flex:1,minWidth:0,height:40,fontSize:16,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)"}}),(0,r.jsx)("button",{type:"button",onClick:R,style:{...pv,height:40,minWidth:56,fontSize:14,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:e("terminal_sendEnter")})]}),(0,r.jsx)(pf,{pad:g,onSend:I,onOpenConfig:()=>v(!0),isMobile:t}),x&&(0,r.jsx)(pg,{value:g,isMobile:t,onClose:()=>v(!1),onSave:e=>{m(e),"u">typeof localStorage&&localStorage.setItem(po,JSON.stringify(e)),v(!1)}})]})}function pf({pad:e,onSend:t,onOpenConfig:n,isMobile:i}){let{t:o}=(0,eU.s9)(),l={flex:"0 0 auto",height:i?36:30,minWidth:i?38:void 0,padding:i?"0 12px":"0 10px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontSize:i?13:12,whiteSpace:"nowrap"};return(0,r.jsxs)("div",{style:{flexShrink:0,borderTop:"1px solid var(--border)",background:"var(--bg)"},children:[e.commands.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,overflowX:"auto",padding:"6px 8px 2px",WebkitOverflowScrolling:"touch"},children:e.commands.map(e=>(0,r.jsx)("button",{type:"button",onPointerUp:n=>{n.preventDefault(),t(ps(e.send))},style:{...l,touchAction:"manipulation",cursor:"pointer"},children:e.label||e.send},e.id))}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,overflowX:"auto",padding:"6px 8px",WebkitOverflowScrolling:"touch"},children:[(0,r.jsx)("button",{type:"button",onClick:n,"aria-label":o("terminal_configure"),title:o("terminal_configure"),style:{flex:"0 0 auto",width:i?36:30,height:i?36:30,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-muted)",touchAction:"manipulation"},children:(0,r.jsx)(pi.A,{size:i?17:15})}),e.keys.map(e=>(0,r.jsx)("button",{type:"button",onPointerUp:n=>{n.preventDefault(),t(ps(e.send))},style:{...l,touchAction:"manipulation",cursor:"pointer"},children:e.label||e.send},e.id))]})]})}function pg({value:e,isMobile:t,onClose:n,onSave:o}){let{t:l}=(0,eU.s9)(),[s,a]=(0,i.useState)(()=>({keys:e.keys.map(e=>({...e})),commands:e.commands.map(e=>({...e}))})),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)({ctrl:!1,alt:!1,shift:!1}),[h,f]=(0,i.useState)(""),g=e=>{a(t=>({...t,keys:[...t.keys,function(e,t){let n=`key-${Math.random().toString(36).slice(2,10)}`;if("char"===t.kind){let r=e.shift?t.ch.toUpperCase():t.ch.toLowerCase(),i=t.ch.toUpperCase();if(e.ctrl){let t=i.charCodeAt(0)-64,r=e.alt?`\\e${pu(t)}`:pu(t);return{id:n,label:pp(e,i),send:r}}return e.alt?{id:n,label:pp(e,i),send:`\\e${r}`}:{id:n,label:pp(e,i),send:r}}let r=e.shift&&t.shiftSend?t.shiftSend:t.send,i=pp({ctrl:e.ctrl,alt:e.alt,shift:!!(e.shift&&t.shiftSend)},t.label);return e.alt&&"\\e"!==r?{id:n,label:pp(e,t.label),send:`\\e${r}`}:{id:n,label:i,send:r}}(u,e)]}))};return(0,r.jsxs)(tw,{open:!0,onClose:n,title:l("terminal_configure"),width:440,closeLabel:l("dialog_close"),children:[(0,r.jsxs)("label",{style:{display:"inline-flex",alignItems:"center",gap:8,fontSize:13,marginBottom:12},children:[(0,r.jsx)("input",{type:"checkbox",checked:d,onChange:e=>c(e.target.checked)}),l("terminal_comboMode")]}),d?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{display:"flex",gap:8,marginBottom:10},children:["ctrl","alt","shift"].map(e=>(0,r.jsxs)("label",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:13},children:[(0,r.jsx)("input",{type:"checkbox",checked:u[e],onChange:t=>p(n=>({...n,[e]:t.target.checked}))}),"ctrl"===e?"Ctrl":"alt"===e?"Alt":"Shift"]},e))}),(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:8},children:pd.map(e=>(0,r.jsx)(pm,{label:e.label,onClick:()=>g(e),isMobile:t},e.label))}),pc.map(e=>(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginBottom:4},children:[...e].map(e=>(0,r.jsx)(pm,{label:u.shift?e.toUpperCase():e,onClick:()=>g({kind:"char",label:e,ch:e}),isMobile:t},e))},e)),(0,r.jsx)(px,{items:s.keys,onRemove:e=>a(t=>({...t,keys:t.keys.filter(t=>t.id!==e)}))})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,marginBottom:8},children:l("terminal_commands")}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),(()=>{let e=h.trim();if(!e)return;let t={id:`cmd-${Math.random().toString(36).slice(2,8)}`,label:"",send:""};t.label=e,t.send=e.endsWith("\\n")||e.endsWith("\\r")?e:`${e}\\n`,a(e=>({...e,commands:[...e.commands,t]})),f("")})()},style:{display:"flex",gap:6,marginBottom:8},children:[(0,r.jsx)("input",{value:h,onChange:e=>f(e.target.value),placeholder:l("terminal_commandPlaceholder"),style:{flex:1,minWidth:0,height:t?40:32,fontSize:16,padding:"0 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)"}}),(0,r.jsx)("button",{type:"submit",style:pv,children:l("terminal_addCommand")})]}),(0,r.jsx)(px,{items:s.commands,onRemove:e=>a(t=>({...t,commands:t.commands.filter(t=>t.id!==e)}))})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,marginTop:14,flexWrap:"wrap"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>o(s),style:{...pv,border:"1px solid var(--accent)",background:"var(--accent)",color:"var(--accent-foreground)",fontWeight:600},children:l("terminal_saveConfig")}),(0,r.jsx)("button",{type:"button",onClick:()=>a(e=>({...e,keys:pl.map(e=>({...e}))})),style:pv,children:l("terminal_resetKeys")})]})]})}function pm({label:e,onClick:t,isMobile:n}){return(0,r.jsx)("button",{type:"button",onClick:t,style:{minWidth:n?36:28,height:n?38:32,padding:"0 8px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontSize:n?13:12,touchAction:"manipulation"},children:e})}function px({items:e,onRemove:t}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:e.map(e=>(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:4,height:28,padding:"0 6px 0 8px",border:"1px solid var(--border)",borderRadius:6,fontSize:12},children:[e.label||e.send,(0,r.jsx)("button",{type:"button",onClick:()=>t(e.id),"aria-label":"remove",style:{border:"none",background:"none",color:"var(--text-muted)",display:"flex"},children:(0,r.jsx)(cO.A,{size:12})})]},e.id))})}let pv={minHeight:32,padding:"0 12px",borderRadius:7,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},py="pidance:active-session";function pb(e){if("string"!=typeof e)return null;let t=e.trim();return!t||t.length>128||/\s/.test(t)?null:t}function pw(e,t){if(!e)return;let n=pb(t);if(n)try{e.setItem(py,n)}catch{}}function pk(e){if(e)try{e.removeItem(py)}catch{}}function pj(){try{return window.sessionStorage}catch{return null}}function pS(e,t){return new Promise((n,r)=>{if(t.aborted)return void r(new DOMException("Aborted","AbortError"));let i=setTimeout(()=>{t.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(i),t.removeEventListener("abort",o),r(new DOMException("Aborted","AbortError"))};t.addEventListener("abort",o,{once:!0})})}async function pC(e){let{sessionId:t,isCurrent:n,fetchSession:r,parseBody:i,signal:o,maxAttempts:l=5,baseDelayMs:s=200,delay:a=pS}=e,d=Math.max(1,Math.floor(l)),c=0;for(;c<d;){if(c+=1,o?.aborted)return{ok:!1,reason:"aborted",attempts:c};if(!n())return{ok:!1,reason:"stale",attempts:c};try{let e,l=await r(t,o??new AbortController().signal);if(o?.aborted||!n())return{ok:!1,reason:o?.aborted?"aborted":"stale",attempts:c};if(404===l.status){if(c>=d)return{ok:!1,reason:"not_found",attempts:c,status:404};let e=s*2**(c-1);try{await a(e,o??new AbortController().signal)}catch{return{ok:!1,reason:"aborted",attempts:c}}continue}if(!l.ok)return{ok:!1,reason:"error",attempts:c,status:l.status,error:`HTTP ${l.status}`};try{e=await l.json()}catch(e){return{ok:!1,reason:"error",attempts:c,status:l.status,error:e instanceof Error?e.message:String(e)}}if(!n()||o?.aborted)return{ok:!1,reason:o?.aborted?"aborted":"stale",attempts:c};let u=i(e);if(null==u)return{ok:!1,reason:"error",attempts:c,status:l.status,error:"empty body"};return{ok:!0,value:u,attempts:c}}catch(e){if(o?.aborted||e instanceof DOMException&&"AbortError"===e.name)return{ok:!1,reason:"aborted",attempts:c};return{ok:!1,reason:"error",attempts:c,error:e instanceof Error?e.message:String(e)}}}return{ok:!1,reason:"exhausted",attempts:c}}function p_(){return(0,r.jsx)(eN,{children:(0,r.jsx)(pI,{})})}function pI(){let e,t,n,s,a,d,{t:c}=(0,eU.s9)(),[u]=((0,o.useSearchParams)(),(0,i.useState)(()=>{let e,t,n;return e=new URLSearchParams(window.location.search),n=(t=e.get("cwd")?.trim()||null)?null:e.get("session"),{requestedCwd:t,sessionId:n,rememberedSessionId:t||n?null:function(){var e=pj();if(!e)return null;try{return pb(e.getItem(py))}catch{return null}}()}})),{toggleTheme:p}=rF(),h=ra(),[f,g]=(0,i.useState)(null),[m,x]=(0,i.useState)(()=>u.requestedCwd?"validating":"idle"),[v,y]=(0,i.useState)(null),[b,w]=(0,i.useState)(0),[R,T]=(0,i.useState)(0),[E,z]=(0,i.useState)(()=>{try{return"1"===localStorage.getItem("pidance.footerCollapsed")}catch{return!1}}),W=(0,i.useRef)((e=void 0,t={target:{kind:"none"},urlRestore:{kind:"idle"},intentGeneration:0,transitionSeq:0},n=new Set,s=e=>{var r,i,o,l;if(r=t.target,i=e.target,r.kind===i.kind&&("none"===r.kind&&"none"===i.kind||("new"===r.kind&&"new"===i.kind?r.intentId===i.intentId&&r.cwd===i.cwd&&r.generation===i.generation:"persisted"===r.kind&&"persisted"===i.kind&&r.sessionId===i.sessionId&&r.cwd===i.cwd&&r.projectRoot===i.projectRoot))&&(o=t.urlRestore,l=e.urlRestore,o.kind===l.kind&&("loading"===o.kind&&"loading"===l.kind||"not-found"===o.kind&&"not-found"===l.kind?o.sessionId===l.sessionId:"error"!==o.kind||"error"!==l.kind||o.sessionId===l.sessionId&&o.message===l.message))&&t.intentGeneration===e.intentGeneration&&t.transitionSeq===e.transitionSeq)return t;for(let r of(t=e,n))r();return t},d={getState:()=>t,subscribe:e=>(n.add(e),()=>{n.delete(e)}),selectPersisted:e=>(t.transitionSeq+=1,s({target:{kind:"persisted",sessionId:e.id,cwd:e.cwd,projectRoot:e.projectRoot??void 0},urlRestore:{kind:"ready"},intentGeneration:t.intentGeneration,transitionSeq:t.transitionSeq})),startNew:a=n=>{t.intentGeneration+=1,t.transitionSeq+=1;let r=t9(n,t.intentGeneration,e);return s({target:{kind:"new",intentId:r.id,cwd:r.cwd,generation:r.generation},urlRestore:{kind:"ready"},intentGeneration:t.intentGeneration,transitionSeq:t.transitionSeq})},promote(e,n){let r=t.target;return"new"===r.kind&&r.intentId===e&&(t.transitionSeq+=1,s({target:{kind:"persisted",sessionId:n.id,cwd:n.cwd||r.cwd,projectRoot:n.projectRoot??void 0},urlRestore:{kind:"ready"},intentGeneration:t.intentGeneration,transitionSeq:t.transitionSeq}),!0)},applyHydrate(e){let n=t.target;return"persisted"===n.kind&&n.sessionId===e.id&&(s({...t,target:{kind:"persisted",sessionId:e.id,cwd:e.cwd||n.cwd,projectRoot:e.projectRoot??n.projectRoot}}),!0)},applyIdentityChange(e,n,r){var i,o;if(void 0!==r&&r!==t.transitionSeq)return t;let l=n.cwd!==e.cwd,d=n.projectRoot!==e.projectRoot;if(!l&&!d||"loading"===t.urlRestore.kind&&!(n.cwd&&e.cwd&&n.cwd!==e.cwd))return t;if(!n.cwd&&!n.projectRoot)return"none"===t.target.kind&&e.cwd?a(e.cwd):t;return(i=t.target,!(o=e).cwd||("new"===i.kind?i.cwd!==o.cwd:("persisted"!==i.kind||i.cwd!==o.cwd&&(!o.projectRoot||(i.projectRoot??i.cwd)!==o.projectRoot))&&1))?e.cwd?a(e.cwd):s({target:{kind:"none"},urlRestore:{kind:"ready"},intentGeneration:t.intentGeneration,transitionSeq:t.transitionSeq}):"persisted"===t.target.kind&&e.projectRoot&&t.target.projectRoot!==e.projectRoot?s({...t,target:{...t.target,projectRoot:e.projectRoot}}):t},deleteSession(e,n){let r=t.target;return"persisted"!==r.kind||r.sessionId!==e?t:n?a(n):(t.transitionSeq+=1,s({target:{kind:"none"},urlRestore:{kind:"ready"},intentGeneration:t.intentGeneration,transitionSeq:t.transitionSeq}))},forkTo:e=>d.selectPersisted(e),beginUrlRestore:e=>s({...t,urlRestore:{kind:"loading",sessionId:e}}),completeUrlRestore(e){let n=t.urlRestore,r="loading"===n.kind||"error"===n.kind||"not-found"===n.kind?n.sessionId:null;return r?"error"in e?s({...t,urlRestore:{kind:"error",sessionId:r,message:e.error}}):!0===e.found?d.selectPersisted(e.session):s({target:"persisted"===t.target.kind&&t.target.sessionId===r?{kind:"none"}:t.target,urlRestore:{kind:"not-found",sessionId:r},intentGeneration:t.intentGeneration,transitionSeq:t.transitionSeq}):t},retryUrlRestore(){let e=t.urlRestore;return"error"!==e.kind?null:(s({...t,urlRestore:{kind:"loading",sessionId:e.sessionId}}),e.sessionId)},currentIntent(){let e=t.target;return"new"!==e.kind?null:{id:e.intentId,cwd:e.cwd,generation:e.generation}},selectedSessionId:()=>"persisted"===t.target.kind?t.target.sessionId:null})),P=(0,i.useRef)(tJ());(0,i.useEffect)(()=>{var e,t;let n,r,i,o;return e=P.current,t=nz(),n=new Map,r=!1,i=()=>{if(r)return;let i=e.getState().startingIds;for(let[e,t]of[...n])i.has(e)||(n.delete(e),t.unsubscribe());for(let o of i){if(n.has(o)||!e.getState().startingIds.has(o))continue;let i={unsubscribe:()=>{}};n.set(o,i);let l=t.subscribe(o,t=>{t.agentRunning||t.sendInFlight||e.clearStarting(o)});!r&&n.get(o)===i&&e.getState().startingIds.has(o)?i.unsubscribe=l:l()}},o=e.subscribe(i),i(),()=>{r=!0,o();let e=[...n.values()];for(let t of(n.clear(),e))t.unsubscribe()}},[]);let[F,H]=(0,i.useState)(0);(0,i.useEffect)(()=>W.current.subscribe(()=>H(e=>e+1)),[]);let D=W.current.getState().target,[N,B]=(0,i.useState)(0),[K,J]=(0,i.useState)(0),[X,G]=(0,i.useState)(null),[Z,Q]=(0,i.useState)(null),ee=(0,i.useRef)(null),et=(0,i.useRef)(0),[en,er]=(0,i.useState)(null),ei=(0,i.useRef)(null),eo=(0,i.useRef)(null),el=(0,i.useRef)(null),es=(0,i.useRef)(0),[ea,ed]=(0,i.useState)(null),[ec,eu]=(0,i.useState)(null),ef=(0,i.useRef)(0),eg=(0,i.useCallback)(()=>eu(null),[]),[ex,ev]=(0,i.useState)(!1),[ey,eb]=(0,i.useState)(null),ew=em();(0,i.useEffect)(()=>{if(ew)return ew.onOpenSettings(()=>{eb("desktop"),ev(!0)})},[ew]);let[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(!1),[e_,eI]=(0,i.useState)(0),[eR,eT]=(0,i.useState)([]),[eE,eM]=(0,i.useState)(!0),[eA,eL]=(0,i.useState)(!1),[ez,eW]=(0,i.useState)(!1),[e$,eP]=(0,i.useState)(400),[eF,eH]=(0,i.useState)(!1),[eD,eN]=(0,i.useState)(560),[eq,eK]=(0,i.useState)("content"),[eJ,eV]=(0,i.useState)(!1),eY=(0,i.useRef)(null),[eX,eG]=(0,i.useState)(!1),[eZ,eQ]=(0,i.useState)(300),[e0,e1]=(0,i.useState)(!1),e2=(0,i.useRef)(null),e4=(0,i.useCallback)(e=>{let t=M(e);eQ(t);var n=window.localStorage;try{let e=U(n);n.setItem($,O({...e,sidebarWidth:M(t)}))}catch{}},[]),e6=(0,i.useCallback)(e=>{h||(e.preventDefault(),e2.current={startX:e.clientX,startWidth:eZ},e1(!0),e.currentTarget.setPointerCapture(e.pointerId))},[h,eZ]),e5=(0,i.useCallback)(e=>{let t=e2.current;t&&e4(t.startWidth+(e.clientX-t.startX))},[e4]),e8=(0,i.useCallback)(e=>{e2.current&&(e2.current=null,e1(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),e3=(0,i.useCallback)(e=>{let t=e.shiftKey?32:8;"ArrowLeft"===e.key?(e.preventDefault(),e4(eZ-t)):"ArrowRight"===e.key?(e.preventDefault(),e4(eZ+t)):"Home"===e.key?(e.preventDefault(),e4(240)):"End"===e.key&&(e.preventDefault(),e4(520))},[e4,eZ]),e9=(0,i.useCallback)(()=>{e4(300)},[e4]),e7=(0,i.useRef)(null),[te,tt]=(0,i.useState)(k),[tn,tr]=(0,i.useState)(0),[ti,to]=(0,i.useState)(!1),tl=(0,i.useRef)(null),ts=(0,i.useMemo)(()=>C({availableWidth:tn,ratio:te}),[tn,te]),ta=(0,i.useRef)(ts);ta.current=ts;let td=(0,i.useRef)(tn);td.current=tn,(0,i.useEffect)(()=>{let e=e7.current;if(!e)return;let t=()=>{var t;return tr((t=e.clientWidth,!Number.isFinite(t)||t<=0?0:Math.max(0,t-2*(h?16:18))))};if(t(),"u"<typeof ResizeObserver)return;let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[h]);let tc=(0,i.useCallback)(e=>{let t,n=!Number.isFinite(t=(r={width:j(e),availableWidth:td.current}).availableWidth)||t<=0?k:S(j(r.width)/t);tt(n);var r,i=window.localStorage;try{let e=U(i);i.setItem($,O({...e,chatColumnWidthRatio:S(n)}))}catch{}},[]),tu=(0,i.useCallback)(e=>{if(h)return;e.preventDefault();let t="left"===e.currentTarget.dataset.side?"left":"right";tl.current={startX:e.clientX,startWidth:ta.current,side:t},to(!0),e.currentTarget.setPointerCapture(e.pointerId)},[h]),tp=(0,i.useCallback)(e=>{let t=tl.current;if(!t)return;let n=e.clientX-t.startX;tc(t.startWidth+("right"===t.side?n:-n)*2)},[tc]),th=(0,i.useCallback)(e=>{tl.current&&(tl.current=null,to(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),tf=(0,i.useCallback)(e=>{let t=e.shiftKey?64:16;"ArrowLeft"===e.key?(e.preventDefault(),tc(ta.current-t)):"ArrowRight"===e.key?(e.preventDefault(),tc(ta.current+t)):"Home"===e.key?(e.preventDefault(),tc(1e3)):"End"===e.key&&(e.preventDefault(),tc(1600))},[tc]),tg=(0,i.useCallback)(()=>{tc(C({availableWidth:td.current,ratio:k}))},[tc]);(0,i.useEffect)(()=>{let e=q();eQ(e.sidebarWidth),eW(e.rightPanelOpen),eP(e.rightPanelWidth),eN(e.changesPanelWidth),tt(e.chatColumnWidthRatio)},[]);let tm=(0,i.useCallback)(e=>{let t=A(e);eP(t),V({width:t})},[]),tx=(0,i.useCallback)(e=>{eW(e),V({open:e})},[]),tv=(0,i.useCallback)(e=>{let t=L(e);eN(t),Y({width:t})},[]),ty=(0,i.useCallback)(e=>{eH(e),Y({open:e})},[]),tb=(0,i.useCallback)(e=>{e.preventDefault(),eY.current={startX:e.clientX,startWidth:eD},eV(!0),e.currentTarget.setPointerCapture(e.pointerId)},[eD]),tw=(0,i.useCallback)(e=>{let t=eY.current;t&&tv(t.startWidth+t.startX-e.clientX)},[tv]),tk=(0,i.useCallback)(e=>{eY.current&&(eY.current=null,eV(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))},[]),tj=(0,i.useCallback)(e=>{let t=e.shiftKey?32:8;"ArrowLeft"===e.key?(e.preventDefault(),tv(eD+t)):"ArrowRight"===e.key?(e.preventDefault(),tv(eD-t)):"Home"===e.key?(e.preventDefault(),tv(320)):"End"===e.key&&(e.preventDefault(),tv(960))},[tv,eD]);(0,i.useEffect)(()=>{h?(eM(!1),eW(!1)):eW(q().rightPanelOpen)},[h]),(0,i.useEffect)(()=>{eL(!0),eG(!0)},[]);let tS=(0,i.useRef)(null),[tC,t_]=(0,i.useState)([]),[tI,tR]=(0,i.useState)(null),tT=(0,i.useRef)(null),[tE,tM]=(0,i.useState)(null),tA=(0,i.useCallback)((e,t,n,r)=>{t_(e),tR(t),tT.current=n,tM(r)},[]),tL=(0,i.useCallback)(e=>{tT.current?.(e)},[]),[tz,tW]=(0,i.useState)(null),t$=(0,i.useCallback)(e=>{tW(e)},[]),[tP,tF]=(0,i.useState)(null);(0,i.useRef)(f?.id??null).current=f?.id??null;let tH=(0,i.useCallback)(e=>{tF(e)},[]),[tD,tN]=(0,i.useState)(null),tB=(0,i.useCallback)(e=>{tN(e)},[]),[tO,tU]=(0,i.useState)({}),tq=(0,i.useCallback)(e=>{tU(e)},[]),tK=(0,i.useCallback)(()=>{h&&eW(!1),eM(e=>!e)},[h]),tV=(0,i.useCallback)(()=>{h?(eM(!1),eW(e=>!e)):tx(!ez)},[tx,h,ez]),[tY,tX]=(0,i.useState)([]),[tG,tZ]=(0,i.useState)("files"),[t0,t1]=(0,i.useState)(null),[t2,t4]=(0,i.useState)(null),[t6,t5]=(0,i.useReducer)(aV,aU),t8=(0,i.useRef)(t6);t8.current=t6;let t3=(0,i.useCallback)(e=>{t8.current=aV(t8.current,e),t5(e)},[]);(0,i.useEffect)(()=>{if(!Object.values(t6.buffers).some(e=>e.dirty))return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[t6]);let nt=(0,i.useCallback)(async e=>{let t=aY(t8.current,e);if(!t||!t.sourceSessionId||!t.dirty||"saving"===t.saveState)return!1;let n=globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,r=t.revision,i=t.content;t3({type:"markSaving",key:e,requestId:n,requestRevision:r});try{let o=(0,rH.HG)(t.filePath),l=new URLSearchParams({type:"save",sessionId:t.sourceSessionId}),s=await fetch(`/api/files/${o}?${l.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:i,baseline:t.baseline})}),a=await s.json().catch(()=>({}));if(409===s.status)return t3({type:"saveConflict",key:e,requestId:n,baseline:a.baseline,message:a.error??c("viewer_externalChange")}),!1;if(!s.ok||"number"!=typeof a.size||"number"!=typeof a.mtimeMs)throw Error(a.error??c("app_saveFailed",{status:s.status}));t3({type:"saveSuccess",key:e,requestId:n,requestRevision:r,savedContent:i,baseline:{size:a.size,mtimeMs:a.mtimeMs}}),J(e=>e+1),G(e=>[...new Set([...e??[],t.filePath])]);let d=aY(t8.current,e);return!!(d&&d.revision===r&&!d.dirty)}catch(t){return t3({type:"saveError",key:e,requestId:n,message:t instanceof Error?t.message:String(t)}),!1}},[t3,c]),nn=(0,i.useCallback)((e,t)=>{tS.current?.insertText(oA(e,t))},[]),nr=(0,i.useCallback)(e=>{let t=e.map(e=>oA(e,!1)).join("");t&&tS.current?.insertText(t)},[]),ni=u.sessionId??u.rememberedSessionId,no=null===u.sessionId&&null!==u.rememberedSessionId,nl=eO(),{setIdentity:ns,getIdentitySnapshot:na}=eB(),nd=nl.cwd,nc=(0,i.useCallback)(e=>{var t;tS.current?.insertText((t=nd??void 0,oA((0,rH.A0)((0,rH.qP)(e,t)),!1)))},[nd]),[nu,np]=(0,i.useState)(()=>!ni),[nh,nf]=(0,i.useState)(()=>ni?"loading":"ready"),[ng,nm]=(0,i.useState)(null);(0,i.useEffect)(()=>{ei.current=f?.id??null},[f?.id]),(0,i.useEffect)(()=>{ee.current=Z},[Z]);let nx=(0,i.useCallback)(()=>{eo.current?.abort(),eo.current=null},[]),nv=(0,i.useCallback)(e=>{try{window.history.replaceState(null,"",e)}catch{}!function(e,t){if(!t)return;let n=null;try{n=pb(new URLSearchParams(e.startsWith("?")?e:`?${e.replace(/^\/\??/,"")}`).get("session"))}catch{n=null}n?pw(t,n):pk(t)}(e,pj())},[]);(0,i.useEffect)(()=>{let e=u.requestedCwd;if(!e)return;let t=new AbortController;el.current=t;let n=es.current;return x("validating"),y(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);es.current===n&&(ns({cwd:t.cwd,projectRoot:t.cwd,status:"ready",error:null}),x("ready"))}).catch(e=>{t.signal.aborted||es.current===n&&(y(e instanceof Error?e.message:String(e)),x("error"))}),()=>{t.abort(),el.current===t&&(el.current=null)}},[u,ns]);let ny=(0,i.useRef)({cwd:nl.cwd,projectRoot:nl.projectRoot});(0,i.useEffect)(()=>{let e=ny.current,t={cwd:nl.cwd,projectRoot:nl.projectRoot};ny.current=t;let n=e.cwd!==t.cwd,r=e.projectRoot!==t.projectRoot;if(!n&&!r)return;let i=W.current.applyIdentityChange(t,e);if("persisted"===i.target.kind){let e=i.target;e.projectRoot&&f&&f.id===e.sessionId&&g(t=>t&&t.id===e.sessionId?{...t,projectRoot:e.projectRoot}:t);return}if("none"===i.target.kind){ei.current=null,g(null),ee.current=null,Q(null);return}ei.current=null,g(null);let o={id:i.target.intentId,cwd:i.target.cwd,generation:i.target.generation};ee.current=o,Q(o),nx(),t_([]),tR(null),tW(null),nv("/")},[nl.cwd,nl.projectRoot,f,nx,nv]);let nb=(0,i.useCallback)((e,t=!1,n)=>{es.current+=1,el.current?.abort(),W.current.selectPersisted({id:e.id,cwd:e.cwd}),ei.current=e.id,g(e),e.cwd&&ns({cwd:e.cwd,status:"ready",error:null}),nx(),ee.current=null,Q(null),ed(null),eu(n?{sessionId:e.id,entryId:n,nonce:ef.current+=1}:null),tW(null),np(!0),"ready"!==nh&&nf("ready"),h&&!t&&eM(!1),t||nv(`?session=${encodeURIComponent(e.id)}`)},[h,nx,nv,nh]),nw=(0,i.useCallback)(e=>{let t=e??na().cwd;if(!t)return;es.current+=1,el.current?.abort();let n=W.current.startNew(t);er(t),na().cwd!==t&&ns({cwd:t,status:"ready",error:null}),nx();let r="new"===n.target.kind?{id:n.target.intentId,cwd:n.target.cwd,generation:n.target.generation}:t9(t,++et.current);ee.current=r,Q(r),ei.current=null,ed(null),g(null),t_([]),tR(null),tW(null),h&&eM(!1),nv("/")},[h,na,ns,nx,nv]),nk=(0,i.useCallback)(e=>{if(ns({cwd:e,status:"ready",error:null}),er(e),ee.current){let t={...ee.current,cwd:e};ee.current=t,Q(t)}},[ns]);!function(e){let{onNewSession:t,activeCwd:n,disabled:r=!1}=e;(0,i.useEffect)(()=>{if(!function(e=!1){return!e}(r))return;let e=e=>{if(!e.defaultPrevented){if("Escape"===e.key){if(!l)return;let t=e.target?.tagName;if("TEXTAREA"===t||"INPUT"===t)return;e.preventDefault(),l();return}if("n"===e.key&&e.ctrlKey&&e.altKey){if(!n||!t)return;e.preventDefault(),t(n)}}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[n,t,r])}({onNewSession:()=>nw(),activeCwd:nd,disabled:ex||eS}),(0,i.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&"k"===e.key.toLowerCase()&&(ex||eS||(e.preventDefault(),ej(e=>!e)))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ex,eS]);let nj=(0,i.useCallback)((e,t)=>{W.current.applyHydrate({id:e,cwd:t.cwd??""})},[]),nS=(0,i.useCallback)((e,t)=>{nx();let n=new AbortController;eo.current=n;let r=t?.intentId??null,i=t?.forFork===!0;pC({sessionId:e,signal:n.signal,maxAttempts:5,baseDelayMs:200,isCurrent:()=>{if(n.signal.aborted||ei.current!==e)return!1;if(!i&&r){let e=ee.current;if(e&&e.id!==r)return!1}return!0},fetchSession:(e,t)=>fetch(`/api/sessions/${encodeURIComponent(e)}/info`,{signal:t}),parseBody:t=>{let n=t?.session;return n?.id===e?n:null}}).then(t=>{var n;t.ok&&((n={selectedSessionId:ei.current,hydratedId:t.value.id,intentId:r,activeIntentId:i?r:ee.current?.id}).selectedSessionId!==n.hydratedId||n.activeIntentId&&n.intentId&&n.activeIntentId!==n.intentId||(g(n=>n&&n.id===e?{...n,...t.value}:n),nj(e,t.value),P.current.upsertPending(t.value)))}).catch(()=>{})},[nx,nj]),nC=(0,i.useCallback)((e,t)=>{let n=function(e){let{currentIntentId:t,eventIntentId:n,selectedSessionId:r,createdSessionId:i}=e;return(!r||r===i)&&(!t||!n||t===n)&&(!t||!!n)}({currentIntentId:ee.current?.id,eventIntentId:t,selectedSessionId:ei.current,createdSessionId:e.id});if(t&&e.id!==ne(t)&&P.current.removePending(ne(t)),P.current.upsertPending(e),e.id.startsWith(t7)){n&&ed(e.id);return}n&&(W.current.promote(t??"",{id:e.id,cwd:e.cwd}),ed(null),ei.current=e.id,g(e),Q(null),ee.current=null,nv(`?session=${encodeURIComponent(e.id)}`));let r=ep();r&&eh([e,...r.filter(t=>t.id!==e.id)].slice(0,50)),w(e=>e+1)},[nv]),n_=(0,i.useCallback)(()=>{w(e=>e+1),J(e=>e+1),G(null)},[]),nI=(0,i.useCallback)((e,t)=>{t&&P.current[e?"markStarting":"clearStarting"](t)},[]),nR=(0,i.useCallback)((e,t)=>{void 0!==t&&tQ(e,{value:t,images:[]}),nx(),Q(null),ee.current=null,w(e=>e+1),g(t=>{let n={...t??{path:"",cwd:nd??"",created:"",modified:"",messageCount:0,firstMessage:""},id:e};return P.current.upsertPending(n),n}),ei.current=e,W.current.forkTo({id:e,cwd:nd??""}),nS(e,{forFork:!0}),nv(`?session=${encodeURIComponent(e)}`)},[nS,nx,nd,nv]),nT=(0,i.useCallback)(e=>{if(e?.error)W.current.completeUrlRestore({error:e.error}),nf("error"),nm(e.error);else if(e&&!1===e.found)W.current.completeUrlRestore({found:!1}),no?(pk(pj()),nf("ready")):nf("not-found");else{var t;u.sessionId&&(t=u.sessionId,pw(pj(),t)),nf("ready")}np(!0)},[u.sessionId,no]);(0,i.useEffect)(()=>{ni&&W.current.beginUrlRestore(ni)},[ni]);let nE=(0,i.useCallback)(e=>{w(e=>e+1),P.current.markDeleted(e),f?.id===e&&(nx(),Q(null),ee.current=null,ei.current=null,W.current.deleteSession(e),g(null),t_([]),tR(null),tW(null),nv("/"))},[f,nx,nv]),nM=(0,i.useCallback)((e,t,n,r=!1,i="content")=>{let o=aq(e,n),l=`file:${o}`;tX(i=>i.find(e=>e.id===l)?i:[...i,{id:l,label:t,filePath:e,sourceSessionId:n,bufferKey:o,writable:r,readOnly:!r,kind:"file"}]),t4(null),t1(l),eK(i),ty(!0),eN(e=>{let t=L(Math.max(e,480));return t!==e&&Y({width:t}),t}),h?eM(!1):tx(!0)},[ty,tx,h]),nA=(0,i.useCallback)(e=>{nM(e,(0,rH.WP)(e),f?.id??null,!!(f?.id&&!0!==f.readOnly))},[nM,f?.id,f?.readOnly]),nL=(0,i.useCallback)((e,t=!0)=>{let n=tY.find(t=>t.id===e);t&&n?.bufferKey&&t3({type:"remove",key:n.bufferKey});let r=tY.filter(t=>t.id!==e);tX(r),0===r.length?(t1(null),ty(!1)):t1(t=>t!==e?t:r[r.length-1].id),t4(t=>t===e?null:t)},[ty,t3,tY]),nW=(0,i.useCallback)(e=>{let t=tY.find(t=>t.id===e),n=t?.bufferKey?aY(t8.current,t.bufferKey):void 0;if(n?.dirty){t1(e),t4(e);return}nL(e)},[nL,tY]),nP=(0,i.useCallback)(()=>{let e=tY.find(e=>{if(!e.bufferKey)return!1;let t=aY(t8.current,e.bufferKey);return t?.dirty===!0});if(e){t1(e.id),t4(e.id);return}for(let e of tY)e.bufferKey&&t3({type:"remove",key:e.bufferKey});tX([]),t1(null),t4(null),ty(!1)},[ty,t3,tY]),nF=(0,i.useRef)(nl.cwd),nH=(0,i.useRef)(tY);nH.current=tY;let nD=(0,i.useRef)(t0);nD.current=t0,(0,i.useEffect)(()=>{var e,t;let n=nF.current,r=nl.cwd;if(nF.current=r,n===r)return;let i=function(e){let t=[],n=[],r=[];for(let i of e.tabs){if(i.bufferKey&&e.dirtyBufferKeys.has(i.bufferKey)){t.push(i);continue}n.push(i.id),i.bufferKey&&r.push(i.bufferKey)}return{closeIds:n,removeBufferKeys:r,keepTabs:t,pendingCloseTabId:t[0]?.id??null,closePanel:0===t.length}}({tabs:nH.current,dirtyBufferKeys:new Set(nH.current.filter(e=>e.bufferKey&&aY(t8.current,e.bufferKey)?.dirty===!0).map(e=>e.bufferKey))});for(let e of i.removeBufferKeys)t3({type:"remove",key:e});tX(i.keepTabs),t1((e=nD.current,0===(t=i.keepTabs).length?null:e&&t.some(t=>t.id===e)?e:t[0]?.id??null)),t4(i.pendingCloseTabId),i.closePanel&&ty(!1)},[ty,t3,nl.cwd]);let nN=(0,i.useCallback)(async()=>{let e=tY.find(e=>e.id===t2);e?.bufferKey&&await nt(e.bufferKey)&&nL(e.id)},[nL,tY,t2,nt]),nB=(0,i.useCallback)(()=>{let e=tY.find(e=>e.id===t2);e&&(e.bufferKey&&(t3({type:"discard",key:e.bufferKey}),t3({type:"remove",key:e.bufferKey})),nL(e.id,!1))},[nL,t3,tY,t2]),nO=(0,i.useMemo)(()=>[{id:"branch",label:c("branches"),filePath:"",kind:"branch"},{id:"info",label:c("app_sessionInfo"),filePath:"",kind:"info"},{id:"files",label:c("workspace_files"),filePath:"",kind:"files"},{id:"git",label:c("workspace_gitChanges"),filePath:"",kind:"git"},{id:"terminal",label:c("workspace_terminal"),filePath:"",kind:"terminal"}],[c]),nU=(0,i.useCallback)(e=>{ez&&e===tG?h?eW(!1):tx(!1):(t4(null),tZ(e),h?(eM(!1),eW(!0)):tx(!0))},[tG,tx,h,ez]),nq=(0,i.useCallback)(()=>{h?(eM(!1),eW(!0)):tx(!0),t4(null),tZ("info")},[tx,h]),nK="persisted"===D.kind?f?.id===D.sessionId?f:{id:D.sessionId,path:"",cwd:D.cwd,projectRoot:D.cwd,created:f?.created??"",modified:f?.modified??"",messageCount:f?.messageCount??0,firstMessage:f?.firstMessage??""}:null,nJ="new"===D.kind?{id:D.intentId,cwd:D.cwd,generation:D.generation}:null,nV=null===nK?Z?.cwd??nJ?.cwd??null:null,nY=null!==nK||null!==nV,nX=nu&&!nY,nG=t0?tY.find(e=>e.id===t0)??null:null,nZ=nd?(0,rH.WP)(nd)||nd:null,nQ=nZ?`${nZ} - Pidance`:"Pidance",n0=nK?.id??ea??null;(0,i.useEffect)(()=>{var e,t;s_((e=sS).base===nQ?e:{...e,base:nQ,override:null}),s_((t=sS).sessionKey===n0?t:{...t,sessionKey:n0,override:null});let n=()=>{var e;let t=(e=sS).override??e.base;document.title!==t&&(document.title=t)};n();let r=(sC.add(n),()=>{sC.delete(n)}),i=new MutationObserver(n);return i.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>{r(),i.disconnect()}},[nQ,n0]);let n1=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(n$,{catalogStore:P.current,selectedSessionId:nK?.id??ea,onSelectSession:nb,onNewSession:nw,initialSessionId:ni,skipInitialProjectSelection:null!==u.requestedCwd,onInitialRestoreDone:nT,restoreNonce:R,refreshKey:b,onSessionDeleted:nE,onProjectAdded:()=>w(e=>e+1),onProjectRootsChange:eT}),(0,r.jsxs)("div",{style:{padding:"6px 8px",flexShrink:0,display:"flex",alignItems:"center",gap:4},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eb(null),ev(!0)},"data-tooltip":c("app_settings"),"aria-label":c("app_settings"),className:"sidebar-icon-btn tooltip-up",children:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"}),(0,r.jsx)("path",{d:"M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.83 2.83-.06-.06a1.7 1.7 0 0 0-1.88-.34 1.7 1.7 0 0 0-1.03 1.56V21h-4v-.08A1.7 1.7 0 0 0 8.95 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.83-2.83.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-1.56-1.03H3v-4h.08A1.7 1.7 0 0 0 4.6 8.95a1.7 1.7 0 0 0-.34-1.88l-.06-.06 2.83-2.83.06.06A1.7 1.7 0 0 0 8.95 4.6 1.7 1.7 0 0 0 9.97 3.04V3h4v.08A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.83 2.83-.06.06A1.7 1.7 0 0 0 19.4 9c.12.42.52.98 1.56 1.03H21v4h-.08A1.7 1.7 0 0 0 19.4 15Z"})]})}),(0,r.jsx)("button",{type:"button",onClick:()=>eC(!0),"data-tooltip":c("app_about"),"aria-label":c("app_about"),className:`sidebar-icon-btn tooltip-up${eS?" sidebar-icon-btn--active":""}`,children:(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M12 16v-4"}),(0,r.jsx)("path",{d:"M12 8h.01"})]})})]})]});return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("style",{children:`
6
- @media (max-width: 640px) {
7
- .sidebar-overlay-backdrop.sidebar-mobile-pending {
8
- opacity: 0 !important;
9
- pointer-events: none !important;
10
- }
11
- .sidebar-container.sidebar-mobile-pending.sidebar-open {
12
- transform: translateX(-100%);
13
- box-shadow: none;
14
- }
15
- .workspace-overlay-backdrop.workspace-mobile-pending {
16
- opacity: 0 !important;
17
- pointer-events: none !important;
18
- }
19
- .workspace-container.workspace-mobile-pending.workspace-open {
20
- transform: translateX(100%);
21
- box-shadow: none;
22
- }
23
- }
24
- `}),(0,r.jsxs)("div",{style:{display:"flex",height:"100dvh",overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsx)("div",{className:`sidebar-overlay-backdrop${eA?"":" sidebar-mobile-pending"}`,onClick:()=>eM(!1),style:{position:"fixed",inset:0,zIndex:199,background:"var(--overlay)",opacity:+!!eE,pointerEvents:eE?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsxs)("div",{className:`sidebar-container${eE?" sidebar-open":" sidebar-closed"}${eA?"":" sidebar-mobile-pending"}${e0?" sidebar-dragging":""}`,style:{background:"var(--bg-panel)",borderRight:"1px solid var(--border)",display:"flex",flexDirection:"column",flexShrink:0,zIndex:200,"--sidebar-width":`${eZ}px`},children:[(0,r.jsx)("div",{className:"sidebar-inner",children:n1}),eE&&!h&&(0,r.jsx)("div",{className:`sidebar-resize-handle${e0?" dragging":""}`,role:"separator","aria-orientation":"vertical",tabIndex:0,title:c("app_sidebarResizeHandle"),"aria-label":c("app_sidebarResizeHandle"),"aria-valuenow":eZ,"aria-valuemin":240,"aria-valuemax":520,onPointerDown:e6,onPointerMove:e5,onPointerUp:e8,onPointerCancel:e8,onKeyDown:e3,onDoubleClick:e9})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0,minHeight:0},children:[(0,r.jsxs)("div",{className:"app-top-bar",children:[(0,r.jsx)("button",{onClick:tK,"data-tooltip":eE?c("app_hideSidebar"):c("app_showSidebar"),className:"instant-tooltip","aria-label":eE?c("app_hideSidebar"):c("app_showSidebar"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:"none",border:"none",borderRight:"1px solid var(--border)",color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-muted)"},children:eE?(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]}):(0,r.jsxs)("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),(0,r.jsx)("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),(0,r.jsx)("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),nY&&f&&(0,r.jsx)(pt,{catalogStore:P.current,session:f,onSelectSession:nb}),nY&&(tP||tD||void 0!==tO.tokensPerSecond)&&(()=>{let e=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),t=tD??tP?.contextUsage??null,n="var(--text-muted)",i=null;if(t?.contextWindow){let r=t.percent;null!==r&&r>90?n="var(--status-danger)":null!==r&&r>70&&(n="var(--status-warning)"),i=null!==r?h?`${r.toFixed(0)}%`:`${r.toFixed(0)}% / ${e(t.contextWindow)}`:h?"?":`? / ${e(t.contextWindow)}`}let o=tO.tokensPerSecond,l="number"==typeof o&&Number.isFinite(o)&&o>0?o>=10?String(Math.round(o)):String(Math.round(10*o)/10):null,s="number"==typeof tO.ttftMs&&tO.ttftMs>=0?tO.ttftMs>=1e3?`${(tO.ttftMs/1e3).toFixed(1)}s`:`${Math.round(tO.ttftMs)}ms`:null,a=[];if(t?.contextWindow){let e=t.percent;a.push(c("app_contextTooltip",{pct:null!==e?e.toFixed(1)+"%":c("app_unknown"),total:t.contextWindow.toLocaleString()}))}l&&a.push(c("app_throughputTooltip",{tps:l})),s&&a.push(c("app_ttftTooltip",{ttft:s}));let d=a.length>0?a.join("\n"):null,u=ez&&"info"===tG;return(0,r.jsxs)("button",{type:"button",onClick:nq,"data-tooltip":d||c("app_sessionInfo"),className:"instant-tooltip app-top-bar-stats","aria-label":c("app_sessionInfo"),"aria-pressed":u,style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:h?4:10,paddingLeft:h?8:12,paddingRight:h?8:12,height:"100%",minWidth:0,maxWidth:h?"48vw":void 0,overflow:"hidden",background:u?"var(--bg-selected)":"none",border:"none",borderTop:u?"2px solid var(--accent)":"2px solid transparent",fontSize:h?12:11,color:"var(--text-muted)",whiteSpace:"nowrap",cursor:"pointer",fontVariantNumeric:"tabular-nums",transition:"color 0.1s, background 0.1s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.color=u?"var(--text)":"var(--text-muted)"},children:[h&&(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,r.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]}),i&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:n},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 9 L1 5 Q1 1 5 1 Q9 1 9 5 L9 9"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"9",y2:"9"})]}),i]}),l&&(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:4,color:"var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})}),l,(0,r.jsx)("span",{style:{opacity:.7},children:c("app_tokensPerSecondUnit")})]})]})})(),h&&(0,r.jsx)("button",{type:"button",onClick:tV,"data-tooltip":ez?c("app_hidePanel"):c("app_showPanel"),className:"instant-tooltip","aria-label":ez?c("app_hidePanel"):c("app_showPanel"),"aria-pressed":ez,style:{marginLeft:nY&&(tP||tD)?0:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:36,height:36,padding:0,background:ez?"var(--bg-selected)":"none",border:"none",borderLeft:"1px solid var(--border)",color:ez?"var(--text)":"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),(0,r.jsx)("line",{x1:"15",y1:"3",x2:"15",y2:"21"})]})})]}),(0,r.jsx)("div",{ref:e7,style:{flex:1,minHeight:0,overflow:"hidden",position:"relative",[_]:`${ts}px`},children:(0,r.jsxs)("div",{style:{height:"100%",minHeight:0,overflow:"hidden",position:"relative"},children:[nY&&!h&&(0,r.jsx)("div",{className:"chat-column-resize-layer",style:{left:18,right:18},children:["left","right"].map(e=>(0,r.jsx)("div",{"data-side":e,className:`chat-column-resize-handle${ti?" dragging":""}`,role:"separator","aria-orientation":"vertical",tabIndex:0,title:c("app_chatColumnResizeHandle"),"aria-label":c("app_chatColumnResizeHandle"),"aria-valuenow":ts,"aria-valuemin":1e3,"aria-valuemax":1600,style:{left:"left"===e?`calc(50% - ${I} / 2 - 6px)`:`calc(50% + ${I} / 2)`},onPointerDown:tu,onPointerMove:tp,onPointerUp:th,onPointerCancel:th,onKeyDown:tf,onDoubleClick:tg},e))}),nY?(0,r.jsx)(aI,{session:nK,newSessionCwd:nV,newSessionIntentId:nJ?.id??Z?.id??null,guideDefaultCwd:en,projectRoots:eR,onGuideTargetChange:nk,onAgentEnd:n_,onAgentRunningChange:nI,onSessionCreated:nC,onSessionForked:nR,modelsRefreshKey:e_,chatInputRef:tS,onBranchDataChange:tA,onSystemPromptChange:t$,onSessionStatsChange:tH,onSessionStatsPanelOpen:nq,onContextUsageChange:tB,onTurnMetricsChange:tq,onOpenFile:nA,onReferenceFile:nc,entryJumpRequest:ec,onEntryJumpHandled:eg,footerCollapsed:E,onFooterToggle:()=>{let e=!E;z(e);try{localStorage.setItem("pidance.footerCollapsed",e?"1":"0")}catch{}}},N):"validating"===m?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:c("app_openWorkspace")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:u.requestedCwd})]}):"error"===m?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--status-danger)"},children:c("app_workspaceUnavailable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:u.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:v})]}):"not-found"===nh?(0,r.jsx)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:c("app_sessionNotFound")})}):"error"===nh?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--status-danger)"},children:c("app_sessionRestoreFailed")}),ng?(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:ng}):null,(0,r.jsx)("button",{type:"button",onClick:()=>{W.current.retryUrlRestore(),nf("loading"),np(!1),T(e=>e+1),w(e=>e+1)},children:c("app_retry")})]}):nX?nd?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:c("app_selectSessionFromSidebar")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:c("app_getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),c("app_setupSelectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),c("app_setupAddModel")]})]})]}):null]})})]}),eF&&(0,r.jsxs)("aside",{className:"changes-panel",style:{width:eD,height:"100%",minHeight:0,display:"flex",flexDirection:"column"},"aria-label":c("changes_title"),children:[(0,r.jsx)("div",{className:`changes-panel-resize-handle${eJ?" dragging":""}`,role:"separator","aria-orientation":"vertical",tabIndex:0,title:c("changes_resizeHandle"),"aria-label":c("changes_resizeHandle"),"aria-valuenow":eD,"aria-valuemin":320,"aria-valuemax":960,onPointerDown:tb,onPointerMove:tw,onPointerUp:tk,onPointerCancel:tk,onKeyDown:tj,onDoubleClick:()=>tv(560)}),(0,r.jsx)(dA,{open:eF,width:eD,onWidthChange:tv,cwd:nd,isMobile:h,mobileReady:eX,tabs:tY,activeTabId:t0??"",onSelectTab:e=>{t4(null),t1(e)},onCloseTab:nW,onCloseAllTabs:nP,pendingCloseTabLabel:t2?tY.find(e=>e.id===t2)?.label??null:null,onSaveAndClose:()=>void nN(),onDiscardAndClose:nB,onCancelClose:()=>t4(null),activeMode:eq,gitAffectedPaths:X,fileViewerContent:nG?.filePath?(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:(0,r.jsx)(dn,{filePath:nG.filePath,cwd:nd??void 0,sourceSessionId:nG.sourceSessionId,writable:!0===nG.writable,buffer:nG.bufferKey?aY(t6,nG.bufferKey):void 0,dispatchBuffer:t3,onSave:nG.bufferKey?()=>nt(nG.bufferKey):void 0,gitAffectedPaths:X,onOpenFile:e=>nM(e,(0,rH.WP)(e),nG.sourceSessionId,!0===nG.writable)})}):null})]}),(0,r.jsx)("div",{className:`sidebar-overlay-backdrop workspace-overlay-backdrop${eX?"":" workspace-mobile-pending"}`,onClick:()=>eW(!1),style:{position:"fixed",inset:0,zIndex:199,background:"var(--overlay)",opacity:h&&ez?1:0,pointerEvents:h&&ez?"auto":"none",transition:"opacity 0.25s ease"}}),(0,r.jsx)(dT,{open:ez,width:e$,onWidthChange:tm,onClose:()=>h?eW(!1):tx(!1),cwd:nd,isMobile:h,mobileReady:eX,tabs:nO,activeTabId:tG,onSelectTab:nU,sessionInfoContent:(0,r.jsx)(dL,{session:f,sessionStats:tP,contextUsage:tD,systemPrompt:tz}),terminalContent:(0,r.jsx)(ph,{}),branchContent:(0,r.jsx)(u6,{tree:tC,activeLeafId:tI,onLeafChange:tL,branchActions:tE,hasSession:nY,panel:!0}),onOpenFile:(e,t,n)=>nM(e,t,f?.id??null,!!(f?.id&&!0!==f.readOnly),n),fileRefreshKey:K,gitRefreshKey:K,onAtMention:nn,onAtMentions:nr})]}),ex&&(0,r.jsx)(uW,{initialPage:ey,cwd:nd??f?.cwd??null,sessionId:f?.id??null,onClose:()=>{ev(!1),eb(null),eI(e=>e+1)},onModelsChanged:()=>{ev(!1),eI(e=>e+1)},onAuthStateChange:()=>eI(e=>e+1),onPluginsReloaded:()=>B(e=>e+1)}),(0,r.jsx)(uY,{}),(0,r.jsx)(uZ,{}),(0,r.jsx)(uJ,{open:eS,onClose:()=>eC(!1)}),(0,r.jsx)(uP,{open:ek,onClose:()=>ej(!1),onSelectSession:e=>nb(e),onNewSession:()=>nw(),onOpenFile:(e,t)=>nM(e,t,f?.id??null,!!(f?.id&&!0!==f.readOnly),"content"),onOpenSettings:e=>{ev(!0),eb(e)},onToggleTheme:p,cwd:nd??f?.cwd??null})]})}},17581:(e,t,n)=>{Promise.resolve().then(n.bind(n,15427)),Promise.resolve().then(n.bind(n,84747))},28999:(e,t,n)=>{"use strict";function r(e){try{return decodeURIComponent(e)}catch{return e}}function i(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function o(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function l(e){return i(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function s(e){var t;if("string"!=typeof e)return null;let n="/api/files/",i=e.indexOf(n);if(i<0)return null;let o=e.slice(i+n.length).split("?")[0].split("#")[0];if(!o)return null;let l=o.split("/").filter(e=>e.length>0).map(r);if(0===l.length)return null;let s=l.join("/").replace(/\\/g,"/");return(t=s,/^[a-zA-Z]:\//.test(t)||t.startsWith("//"))?s:`/${s.replace(/^\/+/,"")}`}function a(e){let t=i(e).replace(/\/+$/,"");return t.split("/").pop()??t}function d(e){let t=i(e).replace(/\/+$/,""),n=t.lastIndexOf("/");return n<0?"":0===n?"/":2===n&&/^[a-zA-Z]:\//.test(t)?t.slice(0,3):t.slice(0,n)}function c(e,t){if(!t)return e;let n=i(e),r=i(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}function u(e,t){return`${i(e).replace(/\/$/,"")}/${t}`}n.d(t,{A0:()=>i,HG:()=>l,WP:()=>a,e_:()=>u,ex:()=>r,gX:()=>d,n$:()=>s,nf:()=>o,qP:()=>c})},32383:(e,t,n)=>{"use strict";n.d(t,{$J:()=>d,LY:()=>a,Us:()=>u,submitAgentPrompt:()=>c});var r=n(54180),i=n(99838);let o=["accepted","queued","rejected"],l=["prompt","steer","queued"],s=["busy","compacting","bash","media","locked","model","auth","extension","error"];function a(e){let t=e?.agentCommandStatus;return"number"==typeof t&&t>=400&&t<500}async function d(e,t,n){let r=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n?.signal}),i=await r.json().catch(()=>({}));if(!r.ok||i.error)throw function(e,t){if(e&&"object"==typeof e)try{e.agentCommandStatus=t}catch{}return e}(Error(i.error??`HTTP ${r.status}`),r.status);return i.data}async function c(e,t,n){let a=await d(e,{type:"prompt",message:t.message,submissionId:t.submissionId,...t.images?.length?{images:(0,r.py)(t.images)}:{},...t.binaryBlocks?.length?{binaryBlocks:t.binaryBlocks}:{}},n);if(!a||"object"!=typeof a)throw Error("Invalid prompt receipt: expected an object");if("string"!=typeof a.submissionId||!a.submissionId||"string"!=typeof a.sessionId||!a.sessionId||!o.includes(a.status)||a.submissionId!==t.submissionId||a.sessionId!==e)throw Error("Invalid prompt receipt");return{submissionId:a.submissionId,sessionId:a.sessionId,status:a.status,...l.includes(a.action)?{action:a.action}:{},...s.includes(a.reason)?{reason:a.reason}:{},...function(e){if(!e||"object"!=typeof e||!Array.isArray(e.items)||"number"!=typeof e.revision)return null;let t=Array.isArray(e.inFlight)?e.inFlight.filter(e=>"string"==typeof e):[];return{queue:{items:(0,i.hh)(e.items),revision:e.revision,inFlight:t}}}(a.queue)??{}}}function u(e){return"boolean"==typeof e.live?e.live:!0===e.running}},54180:(e,t,n)=>{"use strict";function r(e,t,n){return new Promise(r=>{e.toBlob(e=>r(e&&e.type===t?e:null),t,n)})}async function i(e){if(e.size<=262144)return null;let t=e.type.toLowerCase();if("image/gif"===t||!o.has(t)||"u"<typeof document)return null;let n=await a(e),i=n.naturalWidth,l=n.naturalHeight;if(!i||!l)return null;let s=Math.min(1,1024/i,1024/l),c=d(i,l,s),u=document.createElement("canvas");u.width=c.width,u.height=c.height;let p=u.getContext("2d");if(!p)return null;p.drawImage(n,0,0,c.width,c.height);let h=await r(u,"image/webp",.82).catch(()=>null);if(h&&h.size<e.size)return{blob:h,mimeType:"image/webp"};let f=await r(u,t,"image/png"===t?void 0:.82).catch(()=>null);return f&&f.size<e.size?{blob:f,mimeType:t}:null}n.d(t,{Pk:()=>C,FZ:()=>k,zr:()=>v,LH:()=>g,kZ:()=>S,I9:()=>w,wZ:()=>b,py:()=>x,CS:()=>y,Rc:()=>f});let o=new Set(["image/gif","image/jpeg","image/png","image/webp"]);function l(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let e="string"==typeof r.result?r.result:"";e?t(e):n(Error("image data is empty"))},r.onerror=()=>n(r.error??Error("image read failed")),r.readAsDataURL(e)})}function s(e){let t=e.indexOf(",");if(t<0)return null;let n=e.slice(0,t),r=e.slice(t+1),i=/^data:(image\/[a-z0-9.+-]+);base64$/i.exec(n);return i&&r?{mimeType:i[1].toLowerCase(),data:r}:null}function a(e){let t=URL.createObjectURL(e);return new Promise((e,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(t),e(r)},r.onerror=()=>{URL.revokeObjectURL(t),n(Error("image decode failed"))},r.src=t})}function d(e,t,n){return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}}async function c(e){let t=e.type.toLowerCase(),n=await a(e),r=n.naturalWidth,i=n.naturalHeight;if(!r||!i)throw Error("image has no dimensions");if(o.has(t)&&r<=2e3&&i<=2e3){let t=s(await l(e));if(t&&t.data.length<=4194304)return{...t,blob:e}}if("u"<typeof document)throw Error("image canvas is unavailable");let c=document.createElement("canvas"),u=Math.min(1,2e3/r,2e3/i),p=[.84,.74,.64,.54,.44];for(let e=0;e<10;e+=1){let e=d(r,i,u);c.width=e.width,c.height=e.height;let t=c.getContext("2d");if(!t)throw Error("image canvas is unavailable");for(let r of(t.fillStyle="#ffffff",t.fillRect(0,0,e.width,e.height),t.drawImage(n,0,0,e.width,e.height),p)){let e=await function(e,t){return new Promise((n,r)=>{e.toBlob(e=>e?n(e):r(Error("image encode failed")),"image/jpeg",t)})}(c,r),t=s(await l(e));if(t&&t.data.length<=4194304)return{...t,blob:e}}u*=.75}throw Error("image is too large to prepare for the selected model")}var u=n(28999);let p={"image/jpeg":"jpg","image/png":"png","image/webp":"webp","image/gif":"gif","image/avif":"avif","image/bmp":"bmp","image/svg+xml":"svg"};function h(e){return p[e.split(";")[0].trim().toLowerCase()]??"bin"}async function f(e,t,n){let r=n||e.type||"application/octet-stream",i=await fetch("/api/message-media",{method:"POST",headers:{"Content-Type":r,"X-Pidance-Filename":encodeURIComponent(t||"file")},body:e}),o=await i.json().catch(()=>({}));if(!i.ok||"string"!=typeof o.path||"string"!=typeof o.storedName||"number"!=typeof o.size||"string"!=typeof o.name)throw Error(o.error??`HTTP ${i.status}`);return{path:o.path,name:o.name,storedName:o.storedName,size:o.size,mimeType:o.mimeType||r}}async function g(e){let t=[...new Set(e.filter(e=>"string"==typeof e&&e.length>0))];if(0!==t.length)try{await fetch("/api/message-media",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:t})})}catch{}}function m(e,t){let n=new URLSearchParams({type:"read"});return t&&n.set("mime",t),`/api/files/${(0,u.HG)(e)}?${n.toString()}`}function x(e){if(!e?.length)return;let t=[];for(let n of e){if(n.media){t.push({type:"ref",path:n.media.model.path,mimeType:n.media.model.mimeType});continue}if(n.data){t.push({type:"image",data:n.data,mimeType:n.mimeType});continue}n.original&&t.push({type:"ref",path:n.original.path,mimeType:n.original.mimeType})}return t.length?t:void 0}function v(e){if(e.previewUrl)return e.previewUrl;let t=e.media?.preview??e.media?.original;return t?m(t.path,t.mimeType):e.original?m(e.original.previewPath??e.original.path,e.original.mimeType):""}async function y(e,t){let n=[];try{let[r,o]=await Promise.all([c(e),f(e,e.name,e.type)]);n.push(o);let l=await f(r.blob,`${e.name}.model.${h(r.mimeType)}`,r.mimeType);n.push(l);let s=r.blob===e?await i(e):null,a=r.blob!==e||s?await f(s?.blob??r.blob,`${e.name}.preview.${h(s?.mimeType??r.mimeType)}`,s?.mimeType??r.mimeType):o;return a!==o&&n.push(a),{data:r.data,mimeType:r.mimeType,previewUrl:t??URL.createObjectURL(e),media:{model:l,original:o,preview:a}}}catch(e){throw await g(n.map(e=>e.path)),e}}function b(e){return e.previewPath?[e.path,e.previewPath]:[e.path]}function w(e){if(e.media){let{model:t,original:n,preview:r}=e.media;return[{role:"model",path:t.path,name:t.name,mimeType:t.mimeType,size:t.size},{role:"original",path:n.path,name:n.name,mimeType:n.mimeType,size:n.size,...r.path!==n.path?{previewPath:r.path}:{}}]}let t=e.original;return t?[{role:"original",path:t.path,name:t.name,mimeType:t.mimeType,size:t.size,...t.previewPath?{previewPath:t.previewPath}:{}}]:[]}function k(e,t){return[...e.flatMap(j),...t]}function j(e){return e.media?[function(e){let{original:t,preview:n}=e;return{path:t.path,name:t.name,mimeType:t.mimeType,size:t.size,...n.path!==t.path?{previewPath:n.path}:{}}}(e.media)]:e.original?[e.original]:[]}function S(e){let t=[],n=null;for(let r of e){if("model"===r.role){n=r;continue}t.push({model:n,original:r}),n=null}return t}function C(e){let t=e=>({path:e.path,name:e.name,storedName:e.path.split(/[\\/]/).pop()??e.name,size:e.size,mimeType:e.mimeType}),n=t(e.original),r=e.original.previewPath?t({...e.original,path:e.original.previewPath}):n,i=e.model?t(e.model):null,o={mimeType:e.model?.mimeType??e.original.mimeType,previewUrl:m(r.path,r.mimeType),original:{path:n.path,name:n.name,mimeType:n.mimeType,size:n.size,...r===n?{}:{previewPath:r.path}}};return i&&(o.media={model:i,original:n,preview:r}),o}},84747:(e,t,n)=>{"use strict";n.d(t,{UiLoginGate:()=>l,b:()=>s});var r=n(95155),i=n(12115),o=n(99780);function l({children:e}){let{t}=(0,o.s9)(),[n,s]=(0,i.useState)("loading"),[a,d]=(0,i.useState)(""),[c,u]=(0,i.useState)(!0),[p,h]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),m=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/auth/ui-session",{method:"GET",credentials:"same-origin",cache:"no-store"}),t=await e.json().catch(()=>({}));if(!t.passwordRequired||e.ok&&t.authenticated)return void s("ready");s("login")}catch{s("login")}},[]);(0,i.useEffect)(()=>{m()},[m]);let x=(0,i.useCallback)(async e=>{if(e.preventDefault(),!f){g(!0),h(null);try{let e=await fetch("/api/auth/ui-session",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:a,trustDevice:c})}),n=await e.json().catch(()=>({}));if(429===e.status)return void h(t("auth_loginRateLimited",{seconds:n.retryAfter??60}));if(!e.ok||!n.authenticated)return void h("Invalid credentials"===n.error?t("auth_invalidCredentials"):n.error??t("auth_loginFailed"));d(""),s("ready")}catch{h(t("auth_loginFailed"))}finally{g(!1)}}},[a,f,t,c]);return"loading"===n?(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg)",color:"var(--text-muted)",fontSize:13},children:t("auth_checking")}):"login"===n?(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg)",padding:24},children:(0,r.jsxs)("form",{onSubmit:e=>{x(e)},style:{width:"100%",maxWidth:360,padding:"28px 24px",borderRadius:"var(--radius-md, 10px)",border:"1px solid var(--border)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float, 0 8px 28px rgba(0,0,0,0.12))"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:18},children:[(0,r.jsx)("img",{src:"/brand/pidance-logo.png",alt:"",width:32,height:32,style:{borderRadius:8}}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:16,fontWeight:600,color:"var(--text)"},children:t("auth_loginTitle")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:2},children:t("auth_loginHint")})]})]}),(0,r.jsxs)("label",{style:{display:"block",fontSize:12,color:"var(--text-muted)",marginBottom:6},children:[t("auth_password"),(0,r.jsx)("input",{type:"password",autoFocus:!0,autoComplete:"current-password",value:a,onChange:e=>d(e.target.value),disabled:f,style:{display:"block",width:"100%",marginTop:6,height:36,padding:"0 10px",boxSizing:"border-box",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",fontSize:14}})]}),(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,marginTop:12,fontSize:12,color:"var(--text-muted)",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("input",{type:"checkbox",checked:c,onChange:e=>u(e.target.checked),disabled:f}),t("auth_trustDevice")]}),p&&(0,r.jsx)("div",{role:"alert",style:{marginTop:12,fontSize:12,color:"var(--status-danger)",lineHeight:1.4},children:p}),(0,r.jsx)("button",{type:"submit",disabled:f||!a,style:{marginTop:18,width:"100%",height:36,border:"none",borderRadius:6,background:!a||f?"var(--border)":"var(--accent)",color:!a||f?"var(--text-dim)":"#fff",fontSize:13,fontWeight:600,cursor:!a||f?"not-allowed":"pointer"},children:f?t("auth_loggingIn"):t("auth_login")})]})}):(0,r.jsx)(r.Fragment,{children:e})}async function s(){await fetch("/api/auth/ui-session",{method:"DELETE",credentials:"same-origin"}).catch(()=>void 0),window.location.reload()}},99838:(e,t,n)=>{"use strict";function r(e){return o(Array.isArray(e)?e:[]).items}function i(e,t){let n=0x811c9dc5;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=0x1000193*n>>>0;return`legacy-${e}-${n.toString(36)}`}function o(e){let t=Array.isArray(e)?e:e&&"object"==typeof e?e.items:void 0,n=e&&"object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.revision&&Number.isFinite(e.revision)?e.revision:0,r=function(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=function(e){if("string"!=typeof e)return null;let t=e.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(t)?t:null}(n);e&&!t.includes(e)&&t.push(e)}return t.length>128?t.slice(t.length-128):t}(e&&"object"==typeof e&&!Array.isArray(e)?e.admittedAttemptIds:void 0);if(!Array.isArray(t))return{items:[],revision:n,admittedAttemptIds:r};let o=[];for(let e=0;e<t.length;e++){let n=function(e,t){var n;if("string"==typeof e){let n=e.trim();return n?{id:i(t,e),text:n,state:"waiting"}:null}if(!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.text)return null;let r=function(e){if(void 0===e)return[];if(!Array.isArray(e)||e.length>32)return null;let t=[];for(let n of e){if(!n||"object"!=typeof n||Array.isArray(n))return null;let e="model"===n.role||"original"===n.role?n.role:null,r="string"==typeof n.path?n.path.trim():"",i="string"==typeof n.mimeType?n.mimeType.trim():"",o="string"==typeof n.name?n.name.trim():"",l=n.size,s="string"==typeof n.previewPath?n.previewPath.trim():void 0;if(!e||!r||!i||!o||"number"!=typeof l||!Number.isSafeInteger(l)||l<0||void 0!==n.previewPath&&!s)return null;t.push({role:e,path:r,name:o,mimeType:i,size:l,...s&&s!==r?{previewPath:s}:{}})}return t}(e.media);return null!==r&&(e.text.trim()||0!==r.length)?{id:"string"==typeof e.id&&e.id.trim()?e.id:i(t,e.text),text:e.text,state:"claimed"===(n=e.state)||"unknown"===n?n:"waiting",...r.length?{media:r}:{}}:null}(t[e],e);n&&o.push(n)}return{items:o,revision:n,admittedAttemptIds:r}}n.d(t,{hh:()=>r,jG:()=>o})}},e=>{e.O(0,[1838,7330,3888,7444,9780,8441,3794,7358],()=>e(e.s=17581)),_N_E=e.O()}]);