@jingyi0605/codingns 0.9.7 → 0.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/public/assets/{AdaptiveButlerPage-DclGPzEx.js → AdaptiveButlerPage-CqBM1XiC.js} +2 -2
- package/dist/public/assets/{App-CcDXqFl1.css → App-7zrCMhE-.css} +1 -1
- package/dist/public/assets/App-Pe30N_Dy.js +30 -0
- package/dist/public/assets/{BootstrapPage-Bl21SsuW.js → BootstrapPage-D9ai1XhC.js} +1 -1
- package/dist/public/assets/ConversationPage-C8aU99KN.js +9 -0
- package/dist/public/assets/{DesktopDetachPreviewPage-uaOHVsjV.js → DesktopDetachPreviewPage-BJVPVFf2.js} +1 -1
- package/dist/public/assets/{DesktopModal-BxsogpLf.js → DesktopModal-DyC_e0eF.js} +1 -1
- package/dist/public/assets/DesktopWindowPage-BZleww0T.js +2 -0
- package/dist/public/assets/FileContextPanel-BklQRQXj.js +1 -0
- package/dist/public/assets/GitSidebar-D0tb3W87.js +6 -0
- package/dist/public/assets/MobileCreateSessionSheet-BS881Agk.js +1 -0
- package/dist/public/assets/{MobileSheet-C5IVmUsO.js → MobileSheet-C32hwIFd.js} +1 -1
- package/dist/public/assets/PluginAccessOverview-BDiz6fV8.js +1 -0
- package/dist/public/assets/{PluginContainerPage-_2u-9thM.js → PluginContainerPage-BMT6J0YS.js} +1 -1
- package/dist/public/assets/{PluginDetailPage-F9cKjSCp.js → PluginDetailPage-ztNhvCWP.js} +1 -1
- package/dist/public/assets/{PluginsListPage-BOhcua_4.js → PluginsListPage-Cuk2-U6E.js} +1 -1
- package/dist/public/assets/PureConversationPage-ShluI2En.js +1 -0
- package/dist/public/assets/{RelayConnectEntryPage-Ck_uZLzj.js → RelayConnectEntryPage-CMbjlD0k.js} +1 -1
- package/dist/public/assets/{ServerSettingsModal-ICd82a_x.js → ServerSettingsModal-CLSWyHu6.js} +1 -1
- package/dist/public/assets/SessionIndexPage-dqfauVAj.js +1 -0
- package/dist/public/assets/SettingsPage-PUga-wwJ.js +2 -0
- package/dist/public/assets/TerminalManagerPanel-75khWhRz.js +1 -0
- package/dist/public/assets/ToolFilesPage-S3eWxO_D.js +1 -0
- package/dist/public/assets/ToolGitPage-8RAMpope.js +1 -0
- package/dist/public/assets/ToolProcessesPage-TZACKEoH.js +1 -0
- package/dist/public/assets/ToolsHomePage-Whgu6Tyf.js +1 -0
- package/dist/public/assets/WorkbenchLandingPage-CC24vHza.js +1 -0
- package/dist/public/assets/{WorkbenchLayout-BksVkkFF.css → WorkbenchLayout-BZdfVest.css} +32 -1
- package/dist/public/assets/WorkbenchLayout-CoYxMzzR.js +1081 -0
- package/dist/public/assets/{WorkbenchModal-CsZeLArg.js → WorkbenchModal-2PaCY_Gj.js} +1 -1
- package/dist/public/assets/WorkbenchShellRoute-DLVRpGzb.css +1 -0
- package/dist/public/assets/WorkbenchShellRoute-QXztW_Ny.js +1 -0
- package/dist/public/assets/WorkspaceDebugDetailPage-Ce_oMmJ8.js +1 -0
- package/dist/public/assets/WorkspaceDetailPage-aX6w4Q7S.js +1 -0
- package/dist/public/assets/WorkspaceHomePage-DQttgj2w.js +1 -0
- package/dist/public/assets/{client-runtime-manager-BgGugw8T.js → client-runtime-manager-CGVLChqs.js} +1 -1
- package/dist/public/assets/host-alias-CeDJeL0T.js +1 -0
- package/dist/public/assets/index-BehUkul4.css +1 -0
- package/dist/public/assets/index-Bp1FnRo_.js +50 -0
- package/dist/public/assets/{login-direct-candidate-resolver-ty2uOY5y.js → login-direct-candidate-resolver-Bvs5uPix.js} +1 -1
- package/dist/public/assets/peer-host-config-sync-oelf2T0_.js +1 -0
- package/dist/public/assets/{plugin-permission-copy-iK3faI3n.js → plugin-permission-copy-Do028HzJ.js} +1 -1
- package/dist/public/assets/{plugins-api-CmV7aDGA.js → plugins-api-BOugklJ-.js} +1 -1
- package/dist/public/assets/{preferences-service-BoSmT_ny.js → preferences-service-Dys1mbBy.js} +1 -1
- package/dist/public/assets/relay-entry-B6UDc5cD.js +1 -0
- package/dist/public/assets/useRegisteredDebugTemplates-BafVuBvE.js +1 -0
- package/dist/public/assets/workbench-navigation-Bs4OQYD3.js +1 -0
- package/dist/public/index.html +2 -2
- package/dist/server/middlewares/auth-guard.js +1 -0
- package/dist/server/middlewares/auth-guard.js.map +1 -1
- package/dist/server/modules/assistant-capability/assistant-capability-controller.d.ts +3 -0
- package/dist/server/modules/assistant-capability/assistant-capability-controller.js +9 -0
- package/dist/server/modules/assistant-capability/assistant-capability-controller.js.map +1 -1
- package/dist/server/modules/assistant-capability/assistant-capability-service.d.ts +3 -0
- package/dist/server/modules/assistant-capability/assistant-capability-service.js +4 -1
- package/dist/server/modules/assistant-capability/assistant-capability-service.js.map +1 -1
- package/dist/server/modules/peer-host/host-api-proxy-service.d.ts +9 -0
- package/dist/server/modules/peer-host/host-api-proxy-service.js +174 -0
- package/dist/server/modules/peer-host/host-api-proxy-service.js.map +1 -0
- package/dist/server/modules/peer-host/host-handshake-controller.d.ts +7 -0
- package/dist/server/modules/peer-host/host-handshake-controller.js +10 -0
- package/dist/server/modules/peer-host/host-handshake-controller.js.map +1 -0
- package/dist/server/modules/peer-host/host-handshake.d.ts +15 -0
- package/dist/server/modules/peer-host/host-handshake.js +20 -0
- package/dist/server/modules/peer-host/host-handshake.js.map +1 -0
- package/dist/server/modules/peer-host/host-ws-proxy-service.d.ts +14 -0
- package/dist/server/modules/peer-host/host-ws-proxy-service.js +256 -0
- package/dist/server/modules/peer-host/host-ws-proxy-service.js.map +1 -0
- package/dist/server/modules/peer-host/peer-host-controller.d.ts +55 -0
- package/dist/server/modules/peer-host/peer-host-controller.js +62 -0
- package/dist/server/modules/peer-host/peer-host-controller.js.map +1 -0
- package/dist/server/modules/peer-host/peer-host-service.d.ts +77 -0
- package/dist/server/modules/peer-host/peer-host-service.js +529 -0
- package/dist/server/modules/peer-host/peer-host-service.js.map +1 -0
- package/dist/server/modules/sessions/codex-session-title-generator.js +18 -5
- package/dist/server/modules/sessions/codex-session-title-generator.js.map +1 -1
- package/dist/server/modules/sessions/session-controller.d.ts +10 -0
- package/dist/server/modules/sessions/session-controller.js +11 -0
- package/dist/server/modules/sessions/session-controller.js.map +1 -1
- package/dist/server/modules/sessions/session-history-service.d.ts +54 -2
- package/dist/server/modules/sessions/session-history-service.js +407 -63
- package/dist/server/modules/sessions/session-history-service.js.map +1 -1
- package/dist/server/modules/sessions/session-live-runtime-service.d.ts +6 -0
- package/dist/server/modules/sessions/session-live-runtime-service.js +181 -80
- package/dist/server/modules/sessions/session-live-runtime-service.js.map +1 -1
- package/dist/server/modules/sessions/session-title-utils.d.ts +3 -0
- package/dist/server/modules/sessions/session-title-utils.js +25 -0
- package/dist/server/modules/sessions/session-title-utils.js.map +1 -0
- package/dist/server/modules/sessions/workspace-office-mcp-config.d.ts +2 -1
- package/dist/server/modules/sessions/workspace-office-mcp-config.js +44 -3
- package/dist/server/modules/sessions/workspace-office-mcp-config.js.map +1 -1
- package/dist/server/modules/tasks/observability-controller.d.ts +2 -0
- package/dist/server/modules/tasks/observability-controller.js +16 -1
- package/dist/server/modules/tasks/observability-controller.js.map +1 -1
- package/dist/server/modules/tasks/observability-service.d.ts +12 -2
- package/dist/server/modules/tasks/observability-service.js +16 -3
- package/dist/server/modules/tasks/observability-service.js.map +1 -1
- package/dist/server/modules/tasks/task-manager.d.ts +2 -1
- package/dist/server/modules/tasks/task-manager.js +3 -0
- package/dist/server/modules/tasks/task-manager.js.map +1 -1
- package/dist/server/modules/tasks/task-scheduler.d.ts +2 -1
- package/dist/server/modules/tasks/task-scheduler.js +21 -0
- package/dist/server/modules/tasks/task-scheduler.js.map +1 -1
- package/dist/server/modules/tasks/task-types.d.ts +5 -0
- package/dist/server/modules/tasks/task-types.js.map +1 -1
- package/dist/server/modules/workbench/workbench-controller.js +3 -2
- package/dist/server/modules/workbench/workbench-controller.js.map +1 -1
- package/dist/server/modules/workbench/workbench-service.d.ts +2 -0
- package/dist/server/modules/workbench/workbench-service.js +162 -19
- package/dist/server/modules/workbench/workbench-service.js.map +1 -1
- package/dist/server/modules/workspace/affairs-library-controller.d.ts +1 -0
- package/dist/server/modules/workspace/affairs-library-controller.js +3 -0
- package/dist/server/modules/workspace/affairs-library-controller.js.map +1 -1
- package/dist/server/modules/workspace/affairs-library-service.d.ts +5 -0
- package/dist/server/modules/workspace/affairs-library-service.js +103 -4
- package/dist/server/modules/workspace/affairs-library-service.js.map +1 -1
- package/dist/server/modules/workspace/workspace-controller.d.ts +7 -1
- package/dist/server/modules/workspace/workspace-controller.js +11 -1
- package/dist/server/modules/workspace/workspace-controller.js.map +1 -1
- package/dist/server/modules/workspace/workspace-service.d.ts +9 -2
- package/dist/server/modules/workspace/workspace-service.js +45 -10
- package/dist/server/modules/workspace/workspace-service.js.map +1 -1
- package/dist/server/routes/affairs.js +4 -0
- package/dist/server/routes/affairs.js.map +1 -1
- package/dist/server/routes/peer-hosts.d.ts +3 -0
- package/dist/server/routes/peer-hosts.js +18 -0
- package/dist/server/routes/peer-hosts.js.map +1 -0
- package/dist/server/routes/public.d.ts +2 -1
- package/dist/server/routes/public.js +2 -1
- package/dist/server/routes/public.js.map +1 -1
- package/dist/server/routes/sessions.js +2 -0
- package/dist/server/routes/sessions.js.map +1 -1
- package/dist/server/server/create-server.d.ts +4 -0
- package/dist/server/server/create-server.js +31 -3
- package/dist/server/server/create-server.js.map +1 -1
- package/dist/server/shared/http/error-handler.js +12 -0
- package/dist/server/shared/http/error-handler.js.map +1 -1
- package/dist/server/storage/repositories/peer-host-repository.d.ts +44 -0
- package/dist/server/storage/repositories/peer-host-repository.js +271 -0
- package/dist/server/storage/repositories/peer-host-repository.js.map +1 -0
- package/dist/server/storage/repositories/session-discovery-diagnostics-repository.d.ts +10 -0
- package/dist/server/storage/repositories/session-discovery-diagnostics-repository.js +68 -0
- package/dist/server/storage/repositories/session-discovery-diagnostics-repository.js.map +1 -0
- package/dist/server/storage/repositories/session-source-index-repository.d.ts +14 -0
- package/dist/server/storage/repositories/session-source-index-repository.js +164 -0
- package/dist/server/storage/repositories/session-source-index-repository.js.map +1 -0
- package/dist/server/storage/repositories/workspace-navigation-state-repository.js +16 -7
- package/dist/server/storage/repositories/workspace-navigation-state-repository.js.map +1 -1
- package/dist/server/storage/sqlite/client.js +107 -0
- package/dist/server/storage/sqlite/client.js.map +1 -1
- package/dist/server/storage/sqlite/schema.sql +121 -0
- package/dist/server/types/domain.d.ts +88 -0
- package/dist/server/ws/workbench-ws-hub.js +5 -14
- package/dist/server/ws/workbench-ws-hub.js.map +1 -1
- package/dist/server/ws/ws-server.d.ts +2 -1
- package/dist/server/ws/ws-server.js +5 -1
- package/dist/server/ws/ws-server.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/providers/claude-session-store.js +19 -2
- package/node_modules/@codingns/session-sync-core/dist/providers/claude-session-store.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/providers/codex.d.ts +1 -0
- package/node_modules/@codingns/session-sync-core/dist/providers/codex.js +74 -6
- package/node_modules/@codingns/session-sync-core/dist/providers/codex.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/providers/opencode.js +11 -4
- package/node_modules/@codingns/session-sync-core/dist/providers/opencode.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/runtime/active-run-registry.js +8 -1
- package/node_modules/@codingns/session-sync-core/dist/runtime/active-run-registry.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.d.ts +3 -0
- package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js +144 -27
- package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js.map +1 -1
- package/package.json +1 -1
- package/dist/public/assets/App-BxX5mm9o.js +0 -30
- package/dist/public/assets/ConversationPage-CmiVCV0q.js +0 -9
- package/dist/public/assets/DesktopWindowPage-Bubfw1nC.js +0 -2
- package/dist/public/assets/FileContextPanel-DrYWcTkp.js +0 -1
- package/dist/public/assets/GitSidebar-CQsfJqun.js +0 -6
- package/dist/public/assets/MobileCreateSessionSheet-CqtmfVNo.js +0 -1
- package/dist/public/assets/MobileTopHeaderFrame-EoBm3-X0.js +0 -1
- package/dist/public/assets/MobileWorkspaceSwitcherHeader-BC8MMQs_.js +0 -1
- package/dist/public/assets/PluginAccessOverview-CrQiQxxZ.js +0 -1
- package/dist/public/assets/SessionIndexPage-Cox6P6dw.js +0 -1
- package/dist/public/assets/SettingsPage-BI5cM3j5.js +0 -2
- package/dist/public/assets/TerminalManagerPanel-DiVhBQhf.js +0 -1
- package/dist/public/assets/TerminalPage-6GBZ9nXN.css +0 -32
- package/dist/public/assets/TerminalPage-DUMUO7Ng.js +0 -55
- package/dist/public/assets/TerminalRuntimeFallbackModal-DGPR_CMh.js +0 -1
- package/dist/public/assets/ToolFilesPage-m88CAp-r.js +0 -1
- package/dist/public/assets/ToolGitPage-DCYpfTsb.js +0 -1
- package/dist/public/assets/ToolProcessesPage-Bk5ulsyq.js +0 -1
- package/dist/public/assets/ToolsHomePage-BrTwfjI7.js +0 -1
- package/dist/public/assets/WorkbenchLandingPage-q4AAmdMV.js +0 -1
- package/dist/public/assets/WorkbenchLayout-DD8b-m2G.js +0 -1027
- package/dist/public/assets/WorkbenchShellRoute-BaiW_vfb.js +0 -1
- package/dist/public/assets/WorkbenchShellRoute-CxKYZ6uF.css +0 -1
- package/dist/public/assets/WorkspaceDebugDetailPage-BcUUDEyw.js +0 -1
- package/dist/public/assets/WorkspaceDetailPage-zEZ1VARA.js +0 -1
- package/dist/public/assets/WorkspaceHomePage-CR0rqS4e.js +0 -1
- package/dist/public/assets/index-CFyk1rgJ.js +0 -50
- package/dist/public/assets/index-CrU73EIV.css +0 -1
- package/dist/public/assets/relay-entry-C8k5qsl5.js +0 -1
- package/dist/public/assets/terminal-runtime-meta-okQIDzfA.js +0 -1
- package/dist/public/assets/useRegisteredDebugTemplates-B_vXUtSe.js +0 -1
- package/dist/public/assets/workbench-navigation-DoDaQR4z.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
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 Vi=Object.defineProperty;var Gi=(e,t,s)=>t in e?Vi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var xe=(e,t,s)=>Gi(e,typeof t!="symbol"?t+"":t,s);import{t as c,b as l,u as Xi,G as zi,j as i,E as yn,o as ys,B as Yi,F as Ki,_ as xn}from"./index-Bp1FnRo_.js";import{D as gs}from"./DesktopModal-DyC_e0eF.js";import{w as vs,M as Pt,s as ss,c as ze,x as $t,n as bs,y as ns,z as Qi,p as ws,A as Zi,B as Pn,l as Ji,C as eo,r as to,D as so,E as wr,P as no,F as Us,b as Rt,d as ro,q as Ir,G as io,t as oo,u as ao,H as lo,I as Mr,J as co,K as Rn,m as uo}from"./workbench-navigation-Bs4OQYD3.js";import{P as ho,Q as fo,b as wt,R as kn,U as po,V as rs,X as Zt,Y as Tn,Z as mo,_ as go,$ as xs,a0 as Lt,a1 as Cn,a2 as vo,a3 as Sr,a4 as bo,d as Ft,a5 as wo,j as En,a6 as yr,a7 as rn,a8 as vt,a9 as xr,aa as Pr,ab as Io,ac as Mo,ad as So,S as yo,ae as xo,af as Po,ag as Ro,ah as ko,ai as To,L as Co,i as Rr,aj as An,ak as kr,al as Eo,am as Ao,an as _o,ao as jo,ap as No,aq as Oo,ar as Ie,as as is,at as Lo,au as $s,av as _n,aw as Do,ax as Ho,ay as qo,az as Bo,aA as Tr,aB as Ke,aC as Ps,aD as Cr,aE as Er,aF as Fo,aG as Ar,aH as Wo,aI as _r,aJ as on,aK as Ct,aL as Vt,u as Uo,I as an,aM as $o,aN as Vo,r as Go,O as ln,aO as cn,aP as Vs,aQ as Xo,aR as Ht,T as zo,aS as jr,aT as un,aU as dn,aV as Yo,aW as Ko,aX as Qo,aY as Zo,aZ as Jo,a_ as ea,w as Gt,a$ as Nr,b0 as Or,b1 as Lr,b2 as Dr,J as Hr,k as hn,f as qr,c as Is,y as Br,b3 as Fr,b4 as Wr,M as Ur,b5 as ta,b6 as sa,x as na,b7 as ra,N as ia}from"./WorkbenchLayout-CoYxMzzR.js";import{f as pt,u as mt,e as Xt,g as Et,h as fn,c as oa}from"./App-Pe30N_Dy.js";import{M as aa}from"./MobileSheet-C32hwIFd.js";import{FileContextPanel as $r}from"./FileContextPanel-BklQRQXj.js";import{GitSidebar as Vr}from"./GitSidebar-D0tb3W87.js";import{W as la}from"./WorkbenchModal-2PaCY_Gj.js";import{TerminalManagerPanel as Gr}from"./TerminalManagerPanel-75khWhRz.js";import{w as qt,r as Rs,a as jn,b as Nn}from"./styles-DwSuZo1w.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./host-alias-CeDJeL0T.js";import"./relay-entry-B6UDc5cD.js";function pn({connectionState:e,onReconnect:t}){const{showToast:s,dismissToast:n}=pt(),r=ho(),o=r?c(fo(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:o?c("conversation.reconnectFailedExplainWithRoute",{route:o}):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:o?c("conversation.reconnectExplainWithRoute",{route:o}):c("conversation.reconnectExplain"),tone:"info",durationMs:3200})},[o,e,n,t,s]),null}const ca=48;function ua(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 da(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(!ua(e))throw new Error(c("conversation.copyContentFailed"))}}function On(e,t,s){return Math.min(Math.max(e,t),s)}function ks(e,t=rs){return e&&t.includes(e)?e:t[0]??"codex"}function ha(e){return rs.includes(e)}function fa(e,t){const s=e.flatMap(n=>ha(n)?[n]:[]);return s.length>0?s:t?[t]:[]}function Gs(e){return e?e.nodeType===Node.ELEMENT_NODE?e:e.parentElement:null}function Ln(e){var s,n;const t=Gs(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 pa(e,t){return[t.trim()||c("conversation.selectionActionDefaultPrompt"),"",c("conversation.selectionActionQuotedLabel"),"```text",e.trim(),"```"].join(`
|
|
3
|
+
`)}function Ts(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=Gs(s.startContainer),r=Gs(s.endContainer);if(!n||!r||!e.contains(n)||!e.contains(r))return null;const o=t.toString().trim();if(!o)return null;const a=s.getBoundingClientRect();if(!a.width&&!a.height)return null;const u=Ln(s.startContainer),d=Ln(s.endContainer);return{text:o,sourceMessageId:u&&u===d?u:null,rect:{left:a.left,top:a.top,right:a.right,bottom:a.bottom,width:a.width,height:a.height}}}function ma({containerRef:e,session:t,currentCapabilities:s}){const n=mt(),r=Xt(),{showToast:o}=pt(),{shellMode:a,requestNavigationRefresh:u,selectWorkspace:d,upsertNavigationSession:h,currentTargetHostId:f,currentWorkspaceRef:I}=wt(),R=Xi(p=>p.profile.providers),w=l.useMemo(()=>kn(t==null?void 0:t.providerConfigMode,t==null?void 0:t.providerPresetId),[t==null?void 0:t.providerConfigMode,t==null?void 0:t.providerPresetId]),[v,m]=l.useState(null),[x,E]=l.useState(null),[S,j]=l.useState(!1),{visibleProviders:T}=po(rs,S,f),[N,b]=l.useState(""),[V,k]=l.useState(!1),[M,g]=l.useState(ks(t==null?void 0:t.provider)),[y,K]=l.useState(Zt),[ie,de]=l.useState(w.providerConfigMode),[te,z]=l.useState(w.providerPresetId),[P,q]=l.useState({}),[G,W]=l.useState(!1),[ee,fe]=l.useState(null),[$,se]=l.useState({}),[ne,ge]=l.useState(!1),[L,U]=l.useState(!1),[H,pe]=l.useState(!1),[me,Ae]=l.useState(0),[He,qe]=l.useState(null),[Pe,B]=l.useState(()=>({width:typeof window>"u"?0:window.innerWidth,height:typeof window>"u"?0:window.innerHeight})),X=l.useRef(!1),F=l.useRef(!1),O=l.useRef(!1),le=l.useRef(null),oe=l.useRef(null),Oe=a==="mobile"||r.isMobile,Le=l.useMemo(()=>p=>{var Y,ae;return(zi(p)?(ae=(Y=R[p])==null?void 0:Y.defaultModel)==null?void 0:ae.trim():null)||Zt},[R]),Z=l.useMemo(()=>kn(ie,te),[ie,te]),Ee=l.useMemo(()=>fa(T,M),[M,T]),J=l.useMemo(()=>Tn(M),[M]),_e=l.useMemo(()=>J?P[J]??null:null,[P,J]),Ye=l.useMemo(()=>mo(_e),[_e]),A=l.useMemo(()=>go(_e),[_e]),D=Z.providerConfigMode==="cc-switch-preset"?Z.providerPresetId??xs:xs,be=l.useMemo(()=>A.find(p=>p.value===D)??A[0]??null,[A,D]),re=l.useMemo(()=>M===(t==null?void 0:t.provider)&&Z.providerConfigMode===w.providerConfigMode&&Z.providerPresetId===w.providerPresetId&&s?s:ee??Lt(M),[s,ee,M,Z.providerConfigMode,Z.providerPresetId,t==null?void 0:t.provider,w.providerConfigMode,w.providerPresetId]),ce=l.useMemo(()=>{var Y;const p=Lt(M).modelOptions??[];return(Y=re.modelOptions)!=null&&Y.length?re.modelOptions:p},[re.modelOptions,M]),ue=l.useMemo(()=>ce.map(p=>({value:p.id,label:Cn(p)?c("conversation.modelUseCliDefault"):p.name})),[ce]),je=l.useMemo(()=>ce.find(p=>p.id===y)??ce[0]??null,[ce,y]),Me=l.useMemo(()=>{const p=je?Cn(je)?c("conversation.modelUseCliDefault"):je.name:c("conversation.modelUseCliDefault");return Ye?`${(be==null?void 0:be.label)??c("conversation.deploymentDefaultPreset")} · ${p}`:p},[je,be,Ye]),Be=l.useCallback(p=>{if(g(p),K(Le(p)),t&&p===t.provider&&Tn(p)){de(w.providerConfigMode),z(w.providerPresetId);return}de("global-default"),z(null)},[Le,t,w.providerConfigMode,w.providerPresetId]),Re=l.useMemo(()=>{const p=$[M]??(M===(t==null?void 0:t.provider)&&Z.providerConfigMode===w.providerConfigMode&&Z.providerPresetId===w.providerPresetId?s:ee);return!p||p.canStartSession!==!1?null:p.limitations[0]??c("conversation.capabilityDenied")},[s,ee,$,M,Z.providerConfigMode,Z.providerPresetId,t==null?void 0:t.provider,w.providerConfigMode,w.providerPresetId]),et=l.useMemo(()=>{var Ne;if(!v||typeof window>"u")return null;const p=(Ne=e.current)==null?void 0:Ne.getBoundingClientRect(),Y=p?Math.max(80,p.left+80):96,ae=p?Math.min(Pe.width-80,p.right-80):Pe.width-96,ye=p?Math.max(12,p.top+12):12,We=p?Math.max(ye,p.bottom-48):Math.max(12,Pe.height-48),$e=v.rect.left+v.rect.width/2;return{left:On($e,Y,Math.max(Y,ae)),top:On(v.rect.top-48,ye,We)}},[e,v,Pe.height,Pe.width]);l.useEffect(()=>{if(typeof window>"u")return;const p=()=>{B({width:window.innerWidth,height:window.innerHeight})};return p(),window.addEventListener("resize",p),()=>{window.removeEventListener("resize",p)}},[]),l.useEffect(()=>{if(!t){oe.current!==null&&typeof window<"u"&&(window.clearTimeout(oe.current),oe.current=null),le.current=null,O.current=!1,m(null),E(null),j(!1);return}const p=ks(t.provider);Be(p)},[Be,t]),l.useEffect(()=>{if(!S){W(!1);return}if(!J){W(!1);return}let p=!1;return W(!0),vo({targetHostId:f}).then(Y=>{p||q(Object.fromEntries(Y.items.map(ae=>[ae.app,ae])))}).catch(()=>{p||q({})}).finally(()=>{p||W(!1)}),()=>{p=!0}},[S,f,J]),l.useEffect(()=>{!J||Z.providerConfigMode!=="cc-switch-preset"||!Z.providerPresetId||G||!_e||_e.options.some(p=>p.id===Z.providerPresetId)||(de("global-default"),z(null))},[G,_e,J,Z.providerConfigMode,Z.providerPresetId]),l.useEffect(()=>{if(!t||!e.current||typeof window>"u"){oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null),le.current=null,O.current=!1,m(null),E(null);return}const p=e.current,Y=Ce=>{X.current||(le.current=Ce,m(Ce),Ce||j(!1))},ae=()=>{oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null)},ye=(Ce,gt)=>{if(le.current=Ce,ae(),gt!=null&>.immediate){Y(Ce);return}oe.current=window.setTimeout(()=>{oe.current=null,Y(le.current)},ca)},We=()=>{const Ce=Ts(p);if(O.current){le.current=Ce;return}ye(Ce)},$e=()=>{const Ce=Ts(p);if(O.current){le.current=Ce;return}ye(Ce,{immediate:!0})},Ne=Ce=>{!(Ce.target instanceof Node)||!p.contains(Ce.target)||(O.current=!0,ae())},De=()=>{O.current&&(O.current=!1,ye(Ts(p)))};return document.addEventListener("pointerdown",Ne),document.addEventListener("selectionchange",We),window.addEventListener("pointerup",De),window.addEventListener("pointercancel",De),window.addEventListener("mouseup",De),window.addEventListener("touchend",De),window.addEventListener("resize",$e),window.addEventListener("scroll",$e,!0),()=>{ae(),document.removeEventListener("pointerdown",Ne),document.removeEventListener("selectionchange",We),window.removeEventListener("pointerup",De),window.removeEventListener("pointercancel",De),window.removeEventListener("mouseup",De),window.removeEventListener("touchend",De),window.removeEventListener("resize",$e),window.removeEventListener("scroll",$e,!0)}},[e,t]),l.useEffect(()=>{(!S||!(x!=null&&x.sourceMessageId))&&k(!1)},[S,x==null?void 0:x.sourceMessageId]),l.useEffect(()=>{if(!S||!t)return;let p=!1;return M===t.provider&&Z.providerConfigMode===w.providerConfigMode&&Z.providerPresetId===w.providerPresetId&&s?(ge(!1),fe(s),()=>{p=!0}):(ge(!0),fe(Lt(M)),Sr(M,t.workspaceId,J?{providerConfigMode:Z.providerConfigMode,providerPresetId:Z.providerPresetId}:void 0,{targetHostId:f}).then(Y=>{p||fe(Y)}).catch(()=>{p||fe(Lt(M))}).finally(()=>{p||ge(!1)}),()=>{p=!0})},[S,f,s,J,M,Z.providerConfigMode,Z.providerPresetId,t,w.providerConfigMode,w.providerPresetId]),l.useEffect(()=>{if(!S||!t){se({});return}let p=!1;return bo(Ee,t.workspaceId,{targetHostId:f}).then(Y=>{p||se(Y)}),()=>{p=!0}},[S,f,t,Ee]),l.useEffect(()=>{if(!S||!t)return;const p=Ee.filter(ae=>{const ye=$[ae];return!ye||ye.canStartSession!==!1});if(p.length===0||p.includes(M))return;const Y=p[0];Be(Y)},[S,Be,$,M,t,Ee]),l.useEffect(()=>{var Y;const p=Le(M);if(!ce.some(ae=>ae.id===y)){if(ce.some(ae=>ae.id===p)){K(p);return}K(((Y=ce[0])==null?void 0:Y.id)??Zt)}},[ce,Le,y,M]),l.useEffect(()=>{if(!S){X.current=!1;return}X.current=!0},[S]),l.useEffect(()=>{if(typeof window>"u")return;const p=Y=>{Y.key==="Escape"&&(j(!1),E(null),m(null),X.current=!1)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);async function tt(){var Y,ae;if(!v)return;const p=v.text;m(null),typeof window<"u"&&((ae=(Y=window.getSelection())==null?void 0:Y.removeAllRanges)==null||ae.call(Y));try{await da(p,r),o({title:c("conversation.copyContentSuccess"),tone:"success"})}catch(ye){o({title:ye instanceof Error?ye.message:c("conversation.copyContentFailed"),tone:"error"})}}function dt(){v&&(qe({title:"",content:v.text}),Ae(p=>p+1),pe(!0),j(!1),E(null),m(null),X.current=!1)}function ht(){var ae,ye;if(!v||!t)return;const p=v,Y=ks(t.provider,Ee.length>0?Ee:rs);Be(Y),b(""),k(!1),E(p),m(null),j(!0),typeof window<"u"&&((ye=(ae=window.getSelection())==null?void 0:ae.removeAllRanges)==null||ye.call(ae))}function at(p){p.preventDefault(),X.current=!0}function ke(){F.current=!0,ht()}function It(){if(F.current){F.current=!1;return}ht()}async function Mt(){var p,Y,ae,ye;if(!(!x||!t)){if(Re){o({title:Re,tone:"error"});return}U(!0);try{const We=pa(x.text,N),$e=(je==null?void 0:je.id)===Zt?null:(je==null?void 0:je.id)??null;let Ne=null;if(V&&x.sourceMessageId)Ne=await yr(t.sessionId,{sourceType:"message",sourceMessageId:x.sourceMessageId,strategy:"auto",targetProvider:M,providerConfigMode:Z.providerConfigMode,providerPresetId:Z.providerPresetId,sessionKind:"annotation",annotationSourceMessageId:x.sourceMessageId,annotationSourceText:x.text},{targetHostId:f}),h(Ne),await rn(Ne.sessionId,{content:We,clientRequestId:((Y=(p=globalThis.crypto)==null?void 0:p.randomUUID)==null?void 0:Y.call(p))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:$e,permissionMode:vt(),providerConfigMode:Z.providerConfigMode,providerPresetId:Z.providerPresetId},{targetHostId:f});else{const Ce=await xr({workspaceId:t.workspaceId,provider:M,content:We,clientRequestId:((ye=(ae=globalThis.crypto)==null?void 0:ae.randomUUID)==null?void 0:ye.call(ae))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:$e,permissionMode:vt(),providerConfigMode:Z.providerConfigMode,providerPresetId:Z.providerPresetId,parentSessionId:t.sessionId,sessionKind:"annotation",annotationSourceMessageId:x.sourceMessageId??null,annotationSourceText:x.text},{targetHostId:f});Ne=Ce.session??await Pr(Ce.sessionId,{targetHostId:f})}h(Ne),u();const De=f&&I?{hostId:f,workspaceId:I.workspaceId}:I;d(Ne.workspaceId,De),n(ze(Ne.workspaceId,Ne.sessionId,De)),j(!1),E(null),m(null),X.current=!1}catch(We){o({title:We instanceof Error?We.message:c("conversation.selectionActionFailed"),tone:"error"})}finally{U(!1)}}}function st(p=!1){j(!1),E(null),X.current=!1,p&&m(null)}const nt=!!(!S&&v&&et),Se=!!(S&&x),Te=i.jsxs(vs,{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:L||!!Re||Ee.length===0,onClick:()=>void Mt(),children:L?c("conversation.sendingState"):c("conversation.selectionActionSubmit")})]}),Fe=x?i.jsxs(i.Fragment,{children:[i.jsx(Pt,{className:"conversation-selection-preview-section",heading:c("conversation.selectionActionPreviewLabel"),children:i.jsx("div",{className:"conversation-selection-action-dialog-quote",children:x.text})}),i.jsxs(Pt,{className:"conversation-selection-request-section",children:[i.jsx(ss,{className:"conversation-selection-field conversation-selection-prompt-field",label:c("conversation.selectionActionPromptLabel"),children:i.jsx("textarea",{value:N,rows:4,placeholder:c("conversation.selectionActionPromptPlaceholder"),onChange:p=>b(p.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:V,disabled:!x.sourceMessageId,onChange:p=>k(p.target.checked)}),i.jsx("span",{children:c("conversation.selectionActionIncludeContext")})]}),x.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(Pt,{className:"conversation-selection-target-section",heading:c("conversation.selectionActionTargetLabel"),children:i.jsxs("div",{className:"conversation-selection-grid",children:[i.jsx(ss,{className:"conversation-selection-field",label:c("conversation.forkTargetProviderLabel"),children:i.jsx("select",{value:M,onChange:p=>{Be(p.target.value)},children:Ee.map(p=>{var Y;return i.jsx("option",{value:p,disabled:((Y=$[p])==null?void 0:Y.canStartSession)===!1,children:Ft(p,"full")},p)})})}),i.jsx(ss,{className:"conversation-selection-field",label:c("conversation.forkTargetModelLabel"),children:J?i.jsx("div",{className:"conversation-selection-deployment-select",children:i.jsx(wo,{ariaLabel:c("conversation.forkTargetModelLabel"),triggerLabel:Me,presetOptions:A,selectedPresetValue:D,selectedPresetSummary:(be==null?void 0:be.summary)??null,onSelectPreset:p=>{if(p===xs){de("global-default"),z(null);return}de("cc-switch-preset"),z(p)},modelOptions:ue,selectedModelValue:y,onSelectModel:K,loadingPresets:G,loadingModels:ne,modelColumnDisabled:ne||!!Re,showPresetColumn:Ye,modelEmptyText:c("conversation.deploymentModelEmpty")})}):i.jsx("select",{value:y,disabled:ne||!!Re,onChange:p=>K(p.target.value),children:ce.map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))})})]})})]}):null;return!t||!nt&&!Se||typeof document>"u"?i.jsx(En,{open:H,preferredWorkspaceId:(t==null?void 0:t.workspaceId)??null,preferredSessionId:(t==null?void 0:t.sessionId)??null,creationRequestId:me,initialDraft:He,onClose:()=>pe(!1)}):i.jsxs(i.Fragment,{children:[Et.createPortal(nt?i.jsxs("div",{className:"conversation-selection-toolbar",style:et??void 0,onMouseDown:p=>p.preventDefault(),children:[i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:()=>void tt(),children:c("conversation.copyAction")}),i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:dt,children:c("conversation.selectionTodoAction")}),i.jsx("button",{type:"button",className:"conversation-selection-action is-primary",onPointerDown:at,onMouseDown:at,onPointerUp:ke,onClick:It,children:c("conversation.selectionActionButton")})]}):null,document.body),Oe?i.jsx(aa,{open:Se,title:c("conversation.selectionActionButton"),height:"auto",kind:"form",showHandle:!0,showCancelButton:!1,cardClassName:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:Te,onClose:()=>st(!1),children:Fe}):i.jsx(gs,{open:Se,title:c("conversation.selectionActionButton"),size:"compact",layout:"form",className:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:Te,onClose:()=>st(!1),children:Fe}),i.jsx(En,{open:H,preferredWorkspaceId:t.workspaceId,preferredSessionId:t.sessionId,creationRequestId:me,initialDraft:He,onClose:()=>pe(!1)})]})}function Xr(e,t){return Array.isArray(e)?e.some(s=>s.sessions.some(n=>n.sessionId===t)||Xr(s.children,t)):!1}const Ot=5,zr=["codex","claude-code"];function Yr(){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 Cs(){var e;return((e=Yr()[0])==null?void 0:e.value)??""}function Es(e,t=zr){return e==="claude-code"&&t.includes("claude-code")?"claude-code":t.includes("codex")?"codex":t[0]??null}function Kr(e){return e==="codex"||e==="claude-code"}function ga(e){return e.flatMap(t=>!t.enabled||!Kr(t.provider)?[]:[t.provider])}function Qr({session:e,showTrigger:t=!0,openRequestKey:s=0}){var qe,Pe;const{showToast:n}=pt(),{requestNavigationRefresh:r,currentTargetHostId:o,navigationGroups:a}=wt(),u=l.useId(),d=l.useId(),h=l.useId(),f=l.useId(),[I,R]=l.useState(!1),[w,v]=l.useState(!1),[m,x]=l.useState(null),[E,S]=l.useState(null),[j,T]=l.useState(null),[N,b]=l.useState(Es(e==null?void 0:e.provider)),[V,k]=l.useState(""),[M,g]=l.useState(()=>Cs()),[y,K]=l.useState(Ot),[ie,de]=l.useState(!1),[te,z]=l.useState(0),P=l.useMemo(()=>{var O,le,oe,Oe;const B=e==null?void 0:e.sessionId;if(!B)return!1;if(!o)return!0;const X=(le=(O=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:O.workspaceId)==null?void 0:le.trim(),F=(Oe=(oe=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:oe.sourceWorkspaceId)==null?void 0:Oe.trim();return!X||!F||X===F?!1:a.some(Le=>Le.sessions.some(Z=>Z.sessionId===B)||Xr(Le.childWorktrees,B))},[o,a,e==null?void 0:e.sessionId,(qe=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:qe.sourceWorkspaceId,(Pe=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:Pe.workspaceId]),{items:q}=Io(!!(e!=null&&e.sessionId&&P),o),G=Yr(),W=l.useMemo(()=>q?ga(q):zr,[q]),ee=q!==null&&W.length===0,fe=l.useMemo(()=>{var B;return((B=e==null?void 0:e.title)==null?void 0:B.trim())||null},[e==null?void 0:e.title]),$=l.useMemo(()=>m?{workspaceId:m.workspaceId,project:m.project,session:m.session}:null,[m]),se=(m==null?void 0:m.latestFollowUpTask)??null,ne=(m==null?void 0:m.latestVerificationRun)??null,ge=se&&(se.status==="active"||se.status==="waiting_user")?se:null,L=ne&&(ne.status==="queued"||ne.status==="running")?ne:null;l.useEffect(()=>{R(!1),de(!1),S(null),x(null),k(""),b(Es(e==null?void 0:e.provider)),g(Cs()),K(Ot)},[e==null?void 0:e.sessionId]),l.useEffect(()=>{const B=Es(e==null?void 0:e.provider,W);(!N||!W.includes(N))&&b(B)},[W,N,e==null?void 0:e.provider]),l.useEffect(()=>{if(!(e!=null&&e.sessionId)||!P){v(!1),x(null),S(null);return}let B=!1;return v(!0),S(null),Mo(e.sessionId,{targetHostId:o}).then(X=>{B||x(X.context)}).catch(X=>{B||(x(null),S(X instanceof Error?X.message:c("conversation.butlerActionLoadFailed")))}).finally(()=>{B||v(!1)}),()=>{B=!0}},[te,o,e==null?void 0:e.sessionId,P]);function U(){w||z(B=>B+1)}function H(){!m&&!w&&U()}if(l.useEffect(()=>{t||s<=0||(R(!0),H())},[w,s,t,m]),!(e!=null&&e.sessionId)||!P)return null;async function pe(){if(!$){H();return}if(!N)return;const B=V.trim(),X=M.trim();if(!B){n({title:c("conversation.butlerFollowUpObjectiveRequired"),tone:"warning"});return}if(!X){n({title:c("conversation.butlerFollowUpCompletionCriteriaRequired"),tone:"warning"});return}T("follow-up");try{const F=await ko({projectId:$.project.id,butlerSessionId:$.session.id,providerId:N,objective:B,completionCriteria:X,maxAutoContinueCount:y},{targetHostId:o});x(O=>O&&{...O,latestFollowUpTask:F.task}),r(),n({title:c("conversation.butlerFollowUpStarted"),description:c("conversation.butlerFollowUpStartedDescription",{projectName:$.project.name}),tone:"success"}),k(""),g(Cs()),K(Ot),R(!1)}catch(F){n({title:c("conversation.butlerFollowUpFailed"),description:F instanceof Error?F.message:void 0,tone:"error"})}finally{T(null)}}async function me(){if(se){T("follow-up");try{const B=await xo(se.id,{targetHostId:o});x(X=>X&&{...X,latestFollowUpTask:B.task}),r(),n({title:c("conversation.butlerFollowUpStopped"),description:c("conversation.butlerFollowUpStoppedDescription"),tone:"success"}),R(!1)}catch(B){n({title:c("conversation.butlerFollowUpStopFailed"),description:B instanceof Error?B.message:void 0,tone:"error"})}finally{T(null)}}}async function Ae(){if(!$){H();return}T("verification");try{const B=await Ro({projectId:$.project.id,butlerSessionId:$.session.id,verificationType:"browser",targetRef:fe||$.session.title||$.project.name},{targetHostId:o});x(X=>X&&{...X,latestVerificationRun:B.result.run}),r(),n({title:c("conversation.butlerVerificationStarted"),description:c("conversation.butlerVerificationStartedDescription",{projectName:$.project.name}),tone:"success"}),R(!1)}catch(B){n({title:c("conversation.butlerVerificationFailed"),description:B instanceof Error?B.message:void 0,tone:"error"})}finally{T(null)}}async function He(){if(ne){T("verification");try{const B=await Po(ne.projectId,ne.id,{targetHostId:o});x(X=>X&&{...X,latestVerificationRun:B.run}),r(),n({title:c("conversation.butlerVerificationStopped"),description:c("conversation.butlerVerificationStoppedDescription"),tone:"success"}),R(!1)}catch(B){n({title:c("conversation.butlerVerificationStopFailed"),description:B instanceof Error?B.message:void 0,tone:"error"})}finally{T(null)}}}return i.jsxs(i.Fragment,{children:[t?i.jsxs("div",{className:"conversation-butler-entry",onMouseEnter:()=>{de(!0),H()},onMouseLeave:()=>{de(!1)},children:[i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("conversation.butlerActionButton"),title:c("conversation.butlerActionButton"),onFocus:()=>{de(!0),H()},onBlur:()=>{de(!1)},onClick:()=>{R(!0),H()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(So,{})})}),ie?i.jsxs("div",{className:"conversation-butler-analysis-popover",role:"status","aria-live":"polite",children:[i.jsx("strong",{children:c("conversation.butlerAnalysisTitle")}),w?i.jsx("p",{children:c("conversation.butlerActionLoading")}):E?i.jsx("p",{children:E}):se?i.jsxs(i.Fragment,{children:[i.jsxs("p",{children:[c("conversation.butlerAnalysisObjectiveLabel"),":",se.objective]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisStatusLabel"),":",Dn(se.status)]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisSummaryLabel"),":",se.lastAutomationSummary||se.waitingReason||c("conversation.butlerAnalysisEmpty")]}),se.waitingReason?i.jsxs("p",{children:[c("conversation.butlerAnalysisWaitingReasonLabel"),":",se.waitingReason]}):null]}):i.jsx("p",{children:c("conversation.butlerAnalysisEmpty")})]}):null]}):null,i.jsx(la,{open:I,title:c("conversation.butlerActionModalTitle"),description:c("conversation.butlerActionModalDescription"),className:"conversation-butler-modal-card",footer:!w&&!E&&$?i.jsxs(vs,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:j!==null,onClick:()=>{Ae()},children:c("conversation.butlerVerificationAction")}),i.jsx("button",{type:"button",className:"primary-button",disabled:j!==null||ee||!N,onClick:()=>{pe()},children:c("conversation.butlerFollowUpAction")})]}):void 0,onClose:()=>{j||R(!1)},children:i.jsxs("div",{className:"conversation-butler-modal",children:[w?i.jsx("p",{className:"conversation-butler-modal-hint",children:c("conversation.butlerActionLoading")}):null,!w&&E?i.jsx("p",{className:"conversation-butler-modal-error",children:E}):null,!w&&!E&&$?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:$.project.name})]}),i.jsxs("div",{className:"conversation-butler-target-card",children:[i.jsx("span",{children:c("conversation.butlerActionSessionLabel")}),i.jsx("strong",{children:$.session.title||fe||$.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")})]}),ee?i.jsx("p",{className:"conversation-butler-modal-hint",children:c("conversation.butlerFollowUpProviderHint")}):i.jsx(yo,{workspaceId:$.workspaceId,providers:W,selectedProvider:N,disabled:j!==null,onSelect:B=>{Kr(B)&&b(B)}})]}),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:f,children:c("conversation.butlerFollowUpRoundLimitLabel")}),i.jsx("small",{children:c("conversation.butlerFollowUpRoundLimitHint")})]}),i.jsx("input",{id:f,type:"number",min:1,max:20,value:y,disabled:j!==null,onChange:B=>{const X=Number.parseInt(B.target.value,10);K(Number.isFinite(X)?X:Ot)}})]})]}),i.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[i.jsx("label",{htmlFor:u,children:c("conversation.butlerFollowUpObjectiveLabel")}),i.jsx("textarea",{id:u,rows:3,value:V,placeholder:c("conversation.butlerFollowUpObjectivePlaceholder"),disabled:j!==null,onChange:B=>{k(B.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:d,children:c("conversation.butlerFollowUpCompletionCriteriaLabel")}),i.jsx("small",{id:h,children:c("conversation.butlerCompletionTemplateSectionHint")})]}),i.jsx("textarea",{id:d,rows:3,value:M,placeholder:c("conversation.butlerFollowUpCompletionCriteriaPlaceholder"),"aria-describedby":h,disabled:j!==null,onChange:B=>{g(B.target.value)}}),i.jsx("div",{className:"conversation-butler-preset-grid",role:"group","aria-label":c("conversation.butlerCompletionTemplateSectionLabel"),children:G.map(B=>i.jsxs("button",{type:"button",className:"conversation-butler-preset-card","data-selected":M.trim()===B.value,"aria-pressed":M.trim()===B.value,disabled:j!==null,onClick:()=>{g(B.value)},children:[i.jsx("strong",{children:B.label}),i.jsx("span",{children:B.description})]},B.id))})]}),ge||L?i.jsxs("div",{className:"conversation-butler-meta-grid",children:[ge?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:Dn(ge.status)}),i.jsx("small",{children:c("conversation.butlerCurrentFollowUpProgress",{current:ge.autoContinueCount,max:ge.maxAutoContinueCount??Ot})}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:j!==null,onClick:()=>{me()},children:c("conversation.butlerStopFollowUpAction")})]}):null,L?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:va(L.status)}),i.jsx("small",{children:L.targetRef||L.verificationType}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:j!==null,onClick:()=>{He()},children:c("conversation.butlerStopVerificationAction")})]}):null]}):null]}):null]})})]})}function Dn(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 va(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 ba=340;function wa({session:e,onOpenBranchTree:t}){const s=mt(),n=fn(),r=l.useRef(null),o=l.useRef(null),[a,u]=l.useState(!1),[d,h]=l.useState(null),[f,I]=l.useState(null),[R,w]=l.useState(0);l.useEffect(()=>{u(!1),h(null)},[n.pathname,n.search]),l.useLayoutEffect(()=>{if(!a||!d||typeof window>"u"){I(null);return}const b=()=>{var g,y;const M=Co(d,{width:((g=o.current)==null?void 0:g.offsetWidth)??0,height:((y=o.current)==null?void 0:y.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:ba});I({position:"fixed",left:`${Math.round(M.left)}px`,top:`${Math.round(M.top)}px`,width:`${Math.round(M.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(M.maxHeight)}px`,transformOrigin:M.transformOrigin})},V=M=>{var y,K;const g=M.target;g&&!((y=o.current)!=null&&y.contains(g))&&!((K=r.current)!=null&&K.contains(g))&&m()},k=M=>{M.key==="Escape"&&m()};return b(),window.addEventListener("pointerdown",V),window.addEventListener("keydown",k),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("pointerdown",V),window.removeEventListener("keydown",k),window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[d,a]);function v(){var V;const b=(V=r.current)==null?void 0:V.getBoundingClientRect();b&&(h({x:b.right,y:b.bottom}),u(!0))}function m(){u(!1),h(null)}function x(b){s(b),m()}function E(b){const V=new URLSearchParams(n.search);V.set("toolPanel",b),x(`${n.pathname}?${V.toString()}`)}function S(){if(a){m();return}v()}function j(b){b.key!=="ContextMenu"&&!(b.shiftKey&&b.key==="F10")||(b.preventDefault(),b.stopPropagation(),v())}if(!e)return null;const T=[{key:"assistant",label:c("shell.butlerEntry"),onSelect:()=>{w(b=>b+1),m()}},...t?[{key:"branch",label:c("conversation.branchAction"),onSelect:()=>{t(),m()}}]:[],{key:"files",label:c("shell.filesEntry"),onSelect:()=>{E("files")}},{key:"git",label:c("shell.gitEntry"),onSelect:()=>{E("git")}},{key:"processes",label:c("shell.mobileConversationToolProcessesTab"),onSelect:()=>{E("processes")}}],N=a&&typeof document<"u"?Et.createPortal(i.jsx("div",{ref:o,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:b=>b.stopPropagation(),children:T.map(b=>i.jsx("button",{type:"button",className:"session-action-menu-item mobile-conversation-action-menu-item",role:"menuitem",onClick:b.onSelect,children:b.label},b.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":a,onClick:S,onKeyDown:j,children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(To,{})})}),i.jsx(Qr,{session:e,showTrigger:!1,openRequestKey:R})]}),N]})}function Zr({items:e,deletingQueueItemId:t=null,steeringQueueItemId:s=null,canSteer:n=!1,onDelete:r,onSteer:o}){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((a,u)=>{const d=a.status==="queued"||a.status==="failed",h=n&&typeof o=="function"&&(a.status==="queued"||a.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:a.content||c("conversation.queueImageOnly"),children:a.content||c("conversation.queueImageOnly")}),i.jsx("span",{className:`queued-message-item__status queued-message-item__status--${a.status}`,children:a.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 o(a.id),disabled:s===a.id,"aria-label":c("conversation.queueSteer"),title:c("conversation.queueSteer"),children:s===a.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(a.id),disabled:t===a.id,"aria-label":c("conversation.queueDelete"),title:c("conversation.queueDelete"),children:t===a.id?"…":"×"}):null]})]}),a.errorDetail?i.jsx("p",{className:"queued-message-item__error",children:a.errorDetail}):null]},a.id)})})]})}function Ia(e){const{sending:t,setSending:s,session:n,runtimeHasActiveRun:r,runtimeCanInterrupt:o}=e,a=l.useRef(!1);l.useEffect(()=>{if(!t){a.current=!1;return}if(Ma(n,r,o)){a.current=!0;return}a.current&&(a.current=!1,s(!1))},[o,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:Rr(e)}const Sa=30,As=80,Dt=60,Jr=600,Hn=300*1e3,ya=600,xa=5e3,Pa=1e4,Xs=120*1e3,ei=8,Ra=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/g;class ka{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 a;this.sessionId=t,this.options=s;const n=yn(Bs(t,s.targetHostId),Hn);this.hasAuthoritativeBootstrapMessages=(((a=s.bootstrapMessages)==null?void 0:a.length)??0)>0;const r=Jt(s.initialSession??null,(n==null?void 0:n.session)??null),o=Un(Ta(),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)<Dt&&((n==null?void 0:n.pagesLoaded)??0)<=1});this.authoritativeMessages=o.timeline.authoritativeMessages,this.runtimeOverlayMessages=o.timeline.runtimeOverlayMessages,this.activeRuntimeOverlayKeys=o.timeline.activeRuntimeOverlayKeys,this.pendingMessages=o.timeline.pendingMessages,this.replaceSnapshotSeedOnBackfill=o.timeline.replaceSnapshotSeedOnBackfill,this.state=An({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:o.messages,timelineItems:Ns(r,o.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:rl(this.state.session,n?this.authoritativeMessages.length:0),loadingOlderMessages:!1,olderCursor:n?null:this.state.olderCursor,hasOlderMessages:xt({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=yn(Bs(this.sessionId,this.options.targetHostId),Hn),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)<Dt&&((t==null?void 0:t.pagesLoaded)??0)<=1});this.state=An({session:Jt(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=Jt(this.state.session,t);s!==this.state.session&&this.patch({session:s,hasOlderMessages:xt({session:s,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})})}async sendMessage(t,s){const n=Jn();this.beginPendingReplyDebugTrace("send_live",n,t.length);const r=kr(this.sessionId,t,n,(s==null?void 0:s.attachmentMeta)??[],(s==null?void 0:s.attachments)??[],el(this.buildTimelineMessages("send_sequence"),this.state.session)),o=this.applyTimelineEvent({type:"pending.insert",source:"send_pending",pending:r});this.patch({messages:o.messages,session:ot(this.state.session,"running"),runtimeHasActiveRun:er(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:tr(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt});try{const a=await this.sendMessageWithFallback(t,n,s);this.markPendingReplyDebugTraceResponseReady(n,{returnedMessageId:a.message.messageId,returnedProviderSessionId:a.message.providerSessionId}),this.resolvePendingMessage(a.message,n),this.patch({messages:this.buildTimelineMessages("send_resolved")})}catch(a){this.failPendingReplyDebugTrace(n,a);const u=this.applyTimelineEvent({type:"pending.fail",source:"send_failed",clientRequestId:n});throw this.patch({messages:u.messages,session:ot(this.state.session,"failed"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1}),a}}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:er(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:tr(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 o=this.applyTimelineEvent({type:"pending.fail",source:"retry_failed",clientRequestId:t});throw this.patch({messages:o.messages,session:ot(this.state.session,"failed")}),r}}async enqueueMessage(t,s){const n=Jn();try{const r=await Eo(this.sessionId,{content:t,clientRequestId:n,model:(s==null?void 0:s.model)??null,reasoningLevel:(s==null?void 0:s.reasoningLevel)??null,permissionMode:vt(),attachments:(s==null?void 0:s.attachments)??[],providerConfigMode:s==null?void 0:s.providerConfigMode,providerPresetId:(s==null?void 0:s.providerPresetId)??null},{targetHostId:this.options.targetHostId});this.patch({queuedMessages:pl(this.state.queuedMessages,r)}),await this.refreshQueue()}catch(r){throw r}}async deleteQueuedMessage(t){await Ao(this.sessionId,t,{targetHostId:this.options.targetHostId}),await this.refreshQueue()}async steerQueuedMessage(t){await _o(this.sessionId,t,{targetHostId:this.options.targetHostId}),await this.refreshRuntimeSnapshot("queue_steer")}async interrupt(){await jo(this.sessionId,{targetHostId:this.options.targetHostId}),this.patch({session:ot(this.state.session,"interrupted"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:"user",errorCode:null,errorDetail:null})}async replyPermissionRequest(t,s){if(!(this.state.permissionRequests.find(o=>o.id===t)??null))return;const r=await No(this.sessionId,t,s,{targetHostId:this.options.targetHostId});this.patch({permissionRequests:Fs(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,As)))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=ys.getState().session)==null?void 0:s.accessToken)){ys.clear();return}this.realtimeClient=new Oo({targetHostId:this.options.targetHostId,sessionId:this.sessionId,cursor:this.state.lastCursor,limit:Dt,onSubscribed:()=>{Ie("session_send.realtime_subscribed",{sessionId:this.sessionId,lastCursor:this.state.lastCursor}),this.patch({connectionState:"connected",hasOlderMessages:xt({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 o;const r=this.state.connectionState;if(this.patch({connectionState:n,session:n==="reconnecting"&&Je((o=this.state.session)==null?void 0:o.runningState)?ot(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:o,replacedSnapshotSeed:a}=this.mergeHistoryMessages(n.messages,r,n.type==="session.backfill"?"realtime_backfill":"realtime_delta");this.patch({messages:o,lastCursor:n.cursor,historyState:"ready",olderCursor:n.type==="session.backfill"&&!a&&this.state.pagesLoaded>1?this.state.olderCursor:n.olderCursor??this.state.olderCursor,hasOlderMessages:n.type==="session.backfill"?!a&&this.state.pagesLoaded>1?this.state.hasOlderMessages:!!n.olderCursor:xt({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"?!a&&this.state.pagesLoaded>1?this.state.pagesLoaded:Math.max(this.state.pagesLoaded,this.authoritativeMessages.length>0?1:0):this.state.pagesLoaded,session:ot(this.state.session,Yn(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:()=>{ys.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:Ns((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=Un({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=Za(s.previousMessages,s.messages,"assistant"),r=Qa(t);return(s.validationIssues.length>0||r.some(a=>a.role==="assistant")||n.length>0)&&is("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(a=>hi(a)),assistantMoves:n,previousTail:Vn(s.previousMessages.slice(-6)),nextTail:Vn(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 Qs({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(ya,s);this.markSeenTimer=window.setTimeout(()=>{this.markSeenTimer=null;const r=this.getTargetSeenAt();r!==null&&(Ie("session_seen.start",{sessionId:this.sessionId,targetSeenAt:r,seenWatermark:this.seenWatermark}),this.markSeenInFlight=!0,this.lastMarkSeenRequestAt=Date.now(),Lo(this.sessionId,{targetHostId:this.options.targetHostId}).then(()=>{var o,a;this.bumpSeenWatermark(r),this.patch({session:Gn(this.state.session,r)}),(a=(o=this.options).onSeen)==null||a.call(o,this.sessionId,r),Ie("session_seen.end",{sessionId:this.sessionId,seenWatermark:this.seenWatermark})}).catch(()=>{Ie("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(Jr,Math.max(Dt,this.authoritativeMessages.length,Sa)),s=await $s(this.sessionId,null,t,"backward",{targetHostId:this.options.targetHostId});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:xt({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}),Ie("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,Ie("session.history_older.prefetch.start",{sessionId:this.sessionId,requestedCursor:t,reason:s,limit:As});const n=$s(this.sessionId,t,As,"backward",{targetHostId:this.options.targetHostId}).then(o=>(this.state.olderCursor===t&&(this.prefetchedOlderHistoryPage={requestedCursor:t,page:o}),Ie("session.history_older.prefetch.end",{sessionId:this.sessionId,requestedCursor:t,messageCount:o.messages.length,nextCursor:o.nextCursor}),o)).catch(o=>(Ie("session.history_older.prefetch.error",{sessionId:this.sessionId,requestedCursor:t,message:o instanceof Error?o.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,Ie("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,Ie("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(!Je((n=this.state.session)==null?void 0:n.runningState)){this.clearRuntimeRefreshTimer();return}t==="poll"&&this.state.connectionState==="connected"||(this.clearRuntimeRefreshTimer(),this.runtimeRefreshMode=t,Ie("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 o=this.runtimeRefreshMode??t;this.runtimeRefreshTimer=null,this.runtimeRefreshMode=null,this.refreshRuntimeState(o,s)},t==="poll"?Pa:1200))}async refreshRuntimeState(t,s){var n,r,o,a,u;Ie("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 _n(this.sessionId,{targetHostId:this.options.targetHostId}),h=Hs(this.state.runtimeHasActiveRun,d.runningState,d.hasActiveRun),f=qs(this.state.runtimeCanInterrupt,d.runningState,h,d.canInterrupt);this.patch({session:Xn(this.state.session,d),runtimeHasActiveRun:h,runtimeCanInterrupt:f,contextUsage:d.contextUsage,...Ls(d,this.state.interruptSource)}),await this.refreshQueue();const I=t==="poll"&&this.state.connectionState!=="connected"&&Je((r=this.state.session)==null?void 0:r.runningState);Ie("session_runtime.refresh.end",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((o=this.state.session)==null?void 0:o.runningState)??null,continuePolling:I}),I&&this.scheduleRuntimeRefresh("poll","connection_poll")}catch(d){Ie("session_runtime.refresh.error",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((a=this.state.session)==null?void 0:a.runningState)??null,message:d instanceof Error?d.message:"unknown"}),t==="poll"&&this.state.connectionState!=="connected"&&Je((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(Pr(this.sessionId,{targetHostId:this.options.targetHostId}).then(s=>{this.patch({session:Jt(s,this.state.session)})}).catch(()=>{})),zn(this.state.capabilities)&&t.push(Do(this.sessionId,{targetHostId:this.options.targetHostId}).then(s=>{this.patch({capabilities:s})}).catch(()=>{})),t.length!==0&&await Promise.allSettled(t)}async refreshPermissionRequests(){try{const t=await Ho(this.sessionId,{targetHostId:this.options.targetHostId});this.patch({permissionRequests:t.items})}catch{return}}shouldRefreshSessionDetail(){return this.state.session===null||zn(this.state.capabilities)||this.state.session.runningState===null}shouldRefreshRuntimeSnapshot(){return this.state.contextUsage===null||fl(this.state.session,this.state.runtimeHasActiveRun,this.state.runtimeCanInterrupt)}async refreshRuntimeSnapshot(t){Ie("session_runtime.snapshot.start",{sessionId:this.sessionId,reason:t});try{const s=await _n(this.sessionId,{targetHostId:this.options.targetHostId}),n=Hs(this.state.runtimeHasActiveRun,s.runningState,s.hasActiveRun),r=qs(this.state.runtimeCanInterrupt,s.runningState,n,s.canInterrupt);this.patch({session:Xn(this.state.session,s),runtimeHasActiveRun:n,runtimeCanInterrupt:r,contextUsage:s.contextUsage,...Ls(s,this.state.interruptSource)}),await this.refreshQueue(),Ie("session_runtime.snapshot.end",{sessionId:this.sessionId,reason:t,hasContextUsage:s.contextUsage!==null})}catch(s){Ie("session_runtime.snapshot.error",{sessionId:this.sessionId,reason:t,message:s instanceof Error?s.message:"unknown"})}}async refreshQueue(){try{const t=await qo(this.sessionId,{targetHostId:this.options.targetHostId});this.patch({queuedMessages:t.items})}catch{return}}async sendMessageWithFallback(t,s,n){var r;try{return await rn(this.sessionId,{content:t,clientRequestId:s,model:(n==null?void 0:n.model)??null,reasoningLevel:(n==null?void 0:n.reasoningLevel)??null,permissionMode:vt(),attachments:(n==null?void 0:n.attachments)??[],providerConfigMode:n==null?void 0:n.providerConfigMode,providerPresetId:(n==null?void 0:n.providerPresetId)??null},{targetHostId:this.options.targetHostId})}catch(o){if(!(o instanceof Yi)||o.status!==404&&o.status!==405||(((r=n==null?void 0:n.attachments)==null?void 0:r.length)??0)>0)throw o;return Ie("session_send.live_fallback",{sessionId:this.sessionId,clientRequestId:s,reason:o.message}),Bo(this.sessionId,{content:t,clientRequestId:s,permissionMode:vt()},{targetHostId:this.options.targetHostId})}}handleRuntimeStatus(t){var n;const s=Os((n=this.state.session)==null?void 0:n.runningState,t.status);this.patch({session:ot(this.state.session,s),runtimeHasActiveRun:Je(s)?this.state.runtimeHasActiveRun??!0:!1,runtimeCanInterrupt:Je(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}),Ut(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=Hs(this.state.runtimeHasActiveRun,t.runningState,t.hasActiveRun),n=qs(this.state.runtimeCanInterrupt,t.runningState,s,t.canInterrupt);if(this.patch({session:ol(this.state.session,t),runtimeHasActiveRun:s,runtimeCanInterrupt:n,...Ls(t,this.state.interruptSource)}),Ut(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:Tr(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:xt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),session:ot(this.state.session,Yn("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=Os((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:ot(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=Os((n=this.state.session)==null?void 0:n.runningState,"interrupted");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_interrupted",{detail:t.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:ot(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:Fs(this.state.permissionRequests,t.request)})}handlePermissionRequestResolved(t){this.patch({permissionRequests:Fs(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,xa-(Date.now()-this.lastMarkSeenRequestAt))}applySeenWatermark(t){return!t||!this.seenWatermark?t:Gn(t,this.seenWatermark)}emit(){for(const t of this.listeners)t()}persistSnapshot(){Ki(Bs(this.sessionId,this.options.targetHostId),{session:this.state.session,capabilities:this.state.capabilities,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage,messages:sr(this.authoritativeMessages),timelineItems:Ns(this.state.session,sr(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),Ie(`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(),Ie(`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&&(Ie(`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();Ie(`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&&(Ie(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,o={}){const a=n.filter(ll);if(a.length===0)return;const u=Qn(s),d=Qn(r);Ke("session.messages.merge",{sessionId:this.sessionId,source:t,beforeCount:s.length,incomingCount:n.length,afterCount:r.length,incoming:a.slice(0,5).map(ul),beforeDuplicateGroupCount:u.length,afterDuplicateGroupCount:d.length,afterDuplicateGroups:d.slice(0,3),...o})}}function Ta(){return{authoritativeMessages:[],runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:!1}}function Ca(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 o=s.get(r.id)??null,a=ci(s,n,r,o);if(a){const h=s.get(a)??null;if(h){Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"prefer_equivalent",previous:ve(h),overlay:ve(r),replacedSameId:o?ve(o):null}),s.set(a,_s(h,r));continue}}if(o){Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"same_id",previous:ve(o),overlay:ve(r)}),s.set(r.id,_s(o,r));continue}const u=mn(s,n,r);if(u){const h=s.get(u)??null;if(h){Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"codex_compat",previous:ve(h),overlay:ve(r)}),s.set(u,_s(h,r));continue}}const d=gn(s,r);if(d&&n.has(d)){const h=s.get(d)??null;if(h){if(Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"opencode_compat",previous:ve(h),overlay:ve(r)}),Ms(h,r)){s.set(d,qn(h,r));continue}s.set(d,qn(h,r));continue}}Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"insert",overlay:ve(r)}),s.set(r.id,r)}return Na(Array.from(s.values()))}function _s(e,t){return{...ti(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 ti(e,t){if(e.id!==t.id)return t;if(Wt(e,t)){const a=os(e.toolCall,t.toolCall),u=si(e,t,a,as),d=ls(e.attachments,t.attachments),h=cs(e,t);return{...kt(e,t),kind:(a==null?void 0:a.status)==="running"?"tool_call":"tool_result",content:u,toolCall:a,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 kt(e,t);const s=os(e.toolCall,t.toolCall),n=as(e.content,t.content,e.timestamp,t.timestamp),r=ls(e.attachments,t.attachments),o=cs(e,t);return{...kt(e,t),content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:o.rawRef,timestamp:o.timestamp,sequence:o.sequence}}function qn(e,t){if(Wt(e,t)){const a=os(e.toolCall,t.toolCall),u=si(e,t,a,as),d=ls(e.attachments,t.attachments),h=cs(e,t);return{...kt(e,t),id:e.id,kind:(a==null?void 0:a.status)==="running"?"tool_call":"tool_result",content:u,toolCall:a,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{...kt(e,t),id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId};const s=os(e.toolCall,t.toolCall),n=as(e.content,t.content,e.timestamp,t.timestamp),r=ls(e.attachments,t.attachments),o=cs(e,t);return{...kt(e,t),id:e.id,content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:o.rawRef,timestamp:o.timestamp,sequence:o.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}function Wt(e,t){return Ms(e,t)||Ss(e,t)}function si(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 mn(e,t,s){if(!Ks(s))return null;for(const[n,r]of e.entries())if(!(n===s.id||!t.has(n)||!Ea(r,s)))return Ke("session.messages.codex_identity_bridge_match",{previous:ve(r),incoming:ve(s)}),n;return null}function Ea(e,t){if(!La(e,t))return!1;if(e.rawRef===t.rawRef)return!0;if(e.kind==="tool_call"||e.kind==="tool_result")return Ss(e,t);const s=ds(e.rawRef),n=ds(t.rawRef);if(!s||!n||s!==n)return!1;const r=Math.abs(e.sequence-t.sequence);return r>1?(Ke("session.messages.codex_identity_bridge_rejected",{reason:"sequence_distance",sequenceDistance:r,previous:ve(e),incoming:ve(t)}),!1):!0}function gn(e,t){if(!Fn(t))return null;const s=us(t.rawRef);if(s===null)return null;const n=At(t.timestamp);let r=null,o=Number.POSITIVE_INFINITY;for(const[a,u]of e.entries()){if(a===t.id||!Fn(u)||u.role!==t.role)continue;if(Ms(u,t))return a;if(u.kind!==t.kind||us(u.rawRef)!==s)continue;const h=At(u.timestamp),f=Math.abs(h-n),R=Math.abs(u.sequence-t.sequence)*6e4+f;R<o&&(r=a,o=R)}return r}function Aa(e,t,s){if(!vn(t))return!1;const n=zs(e.authoritativeMessages,t,"authoritative",s);if(n)return Ke("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"authoritative",matched:ve(n),incoming:ve(t)}),!0;const r=zs(e.pendingMessages,t,"pending",s);return r?(Ke("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"pending",matched:ve(r),incoming:ve(t)}),!0):!1}function zs(e,t,s,n){const r=At(t.timestamp),o=Ge(t.content),a=Ys(t.content),u=hs(t.attachments);let d=null,h=Number.POSITIVE_INFINITY;const f=[];for(const I of e){if(!(s==="authoritative"?Oa(I):ri(I)))continue;const w=Ge(I.content),v=Ys(I.content),m=w===o,x=v===a;if(!m&&!x)continue;const E=At(I.timestamp),S=Math.abs(E-r);if(S>300*1e3)continue;const j=Math.abs(I.sequence-t.sequence),T=hs(I.attachments),N=Ha(T,u);if(f.push(Ba(I,{strictTextMatches:m,relaxedTextMatches:x,attachmentCompatibility:N,distanceMs:S,sequenceDistance:j})),N==="conflict"&&(m||o.length===0))continue;const b=S+j*15e3+(m?0:500)+qa(N);b<h&&(d=I,h=b)}return f.length>0&&Ke("session.messages.runtime_user_match",{sessionId:n,target:s,matchedId:(d==null?void 0:d.id)??null,matchedScore:Number.isFinite(h)?h:null,incoming:Fa(t,{relaxedContent:a,attachmentSignature:u}),candidates:f.slice(0,5)}),d}function _a(e,t,s){for(const n of t){if(n.role!=="user"||n.kind!=="text")continue;const r=Tr(s,n,"sent",null);if(!zs(e,r,"authoritative",s))return!0}return!1}function os(e,t){return e?t?{...ja(e,t),input:ni(e.input,t.input),output:Bn(e.output,t.output),error:Bn(e.error,t.error)}:e:t}function ja(e,t){const s=e.status==="running"?0:1,n=t.status==="running"?0:1;return n!==s?n>s?t:e:t}function as(e,t,s,n){const r=Ge(e),o=Ge(t);return r===o?e.length>=t.length?e:t:r.length>o.length&&r.includes(o)?e:o.length>r.length&&o.includes(r)||n.localeCompare(s)>=0?t:e}function ls(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 ni(e,t){return t.length>e.length?t:e}function Bn(e,t){return e===null?t:t===null?e:ni(e,t)}function kt(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 cs(e,t){return Vt(e,t)<=0?e:t}function Ge(e){return e.replace(Ra,"").replace(/\r\n/g,`
|
|
4
|
+
`).trimEnd()}function Ys(e){return Ge(e).replace(/[ \t]+\n/g,`
|
|
5
|
+
`).replace(/\n{2,}/g,`
|
|
6
|
+
`).trim()}function Na(e){return[...e].sort((t,s)=>Vt(t,s))}function Ks(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("codex://")&&(e.role==="assistant"||e.role==="tool")}function vn(e){return e.role==="user"&&e.kind==="text"}function ri(e){return vn(e)&&e.deliveryState!=="failed"&&(e.rawRef.startsWith("pending://")||e.rawRef.startsWith("synthetic://")||e.rawRef.includes("#synthetic"))}function Oa(e){return vn(e)&&!ri(e)}function Fn(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&!(e.rawRef.startsWith("pending://")||e.rawRef.startsWith("synthetic://")||e.rawRef.includes("#synthetic"))&&(e.role==="user"||e.role==="assistant"||e.role==="tool")}function Wn(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")&&e.toolCall!==null}function Ms(e,t){var r,o;if(!Wn(e)||!Wn(t))return!1;const s=((r=e.toolCall)==null?void 0:r.callId.trim())??"",n=((o=t.toolCall)==null?void 0:o.callId.trim())??"";return s&&n?s===n:us(e.rawRef)===us(t.rawRef)}function us(e){if(!e.startsWith("opencode://"))return null;const t=e.indexOf("#"),s=t>=0?e.slice(t):"",n=t>=0?e.slice(0,t):e,r=n.indexOf("?");if(r<0)return e;const o=n.slice(0,r),a=new URLSearchParams(n.slice(r+1));if(!a.has("part"))return e;a.delete("part");const u=a.toString();return`${o}${u?`?${u}`:""}${s}`}function La(e,t){if(!Ks(e)||!Ks(t)||e.role!==t.role)return!1;const s=(e.kind==="tool_call"||e.kind==="tool_result")&&(t.kind==="tool_call"||t.kind==="tool_result");return!s&&e.kind!==t.kind?!1:s?Ss(e,t):Math.abs(e.sequence-t.sequence)>ei||!oi(e.timestamp,t.timestamp,Xs)?!1:t.kind==="text"||t.kind==="thinking"?ii(e,t,Xs):!1}function ii(e,t,s){if(e.deliveryState!=="sent"||t.deliveryState!=="sent"||!e.rawRef.startsWith("codex://")||!t.rawRef.startsWith("codex://")||e.role!==t.role||e.kind!==t.kind||e.toolCall!==null||t.toolCall!==null||e.kind!=="text"&&e.kind!=="thinking")return!1;const n=Ct(e.content),r=Ct(t.content);return oi(e.timestamp,t.timestamp,s)&&Ge(n.text)===Ge(r.text)&&Da(n.inlineImages,r.inlineImages)}function Ss(e,t){if(e.deliveryState!=="sent"||t.deliveryState!=="sent"||!e.rawRef.startsWith("codex://")||!t.rawRef.startsWith("codex://")||e.role!=="tool"||t.role!=="tool"||e.kind!=="tool_call"&&e.kind!=="tool_result"||t.kind!=="tool_call"&&t.kind!=="tool_result"||e.toolCall===null||t.toolCall===null)return!1;const s=e.toolCall.callId.trim(),n=t.toolCall.callId.trim();return s.length>0&&s===n}function ds(e){const t=e.match(/^codex:\/\/(.+?)(?:#|$)/);return(t==null?void 0:t[1])??null}function Da(e,t){return e.length===0||t.length===0?!0:e.length!==t.length?!1:e.every((s,n)=>{var r;return s.url===((r=t[n])==null?void 0:r.url)})}function oi(e,t,s){return Math.abs(At(e)-At(t))<=s}function At(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function ve(e){var t;return{id:e.id,rawRef:e.rawRef,role:e.role,kind:e.kind,sequence:e.sequence,timestamp:e.timestamp,callId:((t=e.toolCall)==null?void 0:t.callId)??null,contentPreview:e.kind==="text"||e.kind==="thinking"?Ge(Ct(e.content).text).slice(0,160):Ge(e.content).slice(0,160)}}function hs(e){return(e??[]).map(t=>[t.kind,t.fileName.trim().toLowerCase(),t.mimeType.trim().toLowerCase(),String(t.fileSize)].join(":")).sort().join("|")}function Ha(e,t){return!e&&!t?"same":!e||!t?"one_side_missing":e===t?"same":"conflict"}function qa(e){switch(e){case"same":return 0;case"one_side_missing":return 2500;case"conflict":default:return 12e4}}function Ba(e,t){return{...ve(e),comparableContent:Ys(e.content).slice(0,160),attachmentSignature:hs(e.attachments),strictTextMatches:t.strictTextMatches,relaxedTextMatches:t.relaxedTextMatches,attachmentCompatibility:t.attachmentCompatibility,distanceMs:t.distanceMs,sequenceDistance:t.sequenceDistance}}function Fa(e,t){return{...ve(e),comparableContent:t.relaxedContent.slice(0,160),attachmentSignature:t.attachmentSignature}}function Qs(e){let t=Ca(e.authoritativeMessages,e.runtimeOverlayMessages);for(const s of e.pendingMessages)t=Er(t,s);return $a(t,e.authoritativeMessages,e.runtimeOverlayMessages,e.activeRuntimeOverlayKeys)}function Un(e,t,s){const n=Qs(e);let r=e,o=!1;switch(s.type){case"timeline.seed":{r={authoritativeMessages:Ps(s.snapshotMessages,t,s.bootstrapMessages),runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:s.replaceSnapshotSeedOnBackfill};break}case"history.merge":{o=s.replaceSnapshotSeed&&e.replaceSnapshotSeedOnBackfill&&tl(e.authoritativeMessages,s.messages);const u=o?[]:e.authoritativeMessages;r={...e,authoritativeMessages:Ps(u,t,s.messages),activeRuntimeOverlayKeys:_a(e.authoritativeMessages,s.messages,t)?[]:e.activeRuntimeOverlayKeys,replaceSnapshotSeedOnBackfill:o?!1:e.replaceSnapshotSeedOnBackfill};break}case"runtime.message":{if(Aa(e,s.message,t)){r=e;break}r={...e,runtimeOverlayMessages:Fo(e.runtimeOverlayMessages,[s.message]),activeRuntimeOverlayKeys:Va(e,e.activeRuntimeOverlayKeys,s.message)};break}case"pending.insert":{r={...e,activeRuntimeOverlayKeys:s.pending.role==="user"?[]:e.activeRuntimeOverlayKeys,pendingMessages:Er(e.pendingMessages,s.pending)};break}case"pending.retry":{r={...e,pendingMessages:e.pendingMessages.map(u=>u.clientRequestId===s.clientRequestId?{...u,deliveryState:"sending"}:u)};break}case"pending.fail":{r={...e,pendingMessages:Cr(e.pendingMessages,s.clientRequestId)};break}case"pending.resolve":{const u=e.pendingMessages.find(h=>h.clientRequestId===s.clientRequestId)??null;let d=Ps(e.authoritativeMessages,t,[s.message]);u&&(d=d.map(h=>{if(h.id!==s.message.messageId)return h;const f=h.attachments??[];return{...h,attachments:f.length>0?f:u.attachments??[],attachmentPayloads:u.attachmentPayloads??h.attachmentPayloads??null,clientRequestId:s.clientRequestId}})),r={...e,authoritativeMessages:d,activeRuntimeOverlayKeys:s.message.role==="user"?[]:e.activeRuntimeOverlayKeys,pendingMessages:e.pendingMessages.filter(h=>h.clientRequestId!==s.clientRequestId)};break}}r={...r,runtimeOverlayMessages:Ua(r.authoritativeMessages,r.runtimeOverlayMessages)},r={...r,activeRuntimeOverlayKeys:Xa(r.authoritativeMessages,r.runtimeOverlayMessages,r.activeRuntimeOverlayKeys)};const a=Qs(r);return{timeline:r,previousMessages:n,messages:a,replacedSnapshotSeed:o,validationIssues:Wa(e,r,s,n,a)}}function Wa(e,t,s,n,r){var f,I,R;const o=[],a=ai(r,t.authoritativeMessages,t.runtimeOverlayMessages,t.activeRuntimeOverlayKeys),u=js(r.map(w=>w.id));u.length>0&&o.push(`rendered_duplicate_ids:${u.join(",")}`);const d=js(t.authoritativeMessages.map(w=>w.id));d.length>0&&o.push(`authoritative_duplicate_ids:${d.join(",")}`);const h=js(t.pendingMessages.map(w=>w.clientRequestId).filter(w=>!!w));if(h.length>0&&o.push(`pending_duplicate_client_request_ids:${h.join(",")}`),Js(r,a)||o.push("rendered_order_not_monotonic"),s.type==="pending.resolve"&&t.pendingMessages.some(v=>v.clientRequestId===s.clientRequestId)&&o.push(`pending_not_cleared:${s.clientRequestId}`),s.type==="runtime.message"&&!di(e.authoritativeMessages,t.authoritativeMessages)&&o.push("runtime_message_mutated_authoritative_layer"),s.type==="history.merge"&&s.source.startsWith("older_history")&&!Ka(e.authoritativeMessages,t.authoritativeMessages)&&o.push("older_history_rewound_authoritative_tail"),n.length>0&&r.length>0&&s.type==="history.merge"&&s.source.startsWith("older_history")&&((f=n.at(-1))==null?void 0:f.id)!==((I=r.at(-1))==null?void 0:I.id)&&o.push("older_history_changed_rendered_tail"),a.length>0){const w=((R=r.at(-1))==null?void 0:R.id)??null;(!w||!a.includes(w))&&o.push("runtime_live_item_not_pinned_to_tail")}return o}function Ua(e,t){if(t.length===0)return t;const s=new Map(e.map(a=>[a.id,a])),n=new Set(s.keys()),r=e.at(-1)??null,o=t.filter(a=>{const u=Zs(s,n,a);if(!u)return!0;const d=fs(u,a);return!d&&li(r,a)?(is("timeline.runtime_overlay_stale_dropped",{overlay:ve(a),authoritativeMatch:ve(u),latestAuthoritative:r?ve(r):null}),!1):(!d&&ui(a)&&is("timeline.runtime_overlay_not_absorbed",{overlay:ve(a),authoritativeMatch:ve(u)}),!d)});return o.length===t.length?t:o}function $a(e,t,s,n){const r=ai(e,t,s,n);if(r.length===0)return e;const o=new Set(r),a=[...e.filter(u=>!o.has(u.id)),...e.filter(u=>o.has(u.id))];return di(e,a)?e:a}function ai(e,t,s,n){if(s.length===0||e.length===0||n.length===0)return[];const r=new Map(t.map(f=>[f.id,f])),o=new Set(r.keys()),a=new Map(e.map(f=>[f.id,f])),u=new Set(a.keys()),d=new Map(s.map(f=>[on(f),f])),h=[];for(const f of n){const I=d.get(f)??null;if(!I||!bn(t,I))continue;const R=Zs(r,o,I);if(R&&fs(R,I))continue;const w=Zs(a,u,I);!w||h.includes(w.id)||h.push(w.id)}return h}function Va(e,t,s){if(!bn(e.authoritativeMessages,s))return t;const n=on(s);return t.includes(n)?t:[...t,n]}function bn(e,t){return ui(t)?!li(e.at(-1)??null,t):!1}function li(e,t){return!e||Wt(t,e)?!1:Ga(t,e)<0}function Ga(e,t){const s=e.timestamp.localeCompare(t.timestamp);return s!==0?s:e.sequence!==t.sequence?e.sequence-t.sequence:Vt(e,t)}function Xa(e,t,s){if(s.length===0)return s;const n=new Map(t.map(a=>[on(a),a])),r=e.at(-1)??null,o=s.filter(a=>{const u=n.get(a)??null;if(!u)return!1;const d=bn(e,u);return d||is("timeline.runtime_overlay_tail_deactivated",{overlay:ve(u),latestAuthoritative:r?ve(r):null}),d});return o.length===s.length?s:o}function Zs(e,t,s){const n=e.get(s.id)??null,r=ci(e,t,s,n);if(r)return e.get(r)??null;if(n)return n;const o=mn(e,t,s);if(o)return e.get(o)??null;const a=gn(e,s);return a?e.get(a)??null:null}function ci(e,t,s,n){const r=za(e,t,s),o=mn(e,t,s),a=gn(e,s),u=r??o??a;if(!u)return null;if(!n)return u;const d=e.get(u)??null;return!d||!Ya(n,d,s)?null:u}function za(e,t,s){if(s.role!=="assistant"||s.kind!=="text"&&s.kind!=="thinking"||s.deliveryState!=="sent"||!s.rawRef.startsWith("codex://"))return null;const n=ds(s.rawRef);if(!n)return null;for(const[r,o]of e.entries()){if(r===s.id||!t.has(r)||o.role!==s.role||o.kind!==s.kind||o.deliveryState!=="sent"||!o.rawRef.startsWith("codex://"))continue;const a=ds(o.rawRef),u=Math.abs(o.sequence-s.sequence),d=a===n;if(!(!a||Vt(o,s)<0||!d&&u>ei||!ii(o,s,Xs)))return Ke("session.messages.codex_runtime_overlay_bridge_match",{bridgeMode:d?"same_store":"cross_store_sequence_window",sequenceDistance:u,previous:ve(o),incoming:ve(s)}),r}return null}function Ya(e,t,s){return!Wt(e,s)||!Wt(t,s)?!1:!fs(e,s)&&fs(t,s)}function ui(e){return e.role==="assistant"&&(e.kind==="text"||e.kind==="thinking")||e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")}function fs(e,t){if(e.role!==t.role||e.kind!==t.kind&&!(Ms(e,t)||Ss(e,t)))return!1;const s=ti(e,{...t,id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId});return $n(s)===$n(e)}function $n(e){const t=e.kind==="text"||e.kind==="thinking"?Ge(Ct(e.content).text):Ge(e.content);return JSON.stringify({role:e.role,kind:e.kind,content:t,attachments:hs(e.attachments),toolCall:e.toolCall===null?null:{callId:e.toolCall.callId,name:e.toolCall.name,status:e.toolCall.status,input:Ge(e.toolCall.input),output:Ge(e.toolCall.output??""),error:Ge(e.toolCall.error??"")}})}function js(e){const t=new Map;for(const s of e)t.set(s,(t.get(s)??0)+1);return Array.from(t.entries()).filter(([,s])=>s>1).map(([s])=>s)}function Js(e,t=[]){if(t.length>0){const s=new Set(t),n=e.filter(r=>s.has(r.id));if(n.length>0){const r=e.filter(a=>!s.has(a.id));return e.slice(-n.length).some(a=>!s.has(a.id))?!1:Js(r)&&Js(n)}}for(let s=1;s<e.length;s+=1)if(Vt(e[s-1],e[s])>0)return!1;return!0}function di(e,t){var s,n;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(((s=e[r])==null?void 0:s.id)!==((n=t[r])==null?void 0:n.id))return!1;return!0}function Ka(e,t){const s=e.at(-1)??null;if(!s)return!0;const n=t.at(-1)??null;return n?s.id===n.id:!1}function Qa(e){switch(e.type){case"timeline.seed":return[...e.snapshotMessages,...e.bootstrapMessages];case"history.merge":return e.messages;case"runtime.message":return[e.message];case"pending.insert":return[e.pending];case"pending.resolve":return[e.message];case"pending.retry":case"pending.fail":default:return[]}}function Za(e,t,s){const n=new Map(e.map((h,f)=>[h.id,f])),r=new Map(t.map((h,f)=>[h.id,f])),o=new Map(e.map(h=>[h.id,h])),a=new Map(t.map(h=>[h.id,h])),u=new Set([...e.map(h=>h.id),...t.map(h=>h.id)]),d=[];for(const h of u){const f=o.get(h)??null,I=a.get(h)??null,R=I??f;if(!R||R.role!==s)continue;const w=n.get(h)??null,v=r.get(h)??null;w!==v&&d.push({messageId:h,fromIndex:w,toIndex:v,fromSequence:(f==null?void 0:f.sequence)??null,toSequence:(I==null?void 0:I.sequence)??null,fromRawRef:(f==null?void 0:f.rawRef)??null,toRawRef:(I==null?void 0:I.rawRef)??null,anchorChanged:(f==null?void 0:f.sequence)!==(I==null?void 0:I.sequence)||(f==null?void 0:f.timestamp)!==(I==null?void 0:I.timestamp)||(f==null?void 0:f.rawRef)!==(I==null?void 0:I.rawRef)})}return d.slice(0,8)}function hi(e){return{messageId:"id"in e?e.id:e.messageId,role:e.role,kind:e.kind??"text",sequence:e.sequence,timestamp:e.timestamp,rawRef:e.rawRef,contentPreview:Ja(e.content)}}function Vn(e){return e.map(t=>hi(t))}function Ja(e){const t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}...`:t}function Ue(e,t){const[s,n]=l.useState(()=>t(e.getState()));return l.useEffect(()=>(n(t(e.getState())),e.subscribe(()=>{n(t(e.getState()))})),[t,e]),s}function Ns(e,t){return Ar({messages:t,sessionRunningState:(e==null?void 0:e.runningState)??null,sessionSyncStatus:(e==null?void 0:e.syncStatus)??null,sessionLastErrorCode:(e==null?void 0:e.lastErrorCode)??null,sessionLastErrorDetail:(e==null?void 0:e.lastErrorDetail)??null})}function fi(e){const t=e==null?void 0:e.messageCount;return typeof t=="number"&&Number.isFinite(t)?t:null}function el(e,t){const s=Wo(e),n=fi(t);return n===null?s:Math.max(s,n+1)}function tl(e,t){const s=sl(t);if(!s)return!1;const n=nl(e);return n?wn(s.sequence,s.timestamp,n.sequence,n.timestamp)>=0:!0}function sl(e){let t=null;for(const s of e)(!t||wn(s.sequence,s.timestamp,t.sequence,t.timestamp)>0)&&(t=s);return t}function nl(e){let t=null;for(const s of e)s.deliveryState==="sent"&&(!t||wn(s.sequence,s.timestamp,t.sequence,t.timestamp)>0)&&(t=s);return t}function wn(e,t,s,n){return e!==s?e-s:t.localeCompare(n)}function rl(e,t){return t>0?"ready":"loading"}function il(e,t){const s=fi(e);return s!==null?s>t:t>=Dt}function xt(e){return e.olderCursor?!0:e.pagesLoaded>1?e.currentHasOlderMessages:il(e.session,e.loadedMessageCount)}function ot(e,t){return e&&{...e,runningState:t,activityState:mi(e,t,e.completedAt??null,Je(t))}}function Gn(e,t){return!e||e.lastSeenAt&&e.lastSeenAt>=t?e:{...e,lastSeenAt:t,activityState:e.activityState==="completed_unread"?"idle":e.activityState}}function Xn(e,t){return pi(e,{runningState:t.runningState,activityResolutionSource:t.activityResolutionSource,activityConfidence:t.activityConfidence,runId:t.runId,detail:t.detail,interruptSource:t.interruptSource,errorCode:t.errorCode,errorDetail:t.errorDetail,hasActiveRun:t.hasActiveRun,updatedAt:t.updatedAt,watchdogTriggeredAt:t.watchdogTriggeredAt})}function ol(e,t){return pi(e,t)}function pi(e,t){if(!e)return e;const s=al(t.activityResolutionSource),n=Ut(t.runningState)?Ds(e.completedAt,t.updatedAt):null,r=t.runningState==="completed"||t.runningState==="interrupted"||t.runningState==="failed"?Ds(e.lastEventAt,t.updatedAt):t.updatedAt;return{...e,runningState:t.runningState,activitySource:s,activityResolutionSource:t.activityResolutionSource,activityConfidence:t.activityConfidence,runId:t.runId,lastEventAt:r,completedAt:n,lastErrorCode:t.runningState==="failed"?t.errorCode??e.lastErrorCode:null,lastErrorDetail:t.runningState==="failed"?t.errorDetail??t.detail??e.lastErrorDetail:null,watchdogTriggeredAt:t.watchdogTriggeredAt,updatedAt:Ds(e.updatedAt,t.updatedAt)??t.updatedAt,activityState:mi(e,t.runningState,n,t.hasActiveRun)}}function mi(e,t,s,n){return n||Je(t)?"running":s&&(!e.lastSeenAt||s>e.lastSeenAt)?"completed_unread":e.activityState==="running"||e.activityState==="completed_unread"?"idle":e.activityState??"idle"}function Je(e){return e==="starting"||e==="running"||e==="reconnecting"}function Ut(e){return e==="completed"||e==="interrupted"||e==="failed"}function zn(e){if(e===null||e.provider==="opencode")return!0;const t=e.modelOptions??[];return t.length===0?!0:t.every(s=>s.usesProviderDefault===!0)}function Yn(e,t){return e==="session.backfill"?t??"idle":t==="completed"||t==="interrupted"||t==="failed"?t:"running"}function Os(e,t){return Ut(e)?e:t}function Ls(e,t){return e.runningState==="failed"?{interruptSource:null,errorCode:e.errorCode,errorDetail:e.errorDetail??e.detail}:e.runningState==="interrupted"?{interruptSource:e.interruptSource??null,errorCode:null,errorDetail:e.detail}:e.runningState==="completed"?{interruptSource:null,errorCode:null,errorDetail:e.detail}:{interruptSource:t,errorCode:null,errorDetail:null}}function al(e){return e==="authoritative_runtime"||e==="authoritative_provider_event"?"runtime":e==="inferred_log"?"inferred":"none"}function ll(e){return e.provider==="codex"&&(e.role==="assistant"||e.role==="tool")}function cl(e){return e.rawRef.startsWith("codex://")&&e.deliveryState==="sent"&&(e.role==="assistant"||e.role==="tool")}function ul(e){var t;return{id:e.messageId,rawRef:e.rawRef,role:e.role,kind:e.kind??(e.role==="tool"?"tool_result":"text"),sequence:e.sequence,timestamp:e.timestamp,callId:((t=e.toolCall)==null?void 0:t.callId)??null,contentPreview:gi(e.content,e.kind??"text")}}function Kn(e){var t;return{id:e.id,rawRef:e.rawRef,role:e.role,kind:e.kind,sequence:e.sequence,timestamp:e.timestamp,callId:((t=e.toolCall)==null?void 0:t.callId)??null,contentPreview:gi(e.content,e.kind)}}function Qn(e){const t=new Map;for(const n of e){if(!cl(n))continue;const r=dl(n),o=t.get(r);if(o){o.push(n);continue}t.set(r,[n])}const s=[];for(const[n,r]of t.entries()){const o=[...r].sort((u,d)=>u.sequence!==d.sequence?u.sequence-d.sequence:u.timestamp.localeCompare(d.timestamp));let a=[];for(const u of o){const d=a.at(-1)??null;if(!d||hl(d,u)){a.push(u);continue}a.length>1&&s.push({signature:n,messages:a.map(Kn)}),a=[u]}a.length>1&&s.push({signature:n,messages:a.map(Kn)})}return s}function dl(e){var r,o;if(e.kind==="tool_call"||e.kind==="tool_result")return[e.role,e.kind,((r=e.toolCall)==null?void 0:r.callId)??"",((o=e.toolCall)==null?void 0:o.name)??""].join(":");const t=Ct(e.content),s=en(t.text),n=t.inlineImages.map(a=>a.url).join("|");return[e.role,e.kind,s,n].join(":")}function hl(e,t){const s=Zn(e.timestamp),n=Zn(t.timestamp);return Math.abs(s-n)<=120*1e3&&Math.abs(e.sequence-t.sequence)<=8}function gi(e,t){return t==="text"||t==="thinking"?en(Ct(e).text).slice(0,160):en(e).slice(0,160)}function en(e){return e.replace(/\r\n/g,`
|
|
7
|
+
`).trimEnd()}function Zn(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ds(e,t){return e?t?e>=t?e:t:e:t??null}function Jn(){var e,t;if(typeof((e=globalThis.crypto)==null?void 0:e.randomUUID)=="function")return globalThis.crypto.randomUUID();if(typeof((t=globalThis.crypto)==null?void 0:t.getRandomValues)=="function"){const s=new Uint8Array(16);globalThis.crypto.getRandomValues(s),s[6]=s[6]&15|64,s[8]=s[8]&63|128;const n=Array.from(s,r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}return`fallback-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function vi(e,t){return t&&(!e||e.provider===t.provider)?t:null}function er(e,t){const s=vi(e,t);return s?!!s.canSendMessage:e?_r(e.provider):!1}function tr(e,t){const s=vi(e,t);return s?!(!s.supportsInterrupt||(e==null?void 0:e.provider)==="claude-code"&&e.activitySource==="inferred"):e?e.provider==="codex"||e.provider==="opencode"?!0:e.provider==="claude-code"&&e.activitySource!=="inferred":!1}function fl(e,t,s){return t===!0||s===!0?!0:e?e.activityState==="running"||e.runningState==="starting"||e.runningState==="running"||e.runningState==="reconnecting"||e.runningState==="stale"||e.runningState==="unknown":!1}function Hs(e,t,s){return s?!0:e===!0&&Je(t)}function qs(e,t,s,n){return n?!0:e===!0&&(s||Je(t))}function Bs(e,t){const s=t==null?void 0:t.trim();return s?`session-runtime.snapshot.host.${encodeURIComponent(s)}.${e}`:`session-runtime.snapshot.${e}`}function sr(e){return e.filter(t=>t.deliveryState==="sent").slice(-Jr)}function pl(e,t){const s=e.filter(n=>n.id!==t.id);return s.push(t),s.sort((n,r)=>n.orderIndex-r.orderIndex),s}function Fs(e,t){const s=e.filter(n=>n.id!==t.id);return s.push(t),s.sort((n,r)=>n.status!==r.status?n.status==="pending"?-1:1:r.createdAt.localeCompare(n.createdAt)),s}function Jt(e,t){if(!e)return t;if(!t||nr(e,t)||rr(e,t))return e;if(nr(t,e)||rr(t,e))return t;const s=Date.parse(e.updatedAt||e.lastMessageAt||e.createdAt),n=Date.parse(t.updatedAt||t.lastMessageAt||t.createdAt);return!Number.isFinite(s)||!Number.isFinite(n)?t:s>=n?e:t}function nr(e,t){return ir(e)&&!ir(t)&&e.lastEventAt===t.lastEventAt&&e.lastMessageAt===t.lastMessageAt&&e.completedAt===t.completedAt}function rr(e,t){if(!or(e)||or(t))return!1;const s=e.completedAt??e.lastEventAt??null;return s?(!t.lastEventAt||t.lastEventAt<=s)&&(!t.completedAt||t.completedAt<=s):!1}function ir(e){return e.activityState==="running"||Je(e.runningState)}function or(e){return Ut(e.runningState)}const ml="workbench:focus-composer",gl=15e3,vl=320;function bi(){typeof window>"u"||window.dispatchEvent(new CustomEvent(ml))}function wi(e){var Ee,J,_e,Ye;const t=l.useRef(null),s=l.useRef(null),n=l.useRef(null),[r,o]=l.useState(!1),[a,u]=l.useState(null),[d,h]=l.useState(null),[f,I]=l.useState(null),[R,w]=l.useState(null),v=pt(),{showToast:m}=v,x=v.dismissToast??(()=>{}),E=Uo(A=>A.notificationPreferences.notifyOnPermissionRequest),S=Xt(),j=an(),T=l.useRef(null),N=l.useRef(null),b=l.useRef(null),V=l.useRef(((Ee=e.externalSession)==null?void 0:Ee.runningState)??null),k=l.useRef(new Set),M=((J=e.targetHostId)==null?void 0:J.trim())||null;(!t.current||s.current!==e.sessionId||n.current!==M)&&((_e=t.current)==null||_e.destroy(),t.current=new ka(e.sessionId,{targetHostId:M,initialSession:e.externalSession,bootstrapMessages:e.bootstrapMessages??[],onSeen:e.onSeen}),s.current=e.sessionId,n.current=M);const g=t.current,y=Ue(g,A=>A.session),K=Ue(g,A=>A.capabilities),ie=Ue(g,A=>A.runtimeHasActiveRun),de=Ue(g,A=>A.runtimeCanInterrupt),te=Ue(g,A=>A.messages),z=Ue(g,A=>A.timelineItems),P=Ue(g,A=>A.permissionRequests),q=Ue(g,A=>A.queuedMessages),G=Ue(g,A=>A.contextUsage),W=Ue(g,A=>A.historyState),ee=Ue(g,A=>A.errorCode),fe=Ue(g,A=>A.errorDetail),$=Ue(g,A=>A.interruptSource),se=Ue(g,A=>A.loadingOlderMessages),ne=Ue(g,A=>A.hasOlderMessages),ge=Ue(g,A=>A.connectionState),L=Rr(y),U=r&&!R,H=L||ie===!0||U?!0:ie,pe=de===!0||U?!0:de,me=L||U,Ae=(y==null?void 0:y.provider)===(K==null?void 0:K.provider)&&$o(K),He=q.some(A=>A.status==="queued"||A.status==="dispatching"),qe=y??e.externalSession??null,Pe=Il({sessionId:e.sessionId,provider:(y==null?void 0:y.provider)??null,runningState:(y==null?void 0:y.runningState)??null,activityState:(y==null?void 0:y.activityState)??null,runtimeHasActiveRun:ie,messages:te}),B=e.enableThinkingPlaceholder===!1||!Pe?null:c("conversation.runtimeThinkingPlaceholder",{provider:c("conversation.providerCodex")}),X=l.useMemo(()=>Vo(z,B),[z,B]);Ia({sending:r,setSending:o,session:y,runtimeHasActiveRun:ie,runtimeCanInterrupt:de}),l.useEffect(()=>{g.applyNavigationSession(e.externalSession)},[e.externalSession,g]),l.useEffect(()=>(g.initialize(),()=>{g.destroy(),t.current===g&&(t.current=null)}),[g]),l.useEffect(()=>{w(null),k.current.clear()},[e.sessionId]),l.useEffect(()=>{if(e.onBindSessionWorkspace)return e.onBindSessionWorkspace(e.sessionId,(y==null?void 0:y.workspaceId)??null),()=>{var A;(A=e.onBindSessionWorkspace)==null||A.call(e,e.sessionId,null)}},[e.onBindSessionWorkspace,e.sessionId,y==null?void 0:y.workspaceId]),l.useEffect(()=>{if(e.enableCompletionHaptics===!1)return;const A=V.current,D=(y==null?void 0:y.runningState)??null;(A==="starting"||A==="running"||A==="reconnecting")&&D==="completed"&&j.trigger("success"),V.current=D},[j,e.enableCompletionHaptics,y==null?void 0:y.runningState]),l.useEffect(()=>{var re;if((e.permissionRequestNotificationMode??"always")==="current_only"&&!e.isCurrent)return;const D=P.filter(ce=>ce.status==="pending"),be=(y==null?void 0:y.workspaceId)??((re=e.externalSession)==null?void 0:re.workspaceId)??null;for(const ce of D)k.current.has(ce.id)||(k.current.add(ce.id),E&&(m({id:`${e.permissionToastIdPrefix??"permission-request"}-${ce.id}`,title:c("conversation.permissionRequestToastTitle"),description:ce.title,tone:"warning",durationMs:8e3,action:be&&e.onNavigateToSession?{label:c("shell.contextOpenSession"),onClick:()=>{var ue;(ue=e.onNavigateToSession)==null||ue.call(e,be,e.sessionId)}}:void 0}),S.bridge.showNotification(c("conversation.permissionRequestToastTitle"),ce.title)))},[(Ye=e.externalSession)==null?void 0:Ye.workspaceId,e.isCurrent,e.onNavigateToSession,e.permissionRequestNotificationMode,e.permissionToastIdPrefix,e.sessionId,E,P,S.bridge,y==null?void 0:y.workspaceId,m]),l.useEffect(()=>{if(e.enableRuntimeErrorHandling!==!1)return()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)}},[e.enableRuntimeErrorHandling]),l.useEffect(()=>{var A;e.enableRuntimeErrorHandling!==!1&&(ee!=="SESSION_NOT_FOUND"&&ee!=="WORKSPACE_NOT_FOUND"||(x("conversation-runtime-error"),(A=e.onResolveMissingSession)==null||A.call(e)))},[x,e.enableRuntimeErrorHandling,e.onResolveMissingSession,ee]),l.useEffect(()=>{if(e.enableRuntimeErrorHandling===!1)return;if(ee==="SESSION_NOT_FOUND"||ee==="WORKSPACE_NOT_FOUND"){b.current!==null&&(window.clearTimeout(b.current),b.current=null),N.current=null,T.current=null,x("conversation-runtime-error");return}if(!ee||!fe){b.current!==null&&(window.clearTimeout(b.current),b.current=null),N.current=null,T.current=null,x("conversation-runtime-error");return}const A=`${ee}:${fe}`;if(!(T.current===A||N.current===A)){if(b.current!==null&&(window.clearTimeout(b.current),b.current=null),wl((y==null?void 0:y.provider)??null,ee,fe)){N.current=A,b.current=window.setTimeout(()=>{N.current=null,b.current=null,T.current=A,m({id:"conversation-runtime-error",title:c("conversation.runtimeErrorTitle"),description:fe,tone:"error",durationMs:null})},gl);return}N.current=null,T.current=A,m({id:"conversation-runtime-error",title:c("conversation.runtimeErrorTitle"),description:fe,tone:"error",durationMs:null})}},[x,e.enableRuntimeErrorHandling,ee,fe,y==null?void 0:y.provider,m]);const F=l.useCallback(async(A,D)=>{var ce,ue,je,Me,Be,Re,et;const be=R;if(!be){await g.sendMessage(A,{model:D==null?void 0:D.model,reasoningLevel:D==null?void 0:D.reasoningLevel,providerConfigMode:D==null?void 0:D.providerConfigMode,providerPresetId:(D==null?void 0:D.providerPresetId)??null,attachments:D==null?void 0:D.attachments,attachmentMeta:D==null?void 0:D.attachmentMeta}),(ce=e.onRequestNavigationRefresh)==null||ce.call(e);return}let re=null;try{re=await yr(e.sessionId,{sourceType:"message",sourceMessageId:be.sourceMessageId,sourceMessageSnapshot:be.sourceMessageSnapshot,strategy:"auto",targetProvider:be.targetProvider,providerConfigMode:be.targetProviderConfigMode??(D==null?void 0:D.providerConfigMode),providerPresetId:be.targetProviderPresetId??(D==null?void 0:D.providerPresetId)??null}),(ue=e.onUpsertNavigationSession)==null||ue.call(e,re),await rn(re.sessionId,{content:A,clientRequestId:bl(),model:be.targetModel,reasoningLevel:(D==null?void 0:D.reasoningLevel)??null,permissionMode:vt(),attachments:(D==null?void 0:D.attachments)??[],providerConfigMode:be.targetProviderConfigMode??(D==null?void 0:D.providerConfigMode),providerPresetId:be.targetProviderPresetId??(D==null?void 0:D.providerPresetId)??null}),w(null),(je=e.onRequestNavigationRefresh)==null||je.call(e),(Me=e.onNavigateToSession)==null||Me.call(e,re.workspaceId,re.sessionId),(Be=e.onForkSuccess)==null||Be.call(e,re)}catch(tt){throw re&&((Re=e.onUpsertNavigationSession)==null||Re.call(e,re),(et=e.onRequestNavigationRefresh)==null||et.call(e)),tt}},[R,e,g]),O=l.useCallback(async(A,D)=>{o(!0);try{await F(A,D)}finally{o(!1)}},[F]),le=l.useCallback(async(A,D)=>{o(!0);try{R?await F(A,D):await g.enqueueMessage(A,{model:D==null?void 0:D.model,reasoningLevel:D==null?void 0:D.reasoningLevel,providerConfigMode:D==null?void 0:D.providerConfigMode,providerPresetId:(D==null?void 0:D.providerPresetId)??null,attachments:D==null?void 0:D.attachments,attachmentMeta:D==null?void 0:D.attachmentMeta})}finally{o(!1)}},[R,F,g]),oe=l.useCallback(async(A,D)=>{u(A);try{await g.replyPermissionRequest(A,D)}catch(be){m({title:c("conversation.permissionRequestReplyFailed"),description:be instanceof Error?be.message:void 0,tone:"error"})}finally{u(null)}},[m,g]),Oe=l.useCallback(async A=>{h(A);try{await g.deleteQueuedMessage(A)}finally{h(null)}},[g]),Le=l.useCallback(async A=>{var D;I(A);try{await g.steerQueuedMessage(A),(D=e.onRequestNavigationRefresh)==null||D.call(e)}finally{I(null)}},[e.onRequestNavigationRefresh,g]),Z=l.useCallback(async()=>{var A;await g.interrupt(),(A=e.onRequestNavigationRefresh)==null||A.call(e)},[e.onRequestNavigationRefresh,g]);return{session:qe,capabilities:K,runtimeHasActiveRun:ie,runtimeCanInterrupt:de,messages:te,timelineItems:X,permissionRequests:P,queuedMessages:q,contextUsage:G,historyState:W,runtimeErrorCode:ee,runtimeErrorDetail:fe,runtimeInterruptSource:$,loadingOlderMessages:se,hasOlderMessages:ne,connectionState:ge,sending:r,replyingPermissionRequestId:a,deletingQueueItemId:d,steeringQueueItemId:f,forkDraft:R,setForkDraft:w,composerHasActiveRun:H,composerCanInterrupt:pe,composerIsRunning:me,canSteerQueuedMessage:Ae,hasPendingQueuedMessages:He,reconnect:g.reconnect.bind(g),loadOlderMessages:g.loadOlderMessages.bind(g),retryMessage:g.retryMessage.bind(g),send:O,queue:le,interrupt:Z,replyPermissionRequest:oe,deleteQueuedMessage:Oe,steerQueuedMessage:Le}}function bl(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function wl(e,t,s){return e!=="opencode"?!1:t==="OPENCODE_REQUEST_TIMEOUT"||t==="PROVIDER_RUNTIME_TIMEOUT"||/\bSERVER_TIMEOUT\b/i.test(s)||/timeout/i.test(s)||/超时/.test(s)}function Il(e){const t=Ml(e),[s,n]=l.useState(t==="show"),r=l.useRef(null);return l.useEffect(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),n(t==="show")},[e.sessionId]),l.useEffect(()=>{if(t==="show"){r.current!==null&&(window.clearTimeout(r.current),r.current=null),n(!0);return}if(t==="hide_immediately"){r.current!==null&&(window.clearTimeout(r.current),r.current=null),n(!1);return}!s||r.current!==null||(r.current=window.setTimeout(()=>{r.current=null,n(!1)},vl))},[t,s]),l.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),s}function Ml(e){const{provider:t,runningState:s,activityState:n,runtimeHasActiveRun:r,messages:o}=e;if(t!=="codex")return"hide_immediately";const a=xl(o);return a<0||yl(o,a)?"hide_immediately":Sl(s,n,r)?"show":"hide_deferred"}function Sl(e,t,s){return s===!0||t==="running"||e==="starting"||e==="running"||e==="reconnecting"}function yl(e,t){return e.slice(t+1).some(s=>s.role==="assistant"&&(s.kind==="text"||s.kind==="thinking"))}function xl(e){let t=-1;for(let s=e.length-1;s>=0;s-=1){const n=e[s];if(n.role==="user"&&n.kind==="text"){t=s;break}}return t}const Pl=1.5,Rl=24,kl=72,Tl=296,Cl=16,ar={2:496,3:408,4:344};function Ii(e){return ar[e]??ar[4]}function El({memberCount:e,currentWidth:t,monitorWidth:s}){if(e<2||t<=0||s<=0)return t;const n=Tl,r=Math.max(0,e-1)*Cl,o=Math.max(0,(t-n-r)/e),a=Ii(e);if(o>=a)return t;const u=n+r+e*a,d=Math.min(t*Pl,Math.max(t,s-kl)),h=Math.min(Math.max(t,u),d);return h<=t+Rl?t:h}const Al=240,lr=920,cr=760,In=360,Mn=320,Ve=16,ur=428,_l=404,lt=12;function Bt(e,t){if(typeof window>"u")return e;const s=Math.max(0,window.innerWidth-Ve*2),n=Math.max(0,window.innerHeight-Ve*2),r=Math.min((t==null?void 0:t.minWidth)??In,s),o=Math.min((t==null?void 0:t.minHeight)??Mn,n),a=Math.max(r,s),u=Math.max(o,n),d=Math.min(Math.max(e.width,r),a),h=Math.min(Math.max(e.height,o),u),f=Math.min(Math.max(e.x,Ve),Math.max(Ve,window.innerWidth-d-Ve)),I=Math.min(Math.max(e.y,Ve),Math.max(Ve,window.innerHeight-h-Ve));return{x:f,y:I,width:d,height:h}}function jl(e){if(typeof window>"u")return{x:Ve,y:Ve,width:lr,height:cr};const t=Math.min(lr,Math.max(In,window.innerWidth-Ve*2)),s=Math.min(cr,Math.max(Mn,window.innerHeight-Ve*2));return Bt({x:((e==null?void 0:e.right)??window.innerWidth-Ve)-t+28,y:Math.max(((e==null?void 0:e.bottom)??48)+8,Ve),width:t,height:s})}function Nl(e){return!e||e.width<=0||e.height<=0?null:Bt({x:e.left,y:e.top,width:e.width,height:e.height},{minWidth:Math.min(In,e.width),minHeight:Math.min(Mn,e.height)})}function Ol(e){if(typeof window>"u")return{x:lt,y:lt,width:ur};const t=Math.min(ur,Math.max(_l,window.innerWidth-lt*2));return{x:Math.min(Math.max(((e==null?void 0:e.right)??window.innerWidth-lt)-t,lt),Math.max(lt,window.innerWidth-t-lt)),y:Math.max(lt,((e==null?void 0:e.bottom)??lt)+8),width:t}}function Ll({groupId:e,currentSessionId:t}){var se,ne,ge;const s=mt(),n=Xt(),r=Go(n),{showToast:o}=pt(),{navigationGroups:a,requestNavigationRefresh:u,currentTargetHostId:d}=wt(),h=l.useMemo(()=>$t(a),[a]),f=l.useMemo(()=>new Map(h.map(L=>[L.session.sessionId,L])),[h]),I=l.useMemo(()=>bs(h),[h]),R=l.useMemo(()=>{const L=new Map,U=H=>{for(const pe of H)L.set(pe.item.session.sessionId,pe),U(ws(pe))};return U(I),L},[I]),w=l.useMemo(()=>ln(a),[a]),[v,m]=l.useState(null),[x,E]=l.useState(!0),[S,j]=l.useState(null),[T,N]=l.useState(null),[b,V]=l.useState(null),[k,M]=l.useState(null),[g,y]=l.useState(null),[K,ie]=l.useState(!1),de=l.useRef(null),te=l.useRef(null);l.useEffect(()=>{let L=!1;async function U(){E(!0),j(null);try{const H=await Xo(e);if(L)return;m(H)}catch(H){if(L)return;j(H instanceof Error?H.message:c("shell.parallelGroupLoadFailed"))}finally{L||E(!1)}}return U(),()=>{L=!0}},[e]),l.useEffect(()=>{const L=Zi(e);L&&G(L)},[e]),l.useEffect(()=>()=>{te.current!==null&&window.clearTimeout(te.current)},[]);const z=l.useMemo(()=>v?v.members.slice().sort((L,U)=>L.member.ordinal-U.member.ordinal).map(L=>{const U=f.get(L.session.sessionId),H=(U==null?void 0:U.session)??L.session;return{session:H,workspaceId:(U==null?void 0:U.workspace.id)??ns(H,L.sessionIsolatedWorkspace),ordinal:L.member.ordinal,memberPrompt:L.member.memberPrompt,model:L.member.model,sessionIsolatedWorkspace:L.sessionIsolatedWorkspace,subagentTree:Vl(H.sessionId,v.group.id,R)}}):[],[v,f,R]);l.useEffect(()=>{if(!n.isDesktop||n.ui.osFamily!=="macos"&&n.ui.osFamily!=="windows"||z.length<2)return;const L=`${e}:${z.length}`;if(de.current===L)return;de.current=L;let U=!1;async function H(){try{const pe=await xn(()=>import("./window-BVUB8gMK.js").then(oe=>oe.w),__vite__mapDeps([0,1])),me=await xn(()=>import("./window-BVUB8gMK.js").then(oe=>oe.d),__vite__mapDeps([0,1])),Ae=pe.getCurrentWindow(),He=await Ae.innerSize(),qe=await Ae.scaleFactor(),Pe=await pe.currentMonitor();if(U||qe<=0)return;const B=He.width/qe,X=He.height/qe,F=Pe?Pe.workArea.size.width/Pe.scaleFactor:B*1.5,O=El({memberCount:z.length,currentWidth:B,monitorWidth:F});if(O<=B+24)return;const le=10;await new Promise(oe=>window.setTimeout(oe,56));for(let oe=1;oe<=le;oe+=1){if(U)return;const Oe=oe/le,Le=1-Math.pow(1-Oe,3),Z=B+(O-B)*Le;await Ae.setSize(new me.LogicalSize(Z,X)),await new Promise(Ee=>window.setTimeout(Ee,Al/le))}}catch{return}}return H(),()=>{U=!0}},[e,z.length,n.isDesktop,n.ui.osFamily]);async function P(L){V(L);try{const U=await Ko(L);await u(),m(H=>H&&{...H,members:H.members.map(pe=>{var me;return((me=pe.sessionIsolatedWorkspace)==null?void 0:me.id)===L?{...pe,sessionIsolatedWorkspace:{...pe.sessionIsolatedWorkspace,workspaceId:U.workspace.id,lifecycleStatus:"promoted",promotedAt:U.record.promotedAt}}:pe})}),o({title:c("shell.parallelWorkspacePromotedBadge"),tone:"success"})}catch(U){o({title:U instanceof Error?U.message:c("shell.parallelGroupLoadFailed"),tone:"error"})}finally{V(null)}}async function q(L){if(k)return;const U=L.trim();if(!U)return;const H=z.find(me=>me.session.sessionId!==U)??null,pe=(v==null?void 0:v.group.workspaceId)??(H==null?void 0:H.workspaceId)??null;M(U);try{await Yo(U),Us(U,null),N(me=>me===U?null:me),m(me=>me&&{...me,members:me.members.filter(Ae=>Ae.session.sessionId!==U)}),await u(),t===U&&(H?s(ze(H.workspaceId,H.session.sessionId)):pe&&s(Rt(pe))),o({title:c("shell.deleteSessionSuccess"),tone:"success"})}catch(me){o({title:me instanceof Error?me.message:c("shell.deleteSessionFailed"),tone:"error"})}finally{M(null)}}function G(L){y(L),te.current!==null&&window.clearTimeout(te.current),te.current=window.setTimeout(()=>{y(null),te.current=null},L.totalDurationMs)}if(x&&!v)return i.jsx("main",{className:"workbench-page conversation-page-shell parallel-conversation-page",children:i.jsx("section",{className:"parallel-conversation-empty-state",children:i.jsx("strong",{children:c("shell.parallelCreateSubmitting")})})});if(S&&!v)return i.jsx("main",{className:"workbench-page conversation-page-shell parallel-conversation-page",children:i.jsxs("section",{className:"parallel-conversation-empty-state error",children:[i.jsx("strong",{children:c("shell.parallelGroupLoadFailed")}),i.jsx("p",{children:S})]})});if(z.length===0)return i.jsx("main",{className:"workbench-page conversation-page-shell parallel-conversation-page",children:i.jsx("section",{className:"parallel-conversation-empty-state",children:i.jsx("strong",{children:c("shell.parallelGroupEmpty")})})});const W=((se=w[(v==null?void 0:v.group.workspaceId)??""])==null?void 0:se.displayName)??(v==null?void 0:v.group.workspaceId)??c("common.unknown"),ee=z.find(L=>L.session.sessionId===(v==null?void 0:v.group.anchorSessionId))??z[0]??null,fe=z.length<4,$={"--parallel-pane-min-width":`${Ii(z.length)}px`,...g?{"--parallel-pane-enter-delay":`${g.paneEnterDelayMs}ms`,"--parallel-pane-enter-duration":`${g.paneEnterDurationMs}ms`,"--parallel-grid-reveal-delay":`${g.gridRevealDelayMs}ms`,"--parallel-grid-reveal-duration":`${g.gridRevealDurationMs}ms`,"--parallel-shell-expand-duration":`${g.shellExpandDurationMs}ms`,"--parallel-pane-stagger-delay":`${g.paneStaggerMs}ms`}:{}};return i.jsxs("main",{className:"workbench-page conversation-page-shell parallel-conversation-page","data-parallel-count":z.length,"data-parallel-entering":g?"true":void 0,style:$,children:[i.jsx("header",{className:"parallel-conversation-group-header","data-window-drag-handle":"parallel-conversation-group-titlebar","data-tauri-drag-region":r,children:i.jsxs("div",{className:"parallel-conversation-group-titlebar","data-tauri-drag-region":r,children:[i.jsxs("div",{className:"parallel-conversation-group-titlemain","data-tauri-drag-region":r,children:[i.jsx("span",{className:"session-parallel-badge",children:c("shell.parallelGroupBadge")}),i.jsx("strong",{"data-tauri-drag-region":r,children:((ne=v==null?void 0:v.group.sharedPrompt)==null?void 0:ne.trim())||c("common.unknown")})]}),i.jsx("button",{type:"button",className:"secondary-button parallel-conversation-group-add-button","aria-label":c("shell.parallelAppendAction"),title:c("shell.parallelAppendAction"),"data-window-drag":"ignore",disabled:!fe,onClick:()=>{fe&&ie(!0)},children:i.jsx("span",{"aria-hidden":"true",children:"+"})})]})}),i.jsx("div",{className:"parallel-conversation-grid",children:z.map(L=>{const U=w[L.workspaceId]??cn({id:L.workspaceId,name:L.session.workspaceId,path:L.session.workspaceId,repoRoot:L.session.workspaceId});return i.jsx(Dl,{entry:L,isCurrent:L.session.sessionId===t||zt(L.subagentTree,t),routeCurrentSessionId:t,workspaceContext:U,infoOpen:T===L.session.sessionId,promotingWorkspaceId:b,onCloseInfo:()=>{N(null)},onToggleInfo:()=>{N(H=>H===L.session.sessionId?null:L.session.sessionId)},onPromoteWorkspace:P,onRemoveSession:q,removingSessionId:k},L.session.sessionId)})}),i.jsx(Vs,{open:K,source:v?{kind:"group",groupId:v.group.id,workspaceId:v.group.workspaceId,workspaceName:W,sharedPrompt:((ge=v.group.sharedPrompt)==null?void 0:ge.trim())||"",currentMemberCount:z.length,defaultProvider:(ee==null?void 0:ee.session.provider)??"codex"}:null,targetHostId:d,onClose:()=>ie(!1),onCreated:async L=>{m(L),ie(!1),G(Qi("append")),await u(),o({title:c("shell.parallelAppendSucceeded"),tone:"success"})}})]})}function Dl({entry:e,isCurrent:t,routeCurrentSessionId:s,workspaceContext:n,infoOpen:r,onCloseInfo:o,onToggleInfo:a,onPromoteWorkspace:u,promotingWorkspaceId:d,onRemoveSession:h,removingSessionId:f}){var _t,St,Kt,jt,yt,Nt,Qt;const I=mt(),R=Xt(),{showToast:w}=pt(),{navigationGroups:v,requestNavigationRefresh:m,setSessionWorkspace:x,upsertNavigationSession:E,markNavigationSessionSeen:S,selectWorkspace:j}=wt(),T=e.session.sessionId,[N,b]=l.useState(()=>Gl(e,s)),V=l.useMemo(()=>new Map($t(v).map(C=>[C.session.sessionId,C])),[v]),k=N===T?e.session:((_t=V.get(N))==null?void 0:_t.session)??Si(e.subagentTree,N)??e.session,M=N===T?e.workspaceId:((St=V.get(N))==null?void 0:St.workspace.id)??yi(e.subagentTree,N)??e.workspaceId,g=k.sessionId,[y,K]=l.useState(!1),[ie,de]=l.useState("files"),[te,z]=l.useState(!1),[P,q]=l.useState(null),[G,W]=l.useState(null),ee=l.useRef(null),fe=l.useRef(null),$=l.useRef(null),se=l.useRef(null),ne=l.useRef(null),ge=l.useRef(null),[L,U]=l.useState(()=>Pn(T)),{session:H,capabilities:pe,messages:me,timelineItems:Ae,permissionRequests:He,queuedMessages:qe,contextUsage:Pe,historyState:B,runtimeInterruptSource:X,loadingOlderMessages:F,hasOlderMessages:O,connectionState:le,sending:oe,replyingPermissionRequestId:Oe,deletingQueueItemId:Le,steeringQueueItemId:Z,forkDraft:Ee,setForkDraft:J,composerHasActiveRun:_e,composerCanInterrupt:Ye,composerIsRunning:A,canSteerQueuedMessage:D,hasPendingQueuedMessages:be,reconnect:re,loadOlderMessages:ce,retryMessage:ue,send:je,queue:Me,interrupt:Be,replyPermissionRequest:Re,deleteQueuedMessage:et,steerQueuedMessage:tt}=wi({sessionId:g,externalSession:k,onSeen:(C,he)=>{S(C,he)},onRequestNavigationRefresh:m,onUpsertNavigationSession:E,onNavigateToSession:(C,he)=>{j(C),I(ze(C,he))},onBindSessionWorkspace:N===T?x:void 0,onResolveMissingSession:()=>{m()},permissionRequestNotificationMode:"current_only",permissionToastIdPrefix:"parallel-permission-request",isCurrent:t,enableRuntimeErrorHandling:!0,enableCompletionHaptics:!1,enableThinkingPlaceholder:!0,enableForkTimelineSanitizer:!0}),dt=Ji((H==null?void 0:H.parallelGroup)??e.session.parallelGroup),ht=eo({groupId:((Kt=(H==null?void 0:H.parallelGroup)??e.session.parallelGroup)==null?void 0:Kt.groupId)??"parallel-group",ordinal:e.ordinal,overrideColor:L}),at=to((H==null?void 0:H.parallelGroup)??e.session.parallelGroup),ke=(H==null?void 0:H.sessionIsolatedWorkspace)??e.sessionIsolatedWorkspace,It=so(ke),Mt=((jt=Pe==null?void 0:Pe.modelId)==null?void 0:jt.trim())||((yt=e.model)==null?void 0:yt.trim())||c("shell.parallelPaneModelFallback"),st=((Nt=e.memberPrompt)==null?void 0:Nt.trim())||c("shell.parallelPanePromptFallback"),nt=M,Se=wr(H??k,ke),Te=Se===nt?(n==null?void 0:n.displayName)??nt:It??st,Fe=l.useMemo(()=>{var C;return((C=v.find(he=>he.workspace.id===Se))==null?void 0:C.workspace.path)??null},[v,Se]),p=f===g;async function Y(C){await je(Object.entries(C.answers).map(([,he])=>he.filter(Boolean).join(" / ")).filter(Boolean).join(`
|
|
8
|
+
`))}const ae=r&&G?{...Ht(n)??{},...dt??{},...ht,left:`${G.x}px`,top:`${G.y}px`,width:`${G.width}px`}:void 0,ye=y&&P?{...Ht(n)??{},...dt??{},...ht,left:`${P.x}px`,top:`${P.y}px`,width:`${P.width}px`,height:`${P.height}px`}:void 0;l.useEffect(()=>{U(Pn(T)),K(!1),z(!1),q(null),W(null),de("files")},[T]),l.useEffect(()=>{if(zt(e.subagentTree,s)){b(s);return}if(s===T){b(T);return}b(C=>Xl(e,C)?C:T)},[e,T,s]),l.useEffect(()=>{if(!r)return;const C=he=>{var Xe,Qe,Ze;const rt=he.target;rt instanceof HTMLElement&&((Xe=fe.current)!=null&&Xe.contains(rt)||(Qe=se.current)!=null&&Qe.contains(rt)||(Ze=ne.current)!=null&&Ze.contains(rt)||o())};return window.addEventListener("pointerdown",C),()=>{window.removeEventListener("pointerdown",C)}},[r,o]),l.useEffect(()=>{if(!r){W(null);return}const C=()=>{var he;W(Ol(((he=$.current)==null?void 0:he.getBoundingClientRect())??null))};return C(),window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0)}},[r]),l.useEffect(()=>{if(!y)return;const C=()=>{q(he=>he&&Bt(he))};return window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C)}},[y]);async function We(){if(Se===nt&&j(nt),R.isDesktop&&R.bridge.supported){const C=await ea(R,{workspaceId:Se,workspaceName:Te,focusOwner:"terminal-page"});C.ok||w({title:C.detail??c("terminalManager.openExternalFailed"),tone:"error"});return}I(ro(Se))}async function $e(){if(!(!R.isDesktop||!R.bridge.supported)){if(ie==="files"){const C=await Qo(R,{workspaceId:Se,workspaceName:Te,sessionId:g,focusOwner:"file-context-panel"});C.ok||w({title:C.detail??c("conversation.filePanelOpenExternalFailed"),tone:"error"});return}if(ie==="git"){const C=await Zo(R,{workspaceId:Se,workspaceName:Te,focusOwner:"git-sidebar"});C.ok||w({title:C.detail??c("git.openExternalFailed"),tone:"error"});return}if(ie==="processes"){const C=await Jo(R,{workspaceId:Se,workspaceName:Te,focusOwner:"terminal-manager-panel"});C.ok||w({title:C.detail??c("terminalManager.openExternalFailed"),tone:"error"});return}await We()}}function Ne(){var C,he;K(!0),q(Nl(((C=ee.current)==null?void 0:C.getBoundingClientRect())??null)??jl(((he=ge.current)==null?void 0:he.getBoundingClientRect())??null))}function De(C){if(C.button!==0||!P)return;C.preventDefault();const he=C.clientX,rt=C.clientY,Xe=P,Qe=ft=>{q(Bt({...Xe,x:Xe.x+(ft.clientX-he),y:Xe.y+(ft.clientY-rt)}))},Ze=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",Ze)};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",Ze)}function Ce(C){if(C.button!==0||!P)return;C.preventDefault(),C.stopPropagation();const he=C.clientX,rt=C.clientY,Xe=P,Qe=ft=>{q(Bt({...Xe,width:Xe.width+(ft.clientX-he),height:Xe.height+(ft.clientY-rt)}))},Ze=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",Ze)};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",Ze)}const gt=y&&typeof document<"u"?Et.createPortal(i.jsxs("div",{ref:ne,className:"parallel-pane-tools-popover","data-parallel-pane-layer":g,"data-pinned":te?"true":void 0,"data-workspace-tone":(n==null?void 0:n.tone)??"root",style:ye,children:[i.jsxs("div",{className:"parallel-pane-tools-toolbar",children:[i.jsxs("div",{className:"parallel-pane-tools-drag-handle",onPointerDown:De,children:[i.jsx("span",{className:"parallel-pane-tools-drag-dots","aria-hidden":"true",children:i.jsx(Bl,{})}),i.jsx("span",{children:c("shell.parallelPaneToolsAction")})]}),i.jsx("div",{className:"parallel-pane-tools-tabs",role:"tablist","aria-label":c("shell.parallelPaneToolsAction"),children:["files","git","processes","terminals"].map(C=>i.jsx("button",{type:"button",role:"tab","aria-selected":ie===C,className:"parallel-pane-tools-tab",onClick:()=>{de(C)},children:C==="files"?c("shell.filesEntry"):C==="git"?c("shell.gitEntry"):C==="processes"?c("shell.parallelPaneProcessesEntry"):c("shell.terminalsEntry")},C))}),i.jsxs("div",{className:"parallel-pane-tools-actions",children:[i.jsx("button",{type:"button",className:`conversation-header-ai-button${te?" active":""}`,"aria-label":c("shell.parallelPanePinAction"),title:c("shell.parallelPanePinAction"),"aria-pressed":te,onClick:()=>{z(C=>!C)},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Fl,{})})}),R.isDesktop&&R.bridge.supported?i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelPaneDetachAction"),title:c("shell.parallelPaneDetachAction"),onClick:()=>{$e()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Wl,{})})}):null,i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("common.close"),title:c("common.close"),onClick:()=>{K(!1)},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Ul,{})})})]})]}),i.jsx("div",{className:"parallel-pane-tools-body","data-panel":ie,children:ie==="files"?i.jsx($r,{className:"parallel-pane-tools-surface",hideHeading:!0,sessionId:g,workspaceId:Se}):ie==="git"?i.jsx(Vr,{className:"parallel-pane-tools-surface",panelActive:!0,workspaceId:Se}):ie==="processes"?i.jsx(Gr,{className:"parallel-pane-tools-surface parallel-pane-tools-process-panel",currentWorkspaceId:Se,navigationGroups:v}):i.jsx(zo,{embeddedMode:!0,externalWindowWorkspaceId:Se,workbenchShellOverrides:{navigationGroups:v,currentWorkspaceId:Se,selectWorkspace:j}})}),i.jsx("button",{type:"button",className:"parallel-pane-tools-resize-handle","aria-label":c("shell.parallelPaneResizeAction"),title:c("shell.parallelPaneResizeAction"),onPointerDown:Ce,children:i.jsx("span",{"aria-hidden":"true",children:i.jsx($l,{})})})]}),document.body):null,Yt=r&&typeof document<"u"?Et.createPortal(i.jsxs("div",{ref:se,className:"parallel-pane-info-popover","data-parallel-pane-layer":g,"data-workspace-tone":(n==null?void 0:n.tone)??"root",style:ae,children:[i.jsx("strong",{className:"parallel-pane-info-title",children:c("shell.parallelPaneInfoTitle")}),i.jsx(Pt,{children:i.jsxs("dl",{className:"parallel-pane-info-list",children:[i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.createSessionProviderLabel")}),i.jsx("dd",{children:Ft((H??e.session).provider,"full")})]}),i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.parallelPaneModelFallback")}),i.jsx("dd",{children:Mt})]}),i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.parallelPaneIsolatedWorkspaceTitle")}),i.jsx("dd",{children:It??c("common.unknown")})]})]})}),i.jsx(Pt,{heading:c("shell.parallelPaneColorPaletteLabel"),description:c("shell.parallelPaneColorPaletteDescription"),actions:i.jsx("button",{type:"button",className:"ghost-button parallel-pane-color-reset",disabled:!L||p,onClick:()=>{Us(T,null),U(null)},children:c("shell.parallelPaneColorPaletteReset")}),children:i.jsx("div",{className:"workbench-manage-color-palette parallel-pane-color-palette","aria-label":c("shell.parallelPaneColorPaletteLabel"),children:no.map(C=>i.jsx("button",{type:"button",className:"workbench-manage-color-swatch","aria-label":c("shell.manageWorkspaceColorSelectSwatch",{color:C}),"aria-pressed":L===C,"data-selected":L===C,disabled:p,style:{backgroundColor:C},onClick:()=>{const he=Us(T,C);U(he)}},C))})}),i.jsx(Pt,{heading:c("shell.parallelPaneIsolatedWorkspaceTitle"),description:(ke==null?void 0:ke.lifecycleStatus)==="active"?c("shell.parallelPanePromoteDescription"):(ke==null?void 0:ke.lifecycleStatus)==="promoted"?c("shell.parallelPaneRemovePromotedDescription"):c("shell.parallelPaneRemoveDescription"),children:i.jsxs(vs,{align:"start",className:"parallel-pane-action-row",children:[(ke==null?void 0:ke.lifecycleStatus)==="active"?i.jsx("button",{type:"button",className:"secondary-button parallel-pane-promote-action",disabled:d===ke.id||p,onClick:()=>{const C=ke==null?void 0:ke.id;C&&u(C)},children:d===ke.id?c("shell.parallelPanePromoting"):c("shell.parallelPanePromoteAction")}):null,i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:p,onClick:()=>{h(g)},children:p?c("shell.parallelPaneRemoving"):c("shell.parallelPaneRemoveAction")})]})})]}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("article",{ref:ee,className:"parallel-conversation-pane","data-current":t?"true":void 0,"data-workspace-tone":(n==null?void 0:n.tone)??"root","data-parallel-role":((Qt=(H==null?void 0:H.parallelGroup)??e.session.parallelGroup)==null?void 0:Qt.role)??void 0,style:{"--parallel-pane-order":String(e.ordinal),...Ht(n)??{},...dt??{},...ht},children:[i.jsxs("header",{ref:fe,className:"parallel-conversation-pane-header",children:[i.jsx("span",{className:"parallel-conversation-pane-connector","aria-hidden":"true"}),i.jsxs("div",{className:"parallel-conversation-pane-heading",children:[at?i.jsx("span",{className:"session-parallel-badge",children:at}):null,i.jsx("p",{className:"parallel-conversation-pane-subtitle",title:st,children:st}),i.jsxs("div",{className:"parallel-conversation-pane-meta",children:[i.jsx("span",{className:`session-provider-badge ${(H??e.session).provider}`,children:Ft((H??e.session).provider)}),i.jsx("span",{className:"parallel-conversation-pane-model",children:Mt})]})]}),i.jsxs("div",{className:"parallel-conversation-pane-actions",children:[i.jsx("button",{ref:$,type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelPaneInfoAction"),title:c("shell.parallelPaneInfoAction"),"aria-expanded":r,onClick:()=>{K(!1),a()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Hl,{})})}),i.jsx("button",{ref:ge,type:"button",className:`conversation-header-ai-button${y?" active":""}`,"aria-label":c("shell.parallelPaneToolsAction"),title:c("shell.parallelPaneToolsAction"),"aria-expanded":y,onClick:()=>{o(),Ne()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(ql,{})})})]})]}),i.jsxs("div",{className:"parallel-conversation-pane-body",children:[i.jsx(pn,{connectionState:le,onReconnect:re}),i.jsx(jr,{requests:He,replyingRequestId:Oe,onReply:Re}),i.jsx("div",{className:"parallel-conversation-pane-timeline",children:i.jsx(un,{sessionId:g,sessionSummary:H??e.session,workspaceId:Se,workspacePath:Fe,items:Ae,historyState:B,loadingOlderMessages:F,hasOlderMessages:O,provider:(H==null?void 0:H.provider)??e.session.provider,interruptedSource:X,followTailUpdates:!0,onLoadOlderMessages:ce,onRetryMessage:ue,onSubmitStructuredQuestion:Y,onForkMessage:C=>{const he=H??e.session;J({sourceMessageId:C.id,sourceMessageSnapshot:{role:C.role,kind:C.kind??(C.role==="tool"?"tool_result":"text"),content:C.content},content:C.content,sourceProvider:he.provider,workspaceId:he.workspaceId,targetProvider:he.provider,targetModel:null,targetProviderConfigMode:he.providerConfigMode??"global-default",targetProviderPresetId:he.providerPresetId??null}),bi()}})}),i.jsx(Zr,{items:qe,deletingQueueItemId:Le,steeringQueueItemId:Z,canSteer:D,onDelete:et,onSteer:tt}),i.jsx(dn,{capabilities:pe,draftStorageId:g,initialModel:e.model,workspaceId:(H??e.session).workspaceId,initialProviderConfigMode:(H??e.session).providerConfigMode??"global-default",initialProviderPresetId:(H??e.session).providerPresetId??null,forkDraft:Ee,onClearForkDraft:()=>J(null),onForkDraftChange:C=>J(C),hasActiveRun:_e,contextUsage:Pe,taskProvider:(H??e.session).provider,taskMessages:me,hasPendingQueuedMessages:be,canInterrupt:Ye,isSubmitting:oe,isRunning:A,onInterrupt:Be,onSend:je,onQueueSend:Me})]})]}),Yt,gt]})}function Hl(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("circle",{cx:"8",cy:"8",r:"5.5",fill:"none",stroke:"currentColor",strokeWidth:"1.4"}),i.jsx("path",{d:"M8 6.1H8.01M7.35 7.6H8V10.3H8.65",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.4"})]})}function ql(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("rect",{x:"2.5",y:"2.5",width:"4.2",height:"4.2",rx:"1.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("rect",{x:"9.3",y:"2.5",width:"4.2",height:"4.2",rx:"1.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("rect",{x:"2.5",y:"9.3",width:"4.2",height:"4.2",rx:"1.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("rect",{x:"9.3",y:"9.3",width:"4.2",height:"4.2",rx:"1.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Bl(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("circle",{cx:"5",cy:"4.5",r:"0.9",fill:"currentColor"}),i.jsx("circle",{cx:"11",cy:"4.5",r:"0.9",fill:"currentColor"}),i.jsx("circle",{cx:"5",cy:"8",r:"0.9",fill:"currentColor"}),i.jsx("circle",{cx:"11",cy:"8",r:"0.9",fill:"currentColor"}),i.jsx("circle",{cx:"5",cy:"11.5",r:"0.9",fill:"currentColor"}),i.jsx("circle",{cx:"11",cy:"11.5",r:"0.9",fill:"currentColor"})]})}function Fl(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M10.9 3.1 12.9 5.1 10.9 6.1v2.1l-2.1 2.1v2.6l-.8-.8-.8.8v-2.6L5 8.2V6.1L3.1 5.1l2-2h5.8Z",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.1"})})}function Wl(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M5 3.1H3.8A1.3 1.3 0 0 0 2.5 4.4v7.8a1.3 1.3 0 0 0 1.3 1.3h7.8a1.3 1.3 0 0 0 1.3-1.3V11",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.2"}),i.jsx("path",{d:"M8.1 3.1h4.4v4.4M12.3 3.3 7 8.6",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.2"})]})}function Ul(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.3"})})}function $l(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M6.5 12.2 12.2 6.5M9 12.4 12.4 9M11.4 12.4 12.4 11.4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.1"})})}function Vl(e,t,s){const n=s.get(e);return n?ws(n).flatMap(r=>Mi(r,t)):[]}function Mi(e,t){var r;const s=e.item.session;if(((r=s.parallelGroup)==null?void 0:r.groupId)===t)return[];const n=ws(e).flatMap(o=>Mi(o,t));return s.isSubagent!==!0?n:[{session:s,workspaceId:e.item.workspace.id,children:n}]}function zt(e,t){const s=t.trim();return s?e.some(n=>n.session.sessionId===s||zt(n.children,s)):!1}function Gl(e,t){return t===e.session.sessionId?e.session.sessionId:zt(e.subagentTree,t)?t:e.session.sessionId}function Xl(e,t){const s=t.trim();return s?s===e.session.sessionId||zt(e.subagentTree,s):!1}function Si(e,t){const s=t.trim();if(!s)return null;for(const n of e){if(n.session.sessionId===s)return n.session;const r=Si(n.children,s);if(r)return r}return null}function yi(e,t){const s=t.trim();if(!s)return null;for(const n of e){if(n.session.sessionId===s)return n.workspaceId;const r=yi(n.children,s);if(r)return r}return null}const Tt=196,bt=82,dr=28,hr=24,xi=34,tn=18,zl=332,es=360,ps=840,fr=18,Yl=.22,Kl=2.4,Ql=6;function Zl(e,t){return(t.lastMessageAt??t.updatedAt).localeCompare(e.lastMessageAt??e.updatedAt)}function Pi(e,t,s){var w,v;if(!t)return null;const n=e.find(m=>m.workspace.id===t);if(!n)return null;const r=new Map(n.sessions.map(m=>[m.sessionId,m])),o=r.get(s)??null;if(!o)return null;const a=new Map;for(const m of n.sessions){const x=((w=m.parentSessionId)==null?void 0:w.trim())||null;if(!x)continue;const E=a.get(x)??[];a.set(x,[...E,m.sessionId])}const u=new Set,d=new Set;let h=o,f=o.sessionId;for(;h&&!d.has(h.sessionId);){u.add(h.sessionId),d.add(h.sessionId),f=h.sessionId;const m=((v=h.parentSessionId)==null?void 0:v.trim())||null;h=m?r.get(m)??null:null}const I=Ri(f,0,r,a,new Set),R=ec(I);return{root:I,current:o,currentPathIds:u,relatedSessionIds:R,sessionsById:r}}function Jl(e){return((e==null?void 0:e.relatedSessionIds.size)??0)>1}function Ri(e,t,s,n,r){const o=s.get(e);if(!o)throw new Error(`Session ${e} not found`);const a=new Set(r);a.add(e);const u=[...n.get(e)??[]].filter(d=>!a.has(d)).sort((d,h)=>{const f=s.get(d),I=s.get(h);return!f||!I?0:Zl(f,I)});return{session:o,depth:t,children:u.map(d=>Ri(d,t+1,s,n,a))}}function ec(e){const t=new Set;function s(n){t.add(n.session.sessionId),n.children.forEach(s)}return s(e),t}function ki(e){const t=Hr(e),s=e.lastMessageAt??e.updatedAt,n=s?new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(s)):null;return[Ft(e.provider),n,t].filter(Boolean).join(" · ")}function Ti(e){return e.isArchived===!0}function tc(e){return[...e].sort((t,s)=>t.sequence-s.sequence).filter(t=>t.content.trim().length>0||t.kind==="tool_call"||t.kind==="tool_result")}function Ci(e,t){return e<=0||t<=0?1:Math.min(1,e/t)}function sc(e,t,s,n){const r=Ci(e,s),o=s*r,a=n*r,u=o<e?(e-o)/2:0;return{scale:r,offsetX:u,offsetY:0,shellWidth:Math.max(e,o),shellHeight:a}}function sn(e,t,s){return Math.min(s,Math.max(t,e))}function nc(e,t,s,n){if(e<=0||t<=0||s<=0||n<=0)return 1;const r=Math.max(1,e-fr*2),o=Math.max(1,t-fr*2);return Math.min(1,r/s,o/n)}function ms(e,t,s,n,r){const o=n*e.scale,a=r*e.scale,u=(t-o)/2,d=(s-a)/2,h=o<=t?u:sn(e.offsetX,t-o,0),f=a<=s?d:sn(e.offsetY,s-a,0);return{scale:e.scale,offsetX:h,offsetY:f}}function ts(e,t,s,n){const r=nc(e,t,s,n);return ms({scale:r,offsetX:(e-s*r)/2,offsetY:(t-n*r)/2},e,t,s,n)}function rc(e,t,s,n,r,o,a,u){const d=(s-e.offsetX)/e.scale,h=(n-e.offsetY)/e.scale;return ms({scale:t,offsetX:s-d*t,offsetY:n-h*t},r,o,a,u)}function ic(e){var s;const t=e.content.trim();if(t.length>0){const n=t.replace(/\s+/g," ").trim();return n.length<=160?n:`${n.slice(0,157)}...`}return(s=e.toolCall)!=null&&s.name?`${e.toolCall.name} ${c("conversation.branchTreeToolMessageFallback")}`:c("conversation.branchTreeMessageEmpty")}function oc(e){switch(e.role){case"assistant":return c("conversation.roleAssistant");case"system":return c("conversation.roleSystem");case"tool":return c("conversation.roleTool");case"user":default:return c("conversation.roleUser")}}function nn(e,t){const s=t.get(e.session.sessionId);if(s!==void 0)return s;if(e.children.length===0)return t.set(e.session.sessionId,Tt),Tt;const n=e.children.reduce((o,a,u)=>{const d=o+nn(a,t);return u===0?d:d+tn},0),r=Math.max(Tt,n);return t.set(e.session.sessionId,r),r}function ac(e){const t=new Map,s=[],n=new Map;function r(u,d,h){const f=nn(u,t),I=d+f/2,R=hr+h*(bt+xi),w=I-Tt/2,v=u.children.reduce((S,j,T)=>{const N=S+nn(j,t);return T===0?N:N+tn},0);let m=d+Math.max(0,(f-v)/2);const x=u.children.map(S=>{const j=r(S,m,h+1);return m+=j.subtreeWidth+tn,j}),E={node:u,children:x,x:w,y:R,centerX:I,centerY:R+bt/2,subtreeWidth:f};return s.push(E),n.set(u.session.sessionId,E),E}const o=r(e,dr,0),a=s.reduce((u,d)=>Math.max(u,d.y+bt),0);return{root:o,nodes:s,bySessionId:n,width:o.subtreeWidth+dr*2,height:a+hr}}function lc(e){return Math.max(0,Math.min(255,Number.parseFloat(e)))}function cc(e){const t=e.trim();if(t.startsWith("#")){const n=t.slice(1);if(n.length===3){const[r,o,a]=n.split("").map(u=>Number.parseInt(u.repeat(2),16));return{r,g:o,b:a}}if(n.length>=6)return{r:Number.parseInt(n.slice(0,2),16),g:Number.parseInt(n.slice(2,4),16),b:Number.parseInt(n.slice(4,6),16)}}const s=t.match(/rgba?\(([^)]+)\)/i);if(s){const[n,r,o]=s[1].split(",").map(a=>lc(a));return{r:n,g:r,b:o}}return null}function ct(e,t,s){const n=cc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:s}function uc(e,t,s,n,r,o){const a=e.getContext("2d");if(!a)return;const u=a,d=window.devicePixelRatio||1;e.width=Math.max(1,Math.floor(t.width*d)),e.height=Math.max(1,Math.floor(t.height*d)),e.style.width=`${t.width}px`,e.style.height=`${t.height}px`,u.setTransform(d,0,0,d,0,0),u.clearRect(0,0,t.width,t.height);const h=window.getComputedStyle(e),f=h.getPropertyValue("--accent").trim()||"#3b82f6",I=h.getPropertyValue("--border-primary").trim()||"#d4d8df",R=h.getPropertyValue("--bg-surface").trim()||"#ffffff";if(!o){const v=u.createLinearGradient(0,0,t.width,t.height);v.addColorStop(0,ct(R,.38,"rgba(255, 255, 255, 0.38)")),v.addColorStop(1,ct(f,.05,"rgba(59, 130, 246, 0.05)")),u.fillStyle=v,u.fillRect(0,0,t.width,t.height)}function w(v){for(const m of v.children){const x=n.has(v.node.session.sessionId)&&n.has(m.node.session.sessionId),E=v.node.session.sessionId===r||m.node.session.sessionId===r;u.beginPath(),u.moveTo(v.centerX,v.y+bt-10);const S=v.y+bt+xi*.52;u.bezierCurveTo(v.centerX,S,m.centerX,S,m.centerX,m.y+10),u.lineWidth=E?3:x?2.5:1.5,u.strokeStyle=E?ct(f,.52,"rgba(59, 130, 246, 0.52)"):x?ct(f,.32,"rgba(59, 130, 246, 0.32)"):ct(I,.72,"rgba(148, 163, 184, 0.72)"),u.stroke(),u.beginPath(),u.arc(m.centerX,m.y,E?4.5:3.5,0,Math.PI*2),u.fillStyle=E?ct(f,.9,"rgba(59, 130, 246, 0.9)"):ct(I,.78,"rgba(148, 163, 184, 0.78)"),u.fill(),w(m)}}w(t.root);for(const v of t.nodes){const m=v.node.session.sessionId===s,x=v.node.session.sessionId===r,E=n.has(v.node.session.sessionId);if(!m&&!x&&!E)continue;const S=u.createRadialGradient(v.centerX,v.centerY,10,v.centerX,v.centerY,x?90:64);S.addColorStop(0,ct(f,x?.22:.14,"rgba(59, 130, 246, 0.22)")),S.addColorStop(1,"rgba(59, 130, 246, 0)"),u.fillStyle=S,u.beginPath(),u.ellipse(v.centerX,v.centerY,Tt*.72,bt*.9,0,0,Math.PI*2),u.fill(),(x||m)&&(u.beginPath(),u.arc(v.centerX,v.y+12,x?6:5,0,Math.PI*2),u.fillStyle=ct(f,.94,"rgba(59, 130, 246, 0.94)"),u.fill())}}function dc(e,t,s){const n=Math.min(zl,t-24),r=e.left+e.width/2-n/2,o=Math.max(12,Math.min(t-n-12,r)),d=s-e.bottom-12<220&&e.top>es?Math.max(12,e.top-es-12):Math.max(12,Math.min(s-es-12,e.bottom+12));return{width:n,left:o,top:d,maxHeight:Math.min(es,s-24)}}function hc({model:e,selectedSession:t,selectedTreeNode:s,previewEntry:n,onClose:r,onOpenSession:o}){const a=Gt(t.title,c("common.unknown")),u=t.sessionId===e.current.sessionId,d=Ti(t),h=Nr(s.session),f=Or(s.session),I=Lr(s.session),R=Dr(s.session);return i.jsxs("div",{className:"conversation-branch-preview-popover",role:"dialog","aria-label":`${c("conversation.branchTreePreviewTitle")} ${a.fullTitle}`,children:[i.jsxs("div",{className:"conversation-branch-preview-popover-header",children:[i.jsxs("div",{className:"conversation-branch-preview-card-title-row",children:[i.jsx("strong",{title:a.fullTitle,children:a.displayTitle}),u?i.jsx("span",{className:"conversation-branch-current-badge",children:c("conversation.branchTreeCurrentBadge")}):null,d?i.jsx("span",{className:"conversation-branch-archived-badge",children:c("conversation.branchTreeArchivedBadge")}):null]}),i.jsx("button",{type:"button",className:"conversation-branch-preview-close","aria-label":c("common.close"),onClick:r,children:"x"})]}),i.jsx("p",{className:"conversation-branch-preview-popover-meta",children:ki(t)}),f&&h||R&&I?i.jsxs("div",{className:"conversation-branch-badge-row",children:[R&&I?i.jsx("span",{className:`session-fork-badge ${I}`,children:R}):null,f&&h?i.jsx("span",{className:`session-fork-badge ${h}`,children:f}):null]}):null,i.jsx("div",{className:"conversation-branch-preview-messages",children:n.status==="loading"?i.jsx("p",{className:"conversation-branch-empty",children:c("conversation.branchTreePreviewLoading")}):n.status==="error"?i.jsx("p",{className:"conversation-branch-empty",children:n.error||c("conversation.branchTreePreviewFailed")}):n.messages.length>0?n.messages.map(w=>i.jsxs("article",{className:"conversation-branch-preview-message",children:[i.jsxs("div",{className:"conversation-branch-preview-message-meta",children:[i.jsx("span",{children:oc(w)}),i.jsx("span",{children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(w.timestamp))})]}),i.jsx("p",{children:ic(w)})]},`${t.sessionId}:${w.messageId}`)):i.jsx("p",{className:"conversation-branch-empty",children:c("conversation.branchTreePreviewEmpty")})}),i.jsx("div",{className:"conversation-branch-preview-actions",children:i.jsx("button",{type:"button",className:"secondary-button",disabled:u,onClick:()=>o(t),children:u?c("conversation.branchTreeCurrentAction"):c("conversation.branchTreeSwitchAction")})})]})}function fc({layout:e,model:t,selectedSessionId:s,onSelectSession:n,onBackgroundClick:r,stageScale:o,desktopStageLayout:a,transform:u,isMobileViewport:d,viewportRef:h,onRegisterNodeElement:f,onViewportTouchStart:I,onViewportTouchMove:R,onViewportTouchEnd:w}){const v=l.useRef(null);return l.useEffect(()=>{const m=v.current;m&&uc(m,e,t.current.sessionId,t.currentPathIds,s,d)},[d,e,t.current.sessionId,t.currentPathIds,s]),i.jsx("div",{ref:h,className:"conversation-branch-canvas-viewport","data-scaled":o<.999,"data-mobile":d,onClick:m=>{m.target===m.currentTarget&&(r==null||r())},onTouchStart:I,onTouchMove:R,onTouchEnd:w,onTouchCancel:w,children:i.jsx("div",{className:"conversation-branch-canvas-stage-shell",style:{width:d?"100%":a.shellWidth,height:d?"100%":a.shellHeight},onClick:m=>{m.target===m.currentTarget&&(r==null||r())},children:i.jsxs("div",{className:"conversation-branch-canvas-stage",style:{width:e.width,height:e.height,transform:u?`translate(${u.offsetX}px, ${u.offsetY}px) scale(${u.scale})`:`translate(${a.offsetX}px, ${a.offsetY}px) scale(${a.scale})`,transformOrigin:"top left"},onClick:()=>{if(r){r();return}n(null)},children:[i.jsx("canvas",{ref:v,className:"conversation-branch-canvas",width:e.width,height:e.height,"aria-hidden":"true"}),e.nodes.map(m=>{const x=Gt(m.node.session.title,c("common.unknown")),E=Nr(m.node.session),S=Or(m.node.session),j=Lr(m.node.session),T=Dr(m.node.session),N=m.node.session.sessionId===t.current.sessionId,b=m.node.session.sessionId===s,V=t.currentPathIds.has(m.node.session.sessionId),k=Ti(m.node.session);return i.jsx("button",{ref:M=>f(m.node.session.sessionId,M),type:"button",className:"conversation-branch-smart-card conversation-branch-canvas-node","data-current":N,"data-selected":b,"data-current-path":V,"data-archived":k,style:{left:m.x,top:m.y,width:Tt,minHeight:bt},"aria-pressed":b,onClick:M=>{M.stopPropagation(),n(m.node.session.sessionId)},children:i.jsxs("div",{className:"conversation-branch-smart-card-main",children:[i.jsxs("div",{className:"conversation-branch-smart-card-title-row",children:[i.jsx("strong",{title:x.fullTitle,children:x.displayTitle}),N?i.jsx("span",{className:"conversation-branch-current-badge",children:c("conversation.branchTreeCurrentBadge")}):null,k?i.jsx("span",{className:"conversation-branch-archived-badge",children:c("conversation.branchTreeArchivedBadge")}):null]}),i.jsx("p",{children:ki(m.node.session)}),S&&E||T&&j?i.jsxs("div",{className:"conversation-branch-badge-row",children:[T&&j?i.jsx("span",{className:`session-fork-badge ${j}`,children:T}):null,S&&E?i.jsx("span",{className:`session-fork-badge ${E}`,children:S}):null]}):null]})},m.node.session.sessionId)})]})})})}function pr({model:e,onOpenSession:t,onClose:s}){const n=l.useMemo(()=>ac(e.root),[e.root]),r=l.useRef(null),o=l.useRef(new Map),[a,u]=l.useState(null),[d,h]=l.useState(0),[f,I]=l.useState(0),[R,w]=l.useState(null),[v,m]=l.useState({}),x=l.useRef(new Set),[E,S]=l.useState(typeof window<"u"?window.innerWidth<=ps:!1),[j,T]=l.useState(null),N=l.useRef({mode:"idle",startDistance:0,startScale:1,startOffsetX:0,startOffsetY:0,startTouchX:0,startTouchY:0,anchorX:0,anchorY:0,moved:!1});l.useEffect(()=>{const P=r.current;if(!P)return;const q=P;function G(){h(q.clientWidth),I(q.clientHeight),S(window.innerWidth<=ps)}if(G(),typeof ResizeObserver>"u")return window.addEventListener("resize",G),()=>window.removeEventListener("resize",G);const W=new ResizeObserver(G);return W.observe(P),()=>W.disconnect()},[]),l.useEffect(()=>{u(null)},[e.current.sessionId,e.root.session.sessionId]);const b=l.useMemo(()=>Ci(d,n.width),[d,n.width]),V=l.useMemo(()=>sc(d,f,n.width,n.height),[f,d,n.height,n.width]);l.useEffect(()=>{if(!E||d<=0||f<=0){T(null);return}T(P=>P?ms(P,d,f,n.width,n.height):ts(d,f,n.width,n.height))},[f,d,E,n.height,n.width]);const k=a?e.sessionsById.get(a)??null:null,M=k?n.bySessionId.get(k.sessionId)??null:null,g=k?v[k.sessionId]??{status:"idle",messages:[],error:null}:null,y=E&&!!s,K=!!s&&!y;l.useEffect(()=>{if(!a){w(null);return}const P=a;function q(){const G=o.current.get(P);if(!G){w(null);return}w(G.getBoundingClientRect())}return q(),window.addEventListener("resize",q),window.addEventListener("scroll",q,!0),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0)}},[a,b]),l.useEffect(()=>{if(!E)return;const P=a;if(!P)return;const q=window.requestAnimationFrame(()=>{const G=o.current.get(P);G&&w(G.getBoundingClientRect())});return()=>window.cancelAnimationFrame(q)},[E,j,a]),l.useEffect(()=>{if(!(k!=null&&k.sessionId)||(g==null?void 0:g.status)==="ready"||x.current.has(k.sessionId))return;let P=!1;return x.current.add(k.sessionId),m(q=>{var G;return{...q,[k.sessionId]:{status:"loading",messages:((G=q[k.sessionId])==null?void 0:G.messages)??[],error:null}}}),$s(k.sessionId,null,6,"backward").then(q=>{x.current.delete(k.sessionId),!P&&m(G=>({...G,[k.sessionId]:{status:"ready",messages:tc(q.messages),error:null}}))}).catch(q=>{x.current.delete(k.sessionId),!P&&m(G=>{var W;return{...G,[k.sessionId]:{status:"error",messages:((W=G[k.sessionId])==null?void 0:W.messages)??[],error:q instanceof Error?q.message:c("conversation.branchTreePreviewFailed")}}})}),()=>{P=!0}},[k==null?void 0:k.sessionId]);function ie(P){!E||d<=0||f<=0||T(q=>{const G=q??ts(d,f,n.width,n.height);return ms(P(G),d,f,n.width,n.height)})}function de(P){if(!E)return;const q=P.currentTarget.getBoundingClientRect();if(P.touches.length>=2){const ee=P.touches[0],fe=P.touches[1],$=Math.hypot(fe.clientX-ee.clientX,fe.clientY-ee.clientY),se=(ee.clientX+fe.clientX)/2-q.left,ne=(ee.clientY+fe.clientY)/2-q.top,ge=j??ts(d,f,n.width,n.height);N.current={mode:"pinch",startDistance:$,startScale:ge.scale,startOffsetX:ge.offsetX,startOffsetY:ge.offsetY,startTouchX:se,startTouchY:ne,anchorX:se,anchorY:ne,moved:!1};return}const G=P.touches[0],W=j??ts(d,f,n.width,n.height);N.current={mode:"pan",startDistance:0,startScale:W.scale,startOffsetX:W.offsetX,startOffsetY:W.offsetY,startTouchX:G.clientX,startTouchY:G.clientY,anchorX:0,anchorY:0,moved:!1}}function te(P){if(!E)return;const q=N.current;if(P.touches.length>=2){const $=P.currentTarget.getBoundingClientRect(),se=P.touches[0],ne=P.touches[1],ge=Math.hypot(ne.clientX-se.clientX,ne.clientY-se.clientY);if(ge<=0||q.startDistance<=0)return;P.preventDefault();const L=(se.clientX+ne.clientX)/2-$.left,U=(se.clientY+ne.clientY)/2-$.top,H=sn(q.startScale*(ge/q.startDistance),Yl,Kl);N.current={...q,mode:"pinch",moved:!0,anchorX:L,anchorY:U},ie(pe=>rc({...pe,scale:q.startScale,offsetX:q.startOffsetX,offsetY:q.startOffsetY},H,L,U,d,f,n.width,n.height));return}if(q.mode!=="pan"||P.touches.length!==1)return;const G=P.touches[0],W=G.clientX-q.startTouchX,ee=G.clientY-q.startTouchY;(q.moved||Math.hypot(W,ee)>=Ql)&&(P.preventDefault(),N.current={...q,moved:!0},ie($=>({...$,offsetX:q.startOffsetX+W,offsetY:q.startOffsetY+ee})))}function z(){N.current={mode:"idle",startDistance:0,startScale:(j==null?void 0:j.scale)??1,startOffsetX:(j==null?void 0:j.offsetX)??0,startOffsetY:(j==null?void 0:j.offsetY)??0,startTouchX:0,startTouchY:0,anchorX:0,anchorY:0,moved:!1}}return i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:`conversation-branch-tree-pane${s?" conversation-branch-dialog":""}${y?" conversation-branch-dialog-mobile-bare":""}`,role:s?"dialog":void 0,"aria-modal":s?"true":void 0,"aria-label":s?c("conversation.branchTreeTitle"):void 0,children:[K?i.jsx("div",{className:"conversation-branch-tree-pane-header",children:i.jsxs("div",{className:"conversation-branch-tree-pane-topbar",children:[i.jsxs("div",{className:"conversation-branch-tree-pane-heading",children:[i.jsx("h3",{children:c("conversation.branchTreeMapTitle")}),i.jsx("p",{children:c("conversation.branchTreeMapDescription")})]}),s?i.jsx("button",{type:"button",className:"conversation-branch-pane-close","aria-label":c("common.close"),onClick:s,children:"x"}):null]})}):null,i.jsxs("div",{className:"conversation-branch-canvas-shell",children:[y?i.jsx("button",{type:"button",className:"conversation-branch-pane-close conversation-branch-mobile-floating-close","aria-label":c("common.close"),onClick:s,children:"x"}):null,y?null:i.jsx("div",{className:"conversation-branch-canvas-tip",children:c("conversation.branchTreePreviewDescription")}),i.jsx(fc,{layout:n,model:e,selectedSessionId:a,onSelectSession:u,onBackgroundClick:y?s:void 0,stageScale:b,desktopStageLayout:V,transform:E?j:null,isMobileViewport:E,viewportRef:r,onRegisterNodeElement:(P,q)=>{if(q){o.current.set(P,q);return}o.current.delete(P)},onViewportTouchStart:de,onViewportTouchMove:te,onViewportTouchEnd:z})]})]}),k&&M&&g&&R&&typeof document<"u"?Et.createPortal(i.jsx("div",{className:"conversation-branch-preview-floating",style:dc(R,window.innerWidth,window.innerHeight),children:i.jsx(hc,{model:e,selectedSession:k,selectedTreeNode:M.node,previewEntry:g,onClose:()=>u(null),onOpenSession:t})}),document.body):null]})}function pc({open:e,navigationGroups:t,workspaceId:s,sessionId:n,onClose:r,onOpenSession:o}){const a=l.useMemo(()=>Pi(t,s,n),[t,n,s]),[u,d]=l.useState(typeof window<"u"?window.innerWidth>ps:!0);return l.useEffect(()=>{if(typeof window>"u")return;function h(){d(window.innerWidth>ps)}return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]),!e||!a||typeof document>"u"?null:u?i.jsx(gs,{open:e,title:c("conversation.branchTreeMapTitle"),description:c("conversation.branchTreeMapDescription"),size:"regular",layout:"viewer",bodyClassName:"conversation-branch-modal-body",onClose:r,children:i.jsx(pr,{model:a,onOpenSession:o})}):Et.createPortal(i.jsxs("div",{className:"workbench-modal-layer conversation-branch-panel-layer",children:[i.jsx("button",{type:"button",className:"workbench-modal-backdrop","aria-label":c("common.close"),onClick:r}),i.jsx(pr,{model:a,onOpenSession:o,onClose:r})]}),document.body)}function mc(e,t,s){if(!t)return null;const n=e.find(a=>a.workspace.id===t);if(!n)return null;const r=$t([n]).filter(a=>!a.session.isArchived&&!hn(a.session)),o=r.findIndex(a=>a.session.sessionId===s);return o<0?null:r[o+1]??null}const mr=.6,Ws=.6,gr=8,gc=36,vc=48,bc=96;function iu(){const{sessionId:e="",workspaceId:t}=oa(),s=fn(),n=mt(),r=l.useMemo(()=>new URLSearchParams(s.search),[s.search]),o=kc(r.get("toolPanel")),a=(t==null?void 0:t.trim())||null,u=l.useMemo(()=>xc(e,a,r),[a,r,e]),d=l.useMemo(()=>qc(e,s.state),[s.state,e]),h=l.useMemo(()=>Bc(e,s.state),[s.state,e]);return u?i.jsx(yc,{draft:u,navigate:n,initialToolPanel:o}):i.jsx(wc,{sessionId:e,bootstrapMessages:d,initialComposerModel:h.initialModel,initialComposerProviderConfigMode:h.providerConfigMode,initialComposerProviderPresetId:h.providerPresetId,initialToolPanel:o})}function wc(e){const{shellMode:t,navigationGroups:s,currentWorkspaceRef:n,currentTargetHostId:r}=wt(),o=mt(),a=l.useMemo(()=>$t(s),[s]),u=l.useMemo(()=>{var f;return((f=a.find(I=>I.session.sessionId===e.sessionId))==null?void 0:f.session)??null},[a,e.sessionId]),d=!$i(e.sessionId)&&e.bootstrapMessages.length===0&&a.length>0&&u===null,h=l.useMemo(()=>d?Dc({shellMode:t,navigationGroups:s,flattenedNavigationEntries:a,workspaceRef:n,targetHostId:r}):null,[r,n,a,d,s,t]);return l.useEffect(()=>{h&&o(h,{replace:!0})},[h,o]),h?null:i.jsx(Ic,{...e})}function Ic({sessionId:e,bootstrapMessages:t,initialComposerModel:s,initialComposerProviderConfigMode:n,initialComposerProviderPresetId:r,initialToolPanel:o}){var Xe,Qe,Ze,ft;const{shellMode:a,navigationGroups:u,requestNavigationRefresh:d,selectWorkspace:h,setSessionWorkspace:f,markNavigationSessionSeen:I,favoriteSessions:R,archiveSession:w,unarchiveSession:v,startDraftSession:m,upsertNavigationSession:x,currentWorkspaceRef:E,currentTargetHostId:S}=wt(),j=mt(),[T,N]=l.useState(!1),[b,V]=l.useState(!1),[k,M]=l.useState(null),[g,y]=l.useState(!1),[K,ie]=l.useState(!1),[de,te]=l.useState(!1),z=l.useMemo(()=>$t(u),[u]),P=l.useMemo(()=>{var _;return((_=z.find(Q=>Q.session.sessionId===e))==null?void 0:_.session)??null},[z,e]),{showToast:q}=pt(),G=()=>{var we;const _=(P==null?void 0:P.workspaceId)??((we=u[0])==null?void 0:we.workspace.id)??null,Q=(_?z.find(it=>it.workspace.id===_)??null:null)??z[0]??null;j(Q?ze(Q.workspace.id,Q.session.sessionId):_?Rt(_):a==="mobile"?Mr():"/landing",{replace:!0})},{session:W,capabilities:ee,messages:fe,timelineItems:$,permissionRequests:se,queuedMessages:ne,contextUsage:ge,historyState:L,runtimeInterruptSource:U,loadingOlderMessages:H,hasOlderMessages:pe,connectionState:me,sending:Ae,replyingPermissionRequestId:He,deletingQueueItemId:qe,steeringQueueItemId:Pe,forkDraft:B,setForkDraft:X,composerHasActiveRun:F,composerCanInterrupt:O,composerIsRunning:le,canSteerQueuedMessage:oe,hasPendingQueuedMessages:Oe,reconnect:Le,loadOlderMessages:Z,retryMessage:Ee,send:J,queue:_e,interrupt:Ye,replyPermissionRequest:A,deleteQueuedMessage:D,steerQueuedMessage:be}=wi({sessionId:e,targetHostId:S,externalSession:P,bootstrapMessages:t,onSeen:(_,Q)=>{I(_,Q)},onRequestNavigationRefresh:d,onUpsertNavigationSession:x,onNavigateToSession:(_,Q)=>{const we=S?E:{hostId:"current",workspaceId:_};h(_,we),j(ze(_,Q,we))},onBindSessionWorkspace:f,onResolveMissingSession:G,onForkSuccess:()=>{qt("preview"),q({title:c("conversation.forkMessageSucceeded"),tone:"success"})},enableRuntimeErrorHandling:!0,enableCompletionHaptics:!0,enableThinkingPlaceholder:!0,enableForkTimelineSanitizer:!0}),re=a!=="mobile",ce=Bi(!re),ue=W??P??null,je=(W==null?void 0:W.sessionIsolatedWorkspace)??(P==null?void 0:P.sessionIsolatedWorkspace)??null,Me=ue?ns(ue,je):null,Be=ue?wr(ue,je):null,Re=Hi({enabled:!re,initialPanel:o,workspaceId:Be,suspendMainGesture:!re&&ce.isVisible}),et=l.useMemo(()=>new Set(R.map(_=>_.session.sessionId)),[R]),tt=l.useMemo(()=>u.map(_=>_.workspace),[u]),dt=l.useMemo(()=>qr(u),[u]),ht=l.useMemo(()=>ln(u),[u]),at=l.useMemo(()=>_i(u,Me,et),[et,Me,u]),ke=l.useMemo(()=>ji(R,u),[R,u]);async function It(_){await J(Mc(_.answers))}const[Mt,st]=l.useState([]),nt=l.useMemo(()=>[...ke,...at],[ke,at]),Se=l.useMemo(()=>Me?tt.find(_=>_.id===Me)??null:null,[Me,tt]),Te=(Me?ht[Me]??null:null)??(Se?cn(Se):null),Fe=l.useMemo(()=>Is(u,Me),[Me,u]),p=dt.find(_=>_.workspace.id===Me)??(Fe?{workspace:Fe.workspace,label:Fe.workspace.name,subtitle:Fe.workspace.path}:null),Y=l.useMemo(()=>mc(u,Me,e),[Me,u,e]),ae=(W==null?void 0:W.provider)??(P==null?void 0:P.provider)??null,ye=l.useMemo(()=>{var _;return Gt(((_=W??P)==null?void 0:_.title)??null,c("conversation.titleFallback"))},[P,W]),We=re,$e=l.useMemo(()=>{var we;if(!We)return null;if(co(ue))return((we=ue==null?void 0:ue.parallelGroup)==null?void 0:we.groupId)??null;const _=bs(z);return Sc(_,e)},[ue,z,e,We]),Ne=re?null:Di(ce.mainGestureHandlers,Re.mainGestureHandlers);l.useEffect(()=>{const _=Ir(nt,e,Q=>Q.session.sessionId);_.length!==0&&st(Q=>{const we=new Set(Q);let it=!1;for(const Sn of _)we.has(Sn)||(we.add(Sn),it=!0);return it?Array.from(we):Q})},[nt,e]);const De=(ue==null?void 0:ue.workspaceId)??(P==null?void 0:P.workspaceId)??null,Ce=l.useMemo(()=>Pi(u,De,e),[De,u,e]),gt=Jl(Ce),Yt=!!(ue&&De&>),_t=()=>{ie(!0)},St=l.useMemo(()=>(Fe==null?void 0:Fe.sessions.filter(_=>Br(_)))??[],[Fe]),Kt=l.useRef(null),jt=l.useRef(null),yt=l.useRef(null),Nt=l.useRef(null),[Qt,C]=l.useState(null),{composerPortalTarget:he}=Fr();l.useEffect(()=>{ie(!1)},[e]),Oi(yt,Qt,!re,e),Li(yt,Nt,!re,e);function rt(_,Q){h(_,Q),j(Rt(_,Q))}return re&&$e?i.jsxs(i.Fragment,{children:[i.jsx(Ll,{groupId:$e,currentSessionId:e}),i.jsx(Vs,{open:de,source:ue?{kind:"session",sessionId:e,workspaceId:ue.workspaceId,workspaceName:(Te==null?void 0:Te.displayName)??ue.workspaceId,sessionTitle:ue.title,defaultProvider:ue.provider}:null,targetHostId:S,onClose:()=>te(!1),onCreated:async _=>{_.members.forEach(we=>{x(we.session)}),Rn(_.group.id),await d();const Q=_.members.find(we=>we.session.sessionId===_.group.anchorSessionId)??_.members[0]??null;if(Q){const we=ns(Q.session,Q.sessionIsolatedWorkspace),it=ut(S,E);h(we,it),j(ze(we,Q.session.sessionId,it))}te(!1),q({title:c("shell.parallelCreateSucceeded"),tone:"success"})}})]}):i.jsxs(i.Fragment,{children:[i.jsxs("main",{ref:yt,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!re,"data-preview-mode":re?void 0:ce.displayMode,"data-preview-dragging":re?void 0:ce.isDragging,"data-workspace-tone":(Te==null?void 0:Te.tone)??"root","data-worktree-depth":(Te==null?void 0:Te.depth)??0,"data-tool-panel-open":re?void 0:Re.isOpen,style:{...re?{}:ce.pageStyle,...Ht(Te)??{}},children:[re?i.jsx(Wr,{session:W??P,workspaceContext:Te,actions:i.jsxs(i.Fragment,{children:[Yt?i.jsx(Oc,{onOpenBranchTree:_t}):null,ue?i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelCreateAction"),title:c("shell.parallelCreateAction"),onClick:()=>te(!0),children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Lc,{})})}):null,i.jsx(Qr,{session:W??P})]})}):null,re?null:i.jsx(Ur,{containerRef:Nt,className:"mobile-conversation-page-header",gestureHandlers:Ne??void 0,currentWorkspace:p?{id:p.workspace.id,name:p.label,path:p.subtitle}:tt[0]??null,workspaces:tt,workspaceOptions:dt,onSelectWorkspace:rt,heading:ye.fullTitle,trailing:i.jsxs("div",{className:"mobile-conversation-toolbar-main",children:[i.jsx("span",{className:"mobile-conversation-toolbar-title",title:ye.fullTitle,children:ye.displayTitle}),i.jsx(wa,{session:W??P,onOpenBranchTree:Yt?_t:void 0})]})}),re?null:i.jsx(Fi,{visible:!Re.isOpen&&ce.isVisible,widthPx:ce.previewWidthPx,isDragging:ce.isDragging,gestureHandlers:ce.railGestureHandlers,activeSessionId:e,createSessionActionLabel:Me&&ae?c("shell.createSession"):void 0,favoriteItems:ke,items:at,expandedRootIds:Mt,workspaceSectionLabel:(p==null?void 0:p.label)??c("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:Me&&ae?()=>{m(Me,ae)}:void 0,archiveCurrentActionLabel:c("shell.archiveCurrentSessionAction"),archiveFolderActionLabel:St.length>0?c("shell.archiveFolderLabel"):void 0,onArchiveActiveSession:()=>{N(!0)},onOpenArchiveFolder:St.length>0?()=>{V(!0)}:void 0,onToggleSubsessions:_=>{st(Q=>Q.includes(_)?Q.filter(we=>we!==_):[...Q,_])},onActivate:_=>{ce.closePreview();const Q=ut(S,E);h(_.workspace.id,Q),j(ze(_.workspace.id,_.session.sessionId,Q))}}),i.jsx("div",{className:"mobile-conversation-stage",...Ne??{},children:i.jsxs("div",{ref:Kt,className:"mobile-conversation-main",children:[i.jsx(pn,{connectionState:me,onReconnect:Le}),i.jsx(jr,{requests:se,replyingRequestId:He,onReply:A}),i.jsx("div",{ref:jt,className:"conversation-timeline-shell",children:i.jsx(un,{sessionId:e,sessionSummary:W??P??null,workspaceId:Be,workspacePath:(Se==null?void 0:Se.path)??null,items:$,historyState:L,loadingOlderMessages:H,hasOlderMessages:pe,provider:(W==null?void 0:W.provider)??null,interruptedSource:U,onLoadOlderMessages:Z,onRetryMessage:Ee,onSubmitStructuredQuestion:It,onForkMessage:_=>{W&&(X({sourceMessageId:_.id,sourceMessageSnapshot:{role:_.role,kind:_.kind??(_.role==="tool"?"tool_result":"text"),content:_.content},content:_.content,sourceProvider:W.provider,workspaceId:W.workspaceId,targetProvider:W.provider,targetModel:null,targetProviderConfigMode:W.providerConfigMode??"global-default",targetProviderPresetId:W.providerPresetId??null}),bi())}})}),i.jsx(ma,{containerRef:jt,session:W??P??null,currentCapabilities:ee}),i.jsx(Zr,{items:ne,deletingQueueItemId:qe,steeringQueueItemId:Pe,canSteer:oe,onDelete:D,onSteer:be}),Re.isOpen?null:i.jsx(dn,{capabilities:ee,draftStorageId:e,initialModel:s,workspaceId:((Xe=W??P)==null?void 0:Xe.workspaceId)??null,initialProviderConfigMode:n??((Qe=W??P)==null?void 0:Qe.providerConfigMode)??"global-default",initialProviderPresetId:r??((Ze=W??P)==null?void 0:Ze.providerPresetId)??null,forkDraft:B,onClearForkDraft:()=>X(null),onForkDraftChange:_=>X(_),panelRef:re?void 0:C,portalContainer:re?null:he,hasActiveRun:F,contextUsage:ge,taskProvider:((ft=W??P)==null?void 0:ft.provider)??null,taskMessages:fe,hasPendingQueuedMessages:Oe,canInterrupt:O,isSubmitting:Ae,isRunning:le,onInterrupt:Ye,onSend:J,onQueueSend:_e})]})}),!re&&Be?i.jsx(qi,{activePanel:Re.activePanel,open:Re.isOpen,sessionId:e,workspaceId:Be,navigationGroups:u,onClose:()=>{Re.closePanel()},onSelectPanel:_=>{Re.selectPanel(_)},onSelectPanelBySwipe:_=>{if(_===null){Re.closePanel();return}Re.selectPanel(_)}}):null]}),i.jsx(pc,{open:K,navigationGroups:u,workspaceId:De,sessionId:e,onClose:()=>ie(!1),onOpenSession:_=>{ie(!1);const Q=ut(S,E);h(_.workspaceId,Q),qt("preview"),j(ze(_.workspaceId,_.sessionId,Q))}}),i.jsx(Nc,{open:T,busy:g,onClose:()=>{g||N(!1)},onConfirm:async()=>{if(!g){y(!0);try{if(await w(e),N(!1),q({title:c("shell.archiveAdded"),tone:"success"}),Me){if(h(Me,ut(S,E)),qt("preview"),Y){const _=ut(S,E);j(ze(Y.workspace.id,Y.session.sessionId,_));return}j(Rt(Me,ut(S,E)));return}j("/workspaces")}catch(_){q({title:_ instanceof Error?_.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{y(!1)}}}}),i.jsx(Ui,{open:b,workspaceName:(Fe==null?void 0:Fe.workspace.name)??null,sessions:St,restoringSessionId:k,onClose:()=>{k||V(!1)},onRestore:async _=>{M(_);try{await v(_),q({title:c("shell.archiveRestored"),tone:"success"})}catch(Q){q({title:Q instanceof Error?Q.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{M(null)}}}),We?i.jsx(Vs,{open:de,source:ue?{kind:"session",sessionId:e,workspaceId:ue.workspaceId,workspaceName:(Te==null?void 0:Te.displayName)??ue.workspaceId,sessionTitle:ue.title,defaultProvider:ue.provider}:null,targetHostId:S,onClose:()=>te(!1),onCreated:async _=>{_.members.forEach(we=>{x(we.session)}),Rn(_.group.id),await d();const Q=_.members.find(we=>we.session.sessionId===_.group.anchorSessionId)??_.members[0]??null;if(Q){const we=ns(Q.session,Q.sessionIsolatedWorkspace),it=ut(S,E);h(we,it),j(ze(we,Q.session.sessionId,it))}te(!1),q({title:c("shell.parallelCreateSucceeded"),tone:"success"})}}):null]})}function Mc(e){return Object.entries(e).map(([,t])=>t.filter(Boolean).join(" / ")).filter(Boolean).join(`
|
|
9
|
+
`)}function Sc(e,t){const s=t.trim();if(!s)return null;for(const n of e){const r=Ei(n,s,null);if(r)return r}return null}function Ei(e,t,s){var r,o;const n=((o=(r=e.item.session.parallelGroup)==null?void 0:r.groupId)==null?void 0:o.trim())||s;if(e.item.session.sessionId===t)return n;for(const a of ws(e)){const u=Ei(a,t,n);if(u)return u}return null}function yc({draft:e,navigate:t,initialToolPanel:s}){const{shellMode:n,navigationGroups:r,requestNavigationRefresh:o,selectWorkspace:a,setSessionWorkspace:u,upsertNavigationSession:d,favoriteSessions:h,unarchiveSession:f,startDraftSession:I,currentTargetHostId:R,currentWorkspaceRef:w}=wt(),[v,m]=l.useState(!1),[x,E]=l.useState([]),S=Pc(e,R,w),j=l.useMemo(()=>Lt(e.provider),[e.provider]),[T,N]=l.useState(j),b=n!=="mobile",{showToast:V}=pt(),k=l.useMemo(()=>Rc(e),[e]),M=Bi(!b),g=Hi({enabled:!b,initialPanel:s,sessionId:e.sessionId,workspaceId:e.workspaceId,suspendMainGesture:!b&&M.isVisible}),y=l.useMemo(()=>new Set(h.map(F=>F.session.sessionId)),[h]),K=l.useMemo(()=>r.map(F=>F.workspace),[r]),ie=l.useMemo(()=>qr(r),[r]),de=l.useMemo(()=>ln(r),[r]),te=l.useMemo(()=>K.find(F=>F.id===e.workspaceId)??null,[e.workspaceId,K]),z=de[e.workspaceId]??(te?cn(te):null),P=l.useMemo(()=>Gt(k.title??null,c("conversation.titleFallback")),[k]),q=l.useMemo(()=>_i(r,e.workspaceId,y),[e.workspaceId,y,r]),G=l.useMemo(()=>ji(h,r),[h,r]),[W,ee]=l.useState([]),fe=l.useMemo(()=>[...G,...q],[G,q]),$=l.useMemo(()=>Is(r,e.workspaceId),[e.workspaceId,r]),se=l.useMemo(()=>($==null?void 0:$.sessions.filter(F=>Br(F)))??[],[$]),ne=ie.find(F=>F.workspace.id===e.workspaceId)??($?{workspace:$.workspace,label:$.workspace.name,subtitle:$.workspace.path}:null),ge=b?null:Di(M.mainGestureHandlers,g.mainGestureHandlers),[L,U]=l.useState(!1),[H,pe]=l.useState(null),me=l.useRef(null),Ae=l.useRef(null),He=l.useRef(null),[qe,Pe]=l.useState(null),{composerPortalTarget:B}=Fr();l.useEffect(()=>{const F=Ir(fe,e.sessionId,O=>O.session.sessionId);F.length!==0&&ee(O=>{const le=new Set(O);let oe=!1;for(const Oe of F)le.has(Oe)||(le.add(Oe),oe=!0);return oe?Array.from(le):O})},[e.sessionId,fe]),l.useEffect(()=>(u(e.sessionId,e.workspaceId),()=>{u(e.sessionId,null)}),[e.sessionId,e.workspaceId,u]),l.useEffect(()=>{let F=!1;return N(j),Sr(e.provider,S,void 0,{targetHostId:R}).then(O=>{F||N(O)}).catch(()=>{}),()=>{F=!0}},[R,e.provider,S,j]),Oi(Ae,qe,!b,e.sessionId),Li(Ae,He,!b,e.sessionId);function X(F,O){a(F,O),t(Rt(F,O))}return i.jsx(i.Fragment,{children:i.jsxs("main",{ref:Ae,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!b,"data-preview-mode":b?void 0:M.displayMode,"data-preview-dragging":b?void 0:M.isDragging,"data-workspace-tone":(z==null?void 0:z.tone)??"root","data-worktree-depth":(z==null?void 0:z.depth)??0,"data-tool-panel-open":b?void 0:g.isOpen,style:{...b?{}:M.pageStyle,...Ht(z)??{}},children:[b?i.jsx(Wr,{session:k,workspaceContext:z}):null,b?null:i.jsx(Ur,{containerRef:He,className:"mobile-conversation-page-header",gestureHandlers:ge??void 0,currentWorkspace:ne?{id:ne.workspace.id,name:ne.label,path:ne.subtitle}:K[0]??null,workspaces:K,workspaceOptions:ie,onSelectWorkspace:X,heading:P.fullTitle,trailing:i.jsx("span",{className:"mobile-conversation-toolbar-title",title:P.fullTitle,children:P.displayTitle})}),b?null:i.jsx(Fi,{visible:!g.isOpen&&M.isVisible,widthPx:M.previewWidthPx,isDragging:M.isDragging,gestureHandlers:M.railGestureHandlers,activeSessionId:e.sessionId,createSessionActionLabel:c("shell.createSession"),favoriteItems:G,items:q,expandedRootIds:W,workspaceSectionLabel:(ne==null?void 0:ne.label)??c("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:()=>{I(e.workspaceId,e.provider)},archiveFolderActionLabel:se.length>0?c("shell.archiveFolderLabel"):void 0,onOpenArchiveFolder:se.length>0?()=>{U(!0)}:void 0,onToggleSubsessions:F=>{ee(O=>O.includes(F)?O.filter(le=>le!==F):[...O,F])},onActivate:F=>{M.closePreview();const O=ut(R,w);a(F.workspace.id,O),t(ze(F.workspace.id,F.session.sessionId,O))}}),i.jsx("div",{className:"mobile-conversation-stage",...ge??{},children:i.jsxs("div",{ref:me,className:"mobile-conversation-main",children:[i.jsx(pn,{connectionState:"closed",onReconnect:()=>{}}),i.jsx("div",{className:"conversation-timeline-shell",children:i.jsx(un,{sessionId:e.sessionId,sessionSummary:null,workspaceId:e.workspaceId,workspacePath:(te==null?void 0:te.path)??null,items:Ar({messages:x}),historyState:"ready",loadingOlderMessages:!1,hasOlderMessages:!1,provider:e.provider,onLoadOlderMessages:()=>{},onRetryMessage:()=>{}})}),g.isOpen?null:i.jsx(dn,{capabilities:T,draftStorageId:e.sessionId,workspaceId:e.workspaceId,panelRef:b?void 0:Pe,portalContainer:b?null:B,contextUsage:null,taskProvider:e.provider,taskMessages:x,isSubmitting:v,isRunning:!1,onSend:async(F,O)=>{var Oe,Le,Z,Ee;const le=Wc();E(J=>[...J,kr(e.sessionId,F,le,(O==null?void 0:O.attachmentMeta)??[],(O==null?void 0:O.attachments)??[])]),m(!0);const oe=performance.now();Ie("session_send.start_live.client_start",{draftSessionId:e.sessionId,workspaceId:S,provider:e.provider,clientRequestId:le,contentLength:F.length});try{const J=await xr({workspaceId:S,provider:e.provider,content:F,clientRequestId:le,model:(O==null?void 0:O.model)??null,reasoningLevel:(O==null?void 0:O.reasoningLevel)??null,permissionMode:vt(),attachments:(O==null?void 0:O.attachments)??[],providerConfigMode:(O==null?void 0:O.providerConfigMode)??"global-default",providerPresetId:(O==null?void 0:O.providerPresetId)??null},{targetHostId:R});Ie("session_send.start_live.client_response",{draftSessionId:e.sessionId,sessionId:J.sessionId,workspaceId:((Oe=J.session)==null?void 0:Oe.workspaceId)??S,provider:J.provider,clientRequestId:le,durationMs:Math.round(performance.now()-oe),returnedMessageId:((Le=J.message)==null?void 0:Le.messageId)??null}),J.session&&d(J.session);const _e=((Ee=(Z=J.session)==null?void 0:Z.workspaceId)==null?void 0:Ee.trim())||S,Ye=ut(R,w);u(J.sessionId,_e),qt("preview"),t(ze(_e,J.sessionId,Ye),{replace:!0,state:{composer:{sessionId:J.sessionId,initialModel:(O==null?void 0:O.model)??null,providerConfigMode:(O==null?void 0:O.providerConfigMode)??"global-default",providerPresetId:(O==null?void 0:O.providerPresetId)??null},bootstrap:{sessionId:J.sessionId,messages:[Hc({created:J,provider:e.provider,content:F,clientRequestId:le,attachments:(O==null?void 0:O.attachmentMeta)??[]})]}}}),o()}catch(J){throw Ie("session_send.start_live.client_error",{draftSessionId:e.sessionId,workspaceId:S,provider:e.provider,clientRequestId:le,durationMs:Math.round(performance.now()-oe),error:J instanceof Error?J.message:String(J)}),E(_e=>Cr(_e,le)),J}finally{m(!1)}}})]})}),b?null:i.jsx(qi,{activePanel:g.activePanel,open:g.isOpen,sessionId:e.sessionId,workspaceId:e.workspaceId,navigationGroups:r,onClose:()=>{g.closePanel()},onSelectPanel:F=>{g.selectPanel(F)},onSelectPanelBySwipe:F=>{if(F===null){g.closePanel();return}g.selectPanel(F)}}),i.jsx(Ui,{open:L,workspaceName:($==null?void 0:$.workspace.name)??null,sessions:se,restoringSessionId:H,onClose:()=>{H||U(!1)},onRestore:async F=>{pe(F);try{await f(F),V({title:c("shell.archiveRestored"),tone:"success"})}catch(O){V({title:O instanceof Error?O.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{pe(null)}}})]})})}function xc(e,t,s,n=null){var d,h,f;if(!$i(e))return null;const r=((d=s.get("workspaceId"))==null?void 0:d.trim())||null,a=((h=s.get("targetHostId"))==null?void 0:h.trim())||null?r??t:t??r,u=((f=s.get("provider"))==null?void 0:f.trim())??n??null;return!a||!_r(u)?null:{sessionId:e,workspaceId:a,provider:u}}function Pc(e,t,s){return t&&(s==null?void 0:s.hostId)===t&&s.workspaceId.trim()?s.workspaceId.trim():e.workspaceId}function Rc(e){const t=new Date().toISOString();return{sessionId:e.sessionId,workspaceId:e.workspaceId,provider:e.provider,providerSessionId:`draft://${e.sessionId}`,rawStoreRef:`draft://${e.sessionId}`,providerConfigMode:"global-default",providerPresetId:null,parentSessionId:null,isSubagent:!1,subagentLabel:null,isArchived:!1,title:ta(e.provider),messageCount:0,lastMessageAt:null,createdAt:t,updatedAt:t,syncStatus:"idle",syncCursor:null,lastSyncAt:null,lastErrorCode:null,lastErrorDetail:null,resumedAt:null,runningState:"idle",activitySource:"none",lastEventAt:null,completedAt:null,lastSeenAt:null,activityState:"idle"}}function Ai(e){const t=new Map(e.map(r=>[r.sessionId,r])),s=new Map,n=r=>{const o=s.get(r.sessionId);if(typeof o=="boolean")return o;if(r.isArchived)return s.set(r.sessionId,!1),!1;const a=uo(r,{mode:"mobile"});if(!a)return s.set(r.sessionId,!0),!0;const u=t.get(a);if(!u)return s.set(r.sessionId,!0),!0;if(u.isArchived){const h=!hn(r);return s.set(r.sessionId,h),h}const d=n(u);return s.set(r.sessionId,d),d};return e.filter(r=>n(r))}function _i(e,t,s){if(!t)return[];const n=Is(e,t);if(!n)return[];const r=Ai(n.sessions).map(a=>({session:a,workspace:n.workspace}));return bs(r,{mode:"mobile"}).filter(a=>!s.has(a.item.session.sessionId)&&!io(a.children,u=>s.has(u.session.sessionId)))}function ji(e,t){return e.filter(s=>!hn(s.session)).flatMap(s=>{const n=Is(t,s.workspace.id);if(!n)return[];const r=bs(Ai(n.sessions).map(a=>({session:a,workspace:n.workspace})),{mode:"mobile"}),o=Ni(r,s.session.sessionId);return o?[o]:[]})}function Ni(e,t){for(const s of e){if(s.item.session.sessionId===t)return s;const n=Ni(s.children,t);if(n)return n}return null}function Oi(e,t,s,n){l.useEffect(()=>{const r=e.current;if(!s||!r){r&&r.style.removeProperty("--mobile-conversation-composer-height");return}if(!t){r.style.removeProperty("--mobile-conversation-composer-height");return}const o=r,a=t;function u(){!e.current||!a.isConnected||o.style.setProperty("--mobile-conversation-composer-height",`${a.offsetHeight}px`)}u();const d=typeof ResizeObserver<"u"?new ResizeObserver(u):null;return d==null||d.observe(a),window.addEventListener("resize",u),()=>{d==null||d.disconnect(),window.removeEventListener("resize",u),r.style.removeProperty("--mobile-conversation-composer-height")}},[t,s,n,e])}function Li(e,t,s,n){l.useEffect(()=>{const r=e.current,o=t.current;if(!s||!r){r&&r.style.removeProperty("--mobile-conversation-page-header-height");return}if(!o){r.style.removeProperty("--mobile-conversation-page-header-height");return}const a=r,u=o;function d(){!e.current||!u.isConnected||a.style.setProperty("--mobile-conversation-page-header-height",`${u.offsetHeight}px`)}d();const h=typeof ResizeObserver<"u"?new ResizeObserver(d):null;return h==null||h.observe(u),window.addEventListener("resize",d),()=>{h==null||h.disconnect(),window.removeEventListener("resize",d),r.style.removeProperty("--mobile-conversation-page-header-height")}},[s,t,n,e])}function kc(e){return e==="files"||e==="git"||e==="processes"?e:null}function Di(...e){const t=e.filter(Boolean);return{onTouchStart(s){t.forEach(n=>n.onTouchStart(s))},onTouchMove(s){t.forEach(n=>n.onTouchMove(s))},onTouchEnd(s){t.forEach(n=>n.onTouchEnd(s))},onTouchCancel(s){t.forEach(n=>n.onTouchCancel(s))}}}function Hi(e){const t=fn(),s=mt(),n=an(),r=Xt(),o=l.useRef(null),a=l.useRef(!1),[u,d]=l.useState(()=>e.initialPanel??jn()),h=e.initialPanel??u,f=e.enabled&&e.workspaceId!==null&&e.initialPanel!==null;l.useEffect(()=>{if(!e.enabled){o.current=null,a.current=!1;return}const T=e.initialPanel??jn();d(T),Nn(T)},[e.enabled,e.initialPanel]),l.useEffect(()=>{if(!f){a.current=!1;return}if(r.platform!=="android"||!Tc(t.state)||a.current||typeof window>"u"||window.location.pathname!==t.pathname)return;const T=new URLSearchParams(t.search);T.delete("toolPanel");const N=T.toString(),b=`${t.pathname}${N?`?${N}`:""}${t.hash}`,V=`${t.pathname}${t.search}${t.hash}`;window.history.replaceState(window.history.state,"",b),window.history.pushState(window.history.state,"",V),a.current=!0},[f,t.hash,t.pathname,t.search,t.state,r.platform]);function I(T,N){const b=new URLSearchParams(t.search);T?(b.set("toolPanel",T),d(T),Nn(T)):b.delete("toolPanel");const V=b.toString();s({pathname:t.pathname,search:V?`?${V}`:""},{replace:(N==null?void 0:N.replace)??!1})}function R(T){n.trigger("selection"),I(T,{replace:f})}function w(){if(f){if(n.trigger("gesture"),a.current&&typeof window<"u"){a.current=!1,window.history.back();return}I(null,{replace:!0})}}function v(T){if(!e.enabled||!e.workspaceId)return;const N=T??h;n.trigger("gesture"),I(N)}function m(T){if(!e.enabled||T.changedTouches.length!==1){o.current=null;return}if(Cc(T.target)){o.current=null;return}const N=T.changedTouches[0];o.current={x:N.clientX,y:N.clientY}}function x(T){const N=o.current;if(o.current=null,!N||T.changedTouches.length!==1||f||e.suspendMainGesture)return;const b=T.changedTouches[0],V=b.clientX-N.x,k=b.clientY-N.y;V>-56||Math.abs(V)<=Math.abs(k)*1.15||v()}function E(T){const N=o.current;if(o.current=null,!N||T.changedTouches.length!==1||!f)return;const b=T.changedTouches[0],V=b.clientX-N.x,k=b.clientY-N.y;V<56||Math.abs(V)<=Math.abs(k)*1.15||w()}return{activePanel:h,closePanel:w,isOpen:f,mainGestureHandlers:{onTouchStart:m,onTouchMove:()=>{},onTouchEnd:x,onTouchCancel:()=>{o.current=null}},openPanel:v,panelGestureHandlers:{onTouchStart:m,onTouchMove:()=>{},onTouchEnd:E,onTouchCancel:()=>{o.current=null}},selectPanel:R}}function qi(e){const t=l.useRef(null);if(!e.open)return null;function s(r){if(r.changedTouches.length!==1){t.current=null;return}if(Ec(r.target)){t.current=null;return}const o=r.changedTouches[0];t.current={x:o.clientX,y:o.clientY}}function n(r){const o=t.current;if(t.current=null,!o||r.changedTouches.length!==1)return;const a=r.changedTouches[0],u=a.clientX-o.x,d=a.clientY-o.y;if(Math.abs(u)<56||Math.abs(u)<=Math.abs(d)*1.15)return;const h=["files","git","processes"],f=h.indexOf(e.activePanel);if(u<0){e.onSelectPanelBySwipe(h[Math.min(h.length-1,f+1)]??e.activePanel);return}if(f===0){e.onSelectPanelBySwipe(null);return}e.onSelectPanelBySwipe(h[Math.max(0,f-1)]??e.activePanel)}return i.jsxs("section",{className:"mobile-conversation-tool-panel","data-panel":e.activePanel,onTouchStartCapture:s,onTouchEndCapture:n,onTouchCancel:()=>{t.current=null},children:[i.jsxs("header",{className:"mobile-conversation-tool-panel-header","data-preview-gesture":"ignore",children:[i.jsx("button",{type:"button",className:"mobile-conversation-tool-panel-back","aria-label":c("shell.mobileConversationToolCloseAction"),title:c("shell.mobileConversationToolCloseAction"),onClick:e.onClose,children:i.jsx("span",{"aria-hidden":"true",children:"‹"})}),i.jsx("div",{className:"mobile-conversation-tool-panel-tabs",role:"tablist","aria-label":c("shell.mobileConversationToolTabsLabel"),children:["files","git","processes"].map(r=>i.jsx("button",{type:"button",role:"tab","aria-selected":e.activePanel===r,className:"mobile-conversation-tool-panel-tab",onClick:()=>{e.onSelectPanel(r)},children:r==="files"?c("shell.filesEntry"):r==="git"?c("shell.gitEntry"):c("shell.mobileConversationToolProcessesTab")},r))})]}),i.jsx("div",{className:"mobile-conversation-tool-panel-body",children:e.activePanel==="files"?i.jsx($r,{className:"mobile-conversation-tool-surface",hideHeading:!0,sessionId:e.sessionId,workspaceId:e.workspaceId}):e.activePanel==="git"?i.jsx(Vr,{className:"mobile-conversation-tool-surface",panelActive:!0,workspaceId:e.workspaceId}):i.jsx(Gr,{className:"mobile-conversation-tool-surface mobile-tool-native-panel mobile-tool-process-panel",currentWorkspaceId:e.workspaceId,navigationGroups:e.navigationGroups})})]})}function Tc(e){return typeof e=="object"&&e!==null&&"mobileToolPanelRouteRedirect"in e&&e.mobileToolPanelRouteRedirect===!0}function Cc(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function Ec(e){return e instanceof Element?!!e.closest("input, textarea, select, option, [contenteditable='true']"):!1}function Bi(e){const t=an(),[s,n]=l.useState(()=>e?Rs():"immersive"),[r,o]=l.useState(()=>vr()),[a,u]=l.useState(()=>e&&Rs()==="preview"?"default":"closed"),d=l.useRef(a),h=l.useRef(null);l.useEffect(()=>{d.current=a},[a]),l.useEffect(()=>{if(!e){h.current=null,d.current="closed",u("closed"),n("immersive");return}const k=Rs();n(k),u(k==="preview"?"default":"closed")},[e]),l.useEffect(()=>{e&&qt(s)},[e,s]),l.useEffect(()=>{if(typeof window>"u")return;function k(){o(vr())}return k(),window.addEventListener("resize",k),()=>{window.removeEventListener("resize",k)}},[]);function f(k){d.current=k,u(k)}function I(k="default"){f(k),n("preview")}function R(){f("closed"),n("immersive")}function w(){f("expanded"),n("preview")}function v(){if(d.current!=="closed"){t.trigger("gesture"),R();return}t.trigger("gesture"),I()}function m(k,M){const g=M.touches[0]??M.changedTouches[0];if(!e||!g){h.current=null;return}if(_c(M.target)){h.current=null;return}if(k==="main"){if(d.current==="closed"&&g.clientX>bc){h.current=null;return}}else if(d.current==="closed"){h.current=null;return}h.current={source:k,intent:k==="rail"?"rail":d.current==="closed"?"open":"close",startX:g.clientX,startY:g.clientY,lastX:g.clientX,lastY:g.clientY,horizontalLocked:!1}}function x(k){const M=h.current,g=k.touches[0];if(!e||!M||!g)return;const y=g.clientX-M.startX,K=g.clientY-M.startY;if(M.lastX=g.clientX,M.lastY=g.clientY,!M.horizontalLocked){if(Math.abs(y)<gr&&Math.abs(K)<gr)return;if(Math.abs(y)<=Math.abs(K)){h.current=null;return}if(M.intent==="open"&&y<=0){h.current=null;return}if(M.intent==="close"&&y>=0){h.current=null;return}M.horizontalLocked=!0}}function E(k){var K;const M=h.current;if(h.current=null,!(M!=null&&M.horizontalLocked))return;const g=(K=k==null?void 0:k.changedTouches)==null?void 0:K[0];g&&(M.lastX=g.clientX,M.lastY=g.clientY);const y=M.lastX-M.startX;if(M.intent==="open"){y>=gc&&(t.trigger("gesture"),I("default"));return}if(M.intent==="close"){y<=-34&&(t.trigger("gesture"),R());return}if(y<=-34){t.trigger("gesture"),R();return}y>=vc&&d.current==="default"&&(t.trigger("gesture"),w())}const S=a==="expanded"?Ws:a==="default"?mr:0,j=Math.round(r*S*100)/100,T=S===0?0:S/Ws,N={"--mobile-conversation-preview-default-width":`${Math.round(r*mr*100)/100}px`,"--mobile-conversation-preview-max-width":`${Math.round(r*Ws*100)/100}px`,"--mobile-conversation-preview-width":`${j}px`,"--mobile-conversation-preview-progress":T.toFixed(4)};return{closePreview:R,displayMode:a==="closed"?"immersive":"preview",isDragging:!1,isVisible:a!=="closed",mainGestureHandlers:{onTouchStart:k=>m("main",k),onTouchMove:x,onTouchEnd:E,onTouchCancel:E},pageStyle:N,previewWidthPx:j,railGestureHandlers:{onTouchStart:k=>m("rail",k),onTouchMove:x,onTouchEnd:E,onTouchCancel:E},togglePreview:v}}function Fi({visible:e,widthPx:t,isDragging:s,gestureHandlers:n,activeSessionId:r,createSessionActionLabel:o,favoriteItems:a,items:u,expandedRootIds:d,workspaceSectionLabel:h,onCreateSession:f,archiveCurrentActionLabel:I,archiveFolderActionLabel:R,onArchiveActiveSession:w,onOpenArchiveFolder:v,onToggleSubsessions:m,onActivate:x}){if(!e)return null;function E(S,j){const{workspaceName:T,ancestorExpanded:N=!1,ancestorHasNextSiblings:b=[],hasNextSibling:V=!1,isFirstSibling:k=!1}=j??{},M=S.item.session.sessionId,g=S.children,y=S.depth===0&&g.length>0,K=N||y&&d.includes(M),ie=S.depth>0?[...b,V]:[...b];return i.jsxs("div",{className:"mobile-conversation-preview-tree-node",children:[i.jsxs("div",{className:"mobile-conversation-preview-tree-row",style:{"--mobile-preview-tree-depth":S.depth},children:[S.depth>0?i.jsxs("div",{className:"mobile-conversation-preview-guides","aria-hidden":"true",children:[b.map((de,te)=>de?i.jsx("span",{className:"mobile-conversation-preview-guide-column",style:{"--mobile-preview-tree-level":te+1}},`${M}:ancestor:${te}`):null),i.jsx("span",{className:"mobile-conversation-preview-guide-branch","data-continue":V,"data-first":k,style:{"--mobile-preview-tree-level":S.depth},children:i.jsx("span",{className:"mobile-conversation-preview-guide-branch-horizontal"})})]}):null,i.jsx(Ac,{entry:S.item,activeSessionId:r,hasSubsessions:y,subsessionsExpanded:K,workspaceName:T,onToggleSubsessions:y?()=>{m(M)}:void 0,onActivate:x})]}),g.length>0&&K?i.jsx("div",{className:"mobile-conversation-preview-children",children:g.map((de,te)=>E(de,{workspaceName:T,ancestorExpanded:!0,ancestorHasNextSiblings:ie,hasNextSibling:te<g.length-1,isFirstSibling:te===0}))}):null]},`${S.item.workspace.id}:${M}`)}return i.jsxs("aside",{className:"mobile-conversation-preview-rail terminal-mobile-list-rail surface-card","data-dragging":s,style:{width:`${t}px`,maxWidth:`${t}px`},...n,children:[o&&f?i.jsx("div",{className:"mobile-conversation-preview-topbar terminal-mobile-list-footer",children:i.jsxs("button",{type:"button",className:"mobile-conversation-preview-create-button workbench-import-toggle terminal-mobile-list-create",onClick:f,children:[i.jsx("span",{className:"workbench-import-toggle-symbol","aria-hidden":"true",children:"+"}),i.jsx("span",{className:"workbench-import-toggle-label",children:o})]})}):null,i.jsxs("div",{className:"mobile-conversation-preview-body terminal-mobile-list-body",children:[a.length>0?i.jsxs("section",{className:"mobile-conversation-preview-group mobile-conversation-preview-list-favorites terminal-mobile-list-group terminal-mobile-list-group-pinned",children:[i.jsxs("div",{className:"mobile-conversation-preview-group-heading terminal-mobile-list-group-heading",children:[i.jsx("span",{children:c("shell.favoriteSectionTitle")}),i.jsx("span",{className:"workbench-section-counter",children:a.length})]}),i.jsx("div",{className:"mobile-conversation-preview-list mobile-conversation-preview-list-static terminal-mobile-session-list",children:a.map(S=>i.jsx("div",{children:E(S,{workspaceName:S.item.workspace.name})},`favorite:${S.item.workspace.id}:${S.item.session.sessionId}`))})]}):null,i.jsxs("section",{className:"mobile-conversation-preview-group mobile-conversation-preview-group-workspace terminal-mobile-list-group terminal-mobile-list-group-workspace",children:[i.jsxs("div",{className:"mobile-conversation-preview-group-heading terminal-mobile-list-group-heading",children:[i.jsx("span",{children:h}),i.jsx("span",{className:"workbench-section-counter",children:u.length})]}),u.length===0?i.jsx("div",{className:"workbench-session-empty",children:c("shell.emptyWorkspaceSessions")}):i.jsx("div",{className:"mobile-conversation-preview-list terminal-mobile-session-list","data-preview-gesture":"ignore",children:u.map(S=>E(S))})]})]}),I&&w||R&&v?i.jsxs("div",{className:"mobile-conversation-preview-actions terminal-mobile-list-footer",children:[I&&w?i.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:()=>{w()},children:I}):null,R&&v?i.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:v,children:R}):null]}):null]})}function Ac({entry:e,activeSessionId:t,hasSubsessions:s=!1,subsessionsExpanded:n=!1,onActivate:r,onToggleSubsessions:o,workspaceName:a}){const u=e.session.sessionId===t;return i.jsxs("article",{className:"mobile-conversation-preview-entry terminal-mobile-session-card","data-active":u,children:[s?i.jsx("button",{type:"button",className:"mobile-conversation-preview-toggle","aria-label":n?c("shell.subagentCollapse"):c("shell.subagentExpand"),title:n?c("shell.subagentCollapse"):c("shell.subagentExpand"),"aria-expanded":n,onClick:d=>{d.stopPropagation(),o==null||o()},children:i.jsx("span",{className:br(e.session,{isActive:u,hasSubsessions:s}),"aria-hidden":"true"})}):i.jsx("span",{className:br(e.session,{isActive:u,hasSubsessions:s}),"aria-hidden":"true"}),i.jsx("button",{type:"button",className:"mobile-conversation-preview-item terminal-mobile-session-primary","data-active":u,onClick:()=>r(e),children:i.jsxs("div",{className:"mobile-conversation-preview-item-body",children:[i.jsx("span",{className:"mobile-conversation-preview-item-title",children:e.session.title||c("common.unknown")}),i.jsx("span",{className:"mobile-conversation-preview-item-meta",children:Wi(e.session,a)})]})})]})}function vr(){return typeof window>"u"?390:Math.max(window.innerWidth||390,320)}function _c(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function br(e,t){const s=ia("mobile-conversation-preview-indicator",e,{hasSubagents:t.hasSubsessions});return s.endsWith(" is-idle")&&t.isActive?"mobile-conversation-preview-indicator is-active":s}function Wi(e,t){const s=Hr(e);return[t??null,Ft(e.provider),jc(e.lastMessageAt??e.updatedAt),s].filter(Boolean).join(" · ")}function jc(e){return e?new Date(e).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):c("common.unknown")}function Nc({open:e,busy:t,onClose:s,onConfirm:n}){return i.jsx(gs,{open:e,title:c("shell.archiveConfirmTitle"),description:c("shell.archiveConfirmDescription"),size:"narrow",layout:"confirm",dismissible:!t,showCloseButton:!1,footer:i.jsxs(vs,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:t,onClick:s,children:c("common.cancel")}),i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:t,onClick:()=>{n()},children:c("shell.archiveAction")})]}),onClose:s,children:i.jsx(i.Fragment,{})})}function Ui({open:e,workspaceName:t,sessions:s,restoringSessionId:n,onClose:r,onRestore:o}){const{searchOpen:a,searchKeyword:u,filteredSessions:d,summaryLoading:h,summaryError:f,summaryBySessionId:I,setSearchKeyword:R,toggleSearch:w}=sa(e,s),v=l.useId(),m=s.length>0&&u.trim().length>0?c("shell.archiveSearchEmpty"):c("shell.archiveEmpty");return i.jsxs(gs,{open:e,title:c("shell.archiveModalTitle"),description:t?`${t} · ${c("shell.archiveModalDescription")}`:c("shell.archiveModalDescription"),size:"regular",layout:"list",dismissible:!n,headerActions:s.length>0?i.jsx("button",{type:"button",className:"secondary-button","aria-pressed":a,onClick:w,children:c("shell.archiveSearchAction")}):void 0,showCloseButton:!1,onClose:r,children:[a?i.jsxs("div",{className:"workbench-archive-search-panel",children:[i.jsx(ss,{label:c("shell.archiveSearchLabel"),htmlFor:v,children:i.jsx("input",{id:v,type:"text",value:u,placeholder:c("shell.archiveSearchPlaceholder"),autoFocus:!0,onChange:x=>R(x.target.value)})}),h?i.jsx("p",{className:"workbench-archive-search-status",children:c("shell.archiveSearchSummaryLoading")}):null,f?i.jsx("p",{className:"workbench-archive-search-status status-text","data-tone":"warning",children:f}):null]}):null,d.length>0?i.jsx(oo,{className:"workbench-archive-list",children:d.map(x=>{var T;const E=Gt(x.title,c("common.unknown")),S=((T=I[x.sessionId])==null?void 0:T.trim())??"",j=na(x);return i.jsx(ao,{className:"workbench-archive-item",trailing:i.jsx("button",{type:"button",className:"secondary-button",disabled:n===x.sessionId,onClick:()=>{o(x.sessionId)},children:c("shell.unarchiveAction")}),children:i.jsxs("div",{className:"workbench-archive-item-main",children:[i.jsxs("div",{className:"workbench-archive-title-row",children:[i.jsx("strong",{title:E.fullTitle,children:E.displayTitle}),j?i.jsx("span",{className:"session-fork-badge archive-child",children:j}):null]}),i.jsx("p",{children:Wi(x)}),a&&S?i.jsx("p",{className:"workbench-archive-item-summary",children:S}):null]})},x.sessionId)})}):i.jsx(lo,{title:m,compact:!0,className:"workbench-section-empty"})]})}function Oc(e){return i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("conversation.branchTreeAction"),title:c("conversation.branchTreeAction"),onClick:e.onOpenBranchTree,children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(ra,{})})})}function Lc(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 3.25a1.75 1.75 0 1 1 0 3.5a1.75 1.75 0 0 1 0-3.5Zm0 6a1.75 1.75 0 1 1 0 3.5a1.75 1.75 0 0 1 0-3.5Zm8-3a1.75 1.75 0 1 1 0 3.5a1.75 1.75 0 0 1 0-3.5Z",fill:"none",stroke:"currentColor",strokeWidth:"1.4"}),i.jsx("path",{d:"M5.75 5h2.15c1.35 0 2.45 1.1 2.45 2.45v.1M5.75 11h2.15c1.35 0 2.45-1.1 2.45-2.45V8.4",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.4"})]})}function $i(e){return e.startsWith("draft-")}function Dc(e){var n,r,o;const t=((n=e.navigationGroups[0])==null?void 0:n.workspace.id)??null,s=(t?e.flattenedNavigationEntries.find(a=>a.workspace.id===t)??null:null)??e.flattenedNavigationEntries[0]??null;if(s){const a=e.targetHostId?(r=e.workspaceRef)!=null&&r.workspaceId?{hostId:e.targetHostId,workspaceId:e.workspaceRef.workspaceId}:null:e.workspaceRef??null;return ze(s.workspace.id,s.session.sessionId,a)}if(t){const a=e.targetHostId?(o=e.workspaceRef)!=null&&o.workspaceId?{hostId:e.targetHostId,workspaceId:e.workspaceRef.workspaceId}:null:e.workspaceRef??null;return Rt(t,a)}return e.shellMode==="mobile"?Mr():"/landing"}function ut(e,t){return!e||!(t!=null&&t.workspaceId)?null:{hostId:e,workspaceId:t.workspaceId}}function Hc(e){var o,a,u,d,h,f;const t=((a=(o=e.created.message)==null?void 0:o.providerSessionId)==null?void 0:a.trim())||e.created.providerSessionId.trim()||`draft-bootstrap-${e.created.sessionId}`,s=`synthetic-user-${e.clientRequestId}`,n=Number.isFinite((u=e.created.message)==null?void 0:u.sequence)?Math.max(1,((d=e.created.message)==null?void 0:d.sequence)??1):1,r=((f=(h=e.created.message)==null?void 0:h.timestamp)==null?void 0:f.trim())||e.created.acceptedAt.trim()||new Date().toISOString();return{messageId:s,provider:e.provider,providerSessionId:t,role:"user",kind:"text",content:e.content,attachments:e.attachments,timestamp:r,sequence:n,rawRef:`synthetic://${e.provider}/${e.created.sessionId}/${e.clientRequestId}`}}function qc(e,t){if(!t||typeof t!="object")return[];const s=t.bootstrap;if(!s||typeof s!="object")return[];const n=s.sessionId,r=s.messages;return n!==e||!Array.isArray(r)?[]:r.filter(Fc)}function Bc(e,t){if(!t||typeof t!="object")return{initialModel:null,providerConfigMode:"global-default",providerPresetId:null};const s=t.composer;if(!s||typeof s!="object")return{initialModel:null,providerConfigMode:"global-default",providerPresetId:null};const n=s.sessionId,r=s.initialModel,o=s.providerConfigMode,a=s.providerPresetId;if(n!==e)return{initialModel:null,providerConfigMode:"global-default",providerPresetId:null};const u=typeof r=="string"&&r.trim()||null,d=typeof a=="string"&&a.trim()||null,h=o==="cc-switch-preset"&&d?"cc-switch-preset":"global-default";return{initialModel:u,providerConfigMode:h,providerPresetId:h==="cc-switch-preset"?d:null}}function Fc(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.messageId=="string"&&typeof t.provider=="string"&&typeof t.providerSessionId=="string"&&typeof t.role=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string"&&typeof t.sequence=="number"&&typeof t.rawRef=="string"}function Wc(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}export{iu as ConversationPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as d,j as e}from"./index-
|
|
1
|
+
import{b as d,j as e}from"./index-Bp1FnRo_.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-Bp1FnRo_.js";import{g as L}from"./App-Pe30N_Dy.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
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 d,o as F,_ as q,j as s,t as o}from"./index-Bp1FnRo_.js";import{r as O,u as C,W as _,m as N,F as $,T as A,g as U}from"./WorkbenchLayout-CoYxMzzR.js";import{FileContextPanel as V}from"./FileContextPanel-BklQRQXj.js";import{GitSidebar as z}from"./GitSidebar-D0tb3W87.js";import{TerminalManagerPanel as B}from"./TerminalManagerPanel-75khWhRz.js";import{b as H,a as K}from"./workbench-navigation-Bs4OQYD3.js";import{c as J,u as Q,e as X,N as W}from"./App-Pe30N_Dy.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./host-alias-CeDJeL0T.js";import"./DesktopModal-DyC_e0eF.js";import"./relay-entry-B6UDc5cD.js";import"./WorkbenchModal-2PaCY_Gj.js";import"./MobileSheet-C32hwIFd.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 T(n){return n.kind==="file-preview"?o("conversation.fileViewerWindowTitle"):n.kind==="files"?o("shell.filesEntry"):n.kind==="git"?o("shell.gitEntry"):n.kind==="processes"?o("shell.terminalManagerEntry"):n.kind==="terminals"?o("shell.terminalsEntry"):n.kind==="affairs"?o("shell.workbenchModeAffairs"):n.kind==="code"?o("shell.workbenchModeCode"):n.kind}function x(n,a){var t;return n.workspaceName??(n.workspaceId?((t=a.find(l=>l.workspace.id===n.workspaceId))==null?void 0:t.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 l,u;const a=((l=n.payload.routePath)==null?void 0:l.trim())??"";if(a)return a;const t=((u=n.workspaceId)==null?void 0:u.trim())??"";return t?H(t):null}function te(n){var t;return((t=n.workspaceId)==null?void 0:t.trim())??""?K():"/landing"}function ie(n,a){const t=x(n,a);if(n.kind==="file-preview"){const u=j(n.payload.filePath)??T(n);return t?`${u}(${t})`:u}const l=T(n);return t?`CodingNS - ${l}(${t})`:`CodingNS - ${l}`}function be(){var I;const{windowId:n}=J(),a=Q(),t=X(),l=O(t),u=C(i=>i.sessionDisplaySortMode),[e,b]=d.useState(null),[R,m]=d.useState(!0),[M,v]=d.useState(null),[c,f]=d.useState([]),[r,S]=d.useState(null);d.useEffect(()=>{let i=!1;async function p(){if(!n){b(null),m(!1),v(o("desktopWindow.invalidWindowId"));return}m(!0),v(null);const w=await t.bridge.getWindowDescriptor(n),g=w.ok?w.value??null:t.windows.getDescriptor(n);if(!i){if(!g){b(null),m(!1),v(w.detail??o("desktopWindow.loadDescriptorFailed"));return}t.windows.registerDescriptor(g),t.windows.markWindowOpen(g.windowId),b(g),m(!1)}}return p(),()=>{i=!0}},[t,n]),d.useEffect(()=>{if(!(e!=null&&e.workspaceId)){f([]);return}let i=!1;async function p(){try{const w=await U();if(i)return;f(N(w,u))}catch{if(i)return;f([])}}return p(),()=>{i=!0}},[e==null?void 0:e.workspaceId,u]),d.useEffect(()=>{if(!e){S(null);return}const i=new _({onConnectionChange:()=>{},onSnapshot:p=>{f(N(p,u))},onUnauthorized:()=>{F.clear(),a(`/login?returnTo=${encodeURIComponent(`/desktop-window/${e.windowId}`)}`,{replace:!0})}});return S(i),i.start(),()=>{i.close(),S(null)}},[e,a,u]),d.useEffect(()=>{if(!t.isDesktop||!t.bridge.supported||!e||e.mode!=="external")return;const i=ie(e,c);document.title=i,q(async()=>{const{getCurrentWindow:p}=await import("./window-BVUB8gMK.js").then(w=>w.w);return{getCurrentWindow:p}},__vite__mapDeps([0,1])).then(({getCurrentWindow:p})=>p().setTitle(i)).catch(()=>{})},[e,c,t.bridge.supported,t.isDesktop]);const D=d.useMemo(()=>r?{navigationGroups:c,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(c),[c,r]),G=d.useMemo(()=>r?{subscribeGitSnapshot:r.subscribeGit.bind(r),requestGitRefresh:r.requestGitRefresh.bind(r),addGitSnapshotListener:r.addGitSnapshotListener.bind(r)}:Z(),[r]),y=d.useMemo(()=>r?{subscribeTerminalManagerSnapshot:r.subscribeTerminalManager.bind(r),requestTerminalManagerRefresh:r.requestTerminalManagerRefresh.bind(r),addTerminalManagerSnapshotListener:r.addTerminalManagerSnapshotListener.bind(r)}:ee(),[r]),L=d.useMemo(()=>r?{navigationGroups:c,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,c),[e==null?void 0:e.workspaceId,c,r]);if(!t.isDesktop)return s.jsx(W,{to:"/",replace:!0});if(R)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:o("common.loading")})});if(M)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:M})});if(!e)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:o("desktopWindow.loadDescriptorFailed")})});if(e.kind==="code"){const i=ne(e);return i?s.jsx(W,{to:i,replace:!0}):s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:o("desktopWindow.invalidCodeTarget")})})}if(e.kind==="affairs"){const i=te(e);return s.jsx(W,{to:i,replace:!0})}let h=null;if(e.kind==="file-preview"){const i=((I=e.payload.filePath)==null?void 0:I.trim())??"";x(e,c),h=i?s.jsx($,{workspaceId:e.workspaceId,filePath:i,open:!0,chrome:"window",windowTitle:j(i)??i,onClose:()=>void t.bridge.setWindowState("close"),onSaved:()=>{}}):s.jsx("p",{className:"status-text",children:o("desktopWindow.invalidFilePreviewTarget")})}else e.kind==="files"?h=s.jsx(V,{sessionId:e.sessionId,workspaceId:e.workspaceId,externalWindowMode:!0,workbenchShellOverrides:D}):e.kind==="git"?h=s.jsx(z,{workspaceId:e.workspaceId,externalWindowMode:!0,workbenchShellOverrides:G}):e.kind==="processes"?h=s.jsx(B,{currentWorkspaceId:e.workspaceId,navigationGroups:c,externalWindowMode:!0,workbenchShellOverrides:y}):e.kind==="terminals"&&(h=s.jsx(A,{externalWindowMode:!0,externalWindowWorkspaceId:e.workspaceId,workbenchShellOverrides:L}));if(!h)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:o("desktopWindow.unsupportedKind",{kind:e.kind})})});const k=T(e),P=x(e,c),E=e.mode==="external"&&e.kind==="processes";return s.jsxs("main",{className:"desktop-window-page",children:[E?s.jsx("header",{className:"desktop-window-drag-header","data-window-kind":e.kind,"data-window-drag-handle":"desktop-window-drag-header","data-tauri-drag-region":l,"aria-label":k,children:s.jsxs("div",{className:"desktop-window-drag-header-copy","data-tauri-drag-region":l,children:[s.jsx("span",{className:"desktop-window-drag-header-tag","data-tauri-drag-region":l,children:k}),s.jsx("strong",{"data-tauri-drag-region":l,children:P??k})]})}):null,s.jsx("div",{className:"desktop-window-body","data-window-kind":e.kind,"aria-label":k,children:h})]})}export{be as DesktopWindowPage};
|