@jingyi0605/codingns 0.9.5 → 0.9.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/codingns.mjs +75 -0
- package/dist/public/assets/{AdaptiveButlerPage-kkJDsnCO.js → AdaptiveButlerPage-khJQh6a_.js} +1 -1
- package/dist/public/assets/{App-DrNI9lWA.js → App-If9gThKM.js} +6 -6
- package/dist/public/assets/{BootstrapPage-QgVH5Mps.js → BootstrapPage-DcfYtoLC.js} +1 -1
- package/dist/public/assets/{ConversationPage-DVk8VfIj.js → ConversationPage-Bfb7GLTM.js} +1 -1
- package/dist/public/assets/{DesktopDetachPreviewPage-BhfP0TpH.js → DesktopDetachPreviewPage-CXUPMcBz.js} +1 -1
- package/dist/public/assets/{DesktopModal-DRmDrv0S.js → DesktopModal-bMdI1jEe.js} +1 -1
- package/dist/public/assets/{DesktopWindowPage-DNbJXnSs.js → DesktopWindowPage-D1xwgS-7.js} +1 -1
- package/dist/public/assets/{FileContextPanel---fLO4ve.js → FileContextPanel-C4syif3B.js} +1 -1
- package/dist/public/assets/{GitSidebar-sXUE0TqT.js → GitSidebar-DduL9aTV.js} +1 -1
- package/dist/public/assets/{MobileCreateSessionSheet-BftZ5pvb.js → MobileCreateSessionSheet-DWPBsEx8.js} +1 -1
- package/dist/public/assets/{MobileSheet-nw5SCa3N.js → MobileSheet-BXvQPkxt.js} +1 -1
- package/dist/public/assets/{MobileTopHeaderFrame-DH_D02Wy.js → MobileTopHeaderFrame-vdYOyaaB.js} +1 -1
- package/dist/public/assets/{MobileWorkspaceSwitcherHeader-2K406G5p.js → MobileWorkspaceSwitcherHeader-DT330cAx.js} +1 -1
- package/dist/public/assets/{PluginAccessOverview-BVJihw3D.js → PluginAccessOverview-C77TeZTK.js} +1 -1
- package/dist/public/assets/{PluginContainerPage-CR4vStvr.js → PluginContainerPage-DdSwOCw-.js} +1 -1
- package/dist/public/assets/{PluginDetailPage-CrMX0Mnm.js → PluginDetailPage-BK1yTzvO.js} +1 -1
- package/dist/public/assets/{PluginsListPage-FtIL71Yg.js → PluginsListPage-DAAwSc6W.js} +1 -1
- package/dist/public/assets/{RelayConnectEntryPage-Bt1apX53.js → RelayConnectEntryPage-4Yyo2p8b.js} +1 -1
- package/dist/public/assets/{ServerSettingsModal-D-guzPrI.js → ServerSettingsModal-C_DEisHs.js} +1 -1
- package/dist/public/assets/{SessionIndexPage-CX2FppcJ.js → SessionIndexPage-DyMikN_x.js} +1 -1
- package/dist/public/assets/SettingsPage-CDAVsPr3.js +2 -0
- package/dist/public/assets/{TerminalManagerPanel-B5MKGPy-.js → TerminalManagerPanel-4OR47vcf.js} +1 -1
- package/dist/public/assets/{TerminalPage-C2dTNGHK.js → TerminalPage-Pvx396YX.js} +1 -1
- package/dist/public/assets/{TerminalRuntimeFallbackModal-DAqOxFD8.js → TerminalRuntimeFallbackModal-KvG6k4AQ.js} +1 -1
- package/dist/public/assets/{ToolFilesPage-IsNwyE6T.js → ToolFilesPage-DrYHk0N-.js} +1 -1
- package/dist/public/assets/{ToolGitPage-BK1JBERN.js → ToolGitPage-Dz1q-Ns_.js} +1 -1
- package/dist/public/assets/{ToolProcessesPage-DwTYUQCK.js → ToolProcessesPage-CRhphOmM.js} +1 -1
- package/dist/public/assets/{ToolsHomePage-BLOy7lPg.js → ToolsHomePage-BJSDLR6T.js} +1 -1
- package/dist/public/assets/{WorkbenchLandingPage-CqZKR6EA.js → WorkbenchLandingPage-BlkxdOLC.js} +1 -1
- package/dist/public/assets/WorkbenchLayout-D-U7ghT0.js +1022 -0
- package/dist/public/assets/{WorkbenchModal-BM-OeW-b.js → WorkbenchModal-xbx1o6MO.js} +1 -1
- package/dist/public/assets/WorkbenchShellRoute-DyWSCHz_.js +1 -0
- package/dist/public/assets/WorkbenchShellRoute-htbkGbtW.css +1 -0
- package/dist/public/assets/{WorkspaceDebugDetailPage-BMsEN5iG.js → WorkspaceDebugDetailPage-B4ol2_a5.js} +1 -1
- package/dist/public/assets/{WorkspaceDetailPage-5H9Gosx2.js → WorkspaceDetailPage-DMakfmHR.js} +1 -1
- package/dist/public/assets/{WorkspaceHomePage-DQiXKgiP.js → WorkspaceHomePage-tmCafatd.js} +1 -1
- package/dist/public/assets/{client-runtime-manager-CgPJq21V.js → client-runtime-manager-Bwau7p1v.js} +1 -1
- package/dist/public/assets/index-DmUJ8tIw.css +1 -0
- package/dist/public/assets/index-_OCkVmfl.js +50 -0
- package/dist/public/assets/{login-direct-candidate-resolver-CGaxAXV8.js → login-direct-candidate-resolver-CKUQ07IA.js} +1 -1
- package/dist/public/assets/{plugin-permission-copy-BR9gWy8b.js → plugin-permission-copy-DIVk5jNp.js} +1 -1
- package/dist/public/assets/{plugins-api-CdCsrG2e.js → plugins-api-DHJVvPZw.js} +1 -1
- package/dist/public/assets/{preferences-service-lOhnlxzP.js → preferences-service-CyxxeBmS.js} +1 -1
- package/dist/public/assets/{relay-entry-CQpxTS8y.js → relay-entry-B5GmiOrR.js} +1 -1
- package/dist/public/assets/{terminal-runtime-meta-oteTx66X.js → terminal-runtime-meta-DBsyT35T.js} +1 -1
- package/dist/public/assets/{useRegisteredDebugTemplates-Bu2ykZ6s.js → useRegisteredDebugTemplates-wCGD2SLW.js} +1 -1
- package/dist/public/assets/{workbench-navigation-DlgXuFW2.js → workbench-navigation-RyUjchbD.js} +1 -1
- package/dist/public/index.html +2 -2
- package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-repository.d.ts +1 -0
- package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-repository.js +31 -0
- package/dist/server/modules/affairs-indexer/core/src/repositories/catalog-repository.js.map +1 -1
- package/dist/server/modules/affairs-indexer/core/src/services/dirty/dirty-scope-resolver.d.ts +1 -0
- package/dist/server/modules/affairs-indexer/core/src/services/dirty/dirty-scope-resolver.js +1 -0
- package/dist/server/modules/affairs-indexer/core/src/services/dirty/dirty-scope-resolver.js.map +1 -1
- package/dist/server/modules/affairs-indexer/core/src/services/export/export-builder.js +4 -1
- package/dist/server/modules/affairs-indexer/core/src/services/export/export-builder.js.map +1 -1
- package/dist/server/modules/affairs-indexer/core/src/services/search/search-index-builder.js +140 -16
- package/dist/server/modules/affairs-indexer/core/src/services/search/search-index-builder.js.map +1 -1
- package/dist/server/modules/assistant-capability/assistant-capability-controller.d.ts +1 -1
- package/dist/server/modules/assistant-capability/assistant-capability-controller.js +8 -7
- package/dist/server/modules/assistant-capability/assistant-capability-controller.js.map +1 -1
- package/dist/server/modules/assistant-capability/assistant-capability-service.d.ts +14 -13
- package/dist/server/modules/assistant-capability/assistant-capability-service.js +27 -24
- package/dist/server/modules/assistant-capability/assistant-capability-service.js.map +1 -1
- package/dist/server/modules/auth/auth-controller.d.ts +27 -1
- package/dist/server/modules/auth/auth-controller.js +20 -0
- package/dist/server/modules/auth/auth-controller.js.map +1 -1
- package/dist/server/modules/auth/auth-service.d.ts +32 -1
- package/dist/server/modules/auth/auth-service.js +217 -2
- package/dist/server/modules/auth/auth-service.js.map +1 -1
- package/dist/server/modules/bootstrap/bootstrap-service.js +1 -0
- package/dist/server/modules/bootstrap/bootstrap-service.js.map +1 -1
- package/dist/server/modules/butler/assistant-automation-service.d.ts +1 -1
- package/dist/server/modules/butler/assistant-automation-service.js +9 -10
- package/dist/server/modules/butler/assistant-automation-service.js.map +1 -1
- package/dist/server/modules/butler/butler-action-context-service.js +2 -2
- package/dist/server/modules/butler/butler-action-context-service.js.map +1 -1
- package/dist/server/modules/butler/butler-control-action-service.d.ts +5 -5
- package/dist/server/modules/butler/butler-control-action-service.js +19 -19
- package/dist/server/modules/butler/butler-control-action-service.js.map +1 -1
- package/dist/server/modules/butler/butler-control-session-service.d.ts +1 -1
- package/dist/server/modules/butler/butler-control-session-service.js +27 -26
- package/dist/server/modules/butler/butler-control-session-service.js.map +1 -1
- package/dist/server/modules/butler/butler-control-timer-service.js +4 -5
- package/dist/server/modules/butler/butler-control-timer-service.js.map +1 -1
- package/dist/server/modules/butler/butler-controller.d.ts +2 -2
- package/dist/server/modules/butler/butler-controller.js +19 -17
- package/dist/server/modules/butler/butler-controller.js.map +1 -1
- package/dist/server/modules/butler/butler-profile-service.d.ts +5 -5
- package/dist/server/modules/butler/butler-profile-service.js +17 -16
- package/dist/server/modules/butler/butler-profile-service.js.map +1 -1
- package/dist/server/modules/butler/butler-project-service.d.ts +7 -6
- package/dist/server/modules/butler/butler-project-service.js +35 -21
- package/dist/server/modules/butler/butler-project-service.js.map +1 -1
- package/dist/server/modules/butler/butler-session-service.d.ts +2 -2
- package/dist/server/modules/butler/butler-session-service.js +33 -27
- package/dist/server/modules/butler/butler-session-service.js.map +1 -1
- package/dist/server/modules/butler/butler-session-summary-service.d.ts +2 -2
- package/dist/server/modules/butler/butler-session-summary-service.js +23 -9
- package/dist/server/modules/butler/butler-session-summary-service.js.map +1 -1
- package/dist/server/modules/butler/context-aggregator.js +9 -9
- package/dist/server/modules/butler/context-aggregator.js.map +1 -1
- package/dist/server/modules/butler/patrol-execution-service.d.ts +0 -1
- package/dist/server/modules/butler/patrol-execution-service.js +6 -12
- package/dist/server/modules/butler/patrol-execution-service.js.map +1 -1
- package/dist/server/modules/sessions/session-controller.js +3 -3
- package/dist/server/modules/sessions/session-controller.js.map +1 -1
- package/dist/server/modules/sessions/session-history-service.d.ts +8 -3
- package/dist/server/modules/sessions/session-history-service.js +126 -11
- package/dist/server/modules/sessions/session-history-service.js.map +1 -1
- package/dist/server/modules/sessions/session-live-runtime-service.js +25 -15
- package/dist/server/modules/sessions/session-live-runtime-service.js.map +1 -1
- package/dist/server/modules/sessions/session-permission-request-service.js +28 -15
- package/dist/server/modules/sessions/session-permission-request-service.js.map +1 -1
- package/dist/server/modules/workbench/workbench-service.js +9 -9
- package/dist/server/modules/workbench/workbench-service.js.map +1 -1
- package/dist/server/modules/workspace/affairs-library-service.d.ts +3 -1
- package/dist/server/modules/workspace/affairs-library-service.js +112 -54
- package/dist/server/modules/workspace/affairs-library-service.js.map +1 -1
- package/dist/server/modules/workspace/affairs-tag-service.d.ts +12 -0
- package/dist/server/modules/workspace/affairs-tag-service.js +527 -2
- package/dist/server/modules/workspace/affairs-tag-service.js.map +1 -1
- package/dist/server/modules/workspace/workspace-controller.d.ts +1 -1
- package/dist/server/modules/workspace/workspace-controller.js +7 -7
- package/dist/server/modules/workspace/workspace-controller.js.map +1 -1
- package/dist/server/modules/workspace/workspace-service.d.ts +7 -0
- package/dist/server/modules/workspace/workspace-service.js +151 -10
- package/dist/server/modules/workspace/workspace-service.js.map +1 -1
- package/dist/server/routes/auth.js +6 -0
- package/dist/server/routes/auth.js.map +1 -1
- package/dist/server/server/create-server.d.ts +4 -0
- package/dist/server/server/create-server.js +26 -0
- package/dist/server/server/create-server.js.map +1 -1
- package/dist/server/server/start-host.js +20 -0
- package/dist/server/server/start-host.js.map +1 -1
- package/dist/server/shared/http/request-diagnostics.d.ts +56 -0
- package/dist/server/shared/http/request-diagnostics.js +256 -0
- package/dist/server/shared/http/request-diagnostics.js.map +1 -0
- package/dist/server/storage/repositories/auth-token-repository.d.ts +1 -0
- package/dist/server/storage/repositories/auth-token-repository.js +8 -0
- package/dist/server/storage/repositories/auth-token-repository.js.map +1 -1
- package/dist/server/storage/repositories/auth-user-repository.d.ts +50 -0
- package/dist/server/storage/repositories/auth-user-repository.js +198 -27
- package/dist/server/storage/repositories/auth-user-repository.js.map +1 -1
- package/dist/server/storage/repositories/butler-control-session-repository.d.ts +4 -1
- package/dist/server/storage/repositories/butler-control-session-repository.js +55 -8
- package/dist/server/storage/repositories/butler-control-session-repository.js.map +1 -1
- package/dist/server/storage/repositories/butler-profile-repository.d.ts +2 -1
- package/dist/server/storage/repositories/butler-profile-repository.js +35 -6
- package/dist/server/storage/repositories/butler-profile-repository.js.map +1 -1
- package/dist/server/storage/repositories/butler-project-repository.d.ts +2 -0
- package/dist/server/storage/repositories/butler-project-repository.js +38 -4
- package/dist/server/storage/repositories/butler-project-repository.js.map +1 -1
- package/dist/server/storage/repositories/butler-session-repository.d.ts +2 -1
- package/dist/server/storage/repositories/butler-session-repository.js +35 -6
- package/dist/server/storage/repositories/butler-session-repository.js.map +1 -1
- package/dist/server/storage/repositories/session-binding-repository.d.ts +3 -0
- package/dist/server/storage/repositories/session-binding-repository.js +70 -2
- package/dist/server/storage/repositories/session-binding-repository.js.map +1 -1
- package/dist/server/storage/repositories/session-index-repository.js +7 -5
- package/dist/server/storage/repositories/session-index-repository.js.map +1 -1
- package/dist/server/storage/repositories/workspace-repository.d.ts +3 -1
- package/dist/server/storage/repositories/workspace-repository.js +24 -10
- package/dist/server/storage/repositories/workspace-repository.js.map +1 -1
- package/dist/server/storage/sqlite/client.js +288 -0
- package/dist/server/storage/sqlite/client.js.map +1 -1
- package/dist/server/storage/sqlite/schema.sql +33 -9
- package/dist/server/types/domain.d.ts +8 -1
- package/node_modules/@codingns/session-sync-core/dist/providers/claude-session-store.js +34 -7
- package/node_modules/@codingns/session-sync-core/dist/providers/claude-session-store.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/runtime/claude-runtime.js +3 -7
- package/node_modules/@codingns/session-sync-core/dist/runtime/claude-runtime.js.map +1 -1
- package/package.json +1 -1
- package/dist/public/assets/SettingsPage-BI2Olcvr.js +0 -2
- package/dist/public/assets/WorkbenchLayout-CJHQtwuL.js +0 -1022
- package/dist/public/assets/WorkbenchShellRoute-2bKI6Q9k.js +0 -1
- package/dist/public/assets/WorkbenchShellRoute-BjuZD101.css +0 -1
- package/dist/public/assets/index-BARqMVSw.css +0 -1
- package/dist/public/assets/index-BUoNjVrY.js +0 -50
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/window-BVUB8gMK.js","assets/event-DvH9tcej.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Bi=Object.defineProperty;var Fi=(e,t,s)=>t in e?Bi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var xe=(e,t,s)=>Fi(e,typeof t!="symbol"?t+"":t,s);import{t as c,b as l,u as Wi,E as Ui,j as i,F as Mn,m as Ss,A as $i,G as Vi,_ as Sn}from"./index-
|
|
2
|
+
var Bi=Object.defineProperty;var Fi=(e,t,s)=>t in e?Bi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var xe=(e,t,s)=>Fi(e,typeof t!="symbol"?t+"":t,s);import{t as c,b as l,u as Wi,E as Ui,j as i,F as Mn,m as Ss,A as $i,G as Vi,_ as Sn}from"./index-_OCkVmfl.js";import{D as ps}from"./DesktopModal-bMdI1jEe.js";import{M as ms,c as bt,d as es,e as Xe,f as Dt,g as gs,r as ts,h as Gi,i as vs,j as Xi,k as In,l as zi,m as Yi,n as Ki,o as Qi,p as gr,P as Zi,w as Fs,b as wt,q as Ji,s as vr,t as eo,u as to,v as so,x as no,y as br,z as ro,A as yn,B as io}from"./workbench-navigation-RyUjchbD.js";import{c as oo,d as ao,b as ht,n as xn,e as lo,S as ss,P as Kt,f as Pn,s as co,h as uo,G as Is,i as kt,j as Rn,k as ho,l as wr,o as fo,p as Nt,D as po,q as Tn,t as Mr,v as sn,w as ut,x as Sr,y as Ir,z as mo,A as go,B as vo,C as bo,E as wo,H as Mo,I as So,J as Io,M as yo,K as xo,L as yr,N as Cn,O as xr,Q as Po,R as Ro,T as To,U as Co,V as ko,X as Eo,Y as be,Z as ns,_ as Ao,$ as Ws,a0 as kn,a1 as _o,a2 as jo,a3 as No,a4 as Oo,a5 as Pr,a6 as ze,a7 as ys,a8 as Rr,a9 as Tr,aa as Lo,ab as Cr,ac as Do,ad as kr,ae as nn,af as It,ag as qt,u as qo,ah as rn,ai as Ho,aj as Bo,r as Fo,ak as on,al as an,am as Us,an as Wo,ao as At,ap as Er,aq as ln,ar as cn,as as Uo,at as $o,au as Vo,av as Go,aw as Xo,ax as zo,ay as Ht,az as Ar,aA as _r,aB as jr,aC as Nr,aD as Or,aE as Bt,aF as Lr,aG as Dr,aH as Yo,aI as Ko,aJ as Qo,aK as Zo}from"./WorkbenchLayout-D-U7ghT0.js";import{f as at,u as lt,e as Ft,g as yt,h as un,c as Jo}from"./App-If9gThKM.js";import{M as ea}from"./MobileSheet-BXvQPkxt.js";import{FileContextPanel as qr}from"./FileContextPanel-C4syif3B.js";import{GitSidebar as Hr}from"./GitSidebar-DduL9aTV.js";import{W as ta}from"./WorkbenchModal-xbx1o6MO.js";import{TerminalManagerPanel as Br}from"./TerminalManagerPanel-4OR47vcf.js";import{TerminalPage as sa}from"./TerminalPage-Pvx396YX.js";import{f as Fr,a as bs,M as Wr}from"./MobileWorkspaceSwitcherHeader-DT330cAx.js";import{w as _t,r as xs,a as En,b as An}from"./styles-JKFlsYFv.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./relay-entry-B5GmiOrR.js";import"./terminal-runtime-meta-DBsyT35T.js";import"./TerminalRuntimeFallbackModal-KvG6k4AQ.js";import"./MobileTopHeaderFrame-vdYOyaaB.js";function dn({connectionState:e,onReconnect:t}){const{showToast:s,dismissToast:n}=at(),r=oo(),a=r?c(ao(r.kind)):null;return l.useEffect(()=>{if(e==="connected"||e==="closed"){n("conversation-connection-state");return}if(e==="reconnect_failed"){s({id:"conversation-connection-state",title:c("conversation.connectionReconnectFailed"),description:a?c("conversation.reconnectFailedExplainWithRoute",{route:a}):c("conversation.reconnectFailedExplain"),tone:"warning",durationMs:null,action:{label:c("conversation.reconnectButton"),onClick:t}});return}s({id:"conversation-connection-state",title:c("conversation.connectionReconnecting"),description:a?c("conversation.reconnectExplainWithRoute",{route:a}):c("conversation.reconnectExplain"),tone:"info",durationMs:3200})},[a,e,n,t,s]),null}const na=48;function ra(e){if(typeof document>"u")return!1;const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.focus(),t.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(t)}}async function ia(e,t){var s;if(!(t.isDesktop&&(await t.bridge.writeClipboardText(e)).ok)){if(typeof navigator<"u"&&((s=navigator.clipboard)!=null&&s.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!ra(e))throw new Error(c("conversation.copyContentFailed"))}}function _n(e,t,s){return Math.min(Math.max(e,t),s)}function Ps(e,t=ss){return e&&t.includes(e)?e:t[0]??"codex"}function oa(e){return ss.includes(e)}function aa(e,t){const s=e.flatMap(n=>oa(n)?[n]:[]);return s.length>0?s:t?[t]:[]}function $s(e){return e?e.nodeType===Node.ELEMENT_NODE?e:e.parentElement:null}function jn(e){var s,n;const t=$s(e);return((n=(s=t==null?void 0:t.closest("[data-message-id]"))==null?void 0:s.getAttribute("data-message-id"))==null?void 0:n.trim())||null}function la(e,t){return[t.trim()||c("conversation.selectionActionDefaultPrompt"),"",c("conversation.selectionActionQuotedLabel"),"```text",e.trim(),"```"].join(`
|
|
3
3
|
`)}function Rs(e){if(typeof window>"u")return null;const t=window.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return null;const s=t.getRangeAt(0),n=$s(s.startContainer),r=$s(s.endContainer);if(!n||!r||!e.contains(n)||!e.contains(r))return null;const a=t.toString().trim();if(!a)return null;const o=s.getBoundingClientRect();if(!o.width&&!o.height)return null;const u=jn(s.startContainer),d=jn(s.endContainer);return{text:a,sourceMessageId:u&&u===d?u:null,rect:{left:o.left,top:o.top,right:o.right,bottom:o.bottom,width:o.width,height:o.height}}}function ca({containerRef:e,session:t,currentCapabilities:s}){const n=lt(),r=Ft(),{showToast:a}=at(),{shellMode:o,requestNavigationRefresh:u,selectWorkspace:d,upsertNavigationSession:h}=ht(),f=Wi(g=>g.profile.providers),p=l.useMemo(()=>xn(t==null?void 0:t.providerConfigMode,t==null?void 0:t.providerPresetId),[t==null?void 0:t.providerConfigMode,t==null?void 0:t.providerPresetId]),[x,v]=l.useState(null),[w,M]=l.useState(null),[_,y]=l.useState(!1),{visibleProviders:O}=lo(ss,_),[C,j]=l.useState(""),[A,P]=l.useState(!1),[k,m]=l.useState(Ps(t==null?void 0:t.provider)),[b,L]=l.useState(Kt),[G,X]=l.useState(p.providerConfigMode),[Z,te]=l.useState(p.providerPresetId),[D,ge]=l.useState({}),[B,S]=l.useState(!1),[U,H]=l.useState(null),[K,oe]=l.useState({}),[ue,de]=l.useState(!1),[ve,E]=l.useState(!1),[V,z]=l.useState(!1),[$,ae]=l.useState(0),[F,re]=l.useState(null),[Te,Ne]=l.useState(()=>({width:typeof window>"u"?0:window.innerWidth,height:typeof window>"u"?0:window.innerHeight})),q=l.useRef(!1),W=l.useRef(!1),he=l.useRef(!1),Ce=l.useRef(null),me=l.useRef(null),Ee=o==="mobile"||r.isMobile,Be=l.useMemo(()=>g=>{var Y,Q;return(Ui(g)?(Q=(Y=f[g])==null?void 0:Y.defaultModel)==null?void 0:Q.trim():null)||Kt},[f]),J=l.useMemo(()=>xn(G,Z),[G,Z]),se=l.useMemo(()=>aa(O,k),[k,O]),we=l.useMemo(()=>Pn(k),[k]),Fe=l.useMemo(()=>we?D[we]??null:null,[D,we]),R=l.useMemo(()=>co(Fe),[Fe]),N=l.useMemo(()=>uo(Fe),[Fe]),Ie=J.providerConfigMode==="cc-switch-preset"?J.providerPresetId??Is:Is,Pe=l.useMemo(()=>N.find(g=>g.value===Ie)??N[0]??null,[N,Ie]),ne=l.useMemo(()=>k===(t==null?void 0:t.provider)&&J.providerConfigMode===p.providerConfigMode&&J.providerPresetId===p.providerPresetId&&s?s:U??kt(k),[s,U,k,J.providerConfigMode,J.providerPresetId,t==null?void 0:t.provider,p.providerConfigMode,p.providerPresetId]),fe=l.useMemo(()=>{var Y;const g=kt(k).modelOptions??[];return(Y=ne.modelOptions)!=null&&Y.length?ne.modelOptions:g},[ne.modelOptions,k]),le=l.useMemo(()=>fe.map(g=>({value:g.id,label:Rn(g)?c("conversation.modelUseCliDefault"):g.name})),[fe]),Oe=l.useMemo(()=>fe.find(g=>g.id===b)??fe[0]??null,[fe,b]),Me=l.useMemo(()=>{const g=Oe?Rn(Oe)?c("conversation.modelUseCliDefault"):Oe.name:c("conversation.modelUseCliDefault");return R?`${(Pe==null?void 0:Pe.label)??c("conversation.deploymentDefaultPreset")} · ${g}`:g},[Oe,Pe,R]),De=l.useCallback(g=>{if(m(g),L(Be(g)),t&&g===t.provider&&Pn(g)){X(p.providerConfigMode),te(p.providerPresetId);return}X("global-default"),te(null)},[Be,t,p.providerConfigMode,p.providerPresetId]),Re=l.useMemo(()=>{const g=K[k]??(k===(t==null?void 0:t.provider)&&J.providerConfigMode===p.providerConfigMode&&J.providerPresetId===p.providerPresetId?s:U);return!g||g.canStartSession!==!1?null:g.limitations[0]??c("conversation.capabilityDenied")},[s,U,K,k,J.providerConfigMode,J.providerPresetId,t==null?void 0:t.provider,p.providerConfigMode,p.providerPresetId]),et=l.useMemo(()=>{var _e;if(!x||typeof window>"u")return null;const g=(_e=e.current)==null?void 0:_e.getBoundingClientRect(),Y=g?Math.max(80,g.left+80):96,Q=g?Math.min(Te.width-80,g.right-80):Te.width-96,ye=g?Math.max(12,g.top+12):12,qe=g?Math.max(ye,g.bottom-48):Math.max(12,Te.height-48),We=x.rect.left+x.rect.width/2;return{left:_n(We,Y,Math.max(Y,Q)),top:_n(x.rect.top-48,ye,qe)}},[e,x,Te.height,Te.width]);l.useEffect(()=>{if(typeof window>"u")return;const g=()=>{Ne({width:window.innerWidth,height:window.innerHeight})};return g(),window.addEventListener("resize",g),()=>{window.removeEventListener("resize",g)}},[]),l.useEffect(()=>{if(!t){me.current!==null&&typeof window<"u"&&(window.clearTimeout(me.current),me.current=null),Ce.current=null,he.current=!1,v(null),M(null),y(!1);return}const g=Ps(t.provider);De(g)},[De,t]),l.useEffect(()=>{if(!_){S(!1);return}if(!we){S(!1);return}let g=!1;return S(!0),ho().then(Y=>{g||ge(Object.fromEntries(Y.items.map(Q=>[Q.app,Q])))}).catch(()=>{g||ge({})}).finally(()=>{g||S(!1)}),()=>{g=!0}},[_,we]),l.useEffect(()=>{!we||J.providerConfigMode!=="cc-switch-preset"||!J.providerPresetId||B||!Fe||Fe.options.some(g=>g.id===J.providerPresetId)||(X("global-default"),te(null))},[B,Fe,we,J.providerConfigMode,J.providerPresetId]),l.useEffect(()=>{if(!t||!e.current||typeof window>"u"){me.current!==null&&(window.clearTimeout(me.current),me.current=null),Ce.current=null,he.current=!1,v(null),M(null);return}const g=e.current,Y=je=>{q.current||(Ce.current=je,v(je),je||y(!1))},Q=()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},ye=(je,ct)=>{if(Ce.current=je,Q(),ct!=null&&ct.immediate){Y(je);return}me.current=window.setTimeout(()=>{me.current=null,Y(Ce.current)},na)},qe=()=>{const je=Rs(g);if(he.current){Ce.current=je;return}ye(je)},We=()=>{const je=Rs(g);if(he.current){Ce.current=je;return}ye(je,{immediate:!0})},_e=je=>{!(je.target instanceof Node)||!g.contains(je.target)||(he.current=!0,Q())},Le=()=>{he.current&&(he.current=!1,ye(Rs(g)))};return document.addEventListener("pointerdown",_e),document.addEventListener("selectionchange",qe),window.addEventListener("pointerup",Le),window.addEventListener("pointercancel",Le),window.addEventListener("mouseup",Le),window.addEventListener("touchend",Le),window.addEventListener("resize",We),window.addEventListener("scroll",We,!0),()=>{Q(),document.removeEventListener("pointerdown",_e),document.removeEventListener("selectionchange",qe),window.removeEventListener("pointerup",Le),window.removeEventListener("pointercancel",Le),window.removeEventListener("mouseup",Le),window.removeEventListener("touchend",Le),window.removeEventListener("resize",We),window.removeEventListener("scroll",We,!0)}},[e,t]),l.useEffect(()=>{(!_||!(w!=null&&w.sourceMessageId))&&P(!1)},[_,w==null?void 0:w.sourceMessageId]),l.useEffect(()=>{if(!_||!t)return;let g=!1;return k===t.provider&&J.providerConfigMode===p.providerConfigMode&&J.providerPresetId===p.providerPresetId&&s?(de(!1),H(s),()=>{g=!0}):(de(!0),H(kt(k)),wr(k,t.workspaceId,we?{providerConfigMode:J.providerConfigMode,providerPresetId:J.providerPresetId}:void 0).then(Y=>{g||H(Y)}).catch(()=>{g||H(kt(k))}).finally(()=>{g||de(!1)}),()=>{g=!0})},[_,s,we,k,J.providerConfigMode,J.providerPresetId,t,p.providerConfigMode,p.providerPresetId]),l.useEffect(()=>{if(!_||!t){oe({});return}let g=!1;return fo(se,t.workspaceId).then(Y=>{g||oe(Y)}),()=>{g=!0}},[_,t,se]),l.useEffect(()=>{if(!_||!t)return;const g=se.filter(Q=>{const ye=K[Q];return!ye||ye.canStartSession!==!1});if(g.length===0||g.includes(k))return;const Y=g[0];De(Y)},[_,De,K,k,t,se]),l.useEffect(()=>{var Y;const g=Be(k);if(!fe.some(Q=>Q.id===b)){if(fe.some(Q=>Q.id===g)){L(g);return}L(((Y=fe[0])==null?void 0:Y.id)??Kt)}},[fe,Be,b,k]),l.useEffect(()=>{if(!_){q.current=!1;return}q.current=!0},[_]),l.useEffect(()=>{if(typeof window>"u")return;const g=Y=>{Y.key==="Escape"&&(y(!1),M(null),v(null),q.current=!1)};return window.addEventListener("keydown",g),()=>{window.removeEventListener("keydown",g)}},[]);async function it(){var Y,Q;if(!x)return;const g=x.text;v(null),typeof window<"u"&&((Q=(Y=window.getSelection())==null?void 0:Y.removeAllRanges)==null||Q.call(Y));try{await ia(g,r),a({title:c("conversation.copyContentSuccess"),tone:"success"})}catch(ye){a({title:ye instanceof Error?ye.message:c("conversation.copyContentFailed"),tone:"error"})}}function ft(){x&&(re({title:"",content:x.text}),ae(g=>g+1),z(!0),y(!1),M(null),v(null),q.current=!1)}function pt(){var Q,ye;if(!x||!t)return;const g=x,Y=Ps(t.provider,se.length>0?se:ss);De(Y),j(""),P(!1),M(g),v(null),y(!0),typeof window<"u"&&((ye=(Q=window.getSelection())==null?void 0:Q.removeAllRanges)==null||ye.call(Q))}function Ze(g){g.preventDefault(),q.current=!0}function tt(){W.current=!0,pt()}function mt(){if(W.current){W.current=!1;return}pt()}async function Ae(){var g,Y,Q,ye;if(!(!w||!t)){if(Re){a({title:Re,tone:"error"});return}E(!0);try{const qe=la(w.text,C),We=(Oe==null?void 0:Oe.id)===Kt?null:(Oe==null?void 0:Oe.id)??null;let _e=null;if(A&&w.sourceMessageId)_e=await Mr(t.sessionId,{sourceType:"message",sourceMessageId:w.sourceMessageId,strategy:"auto",targetProvider:k,providerConfigMode:J.providerConfigMode,providerPresetId:J.providerPresetId,sessionKind:"annotation",annotationSourceMessageId:w.sourceMessageId,annotationSourceText:w.text}),h(_e),await sn(_e.sessionId,{content:qe,clientRequestId:((Y=(g=globalThis.crypto)==null?void 0:g.randomUUID)==null?void 0:Y.call(g))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:We,permissionMode:ut(),providerConfigMode:J.providerConfigMode,providerPresetId:J.providerPresetId});else{const Le=await Sr({workspaceId:t.workspaceId,provider:k,content:qe,clientRequestId:((ye=(Q=globalThis.crypto)==null?void 0:Q.randomUUID)==null?void 0:ye.call(Q))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:We,permissionMode:ut(),providerConfigMode:J.providerConfigMode,providerPresetId:J.providerPresetId,parentSessionId:t.sessionId,sessionKind:"annotation",annotationSourceMessageId:w.sourceMessageId??null,annotationSourceText:w.text});_e=Le.session??await Ir(Le.sessionId)}h(_e),u(),d(_e.workspaceId),n(Xe(_e.workspaceId,_e.sessionId)),y(!1),M(null),v(null),q.current=!1}catch(qe){a({title:qe instanceof Error?qe.message:c("conversation.selectionActionFailed"),tone:"error"})}finally{E(!1)}}}function st(g=!1){y(!1),M(null),q.current=!1,g&&v(null)}const ot=!!(!_&&x&&et),Ve=!!(_&&w),ke=i.jsxs(ms,{children:[i.jsx("button",{type:"button",className:"secondary-button",onClick:()=>st(!1),children:c("common.cancel")}),i.jsx("button",{type:"button",className:"primary-button",disabled:ve||!!Re||se.length===0,onClick:()=>void Ae(),children:ve?c("conversation.sendingState"):c("conversation.selectionActionSubmit")})]}),ce=w?i.jsxs(i.Fragment,{children:[i.jsx(bt,{className:"conversation-selection-preview-section",heading:c("conversation.selectionActionPreviewLabel"),children:i.jsx("div",{className:"conversation-selection-action-dialog-quote",children:w.text})}),i.jsxs(bt,{className:"conversation-selection-request-section",children:[i.jsx(es,{className:"conversation-selection-field conversation-selection-prompt-field",label:c("conversation.selectionActionPromptLabel"),children:i.jsx("textarea",{value:C,rows:4,placeholder:c("conversation.selectionActionPromptPlaceholder"),onChange:g=>j(g.target.value)})}),i.jsxs("div",{className:"conversation-selection-context-block",children:[i.jsxs("label",{className:"conversation-selection-checkbox",children:[i.jsx("input",{type:"checkbox",checked:A,disabled:!w.sourceMessageId,onChange:g=>P(g.target.checked)}),i.jsx("span",{children:c("conversation.selectionActionIncludeContext")})]}),w.sourceMessageId?null:i.jsx("p",{className:"conversation-selection-hint",children:c("conversation.selectionActionContextUnavailable")}),Re?i.jsx("p",{className:"conversation-selection-hint",children:Re}):null]})]}),i.jsx(bt,{className:"conversation-selection-target-section",heading:c("conversation.selectionActionTargetLabel"),children:i.jsxs("div",{className:"conversation-selection-grid",children:[i.jsx(es,{className:"conversation-selection-field",label:c("conversation.forkTargetProviderLabel"),children:i.jsx("select",{value:k,onChange:g=>{De(g.target.value)},children:se.map(g=>{var Y;return i.jsx("option",{value:g,disabled:((Y=K[g])==null?void 0:Y.canStartSession)===!1,children:Nt(g,"full")},g)})})}),i.jsx(es,{className:"conversation-selection-field",label:c("conversation.forkTargetModelLabel"),children:we?i.jsx("div",{className:"conversation-selection-deployment-select",children:i.jsx(po,{ariaLabel:c("conversation.forkTargetModelLabel"),triggerLabel:Me,presetOptions:N,selectedPresetValue:Ie,selectedPresetSummary:(Pe==null?void 0:Pe.summary)??null,onSelectPreset:g=>{if(g===Is){X("global-default"),te(null);return}X("cc-switch-preset"),te(g)},modelOptions:le,selectedModelValue:b,onSelectModel:L,loadingPresets:B,loadingModels:ue,modelColumnDisabled:ue||!!Re,showPresetColumn:R,modelEmptyText:c("conversation.deploymentModelEmpty")})}):i.jsx("select",{value:b,disabled:ue||!!Re,onChange:g=>L(g.target.value),children:fe.map(g=>i.jsx("option",{value:g.id,children:g.name},g.id))})})]})})]}):null;return!t||!ot&&!Ve||typeof document>"u"?i.jsx(Tn,{open:V,preferredWorkspaceId:(t==null?void 0:t.workspaceId)??null,preferredSessionId:(t==null?void 0:t.sessionId)??null,creationRequestId:$,initialDraft:F,onClose:()=>z(!1)}):i.jsxs(i.Fragment,{children:[yt.createPortal(ot?i.jsxs("div",{className:"conversation-selection-toolbar",style:et??void 0,onMouseDown:g=>g.preventDefault(),children:[i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:()=>void it(),children:c("conversation.copyAction")}),i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:ft,children:c("conversation.selectionTodoAction")}),i.jsx("button",{type:"button",className:"conversation-selection-action is-primary",onPointerDown:Ze,onMouseDown:Ze,onPointerUp:tt,onClick:mt,children:c("conversation.selectionActionButton")})]}):null,document.body),Ee?i.jsx(ea,{open:Ve,title:c("conversation.selectionActionButton"),height:"auto",kind:"form",showHandle:!0,showCancelButton:!1,cardClassName:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:ke,onClose:()=>st(!1),children:ce}):i.jsx(ps,{open:Ve,title:c("conversation.selectionActionButton"),size:"compact",layout:"form",className:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:ke,onClose:()=>st(!1),children:ce}),i.jsx(Tn,{open:V,preferredWorkspaceId:t.workspaceId,preferredSessionId:t.sessionId,creationRequestId:$,initialDraft:F,onClose:()=>z(!1)})]})}const Ct=5,Ur=["codex","claude-code"];function $r(){return[{id:"recommended",label:c("conversation.butlerCompletionTemplateRecommendedLabel"),description:c("conversation.butlerCompletionTemplateRecommendedDescription"),value:c("conversation.butlerCompletionTemplateRecommendedValue")},{id:"spec-finish",label:c("conversation.butlerCompletionTemplateSpecLabel"),description:c("conversation.butlerCompletionTemplateSpecDescription"),value:c("conversation.butlerCompletionTemplateSpecValue")},{id:"bugfix",label:c("conversation.butlerCompletionTemplateBugfixLabel"),description:c("conversation.butlerCompletionTemplateBugfixDescription"),value:c("conversation.butlerCompletionTemplateBugfixValue")}]}function Ts(){var e;return((e=$r()[0])==null?void 0:e.value)??""}function Cs(e,t=Ur){return e==="claude-code"&&t.includes("claude-code")?"claude-code":t.includes("codex")?"codex":t[0]??null}function Vr(e){return e==="codex"||e==="claude-code"}function ua(e){return e.flatMap(t=>!t.enabled||!Vr(t.provider)?[]:[t.provider])}function Gr({session:e,showTrigger:t=!0,openRequestKey:s=0}){const{showToast:n}=at(),{requestNavigationRefresh:r}=ht(),a=l.useId(),o=l.useId(),u=l.useId(),d=l.useId(),[h,f]=l.useState(!1),[p,x]=l.useState(!1),[v,w]=l.useState(null),[M,_]=l.useState(null),[y,O]=l.useState(null),[C,j]=l.useState(Cs(e==null?void 0:e.provider)),[A,P]=l.useState(""),[k,m]=l.useState(()=>Ts()),[b,L]=l.useState(Ct),[G,X]=l.useState(!1),[Z,te]=l.useState(0),{items:D}=mo(!!(e!=null&&e.sessionId)),ge=$r(),B=l.useMemo(()=>D?ua(D):Ur,[D]),S=D!==null&&B.length===0,U=l.useMemo(()=>{var F;return((F=e==null?void 0:e.title)==null?void 0:F.trim())||null},[e==null?void 0:e.title]),H=l.useMemo(()=>v?{workspaceId:v.workspaceId,project:v.project,session:v.session}:null,[v]),K=(v==null?void 0:v.latestFollowUpTask)??null,oe=(v==null?void 0:v.latestVerificationRun)??null,ue=K&&(K.status==="active"||K.status==="waiting_user")?K:null,de=oe&&(oe.status==="queued"||oe.status==="running")?oe:null;l.useEffect(()=>{f(!1),X(!1),_(null),w(null),P(""),j(Cs(e==null?void 0:e.provider)),m(Ts()),L(Ct)},[e==null?void 0:e.sessionId]),l.useEffect(()=>{const F=Cs(e==null?void 0:e.provider,B);(!C||!B.includes(C))&&j(F)},[B,C,e==null?void 0:e.provider]),l.useEffect(()=>{if(!(e!=null&&e.sessionId)){x(!1);return}let F=!1;return x(!0),_(null),go(e.sessionId).then(re=>{F||w(re.context)}).catch(re=>{F||(w(null),_(re instanceof Error?re.message:c("conversation.butlerActionLoadFailed")))}).finally(()=>{F||x(!1)}),()=>{F=!0}},[Z,e==null?void 0:e.sessionId]);function ve(){p||te(F=>F+1)}function E(){!v&&!p&&ve()}if(l.useEffect(()=>{t||s<=0||(f(!0),E())},[p,s,t,v]),!(e!=null&&e.sessionId))return null;async function V(){if(!H){E();return}if(!C)return;const F=A.trim(),re=k.trim();if(!F){n({title:c("conversation.butlerFollowUpObjectiveRequired"),tone:"warning"});return}if(!re){n({title:c("conversation.butlerFollowUpCompletionCriteriaRequired"),tone:"warning"});return}O("follow-up");try{const Te=await Io({projectId:H.project.id,butlerSessionId:H.session.id,providerId:C,objective:F,completionCriteria:re,maxAutoContinueCount:b});w(Ne=>Ne&&{...Ne,latestFollowUpTask:Te.task}),r(),n({title:c("conversation.butlerFollowUpStarted"),description:c("conversation.butlerFollowUpStartedDescription",{projectName:H.project.name}),tone:"success"}),P(""),m(Ts()),L(Ct),f(!1)}catch(Te){n({title:c("conversation.butlerFollowUpFailed"),description:Te instanceof Error?Te.message:void 0,tone:"error"})}finally{O(null)}}async function z(){if(K){O("follow-up");try{const F=await wo(K.id);w(re=>re&&{...re,latestFollowUpTask:F.task}),r(),n({title:c("conversation.butlerFollowUpStopped"),description:c("conversation.butlerFollowUpStoppedDescription"),tone:"success"}),f(!1)}catch(F){n({title:c("conversation.butlerFollowUpStopFailed"),description:F instanceof Error?F.message:void 0,tone:"error"})}finally{O(null)}}}async function $(){if(!H){E();return}O("verification");try{const F=await So({projectId:H.project.id,butlerSessionId:H.session.id,verificationType:"browser",targetRef:U||H.session.title||H.project.name});w(re=>re&&{...re,latestVerificationRun:F.result.run}),r(),n({title:c("conversation.butlerVerificationStarted"),description:c("conversation.butlerVerificationStartedDescription",{projectName:H.project.name}),tone:"success"}),f(!1)}catch(F){n({title:c("conversation.butlerVerificationFailed"),description:F instanceof Error?F.message:void 0,tone:"error"})}finally{O(null)}}async function ae(){if(oe){O("verification");try{const F=await Mo(oe.projectId,oe.id);w(re=>re&&{...re,latestVerificationRun:F.run}),r(),n({title:c("conversation.butlerVerificationStopped"),description:c("conversation.butlerVerificationStoppedDescription"),tone:"success"}),f(!1)}catch(F){n({title:c("conversation.butlerVerificationStopFailed"),description:F instanceof Error?F.message:void 0,tone:"error"})}finally{O(null)}}}return i.jsxs(i.Fragment,{children:[t?i.jsxs("div",{className:"conversation-butler-entry",onMouseEnter:()=>{X(!0),E()},onMouseLeave:()=>{X(!1)},children:[i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("conversation.butlerActionButton"),title:c("conversation.butlerActionButton"),onFocus:()=>{X(!0),E()},onBlur:()=>{X(!1)},onClick:()=>{f(!0),E()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(vo,{})})}),G?i.jsxs("div",{className:"conversation-butler-analysis-popover",role:"status","aria-live":"polite",children:[i.jsx("strong",{children:c("conversation.butlerAnalysisTitle")}),p?i.jsx("p",{children:c("conversation.butlerActionLoading")}):M?i.jsx("p",{children:M}):K?i.jsxs(i.Fragment,{children:[i.jsxs("p",{children:[c("conversation.butlerAnalysisObjectiveLabel"),":",K.objective]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisStatusLabel"),":",Nn(K.status)]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisSummaryLabel"),":",K.lastAutomationSummary||K.waitingReason||c("conversation.butlerAnalysisEmpty")]}),K.waitingReason?i.jsxs("p",{children:[c("conversation.butlerAnalysisWaitingReasonLabel"),":",K.waitingReason]}):null]}):i.jsx("p",{children:c("conversation.butlerAnalysisEmpty")})]}):null]}):null,i.jsx(ta,{open:h,title:c("conversation.butlerActionModalTitle"),description:c("conversation.butlerActionModalDescription"),className:"conversation-butler-modal-card",footer:!p&&!M&&H?i.jsxs(ms,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:y!==null,onClick:()=>{$()},children:c("conversation.butlerVerificationAction")}),i.jsx("button",{type:"button",className:"primary-button",disabled:y!==null||S||!C,onClick:()=>{V()},children:c("conversation.butlerFollowUpAction")})]}):void 0,onClose:()=>{y||f(!1)},children:i.jsxs("div",{className:"conversation-butler-modal",children:[p?i.jsx("p",{className:"conversation-butler-modal-hint",children:c("conversation.butlerActionLoading")}):null,!p&&M?i.jsx("p",{className:"conversation-butler-modal-error",children:M}):null,!p&&!M&&H?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"conversation-butler-target-grid",children:[i.jsxs("div",{className:"conversation-butler-target-card",children:[i.jsx("span",{children:c("conversation.butlerActionProjectLabel")}),i.jsx("strong",{children:H.project.name})]}),i.jsxs("div",{className:"conversation-butler-target-card",children:[i.jsx("span",{children:c("conversation.butlerActionSessionLabel")}),i.jsx("strong",{children:H.session.title||U||H.session.sessionId})]})]}),i.jsxs("div",{className:"conversation-butler-follow-up-grid",children:[i.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[i.jsxs("div",{className:"conversation-butler-field-heading",children:[i.jsx("label",{children:c("conversation.butlerFollowUpProviderLabel")}),i.jsx("small",{children:c("conversation.butlerFollowUpProviderHint")})]}),S?i.jsx("p",{className:"conversation-butler-modal-hint",children:c("conversation.butlerFollowUpProviderHint")}):i.jsx(bo,{workspaceId:H.workspaceId,providers:B,selectedProvider:C,disabled:y!==null,onSelect:F=>{Vr(F)&&j(F)}})]}),i.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field conversation-butler-round-limit-field",children:[i.jsxs("div",{className:"conversation-butler-field-heading",children:[i.jsx("label",{htmlFor:d,children:c("conversation.butlerFollowUpRoundLimitLabel")}),i.jsx("small",{children:c("conversation.butlerFollowUpRoundLimitHint")})]}),i.jsx("input",{id:d,type:"number",min:1,max:20,value:b,disabled:y!==null,onChange:F=>{const re=Number.parseInt(F.target.value,10);L(Number.isFinite(re)?re:Ct)}})]})]}),i.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[i.jsx("label",{htmlFor:a,children:c("conversation.butlerFollowUpObjectiveLabel")}),i.jsx("textarea",{id:a,rows:3,value:A,placeholder:c("conversation.butlerFollowUpObjectivePlaceholder"),disabled:y!==null,onChange:F=>{P(F.target.value)}})]}),i.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[i.jsxs("div",{className:"conversation-butler-field-heading",children:[i.jsx("label",{htmlFor:o,children:c("conversation.butlerFollowUpCompletionCriteriaLabel")}),i.jsx("small",{id:u,children:c("conversation.butlerCompletionTemplateSectionHint")})]}),i.jsx("textarea",{id:o,rows:3,value:k,placeholder:c("conversation.butlerFollowUpCompletionCriteriaPlaceholder"),"aria-describedby":u,disabled:y!==null,onChange:F=>{m(F.target.value)}}),i.jsx("div",{className:"conversation-butler-preset-grid",role:"group","aria-label":c("conversation.butlerCompletionTemplateSectionLabel"),children:ge.map(F=>i.jsxs("button",{type:"button",className:"conversation-butler-preset-card","data-selected":k.trim()===F.value,"aria-pressed":k.trim()===F.value,disabled:y!==null,onClick:()=>{m(F.value)},children:[i.jsx("strong",{children:F.label}),i.jsx("span",{children:F.description})]},F.id))})]}),ue||de?i.jsxs("div",{className:"conversation-butler-meta-grid",children:[ue?i.jsxs("div",{className:"conversation-butler-target-card conversation-butler-current-task-card",children:[i.jsx("span",{children:c("conversation.butlerCurrentFollowUpLabel")}),i.jsx("strong",{children:Nn(ue.status)}),i.jsx("small",{children:c("conversation.butlerCurrentFollowUpProgress",{current:ue.autoContinueCount,max:ue.maxAutoContinueCount??Ct})}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:y!==null,onClick:()=>{z()},children:c("conversation.butlerStopFollowUpAction")})]}):null,de?i.jsxs("div",{className:"conversation-butler-target-card conversation-butler-current-task-card",children:[i.jsx("span",{children:c("conversation.butlerCurrentVerificationLabel")}),i.jsx("strong",{children:da(de.status)}),i.jsx("small",{children:de.targetRef||de.verificationType}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:y!==null,onClick:()=>{ae()},children:c("conversation.butlerStopVerificationAction")})]}):null]}):null]}):null]})})]})}function Nn(e){switch(e){case"waiting_user":return c("shell.butlerAutomationStatusWaitingUser");case"completed":return c("shell.butlerAutomationStatusCompleted");case"failed":return c("shell.butlerAutomationStatusFailed");case"cancelled":return c("shell.butlerAutomationStatusCancelled");case"active":default:return c("shell.butlerAutomationStatusActive")}}function da(e){switch(e){case"queued":case"running":return c("shell.butlerAutomationStatusActive");case"passed":case"skipped":return c("shell.butlerAutomationStatusCompleted");case"failed":return c("shell.butlerAutomationStatusFailed");case"cancelled":default:return c("shell.butlerAutomationStatusCancelled")}}const ha=340;function fa({session:e,onOpenBranchTree:t}){const s=lt(),n=un(),r=l.useRef(null),a=l.useRef(null),[o,u]=l.useState(!1),[d,h]=l.useState(null),[f,p]=l.useState(null),[x,v]=l.useState(0);l.useEffect(()=>{u(!1),h(null)},[n.pathname,n.search]),l.useLayoutEffect(()=>{if(!o||!d||typeof window>"u"){p(null);return}const P=()=>{var L,G;const b=xo(d,{width:((L=a.current)==null?void 0:L.offsetWidth)??0,height:((G=a.current)==null?void 0:G.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:ha});p({position:"fixed",left:`${Math.round(b.left)}px`,top:`${Math.round(b.top)}px`,width:`${Math.round(b.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(b.maxHeight)}px`,transformOrigin:b.transformOrigin})},k=b=>{var G,X;const L=b.target;L&&!((G=a.current)!=null&&G.contains(L))&&!((X=r.current)!=null&&X.contains(L))&&M()},m=b=>{b.key==="Escape"&&M()};return P(),window.addEventListener("pointerdown",k),window.addEventListener("keydown",m),window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("pointerdown",k),window.removeEventListener("keydown",m),window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[d,o]);function w(){var k;const P=(k=r.current)==null?void 0:k.getBoundingClientRect();P&&(h({x:P.right,y:P.bottom}),u(!0))}function M(){u(!1),h(null)}function _(P){s(P),M()}function y(P){const k=new URLSearchParams(n.search);k.set("toolPanel",P),_(`${n.pathname}?${k.toString()}`)}function O(){if(o){M();return}w()}function C(P){P.key!=="ContextMenu"&&!(P.shiftKey&&P.key==="F10")||(P.preventDefault(),P.stopPropagation(),w())}if(!e)return null;const j=[{key:"assistant",label:c("shell.butlerEntry"),onSelect:()=>{v(P=>P+1),M()}},...t?[{key:"branch",label:c("conversation.branchAction"),onSelect:()=>{t(),M()}}]:[],{key:"files",label:c("shell.filesEntry"),onSelect:()=>{y("files")}},{key:"git",label:c("shell.gitEntry"),onSelect:()=>{y("git")}},{key:"processes",label:c("shell.mobileConversationToolProcessesTab"),onSelect:()=>{y("processes")}}],A=o&&typeof document<"u"?yt.createPortal(i.jsx("div",{ref:a,className:"session-action-menu mobile-conversation-action-menu surface-card",role:"menu","aria-label":c("conversation.moreSessionActions"),style:f??{position:"fixed",top:0,left:0,visibility:"hidden"},onClick:P=>P.stopPropagation(),children:j.map(P=>i.jsx("button",{type:"button",className:"session-action-menu-item mobile-conversation-action-menu-item",role:"menuitem",onClick:P.onSelect,children:P.label},P.key))}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mobile-conversation-session-actions",children:[i.jsx("button",{ref:r,type:"button",className:"conversation-header-ai-button mobile-conversation-more-button","aria-label":c("conversation.moreSessionActions"),title:c("conversation.moreSessionActions"),"aria-haspopup":"menu","aria-expanded":o,onClick:O,onKeyDown:C,children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(yo,{})})}),i.jsx(Gr,{session:e,showTrigger:!1,openRequestKey:x})]}),A]})}function Xr({items:e,deletingQueueItemId:t=null,steeringQueueItemId:s=null,canSteer:n=!1,onDelete:r,onSteer:a}){return e.length===0?null:i.jsxs("section",{className:"queued-message-list","aria-label":c("conversation.queueTitle"),children:[i.jsx("div",{className:"queued-message-list__header",children:i.jsx("h2",{children:`${c("conversation.queueTitle")} · ${e.length}`})}),i.jsx("div",{className:"queued-message-list__items",children:e.map((o,u)=>{const d=o.status==="queued"||o.status==="failed",h=n&&typeof a=="function"&&(o.status==="queued"||o.status==="failed");return i.jsxs("article",{className:"queued-message-item",children:[i.jsxs("div",{className:"queued-message-item__main",children:[i.jsx("span",{className:"queued-message-item__order","aria-hidden":"true",children:u+1}),i.jsx("p",{className:"queued-message-item__content",title:o.content||c("conversation.queueImageOnly"),children:o.content||c("conversation.queueImageOnly")}),i.jsx("span",{className:`queued-message-item__status queued-message-item__status--${o.status}`,children:o.status==="failed"?c("conversation.queueStatusFailed"):c("conversation.queueStatusQueued")}),i.jsxs("div",{className:"queued-message-item__actions",children:[h?i.jsx("button",{type:"button",className:"queued-message-item__action queued-message-item__action--steer",onClick:()=>void a(o.id),disabled:s===o.id,"aria-label":c("conversation.queueSteer"),title:c("conversation.queueSteer"),children:s===o.id?c("conversation.queueSteering"):c("conversation.queueSteer")}):null,d?i.jsx("button",{type:"button",className:"queued-message-item__action queued-message-item__action--delete",onClick:()=>void r(o.id),disabled:t===o.id,"aria-label":c("conversation.queueDelete"),title:c("conversation.queueDelete"),children:t===o.id?"…":"×"}):null]})]}),o.errorDetail?i.jsx("p",{className:"queued-message-item__error",children:o.errorDetail}):null]},o.id)})})]})}function pa(e){const{sending:t,setSending:s,session:n,runtimeHasActiveRun:r,runtimeCanInterrupt:a}=e,o=l.useRef(!1);l.useEffect(()=>{if(!t){o.current=!1;return}if(ma(n,r,a)){o.current=!0;return}o.current&&(o.current=!1,s(!1))},[a,r,t,n,s])}function ma(e,t,s){return t===!0||s===!0||(e==null?void 0:e.runningState)==="stale"||(e==null?void 0:e.runningState)==="unknown"?!0:yr(e)}const ga=30,ks=80,Et=60,zr=600,On=300*1e3,va=600,ba=5e3,wa=1e4,Vs=120*1e3,Yr=8,Ma=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/g;class Sa{constructor(t,s={}){xe(this,"state");xe(this,"authoritativeMessages",[]);xe(this,"runtimeOverlayMessages",[]);xe(this,"activeRuntimeOverlayKeys",[]);xe(this,"pendingMessages",[]);xe(this,"listeners",new Set);xe(this,"realtimeClient",null);xe(this,"historyBootstrapFallbackTimer",null);xe(this,"historyBootstrapEnvelopeReceived",!1);xe(this,"markSeenTimer",null);xe(this,"markSeenInFlight",!1);xe(this,"lastMarkSeenRequestAt",0);xe(this,"seenWatermark",null);xe(this,"runtimeRefreshTimer",null);xe(this,"runtimeRefreshMode",null);xe(this,"replaceSnapshotSeedOnBackfill",!1);xe(this,"olderHistoryPrefetchCursor",null);xe(this,"olderHistoryPrefetchPromise",null);xe(this,"prefetchedOlderHistoryPage",null);xe(this,"pendingReplyDebugTraces",[]);xe(this,"hasAuthoritativeBootstrapMessages");xe(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));xe(this,"getState",()=>this.state);var o;this.sessionId=t,this.options=s;const n=Mn(qs(t),On);this.hasAuthoritativeBootstrapMessages=(((o=s.bootstrapMessages)==null?void 0:o.length)??0)>0;const r=Qt(s.initialSession??null,(n==null?void 0:n.session)??null),a=Bn(Ia(),this.sessionId,{type:"timeline.seed",source:"constructor_seed",snapshotMessages:(n==null?void 0:n.messages)??[],bootstrapMessages:s.bootstrapMessages??[],replaceSnapshotSeedOnBackfill:!this.hasAuthoritativeBootstrapMessages&&((n==null?void 0:n.messages.length)??0)>0&&((n==null?void 0:n.messages.length)??0)<Et&&((n==null?void 0:n.pagesLoaded)??0)<=1});this.authoritativeMessages=a.timeline.authoritativeMessages,this.runtimeOverlayMessages=a.timeline.runtimeOverlayMessages,this.activeRuntimeOverlayKeys=a.timeline.activeRuntimeOverlayKeys,this.pendingMessages=a.timeline.pendingMessages,this.replaceSnapshotSeedOnBackfill=a.timeline.replaceSnapshotSeedOnBackfill,this.state=Cn({session:r,capabilities:(n==null?void 0:n.capabilities)??null,runtimeHasActiveRun:(n==null?void 0:n.runtimeHasActiveRun)??null,runtimeCanInterrupt:(n==null?void 0:n.runtimeCanInterrupt)??null,contextUsage:(n==null?void 0:n.contextUsage)??null,messages:a.messages,timelineItems:_s(r,a.messages),permissionRequests:(n==null?void 0:n.permissionRequests)??[],queuedMessages:(n==null?void 0:n.queuedMessages)??[],olderCursor:(n==null?void 0:n.olderCursor)??null,hasOlderMessages:(n==null?void 0:n.hasOlderMessages)??!1,lastCursor:(n==null?void 0:n.lastCursor)??null,interruptSource:(n==null?void 0:n.interruptSource)??null,pagesLoaded:(n==null?void 0:n.pagesLoaded)??0}),this.seenWatermark=(r==null?void 0:r.lastSeenAt)??null}async initialize(){this.historyBootstrapEnvelopeReceived=!1,this.clearHistoryBootstrapFallbackTimer(),this.clearOlderHistoryPrefetch();const t=this.options.bootstrapMessages??[],s=this.applyTimelineEvent({type:"history.merge",source:"initialize_bootstrap",messages:t,replaceSnapshotSeed:!1}),n=this.hasAuthoritativeBootstrapMessages;this.patch({messages:s.messages,historyState:Za(this.state.session,n?this.authoritativeMessages.length:0),loadingOlderMessages:!1,olderCursor:n?null:this.state.olderCursor,hasOlderMessages:vt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:n?null:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),pagesLoaded:n?Math.max(this.state.pagesLoaded,1):this.state.pagesLoaded,errorCode:null,errorDetail:null}),this.shouldRefreshSessionDetail()&&this.refreshSessionMetadata(),this.shouldRefreshRuntimeSnapshot()&&this.refreshRuntimeSnapshot("bootstrap"),this.refreshPermissionRequests(),this.refreshQueue();try{this.startRealtime(),n&&this.scheduleMarkSeen()}catch(r){this.handleError(r)}}async reload(){var n,r;this.clearHistoryBootstrapFallbackTimer(),this.historyBootstrapEnvelopeReceived=!1,this.clearOlderHistoryPrefetch(),(n=this.realtimeClient)==null||n.close(),this.realtimeClient=null;const t=Mn(qs(this.sessionId),On),s=this.applyTimelineEvent({type:"timeline.seed",source:"reload_seed",snapshotMessages:(t==null?void 0:t.messages)??[],bootstrapMessages:this.options.bootstrapMessages??[],replaceSnapshotSeedOnBackfill:!this.hasAuthoritativeBootstrapMessages&&((t==null?void 0:t.messages.length)??0)>0&&((t==null?void 0:t.messages.length)??0)<Et&&((t==null?void 0:t.pagesLoaded)??0)<=1});this.state=Cn({session:Qt(this.options.initialSession??null,(t==null?void 0:t.session)??null),capabilities:(t==null?void 0:t.capabilities)??null,runtimeHasActiveRun:(t==null?void 0:t.runtimeHasActiveRun)??null,runtimeCanInterrupt:(t==null?void 0:t.runtimeCanInterrupt)??null,contextUsage:(t==null?void 0:t.contextUsage)??null,messages:s.messages,permissionRequests:(t==null?void 0:t.permissionRequests)??[],queuedMessages:(t==null?void 0:t.queuedMessages)??[],olderCursor:(t==null?void 0:t.olderCursor)??null,hasOlderMessages:(t==null?void 0:t.hasOlderMessages)??!1,lastCursor:(t==null?void 0:t.lastCursor)??null,pagesLoaded:(t==null?void 0:t.pagesLoaded)??0}),this.seenWatermark=((r=this.state.session)==null?void 0:r.lastSeenAt)??null,this.emit(),await this.initialize()}applyNavigationSession(t){if(!t||t.sessionId!==this.sessionId)return;const s=Qt(this.state.session,t);s!==this.state.session&&this.patch({session:s,hasOlderMessages:vt({session:s,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})})}async sendMessage(t,s){const n=Kn();this.beginPendingReplyDebugTrace("send_live",n,t.length);const r=xr(this.sessionId,t,n,(s==null?void 0:s.attachmentMeta)??[],(s==null?void 0:s.attachments)??[],za(this.buildTimelineMessages("send_sequence"),this.state.session)),a=this.applyTimelineEvent({type:"pending.insert",source:"send_pending",pending:r});this.patch({messages:a.messages,session:Je(this.state.session,"running"),runtimeHasActiveRun:Qn(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:Zn(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt});try{const o=await this.sendMessageWithFallback(t,n,s);this.markPendingReplyDebugTraceResponseReady(n,{returnedMessageId:o.message.messageId,returnedProviderSessionId:o.message.providerSessionId}),this.resolvePendingMessage(o.message,n),this.patch({messages:this.buildTimelineMessages("send_resolved")})}catch(o){this.failPendingReplyDebugTrace(n,o);const u=this.applyTimelineEvent({type:"pending.fail",source:"send_failed",clientRequestId:n});throw this.patch({messages:u.messages,session:Je(this.state.session,"failed"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1}),o}}async retryMessage(t){const s=this.pendingMessages.find(r=>r.clientRequestId===t);if(!s)return;const n=this.applyTimelineEvent({type:"pending.retry",source:"retry_pending",clientRequestId:t});this.patch({messages:n.messages,runtimeHasActiveRun:Qn(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:Zn(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt}),this.beginPendingReplyDebugTrace("retry_live",t,s.content.length);try{const r=await this.sendMessageWithFallback(s.content,t,{attachments:s.attachmentPayloads??[],attachmentMeta:s.attachments});this.markPendingReplyDebugTraceResponseReady(t,{returnedMessageId:r.message.messageId,returnedProviderSessionId:r.message.providerSessionId}),this.resolvePendingMessage(r.message,t),this.patch({messages:this.buildTimelineMessages("retry_resolved")})}catch(r){this.failPendingReplyDebugTrace(t,r);const a=this.applyTimelineEvent({type:"pending.fail",source:"retry_failed",clientRequestId:t});throw this.patch({messages:a.messages,session:Je(this.state.session,"failed")}),r}}async enqueueMessage(t,s){const n=Kn();try{const r=await Po(this.sessionId,{content:t,clientRequestId:n,model:(s==null?void 0:s.model)??null,reasoningLevel:(s==null?void 0:s.reasoningLevel)??null,permissionMode:ut(),attachments:(s==null?void 0:s.attachments)??[],providerConfigMode:s==null?void 0:s.providerConfigMode,providerPresetId:(s==null?void 0:s.providerPresetId)??null});this.patch({queuedMessages:ll(this.state.queuedMessages,r)}),await this.refreshQueue()}catch(r){throw r}}async deleteQueuedMessage(t){await Ro(this.sessionId,t),await this.refreshQueue()}async steerQueuedMessage(t){await To(this.sessionId,t),await this.refreshRuntimeSnapshot("queue_steer")}async interrupt(){await Co(this.sessionId),this.patch({session:Je(this.state.session,"interrupted"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:"user",errorCode:null,errorDetail:null})}async replyPermissionRequest(t,s){if(!(this.state.permissionRequests.find(a=>a.id===t)??null))return;const r=await ko(this.sessionId,t,s);this.patch({permissionRequests:Hs(this.state.permissionRequests,r)})}reconnect(){var t;(t=this.realtimeClient)==null||t.reconnectNow()}async loadOlderMessages(){var t;if(!(this.state.historyState!=="ready"||this.state.loadingOlderMessages||!this.state.olderCursor)){this.patch({loadingOlderMessages:!0,errorCode:null,errorDetail:null});try{const s=this.state.olderCursor,n=await this.takePrefetchedOlderHistoryPage(s);if(n&&this.state.olderCursor===s){this.applyOlderHistoryPage(n,"prefetch_cache");return}if(!((t=this.realtimeClient)==null?void 0:t.requestOlderMessages(s,ks)))throw new Error("REALTIME_NOT_CONNECTED")}catch(s){const n=s instanceof Error?s.message:"unknown";this.patch({loadingOlderMessages:!1,errorCode:"HISTORY_LOAD_MORE_FAILED",errorDetail:n})}}}destroy(){var t;this.clearHistoryBootstrapFallbackTimer(),this.clearOlderHistoryPrefetch(),(t=this.realtimeClient)==null||t.close(),this.realtimeClient=null,this.pendingReplyDebugTraces.length=0,this.markSeenTimer!==null&&(window.clearTimeout(this.markSeenTimer),this.markSeenTimer=null),this.runtimeRefreshTimer!==null&&(window.clearTimeout(this.runtimeRefreshTimer),this.runtimeRefreshTimer=null),this.runtimeRefreshMode=null}startRealtime(){var s;if(!((s=Ss.getState().session)==null?void 0:s.accessToken)){Ss.clear();return}this.realtimeClient=new Eo({sessionId:this.sessionId,cursor:this.state.lastCursor,limit:Et,onSubscribed:()=>{be("session_send.realtime_subscribed",{sessionId:this.sessionId,lastCursor:this.state.lastCursor}),this.patch({connectionState:"connected",hasOlderMessages:vt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})}),this.scheduleHistoryBootstrapFallback()},onConnectionChange:n=>{var a;const r=this.state.connectionState;if(this.patch({connectionState:n,session:n==="reconnecting"&&Qe((a=this.state.session)==null?void 0:a.runningState)?Je(this.state.session,"reconnecting"):this.state.session}),n==="connected"){this.clearRuntimeRefreshTimer("poll"),r!=="closed"&&r!=="connected"&&this.patch({errorCode:null,errorDetail:null});return}this.scheduleRuntimeRefresh("poll","connection_state_change")},onEnvelope:n=>{var u,d;this.historyBootstrapEnvelopeReceived=!0,this.clearHistoryBootstrapFallbackTimer();const r=n.type==="session.backfill"&&this.replaceSnapshotSeedOnBackfill,{messages:a,replacedSnapshotSeed:o}=this.mergeHistoryMessages(n.messages,r,n.type==="session.backfill"?"realtime_backfill":"realtime_delta");this.patch({messages:a,lastCursor:n.cursor,historyState:"ready",olderCursor:n.type==="session.backfill"&&!o&&this.state.pagesLoaded>1?this.state.olderCursor:n.olderCursor??this.state.olderCursor,hasOlderMessages:n.type==="session.backfill"?!o&&this.state.pagesLoaded>1?this.state.hasOlderMessages:!!n.olderCursor:vt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),pagesLoaded:n.type==="session.backfill"?!o&&this.state.pagesLoaded>1?this.state.pagesLoaded:Math.max(this.state.pagesLoaded,this.authoritativeMessages.length>0?1:0):this.state.pagesLoaded,session:Je(this.state.session,Gn(n.type,(u=this.state.session)==null?void 0:u.runningState))}),(d=this.realtimeClient)==null||d.updateCursor(n.cursor),this.scheduleMarkSeen(),this.scheduleOlderHistoryPrefetch(n.type==="session.backfill"?"backfill":"delta"),this.state.queuedMessages.length>0&&this.refreshQueue()},onOlderHistory:n=>{this.applyOlderHistoryPage({messages:n.messages,nextCursor:n.olderCursor},"realtime")},onRuntimeMessage:n=>{this.handleRuntimeMessage(n)},onActivity:n=>{this.handleActivity(n)},onRuntimeStatus:n=>{this.handleRuntimeStatus(n)},onRuntimeError:n=>{this.handleRuntimeError(n)},onInterrupted:n=>{this.handleInterrupted(n)},onPermissionRequest:n=>{this.handlePermissionRequest(n)},onPermissionRequestResolved:n=>{this.handlePermissionRequestResolved(n)},onError:n=>{this.patch({loadingOlderMessages:!1,errorCode:n.error_code,errorDetail:n.detail})},onUnauthorized:()=>{Ss.clear()}}),this.realtimeClient.start()}patch(t){let s=t;Object.prototype.hasOwnProperty.call(t,"session")&&(this.syncSeenWatermark(t.session??null),s={...t,session:this.applySeenWatermark(t.session??null)}),(Object.prototype.hasOwnProperty.call(s,"session")||Object.prototype.hasOwnProperty.call(s,"messages"))&&(s={...s,timelineItems:_s((Object.prototype.hasOwnProperty.call(s,"session")?s.session:this.state.session)??null,(Object.prototype.hasOwnProperty.call(s,"messages")?s.messages:this.state.messages)??[])}),this.state={...this.state,...s},(Object.prototype.hasOwnProperty.call(s,"session")||Object.prototype.hasOwnProperty.call(s,"capabilities")||Object.prototype.hasOwnProperty.call(s,"contextUsage")||Object.prototype.hasOwnProperty.call(s,"messages")||Object.prototype.hasOwnProperty.call(s,"timelineItems")||Object.prototype.hasOwnProperty.call(s,"permissionRequests")||Object.prototype.hasOwnProperty.call(s,"queuedMessages"))&&this.persistSnapshot(),this.emit()}applyTimelineEvent(t){const s=Bn({authoritativeMessages:this.authoritativeMessages,runtimeOverlayMessages:this.runtimeOverlayMessages,activeRuntimeOverlayKeys:this.activeRuntimeOverlayKeys,pendingMessages:this.pendingMessages,replaceSnapshotSeedOnBackfill:this.replaceSnapshotSeedOnBackfill},this.sessionId,t);this.authoritativeMessages=s.timeline.authoritativeMessages,this.runtimeOverlayMessages=s.timeline.runtimeOverlayMessages,this.activeRuntimeOverlayKeys=s.timeline.activeRuntimeOverlayKeys,this.pendingMessages=s.timeline.pendingMessages,this.replaceSnapshotSeedOnBackfill=s.timeline.replaceSnapshotSeedOnBackfill;const n=Ga(s.previousMessages,s.messages,"assistant"),r=Va(t);return(s.validationIssues.length>0||r.some(o=>o.role==="assistant")||n.length>0)&&ns("timeline.event",{sessionId:this.sessionId,eventType:t.type,source:t.source,replacedSnapshotSeed:s.replacedSnapshotSeed,validationIssues:s.validationIssues,authoritativeCount:this.authoritativeMessages.length,runtimeOverlayCount:this.runtimeOverlayMessages.length,pendingCount:this.pendingMessages.length,eventMessages:r.map(o=>ai(o)),assistantMoves:n,previousTail:Wn(s.previousMessages.slice(-6)),nextTail:Wn(s.messages.slice(-6))}),s}mergeHistoryMessages(t,s,n){const r=this.applyTimelineEvent({type:"history.merge",source:n,messages:t,replaceSnapshotSeed:s});return this.logCodexMergeDebug(n,r.previousMessages,t,r.messages,{replacedSnapshotSeedAttempted:s,replacedSnapshotSeed:r.replacedSnapshotSeed,baseMessageCount:r.replacedSnapshotSeed?0:r.previousMessages.length}),{messages:r.messages,replacedSnapshotSeed:r.replacedSnapshotSeed}}buildTimelineMessages(t){return Ys({authoritativeMessages:this.authoritativeMessages,runtimeOverlayMessages:this.runtimeOverlayMessages,activeRuntimeOverlayKeys:this.activeRuntimeOverlayKeys,pendingMessages:this.pendingMessages,replaceSnapshotSeedOnBackfill:this.replaceSnapshotSeedOnBackfill})}clearActiveRuntimeTail(t){if(this.activeRuntimeOverlayKeys.length===0)return;this.activeRuntimeOverlayKeys=[];const s=this.buildTimelineMessages(t);this.patch({messages:s})}resolvePendingMessage(t,s){this.applyTimelineEvent({type:"pending.resolve",source:"pending_resolved",clientRequestId:s,message:t})}handleError(t){this.clearHistoryBootstrapFallbackTimer();const s=t instanceof Error?t.message:"unknown";this.patch({historyState:"error",errorCode:"RUNTIME_INIT_FAILED",errorDetail:s})}scheduleMarkSeen(){if(this.markSeenTimer!==null)return;const t=this.getTargetSeenAt();if(this.markSeenInFlight||t===null)return;const s=this.getMarkSeenThrottleDelayMs(),n=Math.max(va,s);this.markSeenTimer=window.setTimeout(()=>{this.markSeenTimer=null;const r=this.getTargetSeenAt();r!==null&&(be("session_seen.start",{sessionId:this.sessionId,targetSeenAt:r,seenWatermark:this.seenWatermark}),this.markSeenInFlight=!0,this.lastMarkSeenRequestAt=Date.now(),Ao(this.sessionId).then(()=>{var a,o;this.bumpSeenWatermark(r),this.patch({session:Un(this.state.session,r)}),(o=(a=this.options).onSeen)==null||o.call(a,this.sessionId,r),be("session_seen.end",{sessionId:this.sessionId,seenWatermark:this.seenWatermark})}).catch(()=>{be("session_seen.error",{sessionId:this.sessionId,targetSeenAt:r})}).finally(()=>{this.markSeenInFlight=!1,this.shouldMarkSeen()&&this.scheduleMarkSeen()}))},n)}clearRuntimeRefreshTimer(t){this.runtimeRefreshTimer!==null&&(t&&this.runtimeRefreshMode!==t||(window.clearTimeout(this.runtimeRefreshTimer),this.runtimeRefreshTimer=null,this.runtimeRefreshMode=null))}scheduleHistoryBootstrapFallback(){this.historyBootstrapEnvelopeReceived||this.historyBootstrapFallbackTimer!==null||(this.historyBootstrapFallbackTimer=window.setTimeout(()=>{this.historyBootstrapFallbackTimer=null,!this.historyBootstrapEnvelopeReceived&&this.resolveHistoryBootstrapFallback()},350))}clearHistoryBootstrapFallbackTimer(){this.historyBootstrapFallbackTimer!==null&&(window.clearTimeout(this.historyBootstrapFallbackTimer),this.historyBootstrapFallbackTimer=null)}async resolveHistoryBootstrapFallback(){try{const t=Math.min(zr,Math.max(Et,this.authoritativeMessages.length,ga)),s=await Ws(this.sessionId,null,t,"backward");if(this.historyBootstrapEnvelopeReceived)return;this.historyBootstrapEnvelopeReceived=!0;const{messages:n,replacedSnapshotSeed:r}=this.mergeHistoryMessages(s.messages,this.replaceSnapshotSeedOnBackfill,"http_bootstrap_fallback");this.patch({messages:n,historyState:"ready",olderCursor:!r&&this.state.pagesLoaded>1?this.state.olderCursor:s.nextCursor,hasOlderMessages:!r&&this.state.pagesLoaded>1?this.state.hasOlderMessages:vt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:s.nextCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),lastCursor:s.cursor??this.state.lastCursor,pagesLoaded:!r&&this.state.pagesLoaded>1?this.state.pagesLoaded:this.authoritativeMessages.length>0?Math.max(this.state.pagesLoaded,1):this.state.pagesLoaded,errorCode:null,errorDetail:null}),this.scheduleMarkSeen(),this.scheduleOlderHistoryPrefetch("bootstrap_fallback")}catch{}}applyOlderHistoryPage(t,s){const{messages:n}=this.mergeHistoryMessages(t.messages,!1,s==="realtime"?"older_history_realtime":"older_history_prefetch_cache");this.patch({messages:n,historyState:"ready",loadingOlderMessages:!1,olderCursor:t.nextCursor,hasOlderMessages:!!t.nextCursor,pagesLoaded:this.state.pagesLoaded+1,errorCode:null,errorDetail:null}),be("session.history_older.applied",{sessionId:this.sessionId,source:s,messageCount:t.messages.length,nextCursor:t.nextCursor}),this.scheduleOlderHistoryPrefetch(s)}scheduleOlderHistoryPrefetch(t){var n;const s=this.state.olderCursor;this.state.historyState!=="ready"||this.state.loadingOlderMessages||!s||((n=this.prefetchedOlderHistoryPage)==null?void 0:n.requestedCursor)!==s&&(this.olderHistoryPrefetchPromise&&this.olderHistoryPrefetchCursor===s||this.prefetchOlderHistoryPage(s,t))}async prefetchOlderHistoryPage(t,s){var r;if(((r=this.prefetchedOlderHistoryPage)==null?void 0:r.requestedCursor)===t)return this.prefetchedOlderHistoryPage.page;if(this.olderHistoryPrefetchPromise&&this.olderHistoryPrefetchCursor===t)return this.olderHistoryPrefetchPromise;this.olderHistoryPrefetchCursor=t,be("session.history_older.prefetch.start",{sessionId:this.sessionId,requestedCursor:t,reason:s,limit:ks});const n=Ws(this.sessionId,t,ks,"backward").then(a=>(this.state.olderCursor===t&&(this.prefetchedOlderHistoryPage={requestedCursor:t,page:a}),be("session.history_older.prefetch.end",{sessionId:this.sessionId,requestedCursor:t,messageCount:a.messages.length,nextCursor:a.nextCursor}),a)).catch(a=>(be("session.history_older.prefetch.error",{sessionId:this.sessionId,requestedCursor:t,message:a instanceof Error?a.message:"unknown"}),null)).finally(()=>{this.olderHistoryPrefetchPromise===n&&(this.olderHistoryPrefetchPromise=null),this.olderHistoryPrefetchCursor===t&&(this.olderHistoryPrefetchCursor=null)});return this.olderHistoryPrefetchPromise=n,n}async takePrefetchedOlderHistoryPage(t){var s;if(((s=this.prefetchedOlderHistoryPage)==null?void 0:s.requestedCursor)===t){const n=this.prefetchedOlderHistoryPage.page;return this.prefetchedOlderHistoryPage=null,be("session.history_older.prefetch.hit",{sessionId:this.sessionId,requestedCursor:t,messageCount:n.messages.length,nextCursor:n.nextCursor}),n}if(this.olderHistoryPrefetchPromise&&this.olderHistoryPrefetchCursor===t){const n=await this.olderHistoryPrefetchPromise;return!n||this.state.olderCursor!==t?null:(this.prefetchedOlderHistoryPage=null,be("session.history_older.prefetch.await_hit",{sessionId:this.sessionId,requestedCursor:t,messageCount:n.messages.length,nextCursor:n.nextCursor}),n)}return null}clearOlderHistoryPrefetch(){this.olderHistoryPrefetchCursor=null,this.olderHistoryPrefetchPromise=null,this.prefetchedOlderHistoryPage=null}scheduleRuntimeRefresh(t,s){var n,r;if(!Qe((n=this.state.session)==null?void 0:n.runningState)){this.clearRuntimeRefreshTimer();return}t==="poll"&&this.state.connectionState==="connected"||(this.clearRuntimeRefreshTimer(),this.runtimeRefreshMode=t,be("session_runtime.refresh.schedule",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((r=this.state.session)==null?void 0:r.runningState)??null}),this.runtimeRefreshTimer=window.setTimeout(()=>{const a=this.runtimeRefreshMode??t;this.runtimeRefreshTimer=null,this.runtimeRefreshMode=null,this.refreshRuntimeState(a,s)},t==="poll"?wa:1200))}async refreshRuntimeState(t,s){var n,r,a,o,u;be("session_runtime.refresh.start",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((n=this.state.session)==null?void 0:n.runningState)??null});try{const d=await kn(this.sessionId),h=Ls(this.state.runtimeHasActiveRun,d.runningState,d.hasActiveRun),f=Ds(this.state.runtimeCanInterrupt,d.runningState,h,d.canInterrupt);this.patch({session:$n(this.state.session,d),runtimeHasActiveRun:h,runtimeCanInterrupt:f,contextUsage:d.contextUsage,...Ns(d,this.state.interruptSource)}),await this.refreshQueue();const p=t==="poll"&&this.state.connectionState!=="connected"&&Qe((r=this.state.session)==null?void 0:r.runningState);be("session_runtime.refresh.end",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((a=this.state.session)==null?void 0:a.runningState)??null,continuePolling:p}),p&&this.scheduleRuntimeRefresh("poll","connection_poll")}catch(d){be("session_runtime.refresh.error",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((o=this.state.session)==null?void 0:o.runningState)??null,message:d instanceof Error?d.message:"unknown"}),t==="poll"&&this.state.connectionState!=="connected"&&Qe((u=this.state.session)==null?void 0:u.runningState)&&this.scheduleRuntimeRefresh("poll","connection_poll_retry")}}async refreshSessionMetadata(){const t=[];this.state.session===null&&t.push(Ir(this.sessionId).then(s=>{this.patch({session:Qt(s,this.state.session)})}).catch(()=>{})),Vn(this.state.capabilities)&&t.push(_o(this.sessionId).then(s=>{this.patch({capabilities:s})}).catch(()=>{})),t.length!==0&&await Promise.allSettled(t)}async refreshPermissionRequests(){try{const t=await jo(this.sessionId);this.patch({permissionRequests:t.items})}catch{return}}shouldRefreshSessionDetail(){return this.state.session===null||Vn(this.state.capabilities)||this.state.session.runningState===null}shouldRefreshRuntimeSnapshot(){return this.state.contextUsage===null||al(this.state.session,this.state.runtimeHasActiveRun,this.state.runtimeCanInterrupt)}async refreshRuntimeSnapshot(t){be("session_runtime.snapshot.start",{sessionId:this.sessionId,reason:t});try{const s=await kn(this.sessionId),n=Ls(this.state.runtimeHasActiveRun,s.runningState,s.hasActiveRun),r=Ds(this.state.runtimeCanInterrupt,s.runningState,n,s.canInterrupt);this.patch({session:$n(this.state.session,s),runtimeHasActiveRun:n,runtimeCanInterrupt:r,contextUsage:s.contextUsage,...Ns(s,this.state.interruptSource)}),await this.refreshQueue(),be("session_runtime.snapshot.end",{sessionId:this.sessionId,reason:t,hasContextUsage:s.contextUsage!==null})}catch(s){be("session_runtime.snapshot.error",{sessionId:this.sessionId,reason:t,message:s instanceof Error?s.message:"unknown"})}}async refreshQueue(){try{const t=await No(this.sessionId);this.patch({queuedMessages:t.items})}catch{return}}async sendMessageWithFallback(t,s,n){var r;try{return await sn(this.sessionId,{content:t,clientRequestId:s,model:(n==null?void 0:n.model)??null,reasoningLevel:(n==null?void 0:n.reasoningLevel)??null,permissionMode:ut(),attachments:(n==null?void 0:n.attachments)??[],providerConfigMode:n==null?void 0:n.providerConfigMode,providerPresetId:(n==null?void 0:n.providerPresetId)??null})}catch(a){if(!(a instanceof $i)||a.status!==404&&a.status!==405||(((r=n==null?void 0:n.attachments)==null?void 0:r.length)??0)>0)throw a;return be("session_send.live_fallback",{sessionId:this.sessionId,clientRequestId:s,reason:a.message}),Oo(this.sessionId,{content:t,clientRequestId:s,permissionMode:ut()})}}handleRuntimeStatus(t){var n;const s=js((n=this.state.session)==null?void 0:n.runningState,t.status);this.patch({session:Je(this.state.session,s),runtimeHasActiveRun:Qe(s)?this.state.runtimeHasActiveRun??!0:!1,runtimeCanInterrupt:Qe(s)?this.state.runtimeCanInterrupt:!1,interruptSource:s==="interrupted"?t.interruptSource??this.state.interruptSource:s==="completed"||s==="failed"?null:this.state.interruptSource,errorCode:null,errorDetail:s===t.status?t.detail:this.state.errorDetail}),Lt(s)&&(this.clearActiveRuntimeTail("runtime_status_terminal"),this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_terminal_before_message",{status:t.status,detail:t.detail}),this.clearRuntimeRefreshTimer(),this.refreshQueue(),this.refreshRuntimeSnapshot("runtime_terminal"))}handleActivity(t){const s=Ls(this.state.runtimeHasActiveRun,t.runningState,t.hasActiveRun),n=Ds(this.state.runtimeCanInterrupt,t.runningState,s,t.canInterrupt);if(this.patch({session:el(this.state.session,t),runtimeHasActiveRun:s,runtimeCanInterrupt:n,...Ns(t,this.state.interruptSource)}),Lt(t.runningState)){this.clearActiveRuntimeTail("activity_terminal"),this.clearRuntimeRefreshTimer(),this.refreshQueue();return}(t.runningState==="stale"||t.runningState==="unknown")&&this.scheduleRuntimeRefresh("tail","activity_watchdog")}handleRuntimeMessage(t){var r;t.message.role==="assistant"&&this.completePendingReplyDebugTrace(t);const s=this.applyTimelineEvent({type:"runtime.message",source:t.source,message:Pr(this.sessionId,t.message)}),n=s.messages;this.logCodexMergeDebug("runtime_message",s.previousMessages,[t.message],n,{runtimeSource:t.source}),this.patch({messages:n,historyState:"ready",hasOlderMessages:vt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),session:Je(this.state.session,Gn("session.delta",(r=this.state.session)==null?void 0:r.runningState))}),this.scheduleMarkSeen(),this.state.queuedMessages.length>0&&this.refreshQueue()}handleRuntimeError(t){var n;const s=js((n=this.state.session)==null?void 0:n.runningState,"failed");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_runtime_error",{errorCode:t.error_code,detail:t.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:Je(this.state.session,s),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:null,errorCode:s==="failed"?t.error_code:this.state.errorCode,errorDetail:s==="failed"?t.detail:this.state.errorDetail}),this.refreshQueue()}handleInterrupted(t){var n;const s=js((n=this.state.session)==null?void 0:n.runningState,"interrupted");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_interrupted",{detail:t.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:Je(this.state.session,s),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:s==="interrupted"?t.interruptSource??this.state.interruptSource:this.state.interruptSource,errorCode:s==="interrupted"?null:this.state.errorCode,errorDetail:s==="interrupted"?t.detail:this.state.errorDetail}),this.refreshQueue()}handlePermissionRequest(t){this.patch({permissionRequests:Hs(this.state.permissionRequests,t.request)})}handlePermissionRequestResolved(t){this.patch({permissionRequests:Hs(this.state.permissionRequests,t.request)})}shouldMarkSeen(){return this.getTargetSeenAt()!==null}getTargetSeenAt(){const t=[...this.state.messages].reverse().find(n=>n.role!=="user");if(!t)return null;const s=this.seenWatermark;return s?t.timestamp>s?t.timestamp:null:t.timestamp}syncSeenWatermark(t){t!=null&&t.lastSeenAt&&this.bumpSeenWatermark(t.lastSeenAt)}bumpSeenWatermark(t){this.seenWatermark&&this.seenWatermark>=t||(this.seenWatermark=t)}getMarkSeenThrottleDelayMs(){return this.lastMarkSeenRequestAt<=0?0:Math.max(0,ba-(Date.now()-this.lastMarkSeenRequestAt))}applySeenWatermark(t){return!t||!this.seenWatermark?t:Un(t,this.seenWatermark)}emit(){for(const t of this.listeners)t()}persistSnapshot(){Vi(qs(this.sessionId),{session:this.state.session,capabilities:this.state.capabilities,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage,messages:Jn(this.authoritativeMessages),timelineItems:_s(this.state.session,Jn(this.authoritativeMessages)),permissionRequests:this.state.permissionRequests,queuedMessages:this.state.queuedMessages,olderCursor:this.state.olderCursor,hasOlderMessages:this.state.hasOlderMessages,lastCursor:this.state.lastCursor,pagesLoaded:this.state.pagesLoaded,interruptSource:this.state.interruptSource})}beginPendingReplyDebugTrace(t,s,n){const r={mode:t,clientRequestId:s,startedAtMs:performance.now(),responseReadyAtMs:null,contentLength:n};this.pendingReplyDebugTraces.push(r),be(`session_send.${t}.client_start`,{sessionId:this.sessionId,clientRequestId:s,contentLength:n})}markPendingReplyDebugTraceResponseReady(t,s={}){const n=this.pendingReplyDebugTraces.find(r=>r.clientRequestId===t);!n||n.responseReadyAtMs!==null||(n.responseReadyAtMs=performance.now(),be(`session_send.${n.mode}.client_response`,{sessionId:this.sessionId,clientRequestId:t,durationMs:Math.round(n.responseReadyAtMs-n.startedAtMs),...s}))}failPendingReplyDebugTrace(t,s){const n=this.pendingReplyDebugTraces.find(r=>r.clientRequestId===t);n&&(be(`session_send.${n.mode}.client_error`,{sessionId:this.sessionId,clientRequestId:t,durationMs:Math.round(performance.now()-n.startedAtMs),error:s instanceof Error?s.message:String(s)}),this.removePendingReplyDebugTrace(n.clientRequestId))}completePendingReplyDebugTrace(t){const s=this.pendingReplyDebugTraces[0];if(!s)return;const n=performance.now();be(`session_send.${s.mode}.first_assistant_message`,{sessionId:this.sessionId,clientRequestId:s.clientRequestId,durationMs:Math.round(n-s.startedAtMs),responseToAssistantMs:s.responseReadyAtMs===null?null:Math.round(n-s.responseReadyAtMs),messageId:t.message.messageId,kind:t.message.kind,contentLength:t.message.content.length}),this.removePendingReplyDebugTrace(s.clientRequestId)}completePendingReplyDebugTraceWithoutAssistant(t,s={}){const n=this.pendingReplyDebugTraces[0];n&&(be(t,{sessionId:this.sessionId,clientRequestId:n.clientRequestId,durationMs:Math.round(performance.now()-n.startedAtMs),responseReady:n.responseReadyAtMs!==null,...s}),this.removePendingReplyDebugTrace(n.clientRequestId))}removePendingReplyDebugTrace(t){const s=this.pendingReplyDebugTraces.findIndex(n=>n.clientRequestId===t);s<0||this.pendingReplyDebugTraces.splice(s,1)}logCodexMergeDebug(t,s,n,r,a={}){const o=n.filter(sl);if(o.length===0)return;const u=zn(s),d=zn(r);ze("session.messages.merge",{sessionId:this.sessionId,source:t,beforeCount:s.length,incomingCount:n.length,afterCount:r.length,incoming:o.slice(0,5).map(rl),beforeDuplicateGroupCount:u.length,afterDuplicateGroupCount:d.length,afterDuplicateGroups:d.slice(0,3),...a})}}function Ia(){return{authoritativeMessages:[],runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:!1}}function ya(e,t){const s=new Map,n=new Set;for(const r of e)s.set(r.id,r),n.add(r.id);for(const r of t){const a=s.get(r.id)??null,o=ri(s,n,r,a);if(o){const h=s.get(o)??null;if(h){ze("session.messages.runtime_overlay_authoritative_bridge",{mode:"prefer_equivalent",previous:pe(h),overlay:pe(r),replacedSameId:a?pe(a):null}),s.set(o,Es(h,r));continue}}if(a){ze("session.messages.runtime_overlay_authoritative_bridge",{mode:"same_id",previous:pe(a),overlay:pe(r)}),s.set(r.id,Es(a,r));continue}const u=hn(s,n,r);if(u){const h=s.get(u)??null;if(h){ze("session.messages.runtime_overlay_authoritative_bridge",{mode:"codex_compat",previous:pe(h),overlay:pe(r)}),s.set(u,Es(h,r));continue}}const d=fn(s,r);if(d&&n.has(d)){const h=s.get(d)??null;if(h){if(ze("session.messages.runtime_overlay_authoritative_bridge",{mode:"opencode_compat",previous:pe(h),overlay:pe(r)}),ws(h,r)){s.set(d,Ln(h,r));continue}s.set(d,Ln(h,r));continue}}ze("session.messages.runtime_overlay_authoritative_bridge",{mode:"insert",overlay:pe(r)}),s.set(r.id,r)}return Ca(Array.from(s.values()))}function Es(e,t){return{...Kr(e,{...t,id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId}),id:e.id,rawRef:e.rawRef,timestamp:e.timestamp,sequence:e.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}function Kr(e,t){if(e.id!==t.id)return t;if(Ot(e,t)){const o=rs(e.toolCall,t.toolCall),u=Qr(e,t,o,is),d=os(e.attachments,t.attachments),h=as(e,t);return{...Mt(e,t),kind:(o==null?void 0:o.status)==="running"?"tool_call":"tool_result",content:u,toolCall:o,attachments:d,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:h.rawRef,timestamp:h.timestamp,sequence:h.sequence}}if(e.role!==t.role||e.kind!==t.kind)return Mt(e,t);const s=rs(e.toolCall,t.toolCall),n=is(e.content,t.content,e.timestamp,t.timestamp),r=os(e.attachments,t.attachments),a=as(e,t);return{...Mt(e,t),content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:a.rawRef,timestamp:a.timestamp,sequence:a.sequence}}function Ln(e,t){if(Ot(e,t)){const o=rs(e.toolCall,t.toolCall),u=Qr(e,t,o,is),d=os(e.attachments,t.attachments),h=as(e,t);return{...Mt(e,t),id:e.id,kind:(o==null?void 0:o.status)==="running"?"tool_call":"tool_result",content:u,toolCall:o,attachments:d,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:h.rawRef,timestamp:h.timestamp,sequence:h.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}if(e.role!==t.role||e.kind!==t.kind)return{...Mt(e,t),id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId};const s=rs(e.toolCall,t.toolCall),n=is(e.content,t.content,e.timestamp,t.timestamp),r=os(e.attachments,t.attachments),a=as(e,t);return{...Mt(e,t),id:e.id,content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:a.rawRef,timestamp:a.timestamp,sequence:a.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}function Ot(e,t){return ws(e,t)||Ms(e,t)}function Qr(e,t,s,n){if((s==null?void 0:s.status)==="running"){if(t.kind==="tool_call"&&t.content)return t.content;if(e.kind==="tool_call"&&e.content)return e.content}else{if(t.kind==="tool_result"&&t.content)return t.content;if(e.kind==="tool_result"&&e.content)return e.content;if(s!=null&&s.output)return s.output}return n(e.content,t.content,e.timestamp,t.timestamp)}function hn(e,t,s){if(!zs(s))return null;for(const[n,r]of e.entries())if(!(n===s.id||!t.has(n)||!xa(r,s)))return ze("session.messages.codex_identity_bridge_match",{previous:pe(r),incoming:pe(s)}),n;return null}function xa(e,t){if(!Ea(e,t))return!1;if(e.rawRef===t.rawRef)return!0;if(e.kind==="tool_call"||e.kind==="tool_result")return Ms(e,t);const s=cs(e.rawRef),n=cs(t.rawRef);if(!s||!n||s!==n)return!1;const r=Math.abs(e.sequence-t.sequence);return r>1?(ze("session.messages.codex_identity_bridge_rejected",{reason:"sequence_distance",sequenceDistance:r,previous:pe(e),incoming:pe(t)}),!1):!0}function fn(e,t){if(!qn(t))return null;const s=ls(t.rawRef);if(s===null)return null;const n=xt(t.timestamp);let r=null,a=Number.POSITIVE_INFINITY;for(const[o,u]of e.entries()){if(o===t.id||!qn(u)||u.role!==t.role)continue;if(ws(u,t))return o;if(u.kind!==t.kind||ls(u.rawRef)!==s)continue;const h=xt(u.timestamp),f=Math.abs(h-n),x=Math.abs(u.sequence-t.sequence)*6e4+f;x<a&&(r=o,a=x)}return r}function Pa(e,t,s){if(!pn(t))return!1;const n=Gs(e.authoritativeMessages,t,"authoritative",s);if(n)return ze("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"authoritative",matched:pe(n),incoming:pe(t)}),!0;const r=Gs(e.pendingMessages,t,"pending",s);return r?(ze("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"pending",matched:pe(r),incoming:pe(t)}),!0):!1}function Gs(e,t,s,n){const r=xt(t.timestamp),a=$e(t.content),o=Xs(t.content),u=us(t.attachments);let d=null,h=Number.POSITIVE_INFINITY;const f=[];for(const p of e){if(!(s==="authoritative"?ka(p):Jr(p)))continue;const v=$e(p.content),w=Xs(p.content),M=v===a,_=w===o;if(!M&&!_)continue;const y=xt(p.timestamp),O=Math.abs(y-r);if(O>300*1e3)continue;const C=Math.abs(p.sequence-t.sequence),j=us(p.attachments),A=_a(j,u);if(f.push(Na(p,{strictTextMatches:M,relaxedTextMatches:_,attachmentCompatibility:A,distanceMs:O,sequenceDistance:C})),A==="conflict"&&(M||a.length===0))continue;const P=O+C*15e3+(M?0:500)+ja(A);P<h&&(d=p,h=P)}return f.length>0&&ze("session.messages.runtime_user_match",{sessionId:n,target:s,matchedId:(d==null?void 0:d.id)??null,matchedScore:Number.isFinite(h)?h:null,incoming:Oa(t,{relaxedContent:o,attachmentSignature:u}),candidates:f.slice(0,5)}),d}function Ra(e,t,s){for(const n of t){if(n.role!=="user"||n.kind!=="text")continue;const r=Pr(s,n,"sent",null);if(!Gs(e,r,"authoritative",s))return!0}return!1}function rs(e,t){return e?t?{...Ta(e,t),input:Zr(e.input,t.input),output:Dn(e.output,t.output),error:Dn(e.error,t.error)}:e:t}function Ta(e,t){const s=e.status==="running"?0:1,n=t.status==="running"?0:1;return n!==s?n>s?t:e:t}function is(e,t,s,n){const r=$e(e),a=$e(t);return r===a?e.length>=t.length?e:t:r.length>a.length&&r.includes(a)?e:a.length>r.length&&a.includes(r)||n.localeCompare(s)>=0?t:e}function os(e,t){const s=(e==null?void 0:e.length)??0,n=(t==null?void 0:t.length)??0;return n!==s?n>s?t:e:t??e}function Zr(e,t){return t.length>e.length?t:e}function Dn(e,t){return e===null?t:t===null?e:Zr(e,t)}function Mt(e,t){return t.timestamp!==e.timestamp?t.timestamp.localeCompare(e.timestamp)>=0?t:e:t.sequence!==e.sequence?t.sequence>=e.sequence?t:e:t}function as(e,t){return qt(e,t)<=0?e:t}function $e(e){return e.replace(Ma,"").replace(/\r\n/g,`
|
|
4
4
|
`).trimEnd()}function Xs(e){return $e(e).replace(/[ \t]+\n/g,`
|
|
5
5
|
`).replace(/\n{2,}/g,`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as d,j as e}from"./index-
|
|
1
|
+
import{b as d,j as e}from"./index-_OCkVmfl.js";function c(){return d.useEffect(()=>{const t=document.documentElement.style.background,s=document.body.style.background;return document.documentElement.style.background="transparent",document.body.style.background="transparent",()=>{document.documentElement.style.background=t,document.body.style.background=s}},[]),e.jsx("main",{className:"desktop-detach-preview-page","aria-hidden":"true",children:e.jsxs("section",{className:"desktop-detach-preview-card",children:[e.jsx("header",{className:"desktop-detach-preview-bar",children:e.jsx("strong",{className:"desktop-detach-preview-title",children:"小窗口"})}),e.jsx("div",{className:"desktop-detach-preview-body",children:e.jsx("span",{className:"desktop-detach-preview-badge"})})]})})}export{c as DesktopDetachPreviewPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as e,t as j,b as d}from"./index-
|
|
1
|
+
import{j as e,t as j,b as d}from"./index-_OCkVmfl.js";import{g as L}from"./App-If9gThKM.js";function C(){return e.jsx("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true",children:e.jsx("path",{d:"M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})})}function O({className:a,"aria-label":r,...o}){return e.jsx("button",{type:"button",className:a?`workbench-modal-close ${a}`:"workbench-modal-close","aria-label":r??j("common.close"),...o,children:e.jsx(C,{})})}function R({open:a,title:r,description:o,hideHeader:l=!1,size:c="compact",layout:s="form",dismissible:n=!0,closeOnBackdrop:v=!0,closeOnEscape:y=!0,backdropVisible:E=!0,className:i,bodyClassName:u,titleClassName:N,titleRef:D,titleProps:I,headerActions:m,beforeCloseButton:M,footer:b,showCloseButton:h=!0,onClose:t,children:g}){const k=d.useId(),f=d.useId(),x=n&&v,w=n&&y,$=!n;return d.useEffect(()=>{if(!a||!w)return;function p(B){B.key==="Escape"&&t()}return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[w,t,a]),!a||typeof document>"u"?null:L.createPortal(e.jsxs("div",{className:"workbench-modal-layer desktop-modal-layer","data-fullscreen":c==="full"?"true":void 0,"data-layout":s,"data-backdrop-visible":E?"true":"false",children:[e.jsx("button",{type:"button",className:"workbench-modal-backdrop","aria-label":j("common.close"),disabled:!x,onClick:()=>{x&&t()}}),e.jsxs("section",{className:`workbench-modal-card surface-card desktop-modal-card${i?` ${i}`:""}`,"data-size":c,"data-layout":s,role:"dialog","aria-modal":"true","aria-labelledby":l?void 0:k,"aria-label":l?r:void 0,"aria-describedby":!l&&o?f:void 0,children:[l?null:e.jsxs("div",{className:"workbench-modal-header",children:[e.jsxs("div",{className:"workbench-modal-title-wrap",children:[e.jsx("h2",{id:k,className:N,ref:D,...I,children:r}),o?e.jsx("p",{id:f,children:o}):null]}),m||h?e.jsxs("div",{className:"workbench-modal-header-actions",children:[m,M,h?e.jsx(O,{disabled:$,onClick:()=>{n&&t()}}):null]}):null]}),e.jsx("div",{className:u?`workbench-modal-body ${u}`:"workbench-modal-body",children:g}),b?e.jsx("div",{className:"workbench-modal-footer",children:b}):null]})]}),document.body)}export{R as D,O as M};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/window-BVUB8gMK.js","assets/event-DvH9tcej.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{b as c,m as F,_ as q,j as t,t as d}from"./index-
|
|
2
|
+
import{b as c,m as F,_ as q,j as t,t as d}from"./index-_OCkVmfl.js";import{r as O,u as C,W as _,m as I,F as $,g as A}from"./WorkbenchLayout-D-U7ghT0.js";import{FileContextPanel as U}from"./FileContextPanel-C4syif3B.js";import{GitSidebar as V}from"./GitSidebar-DduL9aTV.js";import{TerminalManagerPanel as z}from"./TerminalManagerPanel-4OR47vcf.js";import{TerminalPage as B}from"./TerminalPage-Pvx396YX.js";import{b as H,a as K}from"./workbench-navigation-RyUjchbD.js";import{c as J,u as Q,e as X,N as W}from"./App-If9gThKM.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./DesktopModal-bMdI1jEe.js";import"./WorkbenchModal-xbx1o6MO.js";import"./relay-entry-B5GmiOrR.js";import"./MobileSheet-BXvQPkxt.js";import"./terminal-runtime-meta-DBsyT35T.js";import"./TerminalRuntimeFallbackModal-KvG6k4AQ.js";import"./MobileWorkspaceSwitcherHeader-DT330cAx.js";import"./MobileTopHeaderFrame-vdYOyaaB.js";function Y(n){return{navigationGroups:n,subscribeFileTree:()=>{},requestFileTreeRefresh:()=>{},addFileTreeSnapshotListener:()=>()=>{},subscribeGitSnapshot:()=>{},requestGitRefresh:()=>{},addGitSnapshotListener:()=>()=>{}}}function Z(){return{subscribeGitSnapshot:()=>{},requestGitRefresh:()=>{},addGitSnapshotListener:()=>()=>{}}}function ee(){return{subscribeTerminalManagerSnapshot:()=>{},requestTerminalManagerRefresh:()=>{},addTerminalManagerSnapshotListener:()=>()=>{}}}function re(n,a){return{navigationGroups:a,currentWorkspaceId:n,selectWorkspace:()=>{},subscribeTerminalManagerSnapshot:()=>{},requestTerminalManagerRefresh:()=>{},addTerminalManagerSnapshotListener:()=>()=>{}}}function x(n){return n.kind==="file-preview"?d("conversation.fileViewerWindowTitle"):n.kind==="files"?d("shell.filesEntry"):n.kind==="git"?d("shell.gitEntry"):n.kind==="processes"?d("shell.terminalManagerEntry"):n.kind==="terminals"?d("shell.terminalsEntry"):n.kind==="affairs"?d("shell.workbenchModeAffairs"):n.kind==="code"?d("shell.workbenchModeCode"):n.kind}function T(n,a){var s;return n.workspaceName??(n.workspaceId?((s=a.find(o=>o.workspace.id===n.workspaceId))==null?void 0:s.workspace.name)??null:null)}function j(n){const a=(n==null?void 0:n.trim().replace(/\\/g,"/"))??"";return a?a.split("/").filter(Boolean).at(-1)??a:null}function ne(n){var o,l;const a=((o=n.payload.routePath)==null?void 0:o.trim())??"";if(a)return a;const s=((l=n.workspaceId)==null?void 0:l.trim())??"";return s?H(s):null}function te(n){var o,l;const a=((o=n.payload.routePath)==null?void 0:o.trim())??"";return a||(((l=n.workspaceId)==null?void 0:l.trim())??""?K():null)}function ie(n,a){const s=T(n,a);if(n.kind==="file-preview"){const l=j(n.payload.filePath)??x(n);return s?`${l}(${s})`:l}const o=x(n);return s?`CodingNS - ${o}(${s})`:`CodingNS - ${o}`}function xe(){var N;const{windowId:n}=J(),a=Q(),s=X(),o=O(s),l=C(i=>i.sessionDisplaySortMode),[e,b]=c.useState(null),[D,w]=c.useState(!0),[M,v]=c.useState(null),[u,f]=c.useState([]),[r,S]=c.useState(null);c.useEffect(()=>{let i=!1;async function p(){if(!n){b(null),w(!1),v(d("desktopWindow.invalidWindowId"));return}w(!0),v(null);const h=await s.bridge.getWindowDescriptor(n),g=h.ok?h.value??null:s.windows.getDescriptor(n);if(!i){if(!g){b(null),w(!1),v(h.detail??d("desktopWindow.loadDescriptorFailed"));return}s.windows.registerDescriptor(g),s.windows.markWindowOpen(g.windowId),b(g),w(!1)}}return p(),()=>{i=!0}},[s,n]),c.useEffect(()=>{if(!(e!=null&&e.workspaceId)){f([]);return}let i=!1;async function p(){try{const h=await A();if(i)return;f(I(h,l))}catch{if(i)return;f([])}}return p(),()=>{i=!0}},[e==null?void 0:e.workspaceId,l]),c.useEffect(()=>{if(!e){S(null);return}const i=new _({onConnectionChange:()=>{},onSnapshot:p=>{f(I(p,l))},onUnauthorized:()=>{F.clear(),a(`/login?returnTo=${encodeURIComponent(`/desktop-window/${e.windowId}`)}`,{replace:!0})}});return S(i),i.start(),()=>{i.close(),S(null)}},[e,a,l]),c.useEffect(()=>{if(!s.isDesktop||!s.bridge.supported||!e||e.mode!=="external")return;const i=ie(e,u);document.title=i,q(async()=>{const{getCurrentWindow:p}=await import("./window-BVUB8gMK.js").then(h=>h.w);return{getCurrentWindow:p}},__vite__mapDeps([0,1])).then(({getCurrentWindow:p})=>p().setTitle(i)).catch(()=>{})},[e,u,s.bridge.supported,s.isDesktop]);const R=c.useMemo(()=>r?{navigationGroups:u,subscribeFileTree:r.subscribeFileTree.bind(r),requestFileTreeRefresh:r.requestFileTreeRefresh.bind(r),addFileTreeSnapshotListener:r.addFileTreeSnapshotListener.bind(r),subscribeGitSnapshot:r.subscribeGit.bind(r),requestGitRefresh:r.requestGitRefresh.bind(r),addGitSnapshotListener:r.addGitSnapshotListener.bind(r)}:Y(u),[u,r]),G=c.useMemo(()=>r?{subscribeGitSnapshot:r.subscribeGit.bind(r),requestGitRefresh:r.requestGitRefresh.bind(r),addGitSnapshotListener:r.addGitSnapshotListener.bind(r)}:Z(),[r]),P=c.useMemo(()=>r?{subscribeTerminalManagerSnapshot:r.subscribeTerminalManager.bind(r),requestTerminalManagerRefresh:r.requestTerminalManagerRefresh.bind(r),addTerminalManagerSnapshotListener:r.addTerminalManagerSnapshotListener.bind(r)}:ee(),[r]),y=c.useMemo(()=>r?{navigationGroups:u,currentWorkspaceId:(e==null?void 0:e.workspaceId)??null,selectWorkspace:()=>{},subscribeTerminalManagerSnapshot:r.subscribeTerminalManager.bind(r),requestTerminalManagerRefresh:r.requestTerminalManagerRefresh.bind(r),addTerminalManagerSnapshotListener:r.addTerminalManagerSnapshotListener.bind(r)}:re((e==null?void 0:e.workspaceId)??null,u),[e==null?void 0:e.workspaceId,u,r]);if(!s.isDesktop)return t.jsx(W,{to:"/",replace:!0});if(D)return t.jsx("main",{className:"desktop-window-page",children:t.jsx("p",{className:"status-text",children:d("common.loading")})});if(M)return t.jsx("main",{className:"desktop-window-page",children:t.jsx("p",{className:"status-text",children:M})});if(!e)return t.jsx("main",{className:"desktop-window-page",children:t.jsx("p",{className:"status-text",children:d("desktopWindow.loadDescriptorFailed")})});if(e.kind==="code"){const i=ne(e);return i?t.jsx(W,{to:i,replace:!0}):t.jsx("main",{className:"desktop-window-page",children:t.jsx("p",{className:"status-text",children:d("desktopWindow.invalidCodeTarget")})})}if(e.kind==="affairs"){const i=te(e);return i?t.jsx(W,{to:i,replace:!0}):t.jsx("main",{className:"desktop-window-page",children:t.jsx("p",{className:"status-text",children:d("desktopWindow.invalidAffairsTarget")})})}let m=null;if(e.kind==="file-preview"){const i=((N=e.payload.filePath)==null?void 0:N.trim())??"";T(e,u),m=i?t.jsx($,{workspaceId:e.workspaceId,filePath:i,open:!0,chrome:"window",windowTitle:j(i)??i,onClose:()=>void s.bridge.setWindowState("close"),onSaved:()=>{}}):t.jsx("p",{className:"status-text",children:d("desktopWindow.invalidFilePreviewTarget")})}else e.kind==="files"?m=t.jsx(U,{sessionId:e.sessionId,workspaceId:e.workspaceId,externalWindowMode:!0,workbenchShellOverrides:R}):e.kind==="git"?m=t.jsx(V,{workspaceId:e.workspaceId,externalWindowMode:!0,workbenchShellOverrides:G}):e.kind==="processes"?m=t.jsx(z,{currentWorkspaceId:e.workspaceId,navigationGroups:u,externalWindowMode:!0,workbenchShellOverrides:P}):e.kind==="terminals"&&(m=t.jsx(B,{externalWindowMode:!0,externalWindowWorkspaceId:e.workspaceId,workbenchShellOverrides:y}));if(!m)return t.jsx("main",{className:"desktop-window-page",children:t.jsx("p",{className:"status-text",children:d("desktopWindow.unsupportedKind",{kind:e.kind})})});const k=x(e),L=T(e,u),E=e.mode==="external"&&e.kind==="processes";return t.jsxs("main",{className:"desktop-window-page",children:[E?t.jsx("header",{className:"desktop-window-drag-header","data-window-kind":e.kind,"data-window-drag-handle":"desktop-window-drag-header","data-tauri-drag-region":o,"aria-label":k,children:t.jsxs("div",{className:"desktop-window-drag-header-copy","data-tauri-drag-region":o,children:[t.jsx("span",{className:"desktop-window-drag-header-tag","data-tauri-drag-region":o,children:k}),t.jsx("strong",{"data-tauri-drag-region":o,children:L??k})]})}):null,t.jsx("div",{className:"desktop-window-body","data-window-kind":e.kind,"aria-label":k,children:m})]})}export{xe as DesktopWindowPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as c,F as tn,j as i,t as r,G as ft,A as In}from"./index-BUoNjVrY.js";import{f as ei,e as _i,g as Fi}from"./App-DrNI9lWA.js";import{bG as Ai,bH as Li,bI as ti,bJ as nn,bK as Bi,bL as Mt,bM as Rt,b as Wi,u as $i,Y as _e,bN as Qt,bO as Oi,bP as Hi,bQ as Vi,bR as ut,bS as gt,bT as Xe,bU as Ui,bV as zi,bW as Ki,bX as Gi,bY as Xi}from"./WorkbenchLayout-CJHQtwuL.js";import{d as qi,M as Yi}from"./workbench-navigation-DlgXuFW2.js";import{W as $n}from"./WorkbenchModal-BM-OeW-b.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./DesktopModal-DRmDrv0S.js";import"./relay-entry-CQpxTS8y.js";import"./MobileSheet-nw5SCa3N.js";async function Nt(t,n){const[l,s]=await Promise.all([Ai(n),Li(t)]);return Ji(l.changes,s.items)}function Ji(t,n){const l=new Set(n.map(s=>Et(s.path)));return t.filter(s=>l.has(Et(s.path))||s.oldPath!==null&&l.has(Et(s.oldPath)))}function Qi(t){const n=On("","");for(const l of t){const s=Et(l.path),m=s.split("/").filter(Boolean);let h=n;m.forEach((b,x)=>{const j=m.slice(0,x+1).join("/");if(x===m.length-1){h.children.set(`file:${j}`,{kind:"file",name:b,path:s,change:l});return}const _=`directory:${j}`,M=h.children.get(_);if(M&&M.kind==="directory"){h=M;return}const Z=On(b,j);h.children.set(_,Z),h=Z})}return ai(ii([...n.children.values()]))}function ni(t,n){const l=t.oldPath?`${t.oldPath} -> ${t.path}`:t.path;return ln(t)?`${l} ${n}`:l}function ln(t){return t.status==="D"||t.stagedStatus==="D"||t.worktreeStatus==="D"}function Dt(t){return t.split("/").filter(Boolean).pop()??t}function Et(t){return t.replace(/\\/g,"/").replace(/^\.\//,"").trim()}function On(t,n){return{kind:"directory",name:t,path:n,children:new Map}}function ii(t){return[...t].sort((n,l)=>n.kind!==l.kind?n.kind==="directory"?-1:1:n.name.localeCompare(l.name,"zh-CN")).map(n=>n.kind==="directory"?{kind:"directory",name:n.name,path:n.path,children:ii([...n.children.values()])}:n)}function ai(t){return t.map(n=>{var b;if(n.kind!=="directory")return n;const l=ai(n.children);let s=n.name,m=n.path,h=l;for(;h.length===1&&((b=h[0])==null?void 0:b.kind)==="directory";){const x=h[0];s=`${s}/${x.name}`,m=x.path,h=x.children}return{kind:"directory",name:s,path:m,children:h}})}const Zi=450,Ii=60*1e3,Hn=20,Vn=16;function ea({sessionId:t,workspaceId:n,showSystemFiles:l,selectedPath:s,refreshVersion:m,onCountChange:h,onSelectFile:b,onOpenFile:x}){const[j,_]=c.useState("tree"),[M,Z]=c.useState([]),[ye,K]=c.useState(!0),[xe,ge]=c.useState(!1),[G,ht]=c.useState([]),E=c.useRef(null),_t=ti(),{showToast:Ne}=ei();c.useEffect(()=>{const p=tn(Ct(n,t),Ii);_("tree"),Z(p??[]),K(p===null),ge(!1),ht([]),E.current=null},[t,n]),c.useEffect(()=>{let p=!1;async function w(){K(!0);try{const v=await Nt(t,n);p||(Z(v),ft(Ct(n,t),v))}catch(v){p||Ne({title:Zt(v,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{p||K(!1)}}return w(),()=>{p=!0}},[m,t,Ne,n]);async function De(){K(!0);try{const p=await Nt(t,n);Z(p),ft(Ct(n,t),p)}catch(p){Ne({title:Zt(p,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{K(!1)}}async function D(){if(R.length!==0){ge(!0);try{await Bi(n,R.map(w=>w.path));const p=await Nt(t,n);Z(p),ft(Ct(n,t),p),Ne({title:r("conversation.filePanelSessionStageSuccess"),tone:"success"})}catch(p){Ne({title:Zt(p,r("git.stageFailed")),tone:"error"})}finally{ge(!1)}}}function F(p){ht(w=>w.includes(p)?w.filter(v=>v!==p):[...w,p])}function X(p){const w=Date.now(),v=E.current;return E.current={filePath:p,timestamp:w},(v==null?void 0:v.filePath)===p&&w-v.timestamp<=Zi}async function $(p,w){if(w&&X(p)){await x(p),E.current=null;return}w||(E.current=null),await b(p)}const ie=c.useMemo(()=>nn(M,p=>Dt(p.path),l),[M,l]),R=ie.filter(p=>!p.staged),Fe=Qi(ie),ae=new Set(G);return c.useEffect(()=>{h==null||h(ie.length)},[h,ie.length]),i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"file-panel-session-toolbar",children:[i.jsxs("div",{className:"file-panel-view-modes",role:"tablist","aria-label":r("conversation.filePanelSessionViewLabel"),children:[i.jsx("button",{className:j==="tree"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":j==="tree",onClick:()=>_("tree"),children:r("conversation.filePanelSessionTreeView")}),i.jsx("button",{className:j==="list"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":j==="list",onClick:()=>_("list"),children:r("conversation.filePanelSessionListView")})]}),i.jsxs("div",{className:"file-panel-session-actions",children:[i.jsx("button",{className:"secondary-button",type:"button",onClick:()=>void De(),disabled:ye||xe,children:r("conversation.filePanelRefresh")}),i.jsx("button",{className:"primary-button",type:"button",onClick:()=>void D(),disabled:xe||R.length===0,children:r("conversation.filePanelSessionStageAll")})]})]}),i.jsxs("div",{className:"file-panel-session-summary",children:[i.jsx("span",{children:`${r("conversation.filePanelSessionSummary")} ${ie.length}`}),i.jsx("span",{children:`${r("conversation.filePanelSessionUnstagedSummary")} ${R.length}`})]}),i.jsx("div",{ref:_t,className:"file-tree","data-scrollbar-autohide":"true",children:ye?i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSessionLoading")}):ie.length===0?i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSessionEmpty")}):j==="tree"?li({nodes:Fe,depth:0,collapsedPathSet:ae,selectedPath:s,onToggleTreePath:F,onFileClick:$}):ta({items:ie,selectedPath:s,onFileClick:$})})]})}function li({nodes:t,depth:n,collapsedPathSet:l,selectedPath:s,onToggleTreePath:m,onFileClick:h}){return t.map(b=>{if(b.kind==="directory"){const x=!l.has(b.path);return i.jsxs("div",{className:"file-tree-node",children:[i.jsxs("button",{className:"file-tree-item",type:"button","data-kind":"directory","aria-expanded":x,style:{paddingInlineStart:`${Hn+n*Vn}px`},onClick:()=>m(b.path),children:[i.jsx("span",{className:"file-tree-chevron","aria-hidden":"true",children:x?"v":">"}),i.jsx("span",{className:"file-tree-label",children:b.name})]}),x?i.jsx("div",{className:"file-tree-children",children:li({nodes:b.children,depth:n+1,collapsedPathSet:l,selectedPath:s,onToggleTreePath:m,onFileClick:h})}):null]},`session-directory:${b.path}`)}return i.jsx("div",{className:"file-tree-node",children:i.jsxs("button",{className:"file-tree-item is-session-change",type:"button","data-active":s===b.change.path,"data-kind":"file",style:{paddingInlineStart:`${Hn+n*Vn}px`},onClick:()=>void h(b.change.path,!ln(b.change)),children:[i.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(b.name),"aria-hidden":"true",children:Mt(b.name)}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:b.name}),i.jsx("span",{className:"file-tree-path",children:ni(b.change,r("conversation.filePanelSessionDeleted"))})]}),i.jsxs("span",{className:"file-session-item-meta",children:[i.jsx("span",{className:"file-session-badge","data-status":b.change.status,children:b.change.status}),i.jsx("span",{className:"file-session-badge subtle",children:b.change.staged?r("git.stagedLabel"):r("git.workingTreeLabel")})]})]})},`session-file:${b.path}`)})}function ta({items:t,selectedPath:n,onFileClick:l}){return t.map(s=>i.jsx("div",{className:"file-session-list-item",children:i.jsxs("button",{className:"file-session-list-button",type:"button","data-active":n===s.path,onClick:()=>void l(s.path,!ln(s)),children:[i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(Dt(s.path)),"aria-hidden":"true",children:Mt(Dt(s.path))}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:Dt(s.path)}),i.jsx("span",{className:"file-tree-path",children:ni(s,r("conversation.filePanelSessionDeleted"))})]}),i.jsxs("span",{className:"file-session-item-meta",children:[i.jsx("span",{className:"file-session-badge","data-status":s.status,children:s.status}),i.jsx("span",{className:"file-session-badge subtle",children:s.staged?r("git.stagedLabel"):r("git.workingTreeLabel")})]})]})},`session-list:${s.path}`))}function Ct(t,n){return`file-panel.session-changes.${t}.${n}`}function Zt(t,n){return t instanceof In?t.message:typeof t=="object"&&t&&"message"in t?String(t.message??n):n}const g="",na=450,ne=8,Pt=4,ia=176,aa=120,la=300*1e3,oa=60*1e3,Un=1600,ra=220,sa=20,ca=16;function ua(){if(typeof document>"u")return;const t=document.querySelector(".workbench-modal-card.file-viewer-modal"),n=t==null?void 0:t.getBoundingClientRect();if(!(!n||n.width<=0||n.height<=0))return{width:Math.round(n.width),height:Math.round(n.height),minWidth:720,minHeight:480}}function nl({className:t,sessionId:n,workspaceId:l,hideHeading:s=!1,hideTabs:m=!1,externalRevealRequest:h=null,externalWindowMode:b=!1,workbenchShellOverrides:x}){var Ln,Bn;const j=Wi(),{navigationGroups:_,subscribeFileTree:M,requestFileTreeRefresh:Z,addFileTreeSnapshotListener:ye,subscribeGitSnapshot:K,requestGitRefresh:xe,addGitSnapshotListener:ge}={...j,...x},[G,ht]=c.useState({}),[E,_t]=c.useState([]),[Ne,De]=c.useState([]),[D,F]=c.useState(g),[X,$]=c.useState([]),[ie,R]=c.useState(null),[Fe,ae]=c.useState(!1),[p,w]=c.useState(!1),[v,mt]=c.useState(!1),[Ye,Je]=c.useState(!1),[A,Qe]=c.useState(""),[Ft,q]=c.useState(null),[pt,bt]=c.useState(!1),[le,Ae]=c.useState(null),[O,Ze]=c.useState("workspace"),[rn,Ee]=c.useState(0),[sn,At]=c.useState(0),[Ie,I]=c.useState(!1),[et,L]=c.useState(!1),[oe,H]=c.useState(null),[Ce,Le]=c.useState(null),[B,Be]=c.useState(null),[C,Lt]=c.useState(null),[S,tt]=c.useState(null),[Bt,We]=c.useState(""),[cn,un]=c.useState([]),[ee,Wt]=c.useState(!1),[hi,re]=c.useState(null),fn=c.useId(),se=c.useRef({}),Y=c.useRef({}),T=c.useRef([]),te=c.useRef(g),nt=c.useRef(!1),it=c.useRef(null),mi=ti(),dn=c.useRef(null),hn=c.useRef(null),$t=c.useRef(null),mn=c.useRef(null),pn=c.useRef(null),ce=c.useRef(0),ue=c.useRef(new Map),{showToast:P}=ei(),Pe=_i(),V=$i(e=>e.showSystemFiles),$e=!!(n!=null&&n.trim()),bn=s&&Pe.isMobile;c.useEffect(()=>{_e("file_panel.props",{sessionId:n,workspaceId:l,externalWindowMode:b})},[b,n,l]),c.useEffect(()=>{te.current=D},[D]);function Ot(e){At(e),!(!l||!n)&&ft(Yn(l,n),e)}async function vn(){if(!l||!n){Ot(0);return}const e=await Nt(n,l),a=nn(e,o=>ut(o.path),V).length;Ot(a)}function ke(e){ht(a=>{const o=typeof e=="function"?e(a):e;return se.current=o,o})}function Oe(e){_t(a=>{const o=typeof e=="function"?e(a):e;return T.current=o,o})}c.useEffect(()=>{var f,d;if(zt(),!l){zt(),nt.current=!1,se.current={},Y.current={},T.current=[],te.current=g,ke({}),Oe([]),De([]),F(g),Je(!1),Qe(""),q(null),bt(!1),ae(!1),Wt(!1),re(null),$([]),R(null),H(null),Le(null),Be(null),tt(null),We("");return}nt.current=!0;const e=tn(qn(l),la);_e("file_panel.workspace_snapshot",{workspaceId:l,cached:!!e,cachedRootItems:((d=(f=e==null?void 0:e.treeCache)==null?void 0:f[g])==null?void 0:d.length)??0,cachedDirectoryCount:Object.keys((e==null?void 0:e.treeCache)??{}).length});const a=Ea((e==null?void 0:e.activeDirectoryPath)??g,(e==null?void 0:e.treeCache)??{}),o=Xn((e==null?void 0:e.expandedDirectories)??[],a),u=St((e==null?void 0:e.treeCache)??{},a,o);se.current=u,Y.current=Jn((e==null?void 0:e.treeRevisionByPath)??{},u),T.current=o,te.current=a,ke(u),Oe(o),De([]),F(a),ae(!1),w(!1),Je(!1),Qe(""),q(null),bt(!1),queueMicrotask(()=>{nt.current=!1})},[l]),c.useEffect(()=>{if(!h||h.workspaceId!==l)return;const e=()=>{if(pn.current===h.requestId)return;pn.current=h.requestId,Ze("workspace"),(h.openViewer?ze(h.filePath):he(h.filePath)).catch(o=>{P({title:Q(o,r("conversation.filePanelOpenFailed")),tone:"error"})})};if(nt.current){queueMicrotask(e);return}e()},[h,ze,he,P,l]),c.useEffect(()=>{if(l)return ye(e=>{e.workspaceId===l&&(Y.current={...Y.current,[e.path]:typeof e.revision=="string"?e.revision:null},ke(a=>({...a,[e.path]:e.items})),e.path===g&&ae(!1),De(a=>a.filter(o=>o!==e.path)),wn(e.path,e.items))})},[ye,l]),c.useEffect(()=>()=>{zt()},[]),c.useEffect(()=>{l&&M(l,en(T.current,te.current),{knownRevisionByPath:Y.current})},[D,E,M,l]),c.useEffect(()=>{$([]),R(null),Ae(null),re(null),Ee(0),I(!1),L(!1),H(null),Le(null),Be(null),tt(null),We(""),it.current=null,ce.current+=1},[n]),c.useEffect(()=>{!$e&&O==="session"&&Ze("workspace")},[O,$e]),c.useEffect(()=>{m&&O!=="workspace"&&Ze("workspace")},[O,m]),c.useEffect(()=>{if(!Ie&&!et&&!oe)return;function e(o){var y,N,pe;if(!(o.target instanceof Node))return;const u=((y=dn.current)==null?void 0:y.contains(o.target))??!1,f=((N=hn.current)==null?void 0:N.contains(o.target))??!1,d=((pe=$t.current)==null?void 0:pe.contains(o.target))??!1;!u&&!f&&!d&&(I(!1),L(!1),H(null),Le(null))}function a(o){o.key==="Escape"&&(I(!1),L(!1),H(null),Le(null))}return document.addEventListener("pointerdown",e),document.addEventListener("keydown",a),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",a)}},[Ie,et,oe]),c.useLayoutEffect(()=>{if(!oe||typeof window>"u"){Le(null);return}const e=oe;function a(){const u=$t.current;if(!u)return;const f=u.getBoundingClientRect();Le(ya({x:e.positionX,y:e.positionY},{width:f.width||ia,height:f.height||u.scrollHeight||0},{width:window.innerWidth,height:window.innerHeight}))}a();const o=window.requestAnimationFrame(a);return window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),()=>{window.cancelAnimationFrame(o),window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0)}},[oe]),c.useEffect(()=>{if(!l)return;const e=Xn(E,D),a=St(G,D,e);ft(qn(l),{treeCache:a,treeRevisionByPath:Jn(Y.current,a),expandedDirectories:e,activeDirectoryPath:D})},[D,E,G,l]),c.useEffect(()=>{if(nt.current)return;const e=St(G,D,E);Ma(G,e)||ke(e)},[D,E,G]),c.useEffect(()=>{let e=!1;const a=(l==null?void 0:l.trim())??null;async function o(f){if(!a)return;const d=Qt(se.current[g]??[],V),y=(f==null?void 0:f.silent)!==!0&&d.length===0;y&&ae(!0),_e("file_panel.load_root_tree.start",{sessionId:n,workspaceId:a,silent:(f==null?void 0:f.silent)===!0,cachedRootItems:d.length});try{const N=await Ut(g,{force:!0});e||(_e("file_panel.load_root_tree.end",{sessionId:n,workspaceId:a,itemCount:N.length}),ke(pe=>({...St(pe,te.current,T.current),[g]:N})))}catch(N){!e&&!Qn(N)&&P({title:Q(N,r("conversation.filePanelLoadFailed")),tone:"error"})}finally{!e&&y&&ae(!1)}}if(Qt(se.current[g]??[],V).length>0){const f=window.setTimeout(()=>{a&&(M(a,en(T.current,te.current),{knownRevisionByPath:Y.current}),o({silent:!0}))},1500);return()=>{e=!0,window.clearTimeout(f)}}return o(),()=>{e=!0}},[n,V,P,l]),c.useEffect(()=>{if(!l||!n){At(0);return}const e=tn(Yn(l,n),oa);_e("file_panel.session_change_count.snapshot",{sessionId:n,workspaceId:l,cached:e!==null,cachedCount:e}),At(e??0);let a=!1;return vn().catch(()=>{}),()=>{a=!0}},[n,rn,V,l]),c.useEffect(()=>{if(!l){un([]);return}const e=l.trim();K(e),xe(e)},[l,K,xe]),c.useEffect(()=>{if(!l)return;const e=l.trim();return ge(a=>{var o;a.workspaceId===e&&un(((o=a.status)==null?void 0:o.changes)??[])})},[ge,l]);const vt=c.useMemo(()=>nn(cn,e=>ut(e.path),V),[cn,V]),W=c.useMemo(()=>{const e=new Map,a=new Set;for(const o of vt){const u=o.path.replace(/\\/g,"/"),f=o.worktreeStatus??o.stagedStatus??o.status;e.set(u,f);const d=u.split("/");for(let y=1;y<d.length;y++)a.add(d.slice(0,y).join("/"))}return{statusByPath:e,changedDirs:a}},[vt]),Me=c.useMemo(()=>Oi(G,V),[V,G]),Re=c.useMemo(()=>Ft===null?null:Qt(Ft,V),[Ft,V]),He=Me[g]??[],fe=Ye&&Re!==null,yt=c.useMemo(()=>ee?an(He,Me,W.statusByPath,W.changedDirs):He,[W.changedDirs,W.statusByPath,He,ee,Me]),pi=c.useMemo(()=>fe?(Re??[]).map(e=>z(e.path,e.kind)):oi(yt,Me,E,ee,W.statusByPath,W.changedDirs),[E,W.changedDirs,W.statusByPath,fe,ee,Re,Me,yt]),de=((Ln=_.find(e=>e.workspace.id===l))==null?void 0:Ln.workspace)??null,k=Gn(X),Ht=(k==null?void 0:k.path)??null,je=(k==null?void 0:k.kind)==="file"?k.path:null,xt=c.useMemo(()=>new Set(X.map(e=>e.path)),[X]),at=c.useMemo(()=>wt(X),[X]),Vt=!!(de!=null&&de.path&&X.length===1&&Ht),yn=X.length===1&&(k==null?void 0:k.kind)==="file",xn=at.length>0,Te=at.length>0,lt=!!(C!=null&&C.items.length&&l),gn=!!l&&X.length===1&&k!==null,Cn=!!((je?ve(je):D)&&E.length),Pn=C?C.mode==="copy"?r("conversation.filePanelClipboardCopyReady",{count:C.items.length}):r("conversation.filePanelClipboardCutReady",{count:C.items.length}):null,U=S?Pa(S):null;async function jn(e,a=!1){if(!l)return[];if(!a){const o=se.current[e];if(o)return o}e===g?ae(!0):De(o=>kt(o,e));try{const o=await Ut(e,{force:a});return ke(u=>({...u,[e]:o})),o}catch(o){throw Qn(o)||P({title:Q(o,r("conversation.filePanelLoadFailed")),tone:"error"}),o}finally{e===g?ae(!1):De(o=>o.filter(u=>u!==e))}}async function we(e){if(!l)return;const a=(e==null?void 0:e.activeDirectoryPath)??te.current,o=(e==null?void 0:e.expandedDirectories)??T.current,u=ka(se.current,a,o);_e("file_panel.refresh_tree_cache.start",{sessionId:n,workspaceId:l,targetDirectories:u});const d=(await Promise.all(u.map(async y=>{const N=await Ut(y,{force:!0});return[y,N]}))).reduce((y,[N,pe])=>(y[N]=pe,y),{});_e("file_panel.refresh_tree_cache.end",{sessionId:n,workspaceId:l,targetDirectories:u,directoryCount:Object.keys(d).length}),ke(d)}async function Ut(e,a){if(!l)return[];if(!(a!=null&&a.force)){const d=se.current[e];if(d)return d}const o=en(kt(T.current,e),e||te.current);M(l,o,{knownRevisionByPath:Y.current}),Z(l,[e],{knownRevisionByPath:Y.current});const u=bi(e,Un,{allowCached:(a==null?void 0:a.force)!==!0}),f=Ra(ra).then(async()=>{if(!l)return[];const y=(await Gi(l,e||void 0)).items;return Y.current={...Y.current,[e]:null},wn(e,y),y});try{return await Promise.race([u,f])}catch(d){if(!fi(d))throw d;return await f}}function bi(e,a=Un,o){const u=se.current[e];return(o==null?void 0:o.allowCached)!==!1&&u?Promise.resolve(u):new Promise((f,d)=>{const y=window.setTimeout(()=>{vi(e,y),d(new Error(`FILE_TREE_SNAPSHOT_TIMEOUT:${e}`))},a),N=ue.current.get(e)??[];ue.current.set(e,[...N,{resolve:f,reject:d,timerId:y}])})}function wn(e,a){const o=ue.current.get(e)??[];o.length!==0&&(ue.current.delete(e),o.forEach(u=>{window.clearTimeout(u.timerId),u.resolve(a)}))}function vi(e,a){const u=(ue.current.get(e)??[]).filter(f=>f.timerId!==a);if(u.length===0){ue.current.delete(e);return}ue.current.set(e,u)}function zt(){for(const[e,a]of ue.current.entries())a.forEach(o=>{window.clearTimeout(o.timerId),o.reject(new Error(`FILE_TREE_ABORTED:${e}`))});ue.current.clear()}function Ve(e){$([e]),R(e.path)}function ot(e){F(e.kind==="directory"?e.path:ve(e.path))}function yi(e){const a=ha(pi,ie,e);$(a),R(e.path),ot(e)}function xi(e){const a=da(X,e),o=Gn(a);$(a),R(e.path),o&&ot(o)}function Sn(e){Ve(e),ot(e)}function Ue(e,a){if(a!=null&&a.shiftKey){yi(e);return}if(jt(a)){xi(e);return}Sn(e)}async function rt(e,a=!1){const o=dt(e,a);if(!o.length){F(g);return}Oe(u=>ui(u,o)),F(o[o.length-1]??g);for(const u of o)try{await jn(u)}catch{return}}async function he(e){const a=z(e,"file");Ve(a),ot(a),await rt(e)}async function ze(e){Ae(e),re(null),it.current=null,ce.current+=1,he(e),await gi(e)}async function gi(e){const a=ce.current,o=e.replace(/\\/g,"/"),u=W.statusByPath.get(o);if(l&&u&&u!=="?"&&u!=="D")try{const f=await Hi(l,e,!1);ce.current===a&&re(f.content||null)}catch{ce.current===a&&re(null)}}async function Ci(e){if(!l)return;const a=ua(),o=await Ui(Pe,{workspaceId:l,workspaceName:(de==null?void 0:de.name)??null,sessionId:n??null,filePath:e,bounds:a});if(!o.ok){P({title:o.detail??r("conversation.fileViewerOpenInWindowFailed"),tone:"error"});return}ce.current+=1,Ae(null),re(null)}function Nn(e){const a=Date.now(),o=it.current;return it.current={filePath:e,timestamp:a},(o==null?void 0:o.filePath)===e&&a-o.timestamp<=na}function Se(){it.current=null}async function Pi(e,a){const o=z(e,"file");if(a!=null&&a.shiftKey||jt(a)){Se(),Ue(o,a);return}if(Nn(e)){await ze(e);return}Ue(o,a),await rt(e)}function Dn(){Je(!1),Qe(""),q(null),Se()}async function ji(e,a){const o=z(e.path,e.kind);if(a!=null&&a.shiftKey||jt(a)){Se(),Ue(o,a);return}if(e.kind==="directory"){Dn(),Ue(o,a),await En(e.path);return}if(Nn(e.path)){Dn(),await ze(e.path);return}await he(e.path)}async function En(e){if(Ve(z(e,"directory")),F(e),!T.current.includes(e))try{await jn(e),Oe(a=>kt(a,e))}catch{}}async function kn(e){if(Ve(z(e,"directory")),F(e),T.current.includes(e)){Mn(e);return}await En(e)}function Mn(e){Oe(a=>a.filter(o=>o!==e&&!o.startsWith(`${e}/`))),F(ve(e)),$([]),R(null)}async function Rn(){if(!l)return;const e=l;try{if(xe(e),await we(),je&&await rt(je),fe&&A.trim()){const a=await Xe(e,A.trim());q(a.items)}if($e&&n)if(O==="session")Ee(a=>a+1);else try{await vn()}catch(a){P({title:Q(a,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}}catch(a){P({title:Q(a,r("conversation.filePanelLoadFailed")),tone:"error"})}}async function wi(e){if(e==null||e.preventDefault(),!l||!A.trim()){q(null);return}bt(!0);try{const a=await Xe(l,A.trim());q(a.items)}catch(a){P({title:Q(a,r("conversation.filePanelSearchFailed")),tone:"error"})}finally{bt(!1)}}function Tn(){if(Ye){Je(!1),Qe(""),q(null);return}Je(!0)}function J(e){L(!1),e()}function _n(){var e;(e=mn.current)==null||e.click()}async function Si(e){var d;const a=((d=e.target.files)==null?void 0:d[0])??null;if(e.target.value="",!a||!l)return;const o=fa(a.name);if(!o){P({title:r("conversation.filePanelUploadFailed"),tone:"error"});return}const u=zn(D,k),f=Kn(u,o);mt(!0);try{const y=await ja(a);await zi({workspaceId:l,path:f,contentBase64:y}),await we(),await he(f),P({title:r("conversation.filePanelUploadSuccess",{name:o}),tone:"success"})}catch(y){P({title:Q(y,r("conversation.filePanelUploadFailed")),tone:"error"})}finally{mt(!1)}}async function Kt(e=je){if(!(!l||!e)){mt(!0);try{const a=await Ki(l,e),o=wa(a.contentBase64);Sa(a.fileName,new Blob([o],{type:"application/octet-stream"})),P({title:r("conversation.filePanelDownloadSuccess",{name:a.fileName}),tone:"success"})}catch(a){P({title:Q(a,r("conversation.filePanelDownloadFailed")),tone:"error"})}finally{mt(!1)}}}function Fn(){const e=je?ve(je):D;!e||!T.current.includes(e)||Mn(e)}function Gt(){tt(null),We("")}function Xt(){p||Gt()}function Ke(e,a=zn(D,k)){if(!l)return;const o=a,u=o?`${o}/`:"";I(!1),L(!1),H(null),tt({mode:e,baseDirectory:o}),We(u)}function qt(e=k){!l||!e||(I(!1),L(!1),H(null),tt({mode:"rename",target:e}),We(e.path))}async function Ni(e){if(e==null||e.preventDefault(),!l||!S)return;const a=(Bt??"").trim();if(a){if(S.mode==="rename"&&qe(S.target.path)===qe(a)){Xt();return}w(!0);try{if(S.mode==="rename"){const o=S.target.path,u=z(a,S.target.kind),f=le?ci(le,o,a):null;if(await gt({workspaceId:l,opType:"rename",srcPath:o,dstPath:a}),C&&Lt({...C,items:Ca(C.items,o,a)}),Gt(),Se(),await we(),S.target.kind==="directory"?(await rt(a,!0),Ve(u),F(a)):await he(a),f!==le&&(ce.current+=1,Ae(f),re(null)),fe&&A.trim()){const d=await Xe(l,A.trim());q(d.items)}Ee(d=>d+1),P({title:r("conversation.filePanelRenameSuccess",{name:ut(a)||a}),tone:"success"});return}if(await gt({workspaceId:l,opType:S.mode,dstPath:a,content:S.mode==="create_file"?"":void 0}),Gt(),await we(),S.mode==="create_directory"?(await rt(a,!0),Ve(z(a,"directory")),F(a)):await he(a),fe&&A.trim()){const o=await Xe(l,A.trim());q(o.items)}Ee(o=>o+1)}catch(o){P({title:Q(o,r("conversation.filePanelMutateFailed")),tone:"error"})}finally{w(!1)}}}function me(e,a=at){var u;if(a.length===0)return;const o=wt(a);Lt({mode:e,items:o}),$(o),R(((u=o[o.length-1])==null?void 0:u.path)??null),P({title:e==="copy"?r("conversation.filePanelCopySelectionSuccess",{count:o.length}):r("conversation.filePanelCutSelectionSuccess",{count:o.length}),tone:"success"}),H(null)}async function st(e=ba(k,D)){if(!l||!C||!C.items.length)return;const a=e??g,o=C.items.map(u=>({source:u,destinationPath:Kn(a,ut(u.path)||u.path)}));w(!0);try{for(const d of o)C.mode==="cut"&&qe(d.source.path)===qe(d.destinationPath)||await gt({workspaceId:l,opType:C.mode==="copy"?"copy":"move",srcPath:d.source.path,dstPath:d.destinationPath});const u=o.map(d=>z(d.destinationPath,d.source.kind)),f=u[u.length-1]??null;if(C.mode==="cut"&&Lt(null),$(u),R((f==null?void 0:f.path)??null),f&&ot(f),Se(),await we({activeDirectoryPath:(f==null?void 0:f.kind)==="directory"?f.path:f?ve(f.path):te.current,expandedDirectories:T.current}),fe&&A.trim()){const d=await Xe(l,A.trim());q(d.items)}Ee(d=>d+1),P({title:r("conversation.filePanelPasteSuccess",{count:u.length}),tone:"success"}),H(null)}catch(u){await we().catch(()=>{}),P({title:Q(u,r("conversation.filePanelPasteFailed")),tone:"error"})}finally{w(!1)}}function Yt(e=at){!e.length||p||(Be(wt(e)),H(null))}async function Di(){var a,o;if(!l||!(B!=null&&B.length))return;const e=wt(B);w(!0);try{for(const d of e)await gt({workspaceId:l,opType:"delete",srcPath:d.path});const u=va(D,e),f=T.current.filter(d=>!e.some(y=>y.kind==="directory"&&Tt(y.path,d)));if(le&&e.some(d=>Tt(d.path,le))&&(ce.current+=1,Ae(null),re(null)),Be(null),$([]),R(null),te.current=u,T.current=f,F(u),Oe(f),Se(),await we({activeDirectoryPath:u,expandedDirectories:f}),fe&&A.trim()){const d=await Xe(l,A.trim());q(d.items)}Ee(d=>d+1),P({title:e.length===1?r("conversation.filePanelDeleteSuccess",{name:ut(((a=e[0])==null?void 0:a.path)??"")||((o=e[0])==null?void 0:o.path)||""}):r("conversation.filePanelDeleteSelectionSuccess",{count:e.length}),tone:"success"})}catch(u){P({title:Q(u,r("conversation.filePanelMutateFailed")),tone:"error"})}finally{w(!1)}}async function Ge(e,a=k){const o=(de==null?void 0:de.path)??"",u=(a==null?void 0:a.path)??null;if(u===null||!o){I(!1);return}try{const f=ga(o),d=e==="absolute"?xa(o,u,f):qe(u,f);await Na(d,Pe),P({title:e==="absolute"?r("conversation.filePanelCopyAbsolutePathSuccess"):r("conversation.filePanelCopyRelativePathSuccess"),tone:"success"})}catch(f){P({title:f instanceof Error?f.message:r("conversation.filePanelCopyPathFailed"),tone:"error"})}finally{I(!1),H(null)}}function Ei(e,a,o){return[{id:`open-${e.path}`,label:e.kind==="directory"?E.includes(e.path)?r("conversation.filePanelCollapseDirectory"):r("conversation.filePanelExpandDirectory"):r("conversation.filePanelOpenFile"),onSelect:()=>{if(e.kind==="directory"){kn(e.path);return}ze(e.path)}},{id:`download-${e.path}`,label:r("conversation.filePanelDownload"),disabled:e.kind!=="file"||v,onSelect:()=>{Kt(e.kind==="file"?e.path:null)}},{id:`create-file-${e.path}`,label:r("conversation.filePanelNewFile"),disabled:!l||p||v,onSelect:()=>{Ke("create_file",o)}},{id:`create-directory-${e.path}`,label:r("conversation.filePanelNewDirectory"),disabled:!l||p||v,onSelect:()=>{Ke("create_directory",o)}},{id:`rename-${e.path}`,label:r("conversation.filePanelRenameMove"),disabled:a.length!==1||p||v,onSelect:()=>qt(e)},{id:`copy-${e.path}`,label:r("conversation.filePanelCopy"),disabled:a.length===0,onSelect:()=>me("copy",a)},{id:`cut-${e.path}`,label:r("conversation.filePanelCut"),disabled:a.length===0,onSelect:()=>me("cut",a)},{id:`paste-${e.path}`,label:r("conversation.filePanelPaste"),disabled:!lt,onSelect:()=>{st(o)}},{id:`copy-relative-${e.path}`,label:r("conversation.filePanelCopyRelativePath"),onSelect:()=>{Ge("relative",e)}},{id:`copy-absolute-${e.path}`,label:r("conversation.filePanelCopyAbsolutePath"),onSelect:()=>{Ge("absolute",e)}},{id:`delete-${e.path}`,label:r("conversation.filePanelDelete"),disabled:a.length===0||p||v,onSelect:()=>Yt(a)}]}async function An(e,a){if(Pe.isMobile)return;e.preventDefault();const o=z(a.path,a.kind),u=xt.has(o.path)?at:[o],f=o.kind==="directory"?o.path:ve(o.path);xt.has(o.path)||Sn(o);const d=Ei(o,u,f);if(Pe.isDesktop){await Xi(d);return}Pe.isWeb&&(I(!1),L(!1),H({positionX:e.clientX,positionY:e.clientY,items:d}))}c.useEffect(()=>{if(O!=="workspace")return;function e(a){if(!ma(a)||a.altKey||a.shiftKey||pa(a.target))return;const o=a.key.toLowerCase();if(o==="c"&&Te){a.preventDefault(),me("copy");return}if(o==="x"&&Te){a.preventDefault(),me("cut");return}o==="v"&<&&(a.preventDefault(),st())}return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[O,Te,lt,me,st]);function Jt(e,a){return i.jsx(i.Fragment,{children:e.map(o=>{const u=z(o.path,o.kind),f=o.kind==="directory",d=f&&E.includes(o.path),y=f&&Ne.includes(o.path),N=Me[o.path]??[],pe=ee?an(N,Me,W.statusByPath,W.changedDirs):N,Mi=xt.has(o.path),Ri=Ht===o.path,ct=W.statusByPath.get(o.path.replace(/\\/g,"/")),Wn=f&&W.changedDirs.has(o.path.replace(/\\/g,"/")),Ti=(C==null?void 0:C.mode)==="cut"&&C.items.some(be=>be.path===o.path);return i.jsxs("div",{className:"file-tree-node",children:[i.jsxs("button",{className:"file-tree-item",type:"button","data-active":Ri,"data-selected":Mi,"data-cut-pending":Ti||void 0,"data-kind":o.kind,"aria-expanded":f?d:void 0,style:{paddingInlineStart:`${sa+a*ca}px`},onClick:be=>{if(f){if(be.shiftKey||jt(be)){Se(),Ue(u,be);return}Se(),Ue(u,be),kn(o.path);return}Pi(o.path,be)},onContextMenu:be=>{An(be,o)},children:[i.jsx("span",{className:`file-tree-chevron${f?"":" is-hidden"}`,"aria-hidden":"true",children:d?"v":">"}),f?null:i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(o.name),"aria-hidden":"true",children:Mt(o.name)}),i.jsx("span",{className:"file-tree-label","data-status":ct??void 0,"data-has-changes":Wn||void 0,children:o.name}),!f&&ct?i.jsx("span",{className:"git-status-badge","data-status":ct,"aria-label":ct,children:ct}):null,f&&Wn?i.jsx("span",{className:"file-tree-dir-badge","aria-hidden":"true"}):null,y?i.jsx("span",{className:"file-tree-meta",children:r("common.loading")}):null]}),f&&d?i.jsx("div",{className:"file-tree-children",children:y&&!N.length?i.jsx("p",{className:"file-tree-empty",children:r("common.loading")}):pe.length?Jt(pe,a+1):i.jsx("p",{className:"file-tree-empty",children:r("conversation.filePanelEmptyDirectory")})}):null]},`${o.kind}-${o.path}`)})})}function ki(e){return i.jsx(i.Fragment,{children:e.map(a=>{const o=a.kind==="directory",u=xt.has(a.path),f=Ht===a.path;return i.jsx("div",{className:"file-tree-node",children:i.jsxs("button",{className:"file-tree-item is-search-result",type:"button","data-active":f,"data-selected":u,"data-kind":a.kind,onClick:d=>{ji(a,d)},onContextMenu:d=>{An(d,a)},children:[i.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),o?null:i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(a.name),"aria-hidden":"true",children:Mt(a.name)}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:a.name}),i.jsx("span",{className:"file-tree-path",children:a.path})]})]})},`search-${a.kind}-${a.path}`)})})}return i.jsx("section",{className:["conversation-panel","surface-card","file-panel",t].filter(Boolean).join(" "),"data-testid":"file-context-panel",children:l?i.jsxs(i.Fragment,{children:[i.jsx(Vi,{workspaceId:l,filePath:le,open:le!==null,onClose:()=>{ce.current+=1,Ae(null),re(null)},onSaved:async e=>{await we(),await he(e),Ee(a=>a+1)},diffContent:hi,showDetachAction:Pe.isDesktop&&Pe.bridge.supported,onDetach:()=>{le&&Ci(le)}}),s?null:i.jsx("div",{className:"file-panel-heading-row",children:i.jsx("h2",{className:"file-panel-heading",children:r("conversation.filePanelTitle")})}),m?null:i.jsxs("div",{className:"file-panel-tabs",role:"tablist","aria-label":r("conversation.filePanelTitle"),children:[i.jsx("button",{className:O==="workspace"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":O==="workspace",onClick:()=>Ze("workspace"),children:r("conversation.filePanelWorkspaceTab")}),i.jsxs("button",{className:O==="session"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":O==="session",onClick:()=>{$e&&Ze("session")},disabled:!$e,children:[r("conversation.filePanelSessionTab"),i.jsx("span",{className:"file-panel-tab-badge","aria-label":`${r("conversation.filePanelSessionTab")} ${sn}`,children:sn})]})]}),O==="workspace"?i.jsxs(i.Fragment,{children:[i.jsx("input",{ref:mn,"data-testid":"file-panel-upload-input",type:"file",hidden:!0,onChange:e=>void Si(e)}),bn?i.jsx("div",{className:"file-panel-toolbar file-panel-toolbar-mobile","aria-label":r("conversation.filePanelTitle"),children:i.jsxs("div",{className:"file-mobile-action-shell",ref:hn,children:[i.jsxs("button",{className:"secondary-button file-mobile-action-trigger",type:"button","aria-label":r("conversation.filePanelActionsMenu"),"aria-haspopup":"menu","aria-expanded":et,"data-active":et,onClick:()=>{I(!1),L(e=>!e)},children:[i.jsx("span",{children:r("conversation.filePanelActionsMenu")}),i.jsx(za,{})]}),et?i.jsxs("div",{className:"file-mobile-action-menu",role:"menu","aria-label":r("conversation.filePanelActionsMenu"),children:[i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>me("copy")),disabled:!Te,children:r("conversation.filePanelCopy")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>me("cut")),disabled:!Te,children:r("conversation.filePanelCut")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>st()),disabled:!lt||p||v,children:r("conversation.filePanelPaste")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Tn()},children:Ye?r("conversation.filePanelHideSearch"):r("conversation.filePanelShowSearch")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Wt(e=>!e)},disabled:vt.length===0,children:ee?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(Rn),disabled:Fe||p||pt,children:r("conversation.filePanelRefresh")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Fn()},disabled:!Cn,children:r("conversation.filePanelCollapseCurrent")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),_n()},disabled:p||v,children:r("conversation.filePanelUpload")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(Kt),disabled:!yn||v,children:r("conversation.filePanelDownload")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(qt),disabled:!gn||p||v,children:r("conversation.filePanelRenameMove")}),i.jsx("button",{className:"file-mobile-action-menu-item danger",type:"button",role:"menuitem",onClick:()=>J(Yt),disabled:!xn||p||v,children:r("conversation.filePanelDelete")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ke("create_file")),disabled:p||v,children:r("conversation.filePanelNewFile")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ke("create_directory")),disabled:p||v,children:r("conversation.filePanelNewDirectory")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ge("absolute")),disabled:!Vt,children:r("conversation.filePanelCopyAbsolutePath")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ge("relative")),disabled:!Vt,children:r("conversation.filePanelCopyRelativePath")})]}):null]})}):i.jsxs("div",{className:"file-panel-toolbar","aria-label":r("conversation.filePanelTitle"),children:[i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCopy"),"aria-label":r("conversation.filePanelCopy"),onClick:()=>me("copy"),disabled:!Te,children:i.jsx(Aa,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCut"),"aria-label":r("conversation.filePanelCut"),onClick:()=>me("cut"),disabled:!Te,children:i.jsx(La,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelPaste"),"aria-label":r("conversation.filePanelPaste"),onClick:()=>void st(),disabled:!lt||p||v,children:i.jsx(Ba,{})}),i.jsxs("div",{className:"file-toolbar-menu-shell",ref:dn,children:[i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCopyPath"),"aria-label":r("conversation.filePanelCopyPath"),"aria-haspopup":"menu","aria-expanded":Ie,"data-active":Ie,onClick:()=>{L(!1),I(e=>!e)},disabled:!Vt,children:i.jsx(Fa,{})}),Ie?i.jsxs("div",{className:"file-toolbar-menu",role:"menu",children:[i.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Ge("absolute"),children:r("conversation.filePanelCopyAbsolutePath")}),i.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Ge("relative"),children:r("conversation.filePanelCopyRelativePath")})]}):null]}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCollapseCurrent"),"aria-label":r("conversation.filePanelCollapseCurrent"),onClick:Fn,disabled:!Cn,children:i.jsx(Ta,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelRefresh"),"aria-label":r("conversation.filePanelRefresh"),onClick:()=>void Rn(),disabled:Fe||p||pt,children:i.jsx(_a,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelSearchButton"),"aria-label":r("conversation.filePanelSearchButton"),"data-active":Ye,onClick:Tn,disabled:Fe,children:i.jsx(Zn,{})}),vt.length>0?i.jsx("button",{className:"file-toolbar-button",type:"button",title:ee?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges"),"aria-label":ee?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges"),"data-active":ee,onClick:()=>Wt(e=>!e),children:i.jsx(Ka,{})}):null,i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelUpload"),"aria-label":r("conversation.filePanelUpload"),onClick:_n,disabled:p||v,children:i.jsx($a,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelDownload"),"aria-label":r("conversation.filePanelDownload"),onClick:()=>void Kt(),disabled:!yn||v,children:i.jsx(Oa,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelRenameMove"),"aria-label":r("conversation.filePanelRenameMove"),onClick:()=>qt(),disabled:!gn||p||v,children:i.jsx(Ua,{})}),i.jsx("button",{className:"file-toolbar-button danger",type:"button",title:r("conversation.filePanelDelete"),"aria-label":r("conversation.filePanelDelete"),onClick:()=>Yt(),disabled:!xn||p||v,children:i.jsx(Ha,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelNewFile"),"aria-label":r("conversation.filePanelNewFile"),onClick:()=>void Ke("create_file"),disabled:p||v,children:i.jsx(Wa,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelNewDirectory"),"aria-label":r("conversation.filePanelNewDirectory"),onClick:()=>void Ke("create_directory"),disabled:p||v,children:i.jsx(Va,{})})]}),oe&&typeof document<"u"?Fi.createPortal(i.jsx("div",{className:"file-web-context-menu",ref:$t,role:"menu","aria-label":r("conversation.filePanelActionsMenu"),style:{left:`${(Ce==null?void 0:Ce.left)??Math.max(8,oe.positionX)}px`,top:`${(Ce==null?void 0:Ce.top)??Math.max(8,oe.positionY)}px`,maxHeight:Ce?`${Ce.maxHeight}px`:void 0},children:oe.items.map(e=>i.jsx("button",{className:["file-web-context-menu-item",e.label===r("conversation.filePanelDelete")?"danger":""].filter(Boolean).join(" "),type:"button",role:"menuitem",disabled:e.disabled,onClick:()=>{H(null),e.onSelect()},children:e.label},e.id))}),document.body):null,Pn?i.jsx("p",{className:"file-panel-clipboard-status","data-mode":C==null?void 0:C.mode,children:Pn}):null,Ye?i.jsxs("form",{className:"file-toolbar-search",onSubmit:e=>void wi(e),children:[i.jsx("input",{value:A,onChange:e=>Qe(e.target.value),placeholder:r("conversation.filePanelSearchPlaceholder")}),bn?i.jsx("button",{className:"secondary-button file-mobile-search-submit",type:"submit","aria-label":r("conversation.filePanelSearchButton"),disabled:pt,children:r("conversation.filePanelSearchButton")}):i.jsx("button",{className:"file-toolbar-button",type:"submit",title:r("conversation.filePanelSearchButton"),"aria-label":r("conversation.filePanelSearchButton"),disabled:pt,children:i.jsx(Zn,{})})]}):null,i.jsx("div",{ref:mi,className:"file-tree","data-search-mode":fe,"data-scrollbar-autohide":"true",children:Fe&&He.length===0?i.jsx("p",{className:"file-tree-status status-text",children:r("common.loading")}):fe?Re!=null&&Re.length?ki(Re):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSearchEmpty")}):ee?yt.length?Jt(yt,0):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelNoChanges")}):He.length?Jt(He,0):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelEmptyDirectory")})}),i.jsx($n,{open:S!==null,title:(U==null?void 0:U.title)??"",description:U==null?void 0:U.description,onClose:Xt,children:i.jsxs("form",{className:"workbench-rename-form",onSubmit:e=>void Ni(e),children:[i.jsx(qi,{label:r("conversation.filePanelPathFieldLabel"),htmlFor:fn,description:(S==null?void 0:S.mode)==="rename"?S.target.path:(S==null?void 0:S.baseDirectory)||void 0,children:i.jsx("input",{id:fn,type:"text",value:Bt??"",placeholder:r("conversation.filePanelPathFieldPlaceholder"),autoFocus:!0,onChange:e=>We(e.target.value)})}),i.jsxs(Yi,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:p,onClick:Xt,children:r("common.cancel")}),i.jsx("button",{type:"submit",className:"primary-button",disabled:p||!(Bt??"").trim(),children:p?(U==null?void 0:U.pendingLabel)??r("common.loading"):(U==null?void 0:U.submitLabel)??r("common.save")})]})]})}),i.jsxs($n,{open:B!==null,title:r("conversation.filePanelDeleteConfirmTitle"),description:r("conversation.filePanelDeleteConfirmDescription"),onClose:()=>{p||Be(null)},children:[i.jsx("p",{className:"workbench-section-empty",children:B!=null&&B.length?B.length===1?((Bn=B[0])==null?void 0:Bn.kind)==="directory"?r("conversation.filePanelDeleteDirectoryConfirm",{path:B[0].path}):r("conversation.filePanelDeleteFileConfirm",{path:B[0].path}):r("conversation.filePanelDeleteSelectionConfirm",{count:B.length}):""}),i.jsxs("div",{className:"workbench-modal-actions",children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:p,onClick:()=>Be(null),children:r("common.cancel")}),i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:p,onClick:()=>{Di()},children:p?r("conversation.filePanelDeleting"):r("conversation.filePanelDelete")})]})]})]}):$e&&n?i.jsx(ea,{sessionId:n,workspaceId:l,showSystemFiles:V,selectedPath:je,refreshVersion:rn,onCountChange:Ot,onSelectFile:he,onOpenFile:ze}):i.jsx("section",{className:"file-panel-section",children:i.jsx("p",{className:"status-text",children:r("conversation.filePanelSessionNoSession")})})]}):i.jsx("section",{className:"file-panel-section",children:i.jsx("p",{className:"status-text",children:r("conversation.filePanelNoWorkspace")})})})}function ve(t){return t.includes("/")?t.split("/").slice(0,-1).join("/"):g}function dt(t,n=!1){const l=t.split("/").filter(Boolean),s=n?l.length:l.length-1,m=[];for(let h=0;h<s;h+=1)m.push(l.slice(0,h+1).join("/"));return m}function zn(t,n){return t||((n==null?void 0:n.kind)==="directory"?n.path:n!=null&&n.path?ve(n.path):g)}function Kn(t,n){return t?`${t}/${n}`:n}function fa(t){var n;return((n=t.split(/[/\\]/).pop())==null?void 0:n.trim())??""}function z(t,n){return{path:t,kind:n}}function Gn(t){return t[t.length-1]??null}function da(t,n){return t.findIndex(s=>s.path===n.path)>=0?t.filter(s=>s.path!==n.path):[...t,n]}function ha(t,n,l){const s=t.findIndex(x=>x.path===l.path);if(s<0)return[l];const m=n?t.findIndex(x=>x.path===n):s;if(m<0)return[l];const h=Math.min(m,s),b=Math.max(m,s);return t.slice(h,b+1)}function jt(t){return!!(t!=null&&t.ctrlKey||t!=null&&t.metaKey)}function ma(t){return t.ctrlKey||t.metaKey}function pa(t){if(!(t instanceof HTMLElement))return!1;const n=t.tagName.toLowerCase();return n==="input"||n==="textarea"||n==="select"||t.isContentEditable}function wt(t){const n=[...new Map(t.map(s=>[s.path,s])).values()].sort((s,m)=>s.path.localeCompare(m.path)),l=[];for(const s of n)l.some(m=>m.kind==="directory"&&Tt(m.path,s.path))||l.push(s);return l}function ba(t,n){return(t==null?void 0:t.kind)==="directory"?t.path:t!=null&&t.path?ve(t.path):n}function va(t,n){let l=t;for(;l&&n.some(s=>s.kind==="directory"&&Tt(s.path,l));)l=ve(l);return l}function oi(t,n,l,s,m,h){const b=[];for(const x of t){if(b.push(z(x.path,x.kind)),x.kind!=="directory"||!l.includes(x.path))continue;const j=n[x.path]??[],_=s?an(j,n,m,h):j;b.push(...oi(_,n,l,s,m,h))}return b}function ya(t,n,l){const s=Math.max(0,l.width),m=Math.max(0,l.height),h=Math.max(0,m-ne*2),b=Math.max(0,s-ne*2),x=Math.min(Math.max(n.width,0),b),j=Math.max(0,m-t.y-Pt-ne),_=Math.max(0,t.y-Pt-ne),M=j<n.height&&_>j,ye=It(Math.max(M?_:j,aa),0,h),K=Math.min(Math.max(n.height,0),ye),xe=M?t.y-Pt-K:t.y+Pt,ge=Math.max(ne,m-ne-K),G=Math.max(ne,s-ne-x);return{top:It(xe,ne,ge),left:It(t.x,ne,G),maxHeight:Math.max(0,ye)}}function It(t,n,l){return!Number.isFinite(t)||l<n?n:Math.min(Math.max(t,n),l)}function qe(t,n="posix"){return t?ri(t,n):"."}function xa(t,n,l){const s=ri(t,l),m=qe(n,l).replace(/^\.[/\\]?/,"");if(!m)return s;const h=si(l),b=m.replace(/^[/\\]+/,"");return b?s.endsWith("/")||s.endsWith("\\")?`${s}${b}`:`${s}${h}${b}`:s}function ga(t){return/^[a-zA-Z]:[\\/]/.test(t)||t.includes("\\")?"windows":"posix"}function ri(t,n){return t&&(si(n)==="\\"?t.replace(/\//g,"\\"):t.replace(/\\/g,"/"))}function si(t){return t==="windows"?"\\":"/"}function Tt(t,n){return n===t||n.startsWith(`${t}/`)}function ci(t,n,l){return t===n?l:t.startsWith(`${n}/`)?`${l}${t.slice(n.length)}`:t}function Ca(t,n,l){return t.map(s=>({...s,path:ci(s.path,n,l)}))}function Pa(t){return t.mode==="create_file"?{title:r("conversation.filePanelNewFile"),description:r("conversation.filePanelCreateFileDescription"),submitLabel:r("conversation.filePanelCreateFileSubmit"),pendingLabel:r("conversation.filePanelCreatingFile")}:t.mode==="create_directory"?{title:r("conversation.filePanelNewDirectory"),description:r("conversation.filePanelCreateDirectoryDescription"),submitLabel:r("conversation.filePanelCreateDirectorySubmit"),pendingLabel:r("conversation.filePanelCreatingDirectory")}:{title:r("conversation.filePanelRenameMove"),description:r("conversation.filePanelRenameDescription"),submitLabel:r("conversation.filePanelRenameSubmit"),pendingLabel:r("conversation.filePanelRenaming")}}async function ja(t){const n=await t.arrayBuffer(),l=new Uint8Array(n),s=32768;let m="";for(let h=0;h<l.length;h+=s){const b=l.subarray(h,h+s);m+=String.fromCharCode(...b)}return btoa(m)}function wa(t){const n=atob(t),l=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)l[s]=n.charCodeAt(s);return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}function Sa(t,n){if(typeof document>"u")throw new Error(r("conversation.filePanelDownloadFailed"));const l=window.URL.createObjectURL(n),s=document.createElement("a");s.href=l,s.download=t,document.body.append(s),s.click(),s.remove(),window.URL.revokeObjectURL(l)}async function Na(t,n){var l;if(!(n.isDesktop&&(await n.bridge.writeClipboardText(t)).ok)){if(typeof navigator<"u"&&((l=navigator.clipboard)!=null&&l.writeText))try{await navigator.clipboard.writeText(t);return}catch{}if(!Da(t))throw new Error(r("conversation.filePanelCopyPathFailed"))}}function Da(t){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.top="-9999px",n.style.left="-9999px",n.style.opacity="0",document.body.appendChild(n),n.focus(),n.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(n)}}function Ea(t,n){return t&&dt(t,!0).every(m=>m in n)?t:g}function Xn(t,n){if(!n)return[];const l=dt(n,!0);return t.filter(s=>l.includes(s))}function St(t,n,l){const s=on(n,l);return Object.entries(t).reduce((m,[h,b])=>(s.has(h)&&(m[h]=b),m),{})}function ka(t,n,l){const m=[...on(n,l)].filter(h=>h===g||h in t);return m.length?m:[g]}function on(t,n){const l=new Set([g]),s=ui(n,dt(t,!0));for(const m of s){l.add(m);for(const h of dt(m,!0))l.add(h)}return l}function Ma(t,n){const l=Object.keys(t),s=Object.keys(n);return l.length!==s.length?!1:l.every(m=>t[m]===n[m])}function kt(t,n){return t.includes(n)?t:[...t,n]}function ui(t,n){return n.reduce((l,s)=>kt(l,s),t)}function qn(t){return`file-panel.workspace-tree.${t}`}function Yn(t,n){return`file-panel.session-change-count.${t}.${n}`}function Jn(t,n){return Object.fromEntries(Object.keys(n).map(l=>[l,t[l]??null]))}function en(t,n){return[...on(n,t)]}function Q(t,n){return t instanceof In?t.message:n}function fi(t){return t instanceof Error&&t.message.startsWith("FILE_TREE_SNAPSHOT_TIMEOUT:")}function Qn(t){return fi(t)||t instanceof Error&&t.message.startsWith("FILE_TREE_ABORTED:")}function Ra(t){return new Promise(n=>{window.setTimeout(n,t)})}function Ta(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M2.5 4.5h11v2h-11zM2.5 7.5h7v2h-7zM2.5 10.5h4v2h-4z",fill:"currentColor"})})}function _a(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M12.8 5.2A5.5 5.5 0 1 0 13.5 8h-1.8A3.7 3.7 0 1 1 10.6 5l-1.4 1.4h4V2l-1.4 1.4z",fill:"currentColor"})})}function Zn(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M11.2 10.1l3 3-1.1 1.1-3-3a5 5 0 1 1 1.1-1.1zM6.8 10.3a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z",fill:"currentColor"})})}function Fa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3.5 4.3h5.2v1.4H4.9v5.4H3.5zm3.8-2.1h5.2v9.5H7.3z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M5.7 10.8h4.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Aa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M5 2.5h7.5v9H5z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M3.5 5H2.4V13.5H10V12.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function La(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M4.2 4.2a1.4 1.4 0 1 1 0 2.8 1.4 1.4 0 0 1 0-2.8zm0 5.4a1.4 1.4 0 1 1 0 2.8 1.4 1.4 0 0 1 0-2.8zm1-3.2 6.6 5.6M5.2 9.6l6.6-5.6",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})})}function Ba(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 3.5h8v10H4zM6 2.2h4v2H6z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M6 7.2h4M6 9.6h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Wa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 1.5h5l3 3v10H4z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M9 1.5v3h3",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 6.5v5M5.5 9h5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function $a(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"m5.5 5 2.5-2.5L10.5 5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Oa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"m5.5 8.5 2.5 2.5 2.5-2.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Ha(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M3.5 4.5h9M6.2 2.5h3.6l.6 1.4H13v1.2H3V3.9h2.6zM5.2 5.7v6.1m2.8-6.1v6.1m2.8-6.1v6.1M4.4 13.5h7.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Va(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M1.8 4.5h4l1.2 1.3h7.2v6.7H1.8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8.5 7.2v4M6.5 9.2h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Ua(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M3.2 11.9h2.2l5.9-5.9-2.2-2.2-5.9 5.9zM8.3 3.8l2.2 2.2M2.8 13.2h10.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function za(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"m4 6 4 4 4-4",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}function Ka(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M1.5 2h13l-5 6v5l-3 1.5V8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinejoin:"round"})})}function an(t,n,l,s){const m=[];for(const h of t){const b=h.path.replace(/\\/g,"/");h.kind==="file"?l.has(b)&&m.push(h):di(b,n,l,s)&&m.push(h)}return m}function di(t,n,l,s,m){const h=m??new Set;if(h.has(t))return!1;h.add(t);const b=n[t];if(!b)return s.has(t);for(const x of b){const j=x.path.replace(/\\/g,"/");if(x.kind==="file"){if(l.has(j))return!0}else if(di(j,n,l,s,h))return!0}return!1}export{nl as FileContextPanel};
|
|
1
|
+
import{b as c,F as tn,j as i,t as r,G as ft,A as In}from"./index-_OCkVmfl.js";import{f as ei,e as _i,g as Fi}from"./App-If9gThKM.js";import{bG as Ai,bH as Li,bI as ti,bJ as nn,bK as Bi,bL as Mt,bM as Rt,b as Wi,u as $i,Y as _e,bN as Qt,bO as Oi,bP as Hi,bQ as Vi,bR as ut,bS as gt,bT as Xe,bU as Ui,bV as zi,bW as Ki,bX as Gi,bY as Xi}from"./WorkbenchLayout-D-U7ghT0.js";import{d as qi,M as Yi}from"./workbench-navigation-RyUjchbD.js";import{W as $n}from"./WorkbenchModal-xbx1o6MO.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./DesktopModal-bMdI1jEe.js";import"./relay-entry-B5GmiOrR.js";import"./MobileSheet-BXvQPkxt.js";async function Nt(t,n){const[l,s]=await Promise.all([Ai(n),Li(t)]);return Ji(l.changes,s.items)}function Ji(t,n){const l=new Set(n.map(s=>Et(s.path)));return t.filter(s=>l.has(Et(s.path))||s.oldPath!==null&&l.has(Et(s.oldPath)))}function Qi(t){const n=On("","");for(const l of t){const s=Et(l.path),m=s.split("/").filter(Boolean);let h=n;m.forEach((b,x)=>{const j=m.slice(0,x+1).join("/");if(x===m.length-1){h.children.set(`file:${j}`,{kind:"file",name:b,path:s,change:l});return}const _=`directory:${j}`,M=h.children.get(_);if(M&&M.kind==="directory"){h=M;return}const Z=On(b,j);h.children.set(_,Z),h=Z})}return ai(ii([...n.children.values()]))}function ni(t,n){const l=t.oldPath?`${t.oldPath} -> ${t.path}`:t.path;return ln(t)?`${l} ${n}`:l}function ln(t){return t.status==="D"||t.stagedStatus==="D"||t.worktreeStatus==="D"}function Dt(t){return t.split("/").filter(Boolean).pop()??t}function Et(t){return t.replace(/\\/g,"/").replace(/^\.\//,"").trim()}function On(t,n){return{kind:"directory",name:t,path:n,children:new Map}}function ii(t){return[...t].sort((n,l)=>n.kind!==l.kind?n.kind==="directory"?-1:1:n.name.localeCompare(l.name,"zh-CN")).map(n=>n.kind==="directory"?{kind:"directory",name:n.name,path:n.path,children:ii([...n.children.values()])}:n)}function ai(t){return t.map(n=>{var b;if(n.kind!=="directory")return n;const l=ai(n.children);let s=n.name,m=n.path,h=l;for(;h.length===1&&((b=h[0])==null?void 0:b.kind)==="directory";){const x=h[0];s=`${s}/${x.name}`,m=x.path,h=x.children}return{kind:"directory",name:s,path:m,children:h}})}const Zi=450,Ii=60*1e3,Hn=20,Vn=16;function ea({sessionId:t,workspaceId:n,showSystemFiles:l,selectedPath:s,refreshVersion:m,onCountChange:h,onSelectFile:b,onOpenFile:x}){const[j,_]=c.useState("tree"),[M,Z]=c.useState([]),[ye,K]=c.useState(!0),[xe,ge]=c.useState(!1),[G,ht]=c.useState([]),E=c.useRef(null),_t=ti(),{showToast:Ne}=ei();c.useEffect(()=>{const p=tn(Ct(n,t),Ii);_("tree"),Z(p??[]),K(p===null),ge(!1),ht([]),E.current=null},[t,n]),c.useEffect(()=>{let p=!1;async function w(){K(!0);try{const v=await Nt(t,n);p||(Z(v),ft(Ct(n,t),v))}catch(v){p||Ne({title:Zt(v,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{p||K(!1)}}return w(),()=>{p=!0}},[m,t,Ne,n]);async function De(){K(!0);try{const p=await Nt(t,n);Z(p),ft(Ct(n,t),p)}catch(p){Ne({title:Zt(p,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{K(!1)}}async function D(){if(R.length!==0){ge(!0);try{await Bi(n,R.map(w=>w.path));const p=await Nt(t,n);Z(p),ft(Ct(n,t),p),Ne({title:r("conversation.filePanelSessionStageSuccess"),tone:"success"})}catch(p){Ne({title:Zt(p,r("git.stageFailed")),tone:"error"})}finally{ge(!1)}}}function F(p){ht(w=>w.includes(p)?w.filter(v=>v!==p):[...w,p])}function X(p){const w=Date.now(),v=E.current;return E.current={filePath:p,timestamp:w},(v==null?void 0:v.filePath)===p&&w-v.timestamp<=Zi}async function $(p,w){if(w&&X(p)){await x(p),E.current=null;return}w||(E.current=null),await b(p)}const ie=c.useMemo(()=>nn(M,p=>Dt(p.path),l),[M,l]),R=ie.filter(p=>!p.staged),Fe=Qi(ie),ae=new Set(G);return c.useEffect(()=>{h==null||h(ie.length)},[h,ie.length]),i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"file-panel-session-toolbar",children:[i.jsxs("div",{className:"file-panel-view-modes",role:"tablist","aria-label":r("conversation.filePanelSessionViewLabel"),children:[i.jsx("button",{className:j==="tree"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":j==="tree",onClick:()=>_("tree"),children:r("conversation.filePanelSessionTreeView")}),i.jsx("button",{className:j==="list"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":j==="list",onClick:()=>_("list"),children:r("conversation.filePanelSessionListView")})]}),i.jsxs("div",{className:"file-panel-session-actions",children:[i.jsx("button",{className:"secondary-button",type:"button",onClick:()=>void De(),disabled:ye||xe,children:r("conversation.filePanelRefresh")}),i.jsx("button",{className:"primary-button",type:"button",onClick:()=>void D(),disabled:xe||R.length===0,children:r("conversation.filePanelSessionStageAll")})]})]}),i.jsxs("div",{className:"file-panel-session-summary",children:[i.jsx("span",{children:`${r("conversation.filePanelSessionSummary")} ${ie.length}`}),i.jsx("span",{children:`${r("conversation.filePanelSessionUnstagedSummary")} ${R.length}`})]}),i.jsx("div",{ref:_t,className:"file-tree","data-scrollbar-autohide":"true",children:ye?i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSessionLoading")}):ie.length===0?i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSessionEmpty")}):j==="tree"?li({nodes:Fe,depth:0,collapsedPathSet:ae,selectedPath:s,onToggleTreePath:F,onFileClick:$}):ta({items:ie,selectedPath:s,onFileClick:$})})]})}function li({nodes:t,depth:n,collapsedPathSet:l,selectedPath:s,onToggleTreePath:m,onFileClick:h}){return t.map(b=>{if(b.kind==="directory"){const x=!l.has(b.path);return i.jsxs("div",{className:"file-tree-node",children:[i.jsxs("button",{className:"file-tree-item",type:"button","data-kind":"directory","aria-expanded":x,style:{paddingInlineStart:`${Hn+n*Vn}px`},onClick:()=>m(b.path),children:[i.jsx("span",{className:"file-tree-chevron","aria-hidden":"true",children:x?"v":">"}),i.jsx("span",{className:"file-tree-label",children:b.name})]}),x?i.jsx("div",{className:"file-tree-children",children:li({nodes:b.children,depth:n+1,collapsedPathSet:l,selectedPath:s,onToggleTreePath:m,onFileClick:h})}):null]},`session-directory:${b.path}`)}return i.jsx("div",{className:"file-tree-node",children:i.jsxs("button",{className:"file-tree-item is-session-change",type:"button","data-active":s===b.change.path,"data-kind":"file",style:{paddingInlineStart:`${Hn+n*Vn}px`},onClick:()=>void h(b.change.path,!ln(b.change)),children:[i.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(b.name),"aria-hidden":"true",children:Mt(b.name)}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:b.name}),i.jsx("span",{className:"file-tree-path",children:ni(b.change,r("conversation.filePanelSessionDeleted"))})]}),i.jsxs("span",{className:"file-session-item-meta",children:[i.jsx("span",{className:"file-session-badge","data-status":b.change.status,children:b.change.status}),i.jsx("span",{className:"file-session-badge subtle",children:b.change.staged?r("git.stagedLabel"):r("git.workingTreeLabel")})]})]})},`session-file:${b.path}`)})}function ta({items:t,selectedPath:n,onFileClick:l}){return t.map(s=>i.jsx("div",{className:"file-session-list-item",children:i.jsxs("button",{className:"file-session-list-button",type:"button","data-active":n===s.path,onClick:()=>void l(s.path,!ln(s)),children:[i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(Dt(s.path)),"aria-hidden":"true",children:Mt(Dt(s.path))}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:Dt(s.path)}),i.jsx("span",{className:"file-tree-path",children:ni(s,r("conversation.filePanelSessionDeleted"))})]}),i.jsxs("span",{className:"file-session-item-meta",children:[i.jsx("span",{className:"file-session-badge","data-status":s.status,children:s.status}),i.jsx("span",{className:"file-session-badge subtle",children:s.staged?r("git.stagedLabel"):r("git.workingTreeLabel")})]})]})},`session-list:${s.path}`))}function Ct(t,n){return`file-panel.session-changes.${t}.${n}`}function Zt(t,n){return t instanceof In?t.message:typeof t=="object"&&t&&"message"in t?String(t.message??n):n}const g="",na=450,ne=8,Pt=4,ia=176,aa=120,la=300*1e3,oa=60*1e3,Un=1600,ra=220,sa=20,ca=16;function ua(){if(typeof document>"u")return;const t=document.querySelector(".workbench-modal-card.file-viewer-modal"),n=t==null?void 0:t.getBoundingClientRect();if(!(!n||n.width<=0||n.height<=0))return{width:Math.round(n.width),height:Math.round(n.height),minWidth:720,minHeight:480}}function nl({className:t,sessionId:n,workspaceId:l,hideHeading:s=!1,hideTabs:m=!1,externalRevealRequest:h=null,externalWindowMode:b=!1,workbenchShellOverrides:x}){var Ln,Bn;const j=Wi(),{navigationGroups:_,subscribeFileTree:M,requestFileTreeRefresh:Z,addFileTreeSnapshotListener:ye,subscribeGitSnapshot:K,requestGitRefresh:xe,addGitSnapshotListener:ge}={...j,...x},[G,ht]=c.useState({}),[E,_t]=c.useState([]),[Ne,De]=c.useState([]),[D,F]=c.useState(g),[X,$]=c.useState([]),[ie,R]=c.useState(null),[Fe,ae]=c.useState(!1),[p,w]=c.useState(!1),[v,mt]=c.useState(!1),[Ye,Je]=c.useState(!1),[A,Qe]=c.useState(""),[Ft,q]=c.useState(null),[pt,bt]=c.useState(!1),[le,Ae]=c.useState(null),[O,Ze]=c.useState("workspace"),[rn,Ee]=c.useState(0),[sn,At]=c.useState(0),[Ie,I]=c.useState(!1),[et,L]=c.useState(!1),[oe,H]=c.useState(null),[Ce,Le]=c.useState(null),[B,Be]=c.useState(null),[C,Lt]=c.useState(null),[S,tt]=c.useState(null),[Bt,We]=c.useState(""),[cn,un]=c.useState([]),[ee,Wt]=c.useState(!1),[hi,re]=c.useState(null),fn=c.useId(),se=c.useRef({}),Y=c.useRef({}),T=c.useRef([]),te=c.useRef(g),nt=c.useRef(!1),it=c.useRef(null),mi=ti(),dn=c.useRef(null),hn=c.useRef(null),$t=c.useRef(null),mn=c.useRef(null),pn=c.useRef(null),ce=c.useRef(0),ue=c.useRef(new Map),{showToast:P}=ei(),Pe=_i(),V=$i(e=>e.showSystemFiles),$e=!!(n!=null&&n.trim()),bn=s&&Pe.isMobile;c.useEffect(()=>{_e("file_panel.props",{sessionId:n,workspaceId:l,externalWindowMode:b})},[b,n,l]),c.useEffect(()=>{te.current=D},[D]);function Ot(e){At(e),!(!l||!n)&&ft(Yn(l,n),e)}async function vn(){if(!l||!n){Ot(0);return}const e=await Nt(n,l),a=nn(e,o=>ut(o.path),V).length;Ot(a)}function ke(e){ht(a=>{const o=typeof e=="function"?e(a):e;return se.current=o,o})}function Oe(e){_t(a=>{const o=typeof e=="function"?e(a):e;return T.current=o,o})}c.useEffect(()=>{var f,d;if(zt(),!l){zt(),nt.current=!1,se.current={},Y.current={},T.current=[],te.current=g,ke({}),Oe([]),De([]),F(g),Je(!1),Qe(""),q(null),bt(!1),ae(!1),Wt(!1),re(null),$([]),R(null),H(null),Le(null),Be(null),tt(null),We("");return}nt.current=!0;const e=tn(qn(l),la);_e("file_panel.workspace_snapshot",{workspaceId:l,cached:!!e,cachedRootItems:((d=(f=e==null?void 0:e.treeCache)==null?void 0:f[g])==null?void 0:d.length)??0,cachedDirectoryCount:Object.keys((e==null?void 0:e.treeCache)??{}).length});const a=Ea((e==null?void 0:e.activeDirectoryPath)??g,(e==null?void 0:e.treeCache)??{}),o=Xn((e==null?void 0:e.expandedDirectories)??[],a),u=St((e==null?void 0:e.treeCache)??{},a,o);se.current=u,Y.current=Jn((e==null?void 0:e.treeRevisionByPath)??{},u),T.current=o,te.current=a,ke(u),Oe(o),De([]),F(a),ae(!1),w(!1),Je(!1),Qe(""),q(null),bt(!1),queueMicrotask(()=>{nt.current=!1})},[l]),c.useEffect(()=>{if(!h||h.workspaceId!==l)return;const e=()=>{if(pn.current===h.requestId)return;pn.current=h.requestId,Ze("workspace"),(h.openViewer?ze(h.filePath):he(h.filePath)).catch(o=>{P({title:Q(o,r("conversation.filePanelOpenFailed")),tone:"error"})})};if(nt.current){queueMicrotask(e);return}e()},[h,ze,he,P,l]),c.useEffect(()=>{if(l)return ye(e=>{e.workspaceId===l&&(Y.current={...Y.current,[e.path]:typeof e.revision=="string"?e.revision:null},ke(a=>({...a,[e.path]:e.items})),e.path===g&&ae(!1),De(a=>a.filter(o=>o!==e.path)),wn(e.path,e.items))})},[ye,l]),c.useEffect(()=>()=>{zt()},[]),c.useEffect(()=>{l&&M(l,en(T.current,te.current),{knownRevisionByPath:Y.current})},[D,E,M,l]),c.useEffect(()=>{$([]),R(null),Ae(null),re(null),Ee(0),I(!1),L(!1),H(null),Le(null),Be(null),tt(null),We(""),it.current=null,ce.current+=1},[n]),c.useEffect(()=>{!$e&&O==="session"&&Ze("workspace")},[O,$e]),c.useEffect(()=>{m&&O!=="workspace"&&Ze("workspace")},[O,m]),c.useEffect(()=>{if(!Ie&&!et&&!oe)return;function e(o){var y,N,pe;if(!(o.target instanceof Node))return;const u=((y=dn.current)==null?void 0:y.contains(o.target))??!1,f=((N=hn.current)==null?void 0:N.contains(o.target))??!1,d=((pe=$t.current)==null?void 0:pe.contains(o.target))??!1;!u&&!f&&!d&&(I(!1),L(!1),H(null),Le(null))}function a(o){o.key==="Escape"&&(I(!1),L(!1),H(null),Le(null))}return document.addEventListener("pointerdown",e),document.addEventListener("keydown",a),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",a)}},[Ie,et,oe]),c.useLayoutEffect(()=>{if(!oe||typeof window>"u"){Le(null);return}const e=oe;function a(){const u=$t.current;if(!u)return;const f=u.getBoundingClientRect();Le(ya({x:e.positionX,y:e.positionY},{width:f.width||ia,height:f.height||u.scrollHeight||0},{width:window.innerWidth,height:window.innerHeight}))}a();const o=window.requestAnimationFrame(a);return window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),()=>{window.cancelAnimationFrame(o),window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0)}},[oe]),c.useEffect(()=>{if(!l)return;const e=Xn(E,D),a=St(G,D,e);ft(qn(l),{treeCache:a,treeRevisionByPath:Jn(Y.current,a),expandedDirectories:e,activeDirectoryPath:D})},[D,E,G,l]),c.useEffect(()=>{if(nt.current)return;const e=St(G,D,E);Ma(G,e)||ke(e)},[D,E,G]),c.useEffect(()=>{let e=!1;const a=(l==null?void 0:l.trim())??null;async function o(f){if(!a)return;const d=Qt(se.current[g]??[],V),y=(f==null?void 0:f.silent)!==!0&&d.length===0;y&&ae(!0),_e("file_panel.load_root_tree.start",{sessionId:n,workspaceId:a,silent:(f==null?void 0:f.silent)===!0,cachedRootItems:d.length});try{const N=await Ut(g,{force:!0});e||(_e("file_panel.load_root_tree.end",{sessionId:n,workspaceId:a,itemCount:N.length}),ke(pe=>({...St(pe,te.current,T.current),[g]:N})))}catch(N){!e&&!Qn(N)&&P({title:Q(N,r("conversation.filePanelLoadFailed")),tone:"error"})}finally{!e&&y&&ae(!1)}}if(Qt(se.current[g]??[],V).length>0){const f=window.setTimeout(()=>{a&&(M(a,en(T.current,te.current),{knownRevisionByPath:Y.current}),o({silent:!0}))},1500);return()=>{e=!0,window.clearTimeout(f)}}return o(),()=>{e=!0}},[n,V,P,l]),c.useEffect(()=>{if(!l||!n){At(0);return}const e=tn(Yn(l,n),oa);_e("file_panel.session_change_count.snapshot",{sessionId:n,workspaceId:l,cached:e!==null,cachedCount:e}),At(e??0);let a=!1;return vn().catch(()=>{}),()=>{a=!0}},[n,rn,V,l]),c.useEffect(()=>{if(!l){un([]);return}const e=l.trim();K(e),xe(e)},[l,K,xe]),c.useEffect(()=>{if(!l)return;const e=l.trim();return ge(a=>{var o;a.workspaceId===e&&un(((o=a.status)==null?void 0:o.changes)??[])})},[ge,l]);const vt=c.useMemo(()=>nn(cn,e=>ut(e.path),V),[cn,V]),W=c.useMemo(()=>{const e=new Map,a=new Set;for(const o of vt){const u=o.path.replace(/\\/g,"/"),f=o.worktreeStatus??o.stagedStatus??o.status;e.set(u,f);const d=u.split("/");for(let y=1;y<d.length;y++)a.add(d.slice(0,y).join("/"))}return{statusByPath:e,changedDirs:a}},[vt]),Me=c.useMemo(()=>Oi(G,V),[V,G]),Re=c.useMemo(()=>Ft===null?null:Qt(Ft,V),[Ft,V]),He=Me[g]??[],fe=Ye&&Re!==null,yt=c.useMemo(()=>ee?an(He,Me,W.statusByPath,W.changedDirs):He,[W.changedDirs,W.statusByPath,He,ee,Me]),pi=c.useMemo(()=>fe?(Re??[]).map(e=>z(e.path,e.kind)):oi(yt,Me,E,ee,W.statusByPath,W.changedDirs),[E,W.changedDirs,W.statusByPath,fe,ee,Re,Me,yt]),de=((Ln=_.find(e=>e.workspace.id===l))==null?void 0:Ln.workspace)??null,k=Gn(X),Ht=(k==null?void 0:k.path)??null,je=(k==null?void 0:k.kind)==="file"?k.path:null,xt=c.useMemo(()=>new Set(X.map(e=>e.path)),[X]),at=c.useMemo(()=>wt(X),[X]),Vt=!!(de!=null&&de.path&&X.length===1&&Ht),yn=X.length===1&&(k==null?void 0:k.kind)==="file",xn=at.length>0,Te=at.length>0,lt=!!(C!=null&&C.items.length&&l),gn=!!l&&X.length===1&&k!==null,Cn=!!((je?ve(je):D)&&E.length),Pn=C?C.mode==="copy"?r("conversation.filePanelClipboardCopyReady",{count:C.items.length}):r("conversation.filePanelClipboardCutReady",{count:C.items.length}):null,U=S?Pa(S):null;async function jn(e,a=!1){if(!l)return[];if(!a){const o=se.current[e];if(o)return o}e===g?ae(!0):De(o=>kt(o,e));try{const o=await Ut(e,{force:a});return ke(u=>({...u,[e]:o})),o}catch(o){throw Qn(o)||P({title:Q(o,r("conversation.filePanelLoadFailed")),tone:"error"}),o}finally{e===g?ae(!1):De(o=>o.filter(u=>u!==e))}}async function we(e){if(!l)return;const a=(e==null?void 0:e.activeDirectoryPath)??te.current,o=(e==null?void 0:e.expandedDirectories)??T.current,u=ka(se.current,a,o);_e("file_panel.refresh_tree_cache.start",{sessionId:n,workspaceId:l,targetDirectories:u});const d=(await Promise.all(u.map(async y=>{const N=await Ut(y,{force:!0});return[y,N]}))).reduce((y,[N,pe])=>(y[N]=pe,y),{});_e("file_panel.refresh_tree_cache.end",{sessionId:n,workspaceId:l,targetDirectories:u,directoryCount:Object.keys(d).length}),ke(d)}async function Ut(e,a){if(!l)return[];if(!(a!=null&&a.force)){const d=se.current[e];if(d)return d}const o=en(kt(T.current,e),e||te.current);M(l,o,{knownRevisionByPath:Y.current}),Z(l,[e],{knownRevisionByPath:Y.current});const u=bi(e,Un,{allowCached:(a==null?void 0:a.force)!==!0}),f=Ra(ra).then(async()=>{if(!l)return[];const y=(await Gi(l,e||void 0)).items;return Y.current={...Y.current,[e]:null},wn(e,y),y});try{return await Promise.race([u,f])}catch(d){if(!fi(d))throw d;return await f}}function bi(e,a=Un,o){const u=se.current[e];return(o==null?void 0:o.allowCached)!==!1&&u?Promise.resolve(u):new Promise((f,d)=>{const y=window.setTimeout(()=>{vi(e,y),d(new Error(`FILE_TREE_SNAPSHOT_TIMEOUT:${e}`))},a),N=ue.current.get(e)??[];ue.current.set(e,[...N,{resolve:f,reject:d,timerId:y}])})}function wn(e,a){const o=ue.current.get(e)??[];o.length!==0&&(ue.current.delete(e),o.forEach(u=>{window.clearTimeout(u.timerId),u.resolve(a)}))}function vi(e,a){const u=(ue.current.get(e)??[]).filter(f=>f.timerId!==a);if(u.length===0){ue.current.delete(e);return}ue.current.set(e,u)}function zt(){for(const[e,a]of ue.current.entries())a.forEach(o=>{window.clearTimeout(o.timerId),o.reject(new Error(`FILE_TREE_ABORTED:${e}`))});ue.current.clear()}function Ve(e){$([e]),R(e.path)}function ot(e){F(e.kind==="directory"?e.path:ve(e.path))}function yi(e){const a=ha(pi,ie,e);$(a),R(e.path),ot(e)}function xi(e){const a=da(X,e),o=Gn(a);$(a),R(e.path),o&&ot(o)}function Sn(e){Ve(e),ot(e)}function Ue(e,a){if(a!=null&&a.shiftKey){yi(e);return}if(jt(a)){xi(e);return}Sn(e)}async function rt(e,a=!1){const o=dt(e,a);if(!o.length){F(g);return}Oe(u=>ui(u,o)),F(o[o.length-1]??g);for(const u of o)try{await jn(u)}catch{return}}async function he(e){const a=z(e,"file");Ve(a),ot(a),await rt(e)}async function ze(e){Ae(e),re(null),it.current=null,ce.current+=1,he(e),await gi(e)}async function gi(e){const a=ce.current,o=e.replace(/\\/g,"/"),u=W.statusByPath.get(o);if(l&&u&&u!=="?"&&u!=="D")try{const f=await Hi(l,e,!1);ce.current===a&&re(f.content||null)}catch{ce.current===a&&re(null)}}async function Ci(e){if(!l)return;const a=ua(),o=await Ui(Pe,{workspaceId:l,workspaceName:(de==null?void 0:de.name)??null,sessionId:n??null,filePath:e,bounds:a});if(!o.ok){P({title:o.detail??r("conversation.fileViewerOpenInWindowFailed"),tone:"error"});return}ce.current+=1,Ae(null),re(null)}function Nn(e){const a=Date.now(),o=it.current;return it.current={filePath:e,timestamp:a},(o==null?void 0:o.filePath)===e&&a-o.timestamp<=na}function Se(){it.current=null}async function Pi(e,a){const o=z(e,"file");if(a!=null&&a.shiftKey||jt(a)){Se(),Ue(o,a);return}if(Nn(e)){await ze(e);return}Ue(o,a),await rt(e)}function Dn(){Je(!1),Qe(""),q(null),Se()}async function ji(e,a){const o=z(e.path,e.kind);if(a!=null&&a.shiftKey||jt(a)){Se(),Ue(o,a);return}if(e.kind==="directory"){Dn(),Ue(o,a),await En(e.path);return}if(Nn(e.path)){Dn(),await ze(e.path);return}await he(e.path)}async function En(e){if(Ve(z(e,"directory")),F(e),!T.current.includes(e))try{await jn(e),Oe(a=>kt(a,e))}catch{}}async function kn(e){if(Ve(z(e,"directory")),F(e),T.current.includes(e)){Mn(e);return}await En(e)}function Mn(e){Oe(a=>a.filter(o=>o!==e&&!o.startsWith(`${e}/`))),F(ve(e)),$([]),R(null)}async function Rn(){if(!l)return;const e=l;try{if(xe(e),await we(),je&&await rt(je),fe&&A.trim()){const a=await Xe(e,A.trim());q(a.items)}if($e&&n)if(O==="session")Ee(a=>a+1);else try{await vn()}catch(a){P({title:Q(a,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}}catch(a){P({title:Q(a,r("conversation.filePanelLoadFailed")),tone:"error"})}}async function wi(e){if(e==null||e.preventDefault(),!l||!A.trim()){q(null);return}bt(!0);try{const a=await Xe(l,A.trim());q(a.items)}catch(a){P({title:Q(a,r("conversation.filePanelSearchFailed")),tone:"error"})}finally{bt(!1)}}function Tn(){if(Ye){Je(!1),Qe(""),q(null);return}Je(!0)}function J(e){L(!1),e()}function _n(){var e;(e=mn.current)==null||e.click()}async function Si(e){var d;const a=((d=e.target.files)==null?void 0:d[0])??null;if(e.target.value="",!a||!l)return;const o=fa(a.name);if(!o){P({title:r("conversation.filePanelUploadFailed"),tone:"error"});return}const u=zn(D,k),f=Kn(u,o);mt(!0);try{const y=await ja(a);await zi({workspaceId:l,path:f,contentBase64:y}),await we(),await he(f),P({title:r("conversation.filePanelUploadSuccess",{name:o}),tone:"success"})}catch(y){P({title:Q(y,r("conversation.filePanelUploadFailed")),tone:"error"})}finally{mt(!1)}}async function Kt(e=je){if(!(!l||!e)){mt(!0);try{const a=await Ki(l,e),o=wa(a.contentBase64);Sa(a.fileName,new Blob([o],{type:"application/octet-stream"})),P({title:r("conversation.filePanelDownloadSuccess",{name:a.fileName}),tone:"success"})}catch(a){P({title:Q(a,r("conversation.filePanelDownloadFailed")),tone:"error"})}finally{mt(!1)}}}function Fn(){const e=je?ve(je):D;!e||!T.current.includes(e)||Mn(e)}function Gt(){tt(null),We("")}function Xt(){p||Gt()}function Ke(e,a=zn(D,k)){if(!l)return;const o=a,u=o?`${o}/`:"";I(!1),L(!1),H(null),tt({mode:e,baseDirectory:o}),We(u)}function qt(e=k){!l||!e||(I(!1),L(!1),H(null),tt({mode:"rename",target:e}),We(e.path))}async function Ni(e){if(e==null||e.preventDefault(),!l||!S)return;const a=(Bt??"").trim();if(a){if(S.mode==="rename"&&qe(S.target.path)===qe(a)){Xt();return}w(!0);try{if(S.mode==="rename"){const o=S.target.path,u=z(a,S.target.kind),f=le?ci(le,o,a):null;if(await gt({workspaceId:l,opType:"rename",srcPath:o,dstPath:a}),C&&Lt({...C,items:Ca(C.items,o,a)}),Gt(),Se(),await we(),S.target.kind==="directory"?(await rt(a,!0),Ve(u),F(a)):await he(a),f!==le&&(ce.current+=1,Ae(f),re(null)),fe&&A.trim()){const d=await Xe(l,A.trim());q(d.items)}Ee(d=>d+1),P({title:r("conversation.filePanelRenameSuccess",{name:ut(a)||a}),tone:"success"});return}if(await gt({workspaceId:l,opType:S.mode,dstPath:a,content:S.mode==="create_file"?"":void 0}),Gt(),await we(),S.mode==="create_directory"?(await rt(a,!0),Ve(z(a,"directory")),F(a)):await he(a),fe&&A.trim()){const o=await Xe(l,A.trim());q(o.items)}Ee(o=>o+1)}catch(o){P({title:Q(o,r("conversation.filePanelMutateFailed")),tone:"error"})}finally{w(!1)}}}function me(e,a=at){var u;if(a.length===0)return;const o=wt(a);Lt({mode:e,items:o}),$(o),R(((u=o[o.length-1])==null?void 0:u.path)??null),P({title:e==="copy"?r("conversation.filePanelCopySelectionSuccess",{count:o.length}):r("conversation.filePanelCutSelectionSuccess",{count:o.length}),tone:"success"}),H(null)}async function st(e=ba(k,D)){if(!l||!C||!C.items.length)return;const a=e??g,o=C.items.map(u=>({source:u,destinationPath:Kn(a,ut(u.path)||u.path)}));w(!0);try{for(const d of o)C.mode==="cut"&&qe(d.source.path)===qe(d.destinationPath)||await gt({workspaceId:l,opType:C.mode==="copy"?"copy":"move",srcPath:d.source.path,dstPath:d.destinationPath});const u=o.map(d=>z(d.destinationPath,d.source.kind)),f=u[u.length-1]??null;if(C.mode==="cut"&&Lt(null),$(u),R((f==null?void 0:f.path)??null),f&&ot(f),Se(),await we({activeDirectoryPath:(f==null?void 0:f.kind)==="directory"?f.path:f?ve(f.path):te.current,expandedDirectories:T.current}),fe&&A.trim()){const d=await Xe(l,A.trim());q(d.items)}Ee(d=>d+1),P({title:r("conversation.filePanelPasteSuccess",{count:u.length}),tone:"success"}),H(null)}catch(u){await we().catch(()=>{}),P({title:Q(u,r("conversation.filePanelPasteFailed")),tone:"error"})}finally{w(!1)}}function Yt(e=at){!e.length||p||(Be(wt(e)),H(null))}async function Di(){var a,o;if(!l||!(B!=null&&B.length))return;const e=wt(B);w(!0);try{for(const d of e)await gt({workspaceId:l,opType:"delete",srcPath:d.path});const u=va(D,e),f=T.current.filter(d=>!e.some(y=>y.kind==="directory"&&Tt(y.path,d)));if(le&&e.some(d=>Tt(d.path,le))&&(ce.current+=1,Ae(null),re(null)),Be(null),$([]),R(null),te.current=u,T.current=f,F(u),Oe(f),Se(),await we({activeDirectoryPath:u,expandedDirectories:f}),fe&&A.trim()){const d=await Xe(l,A.trim());q(d.items)}Ee(d=>d+1),P({title:e.length===1?r("conversation.filePanelDeleteSuccess",{name:ut(((a=e[0])==null?void 0:a.path)??"")||((o=e[0])==null?void 0:o.path)||""}):r("conversation.filePanelDeleteSelectionSuccess",{count:e.length}),tone:"success"})}catch(u){P({title:Q(u,r("conversation.filePanelMutateFailed")),tone:"error"})}finally{w(!1)}}async function Ge(e,a=k){const o=(de==null?void 0:de.path)??"",u=(a==null?void 0:a.path)??null;if(u===null||!o){I(!1);return}try{const f=ga(o),d=e==="absolute"?xa(o,u,f):qe(u,f);await Na(d,Pe),P({title:e==="absolute"?r("conversation.filePanelCopyAbsolutePathSuccess"):r("conversation.filePanelCopyRelativePathSuccess"),tone:"success"})}catch(f){P({title:f instanceof Error?f.message:r("conversation.filePanelCopyPathFailed"),tone:"error"})}finally{I(!1),H(null)}}function Ei(e,a,o){return[{id:`open-${e.path}`,label:e.kind==="directory"?E.includes(e.path)?r("conversation.filePanelCollapseDirectory"):r("conversation.filePanelExpandDirectory"):r("conversation.filePanelOpenFile"),onSelect:()=>{if(e.kind==="directory"){kn(e.path);return}ze(e.path)}},{id:`download-${e.path}`,label:r("conversation.filePanelDownload"),disabled:e.kind!=="file"||v,onSelect:()=>{Kt(e.kind==="file"?e.path:null)}},{id:`create-file-${e.path}`,label:r("conversation.filePanelNewFile"),disabled:!l||p||v,onSelect:()=>{Ke("create_file",o)}},{id:`create-directory-${e.path}`,label:r("conversation.filePanelNewDirectory"),disabled:!l||p||v,onSelect:()=>{Ke("create_directory",o)}},{id:`rename-${e.path}`,label:r("conversation.filePanelRenameMove"),disabled:a.length!==1||p||v,onSelect:()=>qt(e)},{id:`copy-${e.path}`,label:r("conversation.filePanelCopy"),disabled:a.length===0,onSelect:()=>me("copy",a)},{id:`cut-${e.path}`,label:r("conversation.filePanelCut"),disabled:a.length===0,onSelect:()=>me("cut",a)},{id:`paste-${e.path}`,label:r("conversation.filePanelPaste"),disabled:!lt,onSelect:()=>{st(o)}},{id:`copy-relative-${e.path}`,label:r("conversation.filePanelCopyRelativePath"),onSelect:()=>{Ge("relative",e)}},{id:`copy-absolute-${e.path}`,label:r("conversation.filePanelCopyAbsolutePath"),onSelect:()=>{Ge("absolute",e)}},{id:`delete-${e.path}`,label:r("conversation.filePanelDelete"),disabled:a.length===0||p||v,onSelect:()=>Yt(a)}]}async function An(e,a){if(Pe.isMobile)return;e.preventDefault();const o=z(a.path,a.kind),u=xt.has(o.path)?at:[o],f=o.kind==="directory"?o.path:ve(o.path);xt.has(o.path)||Sn(o);const d=Ei(o,u,f);if(Pe.isDesktop){await Xi(d);return}Pe.isWeb&&(I(!1),L(!1),H({positionX:e.clientX,positionY:e.clientY,items:d}))}c.useEffect(()=>{if(O!=="workspace")return;function e(a){if(!ma(a)||a.altKey||a.shiftKey||pa(a.target))return;const o=a.key.toLowerCase();if(o==="c"&&Te){a.preventDefault(),me("copy");return}if(o==="x"&&Te){a.preventDefault(),me("cut");return}o==="v"&<&&(a.preventDefault(),st())}return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[O,Te,lt,me,st]);function Jt(e,a){return i.jsx(i.Fragment,{children:e.map(o=>{const u=z(o.path,o.kind),f=o.kind==="directory",d=f&&E.includes(o.path),y=f&&Ne.includes(o.path),N=Me[o.path]??[],pe=ee?an(N,Me,W.statusByPath,W.changedDirs):N,Mi=xt.has(o.path),Ri=Ht===o.path,ct=W.statusByPath.get(o.path.replace(/\\/g,"/")),Wn=f&&W.changedDirs.has(o.path.replace(/\\/g,"/")),Ti=(C==null?void 0:C.mode)==="cut"&&C.items.some(be=>be.path===o.path);return i.jsxs("div",{className:"file-tree-node",children:[i.jsxs("button",{className:"file-tree-item",type:"button","data-active":Ri,"data-selected":Mi,"data-cut-pending":Ti||void 0,"data-kind":o.kind,"aria-expanded":f?d:void 0,style:{paddingInlineStart:`${sa+a*ca}px`},onClick:be=>{if(f){if(be.shiftKey||jt(be)){Se(),Ue(u,be);return}Se(),Ue(u,be),kn(o.path);return}Pi(o.path,be)},onContextMenu:be=>{An(be,o)},children:[i.jsx("span",{className:`file-tree-chevron${f?"":" is-hidden"}`,"aria-hidden":"true",children:d?"v":">"}),f?null:i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(o.name),"aria-hidden":"true",children:Mt(o.name)}),i.jsx("span",{className:"file-tree-label","data-status":ct??void 0,"data-has-changes":Wn||void 0,children:o.name}),!f&&ct?i.jsx("span",{className:"git-status-badge","data-status":ct,"aria-label":ct,children:ct}):null,f&&Wn?i.jsx("span",{className:"file-tree-dir-badge","aria-hidden":"true"}):null,y?i.jsx("span",{className:"file-tree-meta",children:r("common.loading")}):null]}),f&&d?i.jsx("div",{className:"file-tree-children",children:y&&!N.length?i.jsx("p",{className:"file-tree-empty",children:r("common.loading")}):pe.length?Jt(pe,a+1):i.jsx("p",{className:"file-tree-empty",children:r("conversation.filePanelEmptyDirectory")})}):null]},`${o.kind}-${o.path}`)})})}function ki(e){return i.jsx(i.Fragment,{children:e.map(a=>{const o=a.kind==="directory",u=xt.has(a.path),f=Ht===a.path;return i.jsx("div",{className:"file-tree-node",children:i.jsxs("button",{className:"file-tree-item is-search-result",type:"button","data-active":f,"data-selected":u,"data-kind":a.kind,onClick:d=>{ji(a,d)},onContextMenu:d=>{An(d,a)},children:[i.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),o?null:i.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(a.name),"aria-hidden":"true",children:Mt(a.name)}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:a.name}),i.jsx("span",{className:"file-tree-path",children:a.path})]})]})},`search-${a.kind}-${a.path}`)})})}return i.jsx("section",{className:["conversation-panel","surface-card","file-panel",t].filter(Boolean).join(" "),"data-testid":"file-context-panel",children:l?i.jsxs(i.Fragment,{children:[i.jsx(Vi,{workspaceId:l,filePath:le,open:le!==null,onClose:()=>{ce.current+=1,Ae(null),re(null)},onSaved:async e=>{await we(),await he(e),Ee(a=>a+1)},diffContent:hi,showDetachAction:Pe.isDesktop&&Pe.bridge.supported,onDetach:()=>{le&&Ci(le)}}),s?null:i.jsx("div",{className:"file-panel-heading-row",children:i.jsx("h2",{className:"file-panel-heading",children:r("conversation.filePanelTitle")})}),m?null:i.jsxs("div",{className:"file-panel-tabs",role:"tablist","aria-label":r("conversation.filePanelTitle"),children:[i.jsx("button",{className:O==="workspace"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":O==="workspace",onClick:()=>Ze("workspace"),children:r("conversation.filePanelWorkspaceTab")}),i.jsxs("button",{className:O==="session"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":O==="session",onClick:()=>{$e&&Ze("session")},disabled:!$e,children:[r("conversation.filePanelSessionTab"),i.jsx("span",{className:"file-panel-tab-badge","aria-label":`${r("conversation.filePanelSessionTab")} ${sn}`,children:sn})]})]}),O==="workspace"?i.jsxs(i.Fragment,{children:[i.jsx("input",{ref:mn,"data-testid":"file-panel-upload-input",type:"file",hidden:!0,onChange:e=>void Si(e)}),bn?i.jsx("div",{className:"file-panel-toolbar file-panel-toolbar-mobile","aria-label":r("conversation.filePanelTitle"),children:i.jsxs("div",{className:"file-mobile-action-shell",ref:hn,children:[i.jsxs("button",{className:"secondary-button file-mobile-action-trigger",type:"button","aria-label":r("conversation.filePanelActionsMenu"),"aria-haspopup":"menu","aria-expanded":et,"data-active":et,onClick:()=>{I(!1),L(e=>!e)},children:[i.jsx("span",{children:r("conversation.filePanelActionsMenu")}),i.jsx(za,{})]}),et?i.jsxs("div",{className:"file-mobile-action-menu",role:"menu","aria-label":r("conversation.filePanelActionsMenu"),children:[i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>me("copy")),disabled:!Te,children:r("conversation.filePanelCopy")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>me("cut")),disabled:!Te,children:r("conversation.filePanelCut")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>st()),disabled:!lt||p||v,children:r("conversation.filePanelPaste")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Tn()},children:Ye?r("conversation.filePanelHideSearch"):r("conversation.filePanelShowSearch")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Wt(e=>!e)},disabled:vt.length===0,children:ee?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(Rn),disabled:Fe||p||pt,children:r("conversation.filePanelRefresh")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Fn()},disabled:!Cn,children:r("conversation.filePanelCollapseCurrent")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),_n()},disabled:p||v,children:r("conversation.filePanelUpload")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(Kt),disabled:!yn||v,children:r("conversation.filePanelDownload")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(qt),disabled:!gn||p||v,children:r("conversation.filePanelRenameMove")}),i.jsx("button",{className:"file-mobile-action-menu-item danger",type:"button",role:"menuitem",onClick:()=>J(Yt),disabled:!xn||p||v,children:r("conversation.filePanelDelete")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ke("create_file")),disabled:p||v,children:r("conversation.filePanelNewFile")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ke("create_directory")),disabled:p||v,children:r("conversation.filePanelNewDirectory")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ge("absolute")),disabled:!Vt,children:r("conversation.filePanelCopyAbsolutePath")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>J(()=>Ge("relative")),disabled:!Vt,children:r("conversation.filePanelCopyRelativePath")})]}):null]})}):i.jsxs("div",{className:"file-panel-toolbar","aria-label":r("conversation.filePanelTitle"),children:[i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCopy"),"aria-label":r("conversation.filePanelCopy"),onClick:()=>me("copy"),disabled:!Te,children:i.jsx(Aa,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCut"),"aria-label":r("conversation.filePanelCut"),onClick:()=>me("cut"),disabled:!Te,children:i.jsx(La,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelPaste"),"aria-label":r("conversation.filePanelPaste"),onClick:()=>void st(),disabled:!lt||p||v,children:i.jsx(Ba,{})}),i.jsxs("div",{className:"file-toolbar-menu-shell",ref:dn,children:[i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCopyPath"),"aria-label":r("conversation.filePanelCopyPath"),"aria-haspopup":"menu","aria-expanded":Ie,"data-active":Ie,onClick:()=>{L(!1),I(e=>!e)},disabled:!Vt,children:i.jsx(Fa,{})}),Ie?i.jsxs("div",{className:"file-toolbar-menu",role:"menu",children:[i.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Ge("absolute"),children:r("conversation.filePanelCopyAbsolutePath")}),i.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Ge("relative"),children:r("conversation.filePanelCopyRelativePath")})]}):null]}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCollapseCurrent"),"aria-label":r("conversation.filePanelCollapseCurrent"),onClick:Fn,disabled:!Cn,children:i.jsx(Ta,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelRefresh"),"aria-label":r("conversation.filePanelRefresh"),onClick:()=>void Rn(),disabled:Fe||p||pt,children:i.jsx(_a,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelSearchButton"),"aria-label":r("conversation.filePanelSearchButton"),"data-active":Ye,onClick:Tn,disabled:Fe,children:i.jsx(Zn,{})}),vt.length>0?i.jsx("button",{className:"file-toolbar-button",type:"button",title:ee?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges"),"aria-label":ee?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges"),"data-active":ee,onClick:()=>Wt(e=>!e),children:i.jsx(Ka,{})}):null,i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelUpload"),"aria-label":r("conversation.filePanelUpload"),onClick:_n,disabled:p||v,children:i.jsx($a,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelDownload"),"aria-label":r("conversation.filePanelDownload"),onClick:()=>void Kt(),disabled:!yn||v,children:i.jsx(Oa,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelRenameMove"),"aria-label":r("conversation.filePanelRenameMove"),onClick:()=>qt(),disabled:!gn||p||v,children:i.jsx(Ua,{})}),i.jsx("button",{className:"file-toolbar-button danger",type:"button",title:r("conversation.filePanelDelete"),"aria-label":r("conversation.filePanelDelete"),onClick:()=>Yt(),disabled:!xn||p||v,children:i.jsx(Ha,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelNewFile"),"aria-label":r("conversation.filePanelNewFile"),onClick:()=>void Ke("create_file"),disabled:p||v,children:i.jsx(Wa,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelNewDirectory"),"aria-label":r("conversation.filePanelNewDirectory"),onClick:()=>void Ke("create_directory"),disabled:p||v,children:i.jsx(Va,{})})]}),oe&&typeof document<"u"?Fi.createPortal(i.jsx("div",{className:"file-web-context-menu",ref:$t,role:"menu","aria-label":r("conversation.filePanelActionsMenu"),style:{left:`${(Ce==null?void 0:Ce.left)??Math.max(8,oe.positionX)}px`,top:`${(Ce==null?void 0:Ce.top)??Math.max(8,oe.positionY)}px`,maxHeight:Ce?`${Ce.maxHeight}px`:void 0},children:oe.items.map(e=>i.jsx("button",{className:["file-web-context-menu-item",e.label===r("conversation.filePanelDelete")?"danger":""].filter(Boolean).join(" "),type:"button",role:"menuitem",disabled:e.disabled,onClick:()=>{H(null),e.onSelect()},children:e.label},e.id))}),document.body):null,Pn?i.jsx("p",{className:"file-panel-clipboard-status","data-mode":C==null?void 0:C.mode,children:Pn}):null,Ye?i.jsxs("form",{className:"file-toolbar-search",onSubmit:e=>void wi(e),children:[i.jsx("input",{value:A,onChange:e=>Qe(e.target.value),placeholder:r("conversation.filePanelSearchPlaceholder")}),bn?i.jsx("button",{className:"secondary-button file-mobile-search-submit",type:"submit","aria-label":r("conversation.filePanelSearchButton"),disabled:pt,children:r("conversation.filePanelSearchButton")}):i.jsx("button",{className:"file-toolbar-button",type:"submit",title:r("conversation.filePanelSearchButton"),"aria-label":r("conversation.filePanelSearchButton"),disabled:pt,children:i.jsx(Zn,{})})]}):null,i.jsx("div",{ref:mi,className:"file-tree","data-search-mode":fe,"data-scrollbar-autohide":"true",children:Fe&&He.length===0?i.jsx("p",{className:"file-tree-status status-text",children:r("common.loading")}):fe?Re!=null&&Re.length?ki(Re):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSearchEmpty")}):ee?yt.length?Jt(yt,0):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelNoChanges")}):He.length?Jt(He,0):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelEmptyDirectory")})}),i.jsx($n,{open:S!==null,title:(U==null?void 0:U.title)??"",description:U==null?void 0:U.description,onClose:Xt,children:i.jsxs("form",{className:"workbench-rename-form",onSubmit:e=>void Ni(e),children:[i.jsx(qi,{label:r("conversation.filePanelPathFieldLabel"),htmlFor:fn,description:(S==null?void 0:S.mode)==="rename"?S.target.path:(S==null?void 0:S.baseDirectory)||void 0,children:i.jsx("input",{id:fn,type:"text",value:Bt??"",placeholder:r("conversation.filePanelPathFieldPlaceholder"),autoFocus:!0,onChange:e=>We(e.target.value)})}),i.jsxs(Yi,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:p,onClick:Xt,children:r("common.cancel")}),i.jsx("button",{type:"submit",className:"primary-button",disabled:p||!(Bt??"").trim(),children:p?(U==null?void 0:U.pendingLabel)??r("common.loading"):(U==null?void 0:U.submitLabel)??r("common.save")})]})]})}),i.jsxs($n,{open:B!==null,title:r("conversation.filePanelDeleteConfirmTitle"),description:r("conversation.filePanelDeleteConfirmDescription"),onClose:()=>{p||Be(null)},children:[i.jsx("p",{className:"workbench-section-empty",children:B!=null&&B.length?B.length===1?((Bn=B[0])==null?void 0:Bn.kind)==="directory"?r("conversation.filePanelDeleteDirectoryConfirm",{path:B[0].path}):r("conversation.filePanelDeleteFileConfirm",{path:B[0].path}):r("conversation.filePanelDeleteSelectionConfirm",{count:B.length}):""}),i.jsxs("div",{className:"workbench-modal-actions",children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:p,onClick:()=>Be(null),children:r("common.cancel")}),i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:p,onClick:()=>{Di()},children:p?r("conversation.filePanelDeleting"):r("conversation.filePanelDelete")})]})]})]}):$e&&n?i.jsx(ea,{sessionId:n,workspaceId:l,showSystemFiles:V,selectedPath:je,refreshVersion:rn,onCountChange:Ot,onSelectFile:he,onOpenFile:ze}):i.jsx("section",{className:"file-panel-section",children:i.jsx("p",{className:"status-text",children:r("conversation.filePanelSessionNoSession")})})]}):i.jsx("section",{className:"file-panel-section",children:i.jsx("p",{className:"status-text",children:r("conversation.filePanelNoWorkspace")})})})}function ve(t){return t.includes("/")?t.split("/").slice(0,-1).join("/"):g}function dt(t,n=!1){const l=t.split("/").filter(Boolean),s=n?l.length:l.length-1,m=[];for(let h=0;h<s;h+=1)m.push(l.slice(0,h+1).join("/"));return m}function zn(t,n){return t||((n==null?void 0:n.kind)==="directory"?n.path:n!=null&&n.path?ve(n.path):g)}function Kn(t,n){return t?`${t}/${n}`:n}function fa(t){var n;return((n=t.split(/[/\\]/).pop())==null?void 0:n.trim())??""}function z(t,n){return{path:t,kind:n}}function Gn(t){return t[t.length-1]??null}function da(t,n){return t.findIndex(s=>s.path===n.path)>=0?t.filter(s=>s.path!==n.path):[...t,n]}function ha(t,n,l){const s=t.findIndex(x=>x.path===l.path);if(s<0)return[l];const m=n?t.findIndex(x=>x.path===n):s;if(m<0)return[l];const h=Math.min(m,s),b=Math.max(m,s);return t.slice(h,b+1)}function jt(t){return!!(t!=null&&t.ctrlKey||t!=null&&t.metaKey)}function ma(t){return t.ctrlKey||t.metaKey}function pa(t){if(!(t instanceof HTMLElement))return!1;const n=t.tagName.toLowerCase();return n==="input"||n==="textarea"||n==="select"||t.isContentEditable}function wt(t){const n=[...new Map(t.map(s=>[s.path,s])).values()].sort((s,m)=>s.path.localeCompare(m.path)),l=[];for(const s of n)l.some(m=>m.kind==="directory"&&Tt(m.path,s.path))||l.push(s);return l}function ba(t,n){return(t==null?void 0:t.kind)==="directory"?t.path:t!=null&&t.path?ve(t.path):n}function va(t,n){let l=t;for(;l&&n.some(s=>s.kind==="directory"&&Tt(s.path,l));)l=ve(l);return l}function oi(t,n,l,s,m,h){const b=[];for(const x of t){if(b.push(z(x.path,x.kind)),x.kind!=="directory"||!l.includes(x.path))continue;const j=n[x.path]??[],_=s?an(j,n,m,h):j;b.push(...oi(_,n,l,s,m,h))}return b}function ya(t,n,l){const s=Math.max(0,l.width),m=Math.max(0,l.height),h=Math.max(0,m-ne*2),b=Math.max(0,s-ne*2),x=Math.min(Math.max(n.width,0),b),j=Math.max(0,m-t.y-Pt-ne),_=Math.max(0,t.y-Pt-ne),M=j<n.height&&_>j,ye=It(Math.max(M?_:j,aa),0,h),K=Math.min(Math.max(n.height,0),ye),xe=M?t.y-Pt-K:t.y+Pt,ge=Math.max(ne,m-ne-K),G=Math.max(ne,s-ne-x);return{top:It(xe,ne,ge),left:It(t.x,ne,G),maxHeight:Math.max(0,ye)}}function It(t,n,l){return!Number.isFinite(t)||l<n?n:Math.min(Math.max(t,n),l)}function qe(t,n="posix"){return t?ri(t,n):"."}function xa(t,n,l){const s=ri(t,l),m=qe(n,l).replace(/^\.[/\\]?/,"");if(!m)return s;const h=si(l),b=m.replace(/^[/\\]+/,"");return b?s.endsWith("/")||s.endsWith("\\")?`${s}${b}`:`${s}${h}${b}`:s}function ga(t){return/^[a-zA-Z]:[\\/]/.test(t)||t.includes("\\")?"windows":"posix"}function ri(t,n){return t&&(si(n)==="\\"?t.replace(/\//g,"\\"):t.replace(/\\/g,"/"))}function si(t){return t==="windows"?"\\":"/"}function Tt(t,n){return n===t||n.startsWith(`${t}/`)}function ci(t,n,l){return t===n?l:t.startsWith(`${n}/`)?`${l}${t.slice(n.length)}`:t}function Ca(t,n,l){return t.map(s=>({...s,path:ci(s.path,n,l)}))}function Pa(t){return t.mode==="create_file"?{title:r("conversation.filePanelNewFile"),description:r("conversation.filePanelCreateFileDescription"),submitLabel:r("conversation.filePanelCreateFileSubmit"),pendingLabel:r("conversation.filePanelCreatingFile")}:t.mode==="create_directory"?{title:r("conversation.filePanelNewDirectory"),description:r("conversation.filePanelCreateDirectoryDescription"),submitLabel:r("conversation.filePanelCreateDirectorySubmit"),pendingLabel:r("conversation.filePanelCreatingDirectory")}:{title:r("conversation.filePanelRenameMove"),description:r("conversation.filePanelRenameDescription"),submitLabel:r("conversation.filePanelRenameSubmit"),pendingLabel:r("conversation.filePanelRenaming")}}async function ja(t){const n=await t.arrayBuffer(),l=new Uint8Array(n),s=32768;let m="";for(let h=0;h<l.length;h+=s){const b=l.subarray(h,h+s);m+=String.fromCharCode(...b)}return btoa(m)}function wa(t){const n=atob(t),l=new Uint8Array(n.length);for(let s=0;s<n.length;s+=1)l[s]=n.charCodeAt(s);return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}function Sa(t,n){if(typeof document>"u")throw new Error(r("conversation.filePanelDownloadFailed"));const l=window.URL.createObjectURL(n),s=document.createElement("a");s.href=l,s.download=t,document.body.append(s),s.click(),s.remove(),window.URL.revokeObjectURL(l)}async function Na(t,n){var l;if(!(n.isDesktop&&(await n.bridge.writeClipboardText(t)).ok)){if(typeof navigator<"u"&&((l=navigator.clipboard)!=null&&l.writeText))try{await navigator.clipboard.writeText(t);return}catch{}if(!Da(t))throw new Error(r("conversation.filePanelCopyPathFailed"))}}function Da(t){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.top="-9999px",n.style.left="-9999px",n.style.opacity="0",document.body.appendChild(n),n.focus(),n.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(n)}}function Ea(t,n){return t&&dt(t,!0).every(m=>m in n)?t:g}function Xn(t,n){if(!n)return[];const l=dt(n,!0);return t.filter(s=>l.includes(s))}function St(t,n,l){const s=on(n,l);return Object.entries(t).reduce((m,[h,b])=>(s.has(h)&&(m[h]=b),m),{})}function ka(t,n,l){const m=[...on(n,l)].filter(h=>h===g||h in t);return m.length?m:[g]}function on(t,n){const l=new Set([g]),s=ui(n,dt(t,!0));for(const m of s){l.add(m);for(const h of dt(m,!0))l.add(h)}return l}function Ma(t,n){const l=Object.keys(t),s=Object.keys(n);return l.length!==s.length?!1:l.every(m=>t[m]===n[m])}function kt(t,n){return t.includes(n)?t:[...t,n]}function ui(t,n){return n.reduce((l,s)=>kt(l,s),t)}function qn(t){return`file-panel.workspace-tree.${t}`}function Yn(t,n){return`file-panel.session-change-count.${t}.${n}`}function Jn(t,n){return Object.fromEntries(Object.keys(n).map(l=>[l,t[l]??null]))}function en(t,n){return[...on(n,t)]}function Q(t,n){return t instanceof In?t.message:n}function fi(t){return t instanceof Error&&t.message.startsWith("FILE_TREE_SNAPSHOT_TIMEOUT:")}function Qn(t){return fi(t)||t instanceof Error&&t.message.startsWith("FILE_TREE_ABORTED:")}function Ra(t){return new Promise(n=>{window.setTimeout(n,t)})}function Ta(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M2.5 4.5h11v2h-11zM2.5 7.5h7v2h-7zM2.5 10.5h4v2h-4z",fill:"currentColor"})})}function _a(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M12.8 5.2A5.5 5.5 0 1 0 13.5 8h-1.8A3.7 3.7 0 1 1 10.6 5l-1.4 1.4h4V2l-1.4 1.4z",fill:"currentColor"})})}function Zn(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M11.2 10.1l3 3-1.1 1.1-3-3a5 5 0 1 1 1.1-1.1zM6.8 10.3a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z",fill:"currentColor"})})}function Fa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3.5 4.3h5.2v1.4H4.9v5.4H3.5zm3.8-2.1h5.2v9.5H7.3z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M5.7 10.8h4.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Aa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M5 2.5h7.5v9H5z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M3.5 5H2.4V13.5H10V12.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function La(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M4.2 4.2a1.4 1.4 0 1 1 0 2.8 1.4 1.4 0 0 1 0-2.8zm0 5.4a1.4 1.4 0 1 1 0 2.8 1.4 1.4 0 0 1 0-2.8zm1-3.2 6.6 5.6M5.2 9.6l6.6-5.6",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})})}function Ba(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 3.5h8v10H4zM6 2.2h4v2H6z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M6 7.2h4M6 9.6h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Wa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 1.5h5l3 3v10H4z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M9 1.5v3h3",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 6.5v5M5.5 9h5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function $a(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"m5.5 5 2.5-2.5L10.5 5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Oa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"m5.5 8.5 2.5 2.5 2.5-2.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Ha(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M3.5 4.5h9M6.2 2.5h3.6l.6 1.4H13v1.2H3V3.9h2.6zM5.2 5.7v6.1m2.8-6.1v6.1m2.8-6.1v6.1M4.4 13.5h7.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Va(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M1.8 4.5h4l1.2 1.3h7.2v6.7H1.8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8.5 7.2v4M6.5 9.2h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Ua(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M3.2 11.9h2.2l5.9-5.9-2.2-2.2-5.9 5.9zM8.3 3.8l2.2 2.2M2.8 13.2h10.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function za(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"m4 6 4 4 4-4",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}function Ka(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M1.5 2h13l-5 6v5l-3 1.5V8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinejoin:"round"})})}function an(t,n,l,s){const m=[];for(const h of t){const b=h.path.replace(/\\/g,"/");h.kind==="file"?l.has(b)&&m.push(h):di(b,n,l,s)&&m.push(h)}return m}function di(t,n,l,s,m){const h=m??new Set;if(h.has(t))return!1;h.add(t);const b=n[t];if(!b)return s.has(t);for(const x of b){const j=x.path.replace(/\\/g,"/");if(x.kind==="file"){if(l.has(j))return!0}else if(di(j,n,l,s,h))return!0}return!1}export{nl as FileContextPanel};
|