@jingyi0605/codingns 0.9.8 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/bin/codingns.mjs +14 -0
  2. package/dist/public/assets/{AdaptiveButlerPage-D-gXre7Y.js → AdaptiveButlerPage-BYETYaIe.js} +2 -2
  3. package/dist/public/assets/App-CHsm-VrM.js +30 -0
  4. package/dist/public/assets/App-Z0Zd7gXR.css +1 -0
  5. package/dist/public/assets/{BootstrapPage-B-yMdfpQ.js → BootstrapPage-Bp0KfySv.js} +1 -1
  6. package/dist/public/assets/ConversationPage-BCrNml1k.js +9 -0
  7. package/dist/public/assets/{DesktopDetachPreviewPage-D1DMaGcy.js → DesktopDetachPreviewPage-DlDSb_tf.js} +1 -1
  8. package/dist/public/assets/{DesktopModal-BnfGW2gk.js → DesktopModal-Csj5AdAN.js} +1 -1
  9. package/dist/public/assets/DesktopWindowPage-CacXiWjV.js +2 -0
  10. package/dist/public/assets/FileContextPanel-DzMUQvE5.js +1 -0
  11. package/dist/public/assets/GitSidebar-C8IC18GH.js +6 -0
  12. package/dist/public/assets/MobileCreateSessionSheet-BtqR_hKc.js +1 -0
  13. package/dist/public/assets/{MobileSheet-rkn_CUOY.js → MobileSheet-Co-qPMBD.js} +1 -1
  14. package/dist/public/assets/PluginAccessOverview-D-KXkcyj.js +1 -0
  15. package/dist/public/assets/{PluginContainerPage-D-ly3i3H.js → PluginContainerPage-BKwCIs4r.js} +1 -1
  16. package/dist/public/assets/{PluginDetailPage-CWAHYyyG.js → PluginDetailPage-Djv_swcO.js} +1 -1
  17. package/dist/public/assets/{PluginsListPage-Cte3vBgR.js → PluginsListPage-DAECNoN6.js} +1 -1
  18. package/dist/public/assets/PureConversationPage-DP1X7Hix.js +1 -0
  19. package/dist/public/assets/{RelayConnectEntryPage-sRJlstx9.js → RelayConnectEntryPage-xL_IPH8a.js} +1 -1
  20. package/dist/public/assets/{ServerSettingsModal-BBft9KEC.js → ServerSettingsModal-CyhMgk10.js} +1 -1
  21. package/dist/public/assets/SessionIndexPage-CVEz50tc.js +1 -0
  22. package/dist/public/assets/SettingsPage-CQNCrgaj.js +2 -0
  23. package/dist/public/assets/TerminalManagerPanel-wVnoRA8u.js +1 -0
  24. package/dist/public/assets/ToolFilesPage-BospXumK.js +1 -0
  25. package/dist/public/assets/ToolGitPage-B2zOeCAD.js +1 -0
  26. package/dist/public/assets/ToolProcessesPage-BDShao4b.js +1 -0
  27. package/dist/public/assets/{ToolsHomePage-D1n4FU1s.js → ToolsHomePage-s4zH7D9M.js} +1 -1
  28. package/dist/public/assets/{WorkbenchLandingPage-BaU_dXls.js → WorkbenchLandingPage-D51QCU_u.js} +1 -1
  29. package/dist/public/assets/{WorkbenchLayout-BksVkkFF.css → WorkbenchLayout-BZdfVest.css} +32 -1
  30. package/dist/public/assets/WorkbenchLayout-Bo2BbMY6.js +1081 -0
  31. package/dist/public/assets/{WorkbenchModal-DWsNm2B2.js → WorkbenchModal-YsyEdJ_m.js} +1 -1
  32. package/dist/public/assets/WorkbenchShellRoute-D3l4aWJS.js +1 -0
  33. package/dist/public/assets/WorkbenchShellRoute-D5fnyF8z.css +1 -0
  34. package/dist/public/assets/WorkspaceDebugDetailPage-CMjNLqFq.js +1 -0
  35. package/dist/public/assets/WorkspaceDetailPage-CKxTbPKh.js +1 -0
  36. package/dist/public/assets/WorkspaceHomePage-CEy4ShCu.js +1 -0
  37. package/dist/public/assets/{client-runtime-manager-D9VbgJZ_.js → client-runtime-manager-BFXU9DmS.js} +1 -1
  38. package/dist/public/assets/host-alias-Zb2xyVrf.js +1 -0
  39. package/dist/public/assets/index-BilHJjYU.js +50 -0
  40. package/dist/public/assets/index-OR7OITpQ.css +1 -0
  41. package/dist/public/assets/{login-direct-candidate-resolver-17wEvjhh.js → login-direct-candidate-resolver-DL8DS-Si.js} +1 -1
  42. package/dist/public/assets/peer-host-config-sync-d2ZcPC5P.js +1 -0
  43. package/dist/public/assets/{plugin-permission-copy-apDn8EWG.js → plugin-permission-copy-DrLk22m5.js} +1 -1
  44. package/dist/public/assets/{plugins-api-CnZYRKoS.js → plugins-api-COF4oh24.js} +1 -1
  45. package/dist/public/assets/{preferences-service-PZlLLAWH.js → preferences-service-CEWNV1w9.js} +1 -1
  46. package/dist/public/assets/{relay-entry-DhHwflXl.js → relay-entry-Cmc8vTlE.js} +1 -1
  47. package/dist/public/assets/useRegisteredDebugTemplates-FdmHG2S4.js +1 -0
  48. package/dist/public/assets/workbench-navigation-ED0157V-.js +1 -0
  49. package/dist/public/index.html +2 -2
  50. package/dist/server/config/env.js +5 -3
  51. package/dist/server/config/env.js.map +1 -1
  52. package/dist/server/modules/assistant-capability/assistant-capability-controller.d.ts +3 -0
  53. package/dist/server/modules/assistant-capability/assistant-capability-controller.js +9 -0
  54. package/dist/server/modules/assistant-capability/assistant-capability-controller.js.map +1 -1
  55. package/dist/server/modules/assistant-capability/assistant-capability-service.d.ts +3 -0
  56. package/dist/server/modules/assistant-capability/assistant-capability-service.js +4 -1
  57. package/dist/server/modules/assistant-capability/assistant-capability-service.js.map +1 -1
  58. package/dist/server/modules/butler/butler-session-service.d.ts +1 -0
  59. package/dist/server/modules/butler/butler-session-service.js +2 -1
  60. package/dist/server/modules/butler/butler-session-service.js.map +1 -1
  61. package/dist/server/modules/client/npm-global-package-service.js +3 -0
  62. package/dist/server/modules/client/npm-global-package-service.js.map +1 -1
  63. package/dist/server/modules/client/service-update-types.d.ts +3 -0
  64. package/dist/server/modules/peer-host/peer-host-controller.d.ts +5 -0
  65. package/dist/server/modules/peer-host/peer-host-controller.js +3 -0
  66. package/dist/server/modules/peer-host/peer-host-controller.js.map +1 -1
  67. package/dist/server/modules/peer-host/peer-host-service.d.ts +1 -0
  68. package/dist/server/modules/peer-host/peer-host-service.js +44 -0
  69. package/dist/server/modules/peer-host/peer-host-service.js.map +1 -1
  70. package/dist/server/modules/sessions/session-controller.d.ts +10 -0
  71. package/dist/server/modules/sessions/session-controller.js +11 -0
  72. package/dist/server/modules/sessions/session-controller.js.map +1 -1
  73. package/dist/server/modules/sessions/session-history-service.d.ts +43 -1
  74. package/dist/server/modules/sessions/session-history-service.js +362 -27
  75. package/dist/server/modules/sessions/session-history-service.js.map +1 -1
  76. package/dist/server/modules/tasks/observability-controller.d.ts +2 -0
  77. package/dist/server/modules/tasks/observability-controller.js +16 -1
  78. package/dist/server/modules/tasks/observability-controller.js.map +1 -1
  79. package/dist/server/modules/tasks/observability-service.d.ts +12 -2
  80. package/dist/server/modules/tasks/observability-service.js +16 -3
  81. package/dist/server/modules/tasks/observability-service.js.map +1 -1
  82. package/dist/server/modules/terminal/runtime/terminal-log-spooler.d.ts +5 -0
  83. package/dist/server/modules/terminal/runtime/terminal-log-spooler.js +54 -7
  84. package/dist/server/modules/terminal/runtime/terminal-log-spooler.js.map +1 -1
  85. package/dist/server/modules/workbench/affairs-assistant-session-snapshot-service.js +2 -1
  86. package/dist/server/modules/workbench/affairs-assistant-session-snapshot-service.js.map +1 -1
  87. package/dist/server/modules/workbench/workbench-service.d.ts +2 -0
  88. package/dist/server/modules/workbench/workbench-service.js +173 -20
  89. package/dist/server/modules/workbench/workbench-service.js.map +1 -1
  90. package/dist/server/modules/workspace/affairs-library-controller.d.ts +1 -0
  91. package/dist/server/modules/workspace/affairs-library-controller.js +3 -0
  92. package/dist/server/modules/workspace/affairs-library-controller.js.map +1 -1
  93. package/dist/server/modules/workspace/affairs-library-service.d.ts +4 -0
  94. package/dist/server/modules/workspace/affairs-library-service.js +23 -4
  95. package/dist/server/modules/workspace/affairs-library-service.js.map +1 -1
  96. package/dist/server/modules/workspace/affairs-lightweight-session-controller.d.ts +4 -0
  97. package/dist/server/modules/workspace/affairs-lightweight-session-controller.js +26 -0
  98. package/dist/server/modules/workspace/affairs-lightweight-session-controller.js.map +1 -1
  99. package/dist/server/modules/workspace/affairs-lightweight-session-service.d.ts +15 -1
  100. package/dist/server/modules/workspace/affairs-lightweight-session-service.js +201 -22
  101. package/dist/server/modules/workspace/affairs-lightweight-session-service.js.map +1 -1
  102. package/dist/server/modules/workspace/workspace-controller.d.ts +7 -1
  103. package/dist/server/modules/workspace/workspace-controller.js +11 -1
  104. package/dist/server/modules/workspace/workspace-controller.js.map +1 -1
  105. package/dist/server/modules/workspace/workspace-service.d.ts +9 -2
  106. package/dist/server/modules/workspace/workspace-service.js +45 -10
  107. package/dist/server/modules/workspace/workspace-service.js.map +1 -1
  108. package/dist/server/routes/affairs.js +4 -0
  109. package/dist/server/routes/affairs.js.map +1 -1
  110. package/dist/server/routes/peer-hosts.js +1 -0
  111. package/dist/server/routes/peer-hosts.js.map +1 -1
  112. package/dist/server/routes/sessions.js +2 -0
  113. package/dist/server/routes/sessions.js.map +1 -1
  114. package/dist/server/server/create-server.js +2 -2
  115. package/dist/server/server/create-server.js.map +1 -1
  116. package/dist/server/storage/repositories/session-discovery-diagnostics-repository.d.ts +10 -0
  117. package/dist/server/storage/repositories/session-discovery-diagnostics-repository.js +68 -0
  118. package/dist/server/storage/repositories/session-discovery-diagnostics-repository.js.map +1 -0
  119. package/dist/server/storage/repositories/session-source-index-repository.d.ts +14 -0
  120. package/dist/server/storage/repositories/session-source-index-repository.js +164 -0
  121. package/dist/server/storage/repositories/session-source-index-repository.js.map +1 -0
  122. package/dist/server/storage/repositories/workspace-navigation-state-repository.js +16 -7
  123. package/dist/server/storage/repositories/workspace-navigation-state-repository.js.map +1 -1
  124. package/dist/server/storage/sqlite/client.js +26 -0
  125. package/dist/server/storage/sqlite/client.js.map +1 -1
  126. package/dist/server/storage/sqlite/schema.sql +57 -0
  127. package/dist/server/types/domain.d.ts +45 -0
  128. package/node_modules/@codingns/session-sync-core/dist/providers/claude-session-store.js +19 -2
  129. package/node_modules/@codingns/session-sync-core/dist/providers/claude-session-store.js.map +1 -1
  130. package/node_modules/@codingns/session-sync-core/dist/providers/codex.d.ts +1 -0
  131. package/node_modules/@codingns/session-sync-core/dist/providers/codex.js +45 -1
  132. package/node_modules/@codingns/session-sync-core/dist/providers/codex.js.map +1 -1
  133. package/node_modules/@codingns/session-sync-core/dist/providers/opencode.js +11 -4
  134. package/node_modules/@codingns/session-sync-core/dist/providers/opencode.js.map +1 -1
  135. package/package.json +3 -2
  136. package/scripts/node22-runtime.mjs +176 -0
  137. package/scripts/postinstall.mjs +6 -0
  138. package/dist/public/assets/App-7zrCMhE-.css +0 -1
  139. package/dist/public/assets/App-Dl-mcdqy.js +0 -30
  140. package/dist/public/assets/ConversationPage-DRQ5Sg_d.js +0 -9
  141. package/dist/public/assets/DesktopWindowPage-2SWAi0xz.js +0 -2
  142. package/dist/public/assets/FileContextPanel-fbPuE9dO.js +0 -1
  143. package/dist/public/assets/GitSidebar-BkmesJJR.js +0 -6
  144. package/dist/public/assets/MobileCreateSessionSheet-CEJcDBZJ.js +0 -1
  145. package/dist/public/assets/MobileTopHeaderFrame-CU0wsYSS.js +0 -1
  146. package/dist/public/assets/MobileWorkspaceSwitcherHeader-idl8o1OB.js +0 -1
  147. package/dist/public/assets/PluginAccessOverview-BBgM6tb0.js +0 -1
  148. package/dist/public/assets/SessionIndexPage-CN7cEdl9.js +0 -1
  149. package/dist/public/assets/SettingsPage-BGT-YqG2.js +0 -2
  150. package/dist/public/assets/TerminalManagerPanel-6-ZJ8vGn.js +0 -1
  151. package/dist/public/assets/TerminalPage-6GBZ9nXN.css +0 -32
  152. package/dist/public/assets/TerminalPage-CUXXQYU2.js +0 -55
  153. package/dist/public/assets/TerminalRuntimeFallbackModal-zc3qqMKJ.js +0 -1
  154. package/dist/public/assets/ToolFilesPage-QzsZyr0F.js +0 -1
  155. package/dist/public/assets/ToolGitPage-CXg4ncuT.js +0 -1
  156. package/dist/public/assets/ToolProcessesPage-BPsOsg4w.js +0 -1
  157. package/dist/public/assets/WorkbenchLayout-DViAJhHz.js +0 -1027
  158. package/dist/public/assets/WorkbenchShellRoute-BGfRqBUa.js +0 -1
  159. package/dist/public/assets/WorkbenchShellRoute-f2jWjHWu.css +0 -1
  160. package/dist/public/assets/WorkspaceDebugDetailPage-BX0zVSsI.js +0 -1
  161. package/dist/public/assets/WorkspaceDetailPage-Dx6JX4jx.js +0 -1
  162. package/dist/public/assets/WorkspaceHomePage-DQVJ042Z.js +0 -1
  163. package/dist/public/assets/host-alias-0TfFnYxR.js +0 -1
  164. package/dist/public/assets/index-DREvg1Yu.css +0 -1
  165. package/dist/public/assets/index-FOhyOpGY.js +0 -50
  166. package/dist/public/assets/peer-host-config-sync-vYkmqzNz.js +0 -1
  167. package/dist/public/assets/terminal-runtime-meta-2zvacxvM.js +0 -1
  168. package/dist/public/assets/useRegisteredDebugTemplates-CJ-o4tFl.js +0 -1
  169. package/dist/public/assets/workbench-navigation-aqJ1ay4M.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 Yi=Object.defineProperty;var Ki=(e,t,s)=>t in e?Yi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var xe=(e,t,s)=>Ki(e,typeof t!="symbol"?t+"":t,s);import{t as c,b as l,u as Qi,G as Zi,j as i,E as Pn,o as Ss,B as Ji,F as eo,_ as Rn}from"./index-BilHJjYU.js";import{f as gt,u as vt,e as _t,g as St,h as nn,c as to}from"./App-CHsm-VrM.js";import{D as ms}from"./DesktopModal-Csj5AdAN.js";import{w as gs,M as kt,s as ts,c as $e,x as $t,n as vs,y as ss,z as so,p as bs,A as no,B as kn,l as ro,C as io,r as oo,D as ao,E as Mr,P as lo,F as Ws,b as wt,q as Sr,G as co,t as uo,u as ho,H as fo,I as yr,J as po,K as Tn,m as mo}from"./workbench-navigation-ED0157V-.js";import{P as go,Q as vo,b as yt,R as Cn,U as bo,V as ns,X as Qt,Y as En,Z as wo,_ as Io,$ as ys,a0 as Dt,a1 as An,a2 as Mo,a3 as xr,a4 as So,d as Ft,a5 as yo,j as _n,a6 as Pr,a7 as rn,a8 as It,a9 as Rr,aa as kr,ab as xo,ac as Po,ad as Ro,S as ko,ae as To,af as Co,ag as Eo,ah as Ao,ai as _o,L as Tr,i as Cr,aj as jn,ak as Er,al as jo,am as No,an as Oo,ao as Lo,ap as Do,aq as Ho,ar as Se,as as rs,at as qo,au as Us,av as Nn,aw as Bo,ax as Fo,ay as Wo,az as Uo,aA as Ar,aB as Qe,aC as xs,aD as _r,aE as jr,aF as $o,aG as Nr,aH as Vo,aI as Or,aJ as on,aK as Et,aL as Vt,u as Go,I as an,aM as Xo,aN as zo,r as Yo,O as ln,aO as cn,aP as $s,aQ as Ko,aR as qt,aS as Lr,aT as un,aU as dn,aV as Dr,aW as Qo,aX as Zo,aY as Jo,aZ as ea,w as Gt,a_ as Hr,a$ as qr,b0 as Br,b1 as Fr,J as Wr,k as hn,f as Ur,c as ws,y as $r,b2 as Vr,b3 as Gr,M as Xr,b4 as ta,b5 as sa,x as na,b6 as ra,N as ia}from"./WorkbenchLayout-Bo2BbMY6.js";import{M as oa}from"./MobileSheet-Co-qPMBD.js";import{FileContextPanel as zr}from"./FileContextPanel-DzMUQvE5.js";import{GitSidebar as Yr}from"./GitSidebar-C8IC18GH.js";import{W as aa}from"./WorkbenchModal-YsyEdJ_m.js";import{TerminalManagerPanel as Kr}from"./TerminalManagerPanel-wVnoRA8u.js";import{w as Rt,r as Ps,a as On,b as Ln}from"./styles-DwSuZo1w.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./host-alias-Zb2xyVrf.js";import"./relay-entry-Cmc8vTlE.js";function fn({connectionState:e,onReconnect:t}){const{showToast:s,dismissToast:n}=gt(),r=go(),a=r?c(vo(r.kind)):null;return l.useEffect(()=>{if(e==="connected"||e==="closed"){n("conversation-connection-state");return}if(e==="reconnect_failed"){s({id:"conversation-connection-state",title:c("conversation.connectionReconnectFailed"),description:a?c("conversation.reconnectFailedExplainWithRoute",{route:a}):c("conversation.reconnectFailedExplain"),tone:"warning",durationMs:null,action:{label:c("conversation.reconnectButton"),onClick:t}});return}s({id:"conversation-connection-state",title:c("conversation.connectionReconnecting"),description:a?c("conversation.reconnectExplainWithRoute",{route:a}):c("conversation.reconnectExplain"),tone:"info",durationMs:3200})},[a,e,n,t,s]),null}const la=48;function ca(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 ua(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(!ca(e))throw new Error(c("conversation.copyContentFailed"))}}function Dn(e,t,s){return Math.min(Math.max(e,t),s)}function Rs(e,t=ns){return e&&t.includes(e)?e:t[0]??"codex"}function da(e){return ns.includes(e)}function ha(e,t){const s=e.flatMap(n=>da(n)?[n]:[]);return s.length>0?s:t?[t]:[]}function Vs(e){return e?e.nodeType===Node.ELEMENT_NODE?e:e.parentElement:null}function Hn(e){var s,n;const t=Vs(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 fa(e,t){return[t.trim()||c("conversation.selectionActionDefaultPrompt"),"",c("conversation.selectionActionQuotedLabel"),"```text",e.trim(),"```"].join(`
3
+ `)}function ks(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=Vs(s.startContainer),r=Vs(s.endContainer);if(!n||!r||!e.contains(n)||!e.contains(r))return null;const a=t.toString().trim();if(!a)return null;const o=s.getBoundingClientRect();if(!o.width&&!o.height)return null;const u=Hn(s.startContainer),d=Hn(s.endContainer);return{text:a,sourceMessageId:u&&u===d?u:null,rect:{left:o.left,top:o.top,right:o.right,bottom:o.bottom,width:o.width,height:o.height}}}function pa({containerRef:e,session:t,currentCapabilities:s}){const n=vt(),r=_t(),{showToast:a}=gt(),{shellMode:o,requestNavigationRefresh:u,selectWorkspace:d,upsertNavigationSession:h,currentTargetHostId:f,currentWorkspaceRef:I}=yt(),T=Qi(p=>p.profile.providers),w=l.useMemo(()=>Cn(t==null?void 0:t.providerConfigMode,t==null?void 0:t.providerPresetId),[t==null?void 0:t.providerConfigMode,t==null?void 0:t.providerPresetId]),[g,m]=l.useState(null),[R,H]=l.useState(null),[N,C]=l.useState(!1),{visibleProviders:M}=bo(ns,N,f),[y,b]=l.useState(""),[F,k]=l.useState(!1),[S,v]=l.useState(Rs(t==null?void 0:t.provider)),[x,K]=l.useState(Qt),[$,J]=l.useState(w.providerConfigMode),[re,G]=l.useState(w.providerPresetId),[j,A]=l.useState({}),[O,Q]=l.useState(!1),[oe,V]=l.useState(null),[Y,ae]=l.useState({}),[le,me]=l.useState(!1),[L,X]=l.useState(!1),[B,he]=l.useState(!1),[pe,Ee]=l.useState(0),[Le,De]=l.useState(null),[Pe,W]=l.useState(()=>({width:typeof window>"u"?0:window.innerWidth,height:typeof window>"u"?0:window.innerHeight})),ee=l.useRef(!1),U=l.useRef(!1),_=l.useRef(!1),ue=l.useRef(null),ce=l.useRef(null),je=o==="mobile"||r.isMobile,Ne=l.useMemo(()=>p=>{var z,se;return(Zi(p)?(se=(z=T[p])==null?void 0:z.defaultModel)==null?void 0:se.trim():null)||Qt},[T]),te=l.useMemo(()=>Cn($,re),[$,re]),ke=l.useMemo(()=>ha(M,S),[S,M]),ie=l.useMemo(()=>En(S),[S]),Ae=l.useMemo(()=>ie?j[ie]??null:null,[j,ie]),Xe=l.useMemo(()=>wo(Ae),[Ae]),E=l.useMemo(()=>Io(Ae),[Ae]),D=te.providerConfigMode==="cc-switch-preset"?te.providerPresetId??ys:ys,be=l.useMemo(()=>E.find(p=>p.value===D)??E[0]??null,[E,D]),_e=l.useMemo(()=>S===(t==null?void 0:t.provider)&&te.providerConfigMode===w.providerConfigMode&&te.providerPresetId===w.providerPresetId&&s?s:oe??Dt(S),[s,oe,S,te.providerConfigMode,te.providerPresetId,t==null?void 0:t.provider,w.providerConfigMode,w.providerPresetId]),ye=l.useMemo(()=>{var z;const p=Dt(S).modelOptions??[];return(z=_e.modelOptions)!=null&&z.length?_e.modelOptions:p},[_e.modelOptions,S]),ge=l.useMemo(()=>ye.map(p=>({value:p.id,label:An(p)?c("conversation.modelUseCliDefault"):p.name})),[ye]),Ie=l.useMemo(()=>ye.find(p=>p.id===x)??ye[0]??null,[ye,x]),fe=l.useMemo(()=>{const p=Ie?An(Ie)?c("conversation.modelUseCliDefault"):Ie.name:c("conversation.modelUseCliDefault");return Xe?`${(be==null?void 0:be.label)??c("conversation.deploymentDefaultPreset")} · ${p}`:p},[Ie,be,Xe]),Ue=l.useCallback(p=>{if(v(p),K(Ne(p)),t&&p===t.provider&&En(p)){J(w.providerConfigMode),G(w.providerPresetId);return}J("global-default"),G(null)},[Ne,t,w.providerConfigMode,w.providerPresetId]),de=l.useMemo(()=>{const p=Y[S]??(S===(t==null?void 0:t.provider)&&te.providerConfigMode===w.providerConfigMode&&te.providerPresetId===w.providerPresetId?s:oe);return!p||p.canStartSession!==!1?null:p.limitations[0]??c("conversation.capabilityDenied")},[s,oe,Y,S,te.providerConfigMode,te.providerPresetId,t==null?void 0:t.provider,w.providerConfigMode,w.providerPresetId]),ze=l.useMemo(()=>{var Ce;if(!g||typeof window>"u")return null;const p=(Ce=e.current)==null?void 0:Ce.getBoundingClientRect(),z=p?Math.max(80,p.left+80):96,se=p?Math.min(Pe.width-80,p.right-80):Pe.width-96,Me=p?Math.max(12,p.top+12):12,qe=p?Math.max(Me,p.bottom-48):Math.max(12,Pe.height-48),We=g.rect.left+g.rect.width/2;return{left:Dn(We,z,Math.max(z,se)),top:Dn(g.rect.top-48,Me,qe)}},[e,g,Pe.height,Pe.width]);l.useEffect(()=>{if(typeof window>"u")return;const p=()=>{W({width:window.innerWidth,height:window.innerHeight})};return p(),window.addEventListener("resize",p),()=>{window.removeEventListener("resize",p)}},[]),l.useEffect(()=>{if(!t){ce.current!==null&&typeof window<"u"&&(window.clearTimeout(ce.current),ce.current=null),ue.current=null,_.current=!1,m(null),H(null),C(!1);return}const p=Rs(t.provider);Ue(p)},[Ue,t]),l.useEffect(()=>{if(!N){Q(!1);return}if(!ie){Q(!1);return}let p=!1;return Q(!0),Mo({targetHostId:f}).then(z=>{p||A(Object.fromEntries(z.items.map(se=>[se.app,se])))}).catch(()=>{p||A({})}).finally(()=>{p||Q(!1)}),()=>{p=!0}},[N,f,ie]),l.useEffect(()=>{!ie||te.providerConfigMode!=="cc-switch-preset"||!te.providerPresetId||O||!Ae||Ae.options.some(p=>p.id===te.providerPresetId)||(J("global-default"),G(null))},[O,Ae,ie,te.providerConfigMode,te.providerPresetId]),l.useEffect(()=>{if(!t||!e.current||typeof window>"u"){ce.current!==null&&(window.clearTimeout(ce.current),ce.current=null),ue.current=null,_.current=!1,m(null),H(null);return}const p=e.current,z=Re=>{ee.current||(ue.current=Re,m(Re),Re||C(!1))},se=()=>{ce.current!==null&&(window.clearTimeout(ce.current),ce.current=null)},Me=(Re,tt)=>{if(ue.current=Re,se(),tt!=null&&tt.immediate){z(Re);return}ce.current=window.setTimeout(()=>{ce.current=null,z(ue.current)},la)},qe=()=>{const Re=ks(p);if(_.current){ue.current=Re;return}Me(Re)},We=()=>{const Re=ks(p);if(_.current){ue.current=Re;return}Me(Re,{immediate:!0})},Ce=Re=>{!(Re.target instanceof Node)||!p.contains(Re.target)||(_.current=!0,se())},Be=()=>{_.current&&(_.current=!1,Me(ks(p)))};return document.addEventListener("pointerdown",Ce),document.addEventListener("selectionchange",qe),window.addEventListener("pointerup",Be),window.addEventListener("pointercancel",Be),window.addEventListener("mouseup",Be),window.addEventListener("touchend",Be),window.addEventListener("resize",We),window.addEventListener("scroll",We,!0),()=>{se(),document.removeEventListener("pointerdown",Ce),document.removeEventListener("selectionchange",qe),window.removeEventListener("pointerup",Be),window.removeEventListener("pointercancel",Be),window.removeEventListener("mouseup",Be),window.removeEventListener("touchend",Be),window.removeEventListener("resize",We),window.removeEventListener("scroll",We,!0)}},[e,t]),l.useEffect(()=>{(!N||!(R!=null&&R.sourceMessageId))&&k(!1)},[N,R==null?void 0:R.sourceMessageId]),l.useEffect(()=>{if(!N||!t)return;let p=!1;return S===t.provider&&te.providerConfigMode===w.providerConfigMode&&te.providerPresetId===w.providerPresetId&&s?(me(!1),V(s),()=>{p=!0}):(me(!0),V(Dt(S)),xr(S,t.workspaceId,ie?{providerConfigMode:te.providerConfigMode,providerPresetId:te.providerPresetId}:void 0,{targetHostId:f}).then(z=>{p||V(z)}).catch(()=>{p||V(Dt(S))}).finally(()=>{p||me(!1)}),()=>{p=!0})},[N,f,s,ie,S,te.providerConfigMode,te.providerPresetId,t,w.providerConfigMode,w.providerPresetId]),l.useEffect(()=>{if(!N||!t){ae({});return}let p=!1;return So(ke,t.workspaceId,{targetHostId:f}).then(z=>{p||ae(z)}),()=>{p=!0}},[N,f,t,ke]),l.useEffect(()=>{if(!N||!t)return;const p=ke.filter(se=>{const Me=Y[se];return!Me||Me.canStartSession!==!1});if(p.length===0||p.includes(S))return;const z=p[0];Ue(z)},[N,Ue,Y,S,t,ke]),l.useEffect(()=>{var z;const p=Ne(S);if(!ye.some(se=>se.id===x)){if(ye.some(se=>se.id===p)){K(p);return}K(((z=ye[0])==null?void 0:z.id)??Qt)}},[ye,Ne,x,S]),l.useEffect(()=>{if(!N){ee.current=!1;return}ee.current=!0},[N]),l.useEffect(()=>{if(typeof window>"u")return;const p=z=>{z.key==="Escape"&&(C(!1),H(null),m(null),ee.current=!1)};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[]);async function He(){var z,se;if(!g)return;const p=g.text;m(null),typeof window<"u"&&((se=(z=window.getSelection())==null?void 0:z.removeAllRanges)==null||se.call(z));try{await ua(p,r),a({title:c("conversation.copyContentSuccess"),tone:"success"})}catch(Me){a({title:Me instanceof Error?Me.message:c("conversation.copyContentFailed"),tone:"error"})}}function dt(){g&&(De({title:"",content:g.text}),Ee(p=>p+1),he(!0),C(!1),H(null),m(null),ee.current=!1)}function Ze(){var se,Me;if(!g||!t)return;const p=g,z=Rs(t.provider,ke.length>0?ke:ns);Ue(z),b(""),k(!1),H(p),m(null),C(!0),typeof window<"u"&&((Me=(se=window.getSelection())==null?void 0:se.removeAllRanges)==null||Me.call(se))}function ht(p){p.preventDefault(),ee.current=!0}function Te(){U.current=!0,Ze()}function ft(){if(U.current){U.current=!1;return}Ze()}async function pt(){var p,z,se,Me;if(!(!R||!t)){if(de){a({title:de,tone:"error"});return}X(!0);try{const qe=fa(R.text,y),We=(Ie==null?void 0:Ie.id)===Qt?null:(Ie==null?void 0:Ie.id)??null;let Ce=null;if(F&&R.sourceMessageId)Ce=await Pr(t.sessionId,{sourceType:"message",sourceMessageId:R.sourceMessageId,strategy:"auto",targetProvider:S,providerConfigMode:te.providerConfigMode,providerPresetId:te.providerPresetId,sessionKind:"annotation",annotationSourceMessageId:R.sourceMessageId,annotationSourceText:R.text},{targetHostId:f}),h(Ce),await rn(Ce.sessionId,{content:qe,clientRequestId:((z=(p=globalThis.crypto)==null?void 0:p.randomUUID)==null?void 0:z.call(p))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:We,permissionMode:It(),providerConfigMode:te.providerConfigMode,providerPresetId:te.providerPresetId},{targetHostId:f});else{const Re=await Rr({workspaceId:t.workspaceId,provider:S,content:qe,clientRequestId:((Me=(se=globalThis.crypto)==null?void 0:se.randomUUID)==null?void 0:Me.call(se))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:We,permissionMode:It(),providerConfigMode:te.providerConfigMode,providerPresetId:te.providerPresetId,parentSessionId:t.sessionId,sessionKind:"annotation",annotationSourceMessageId:R.sourceMessageId??null,annotationSourceText:R.text},{targetHostId:f});Ce=Re.session??await kr(Re.sessionId,{targetHostId:f})}h(Ce),u();const Be=f&&I?{hostId:f,workspaceId:I.workspaceId}:I;d(Ce.workspaceId,Be),n($e(Ce.workspaceId,Ce.sessionId,Be)),C(!1),H(null),m(null),ee.current=!1}catch(qe){a({title:qe instanceof Error?qe.message:c("conversation.selectionActionFailed"),tone:"error"})}finally{X(!1)}}}function at(p=!1){C(!1),H(null),ee.current=!1,p&&m(null)}const bt=!!(!N&&g&&ze),Oe=!!(N&&R),lt=i.jsxs(gs,{children:[i.jsx("button",{type:"button",className:"secondary-button",onClick:()=>at(!1),children:c("common.cancel")}),i.jsx("button",{type:"button",className:"primary-button",disabled:L||!!de||ke.length===0,onClick:()=>void pt(),children:L?c("conversation.sendingState"):c("conversation.selectionActionSubmit")})]}),et=R?i.jsxs(i.Fragment,{children:[i.jsx(kt,{className:"conversation-selection-preview-section",heading:c("conversation.selectionActionPreviewLabel"),children:i.jsx("div",{className:"conversation-selection-action-dialog-quote",children:R.text})}),i.jsxs(kt,{className:"conversation-selection-request-section",children:[i.jsx(ts,{className:"conversation-selection-field conversation-selection-prompt-field",label:c("conversation.selectionActionPromptLabel"),children:i.jsx("textarea",{value:y,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:F,disabled:!R.sourceMessageId,onChange:p=>k(p.target.checked)}),i.jsx("span",{children:c("conversation.selectionActionIncludeContext")})]}),R.sourceMessageId?null:i.jsx("p",{className:"conversation-selection-hint",children:c("conversation.selectionActionContextUnavailable")}),de?i.jsx("p",{className:"conversation-selection-hint",children:de}):null]})]}),i.jsx(kt,{className:"conversation-selection-target-section",heading:c("conversation.selectionActionTargetLabel"),children:i.jsxs("div",{className:"conversation-selection-grid",children:[i.jsx(ts,{className:"conversation-selection-field",label:c("conversation.forkTargetProviderLabel"),children:i.jsx("select",{value:S,onChange:p=>{Ue(p.target.value)},children:ke.map(p=>{var z;return i.jsx("option",{value:p,disabled:((z=Y[p])==null?void 0:z.canStartSession)===!1,children:Ft(p,"full")},p)})})}),i.jsx(ts,{className:"conversation-selection-field",label:c("conversation.forkTargetModelLabel"),children:ie?i.jsx("div",{className:"conversation-selection-deployment-select",children:i.jsx(yo,{ariaLabel:c("conversation.forkTargetModelLabel"),triggerLabel:fe,presetOptions:E,selectedPresetValue:D,selectedPresetSummary:(be==null?void 0:be.summary)??null,onSelectPreset:p=>{if(p===ys){J("global-default"),G(null);return}J("cc-switch-preset"),G(p)},modelOptions:ge,selectedModelValue:x,onSelectModel:K,loadingPresets:O,loadingModels:le,modelColumnDisabled:le||!!de,showPresetColumn:Xe,modelEmptyText:c("conversation.deploymentModelEmpty")})}):i.jsx("select",{value:x,disabled:le||!!de,onChange:p=>K(p.target.value),children:ye.map(p=>i.jsx("option",{value:p.id,children:p.name},p.id))})})]})})]}):null;return!t||!bt&&!Oe||typeof document>"u"?i.jsx(_n,{open:B,preferredWorkspaceId:(t==null?void 0:t.workspaceId)??null,preferredSessionId:(t==null?void 0:t.sessionId)??null,creationRequestId:pe,initialDraft:Le,onClose:()=>he(!1)}):i.jsxs(i.Fragment,{children:[St.createPortal(bt?i.jsxs("div",{className:"conversation-selection-toolbar",style:ze??void 0,onMouseDown:p=>p.preventDefault(),children:[i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:()=>void He(),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:ht,onMouseDown:ht,onPointerUp:Te,onClick:ft,children:c("conversation.selectionActionButton")})]}):null,document.body),je?i.jsx(oa,{open:Oe,title:c("conversation.selectionActionButton"),height:"auto",kind:"form",showHandle:!0,showCancelButton:!1,cardClassName:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:lt,onClose:()=>at(!1),children:et}):i.jsx(ms,{open:Oe,title:c("conversation.selectionActionButton"),size:"compact",layout:"form",className:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:lt,onClose:()=>at(!1),children:et}),i.jsx(_n,{open:B,preferredWorkspaceId:t.workspaceId,preferredSessionId:t.sessionId,creationRequestId:pe,initialDraft:Le,onClose:()=>he(!1)})]})}function Qr(e,t){return Array.isArray(e)?e.some(s=>s.sessions.some(n=>n.sessionId===t)||Qr(s.children,t)):!1}const Lt=5,Zr=["codex","claude-code"];function Jr(){return[{id:"recommended",label:c("conversation.butlerCompletionTemplateRecommendedLabel"),description:c("conversation.butlerCompletionTemplateRecommendedDescription"),value:c("conversation.butlerCompletionTemplateRecommendedValue")},{id:"spec-finish",label:c("conversation.butlerCompletionTemplateSpecLabel"),description:c("conversation.butlerCompletionTemplateSpecDescription"),value:c("conversation.butlerCompletionTemplateSpecValue")},{id:"bugfix",label:c("conversation.butlerCompletionTemplateBugfixLabel"),description:c("conversation.butlerCompletionTemplateBugfixDescription"),value:c("conversation.butlerCompletionTemplateBugfixValue")}]}function Ts(){var e;return((e=Jr()[0])==null?void 0:e.value)??""}function Cs(e,t=Zr){return e==="claude-code"&&t.includes("claude-code")?"claude-code":t.includes("codex")?"codex":t[0]??null}function ei(e){return e==="codex"||e==="claude-code"}function ma(e){return e.flatMap(t=>!t.enabled||!ei(t.provider)?[]:[t.provider])}function ti({session:e,showTrigger:t=!0,openRequestKey:s=0}){var De,Pe;const{showToast:n}=gt(),{requestNavigationRefresh:r,currentTargetHostId:a,navigationGroups:o}=yt(),u=l.useId(),d=l.useId(),h=l.useId(),f=l.useId(),[I,T]=l.useState(!1),[w,g]=l.useState(!1),[m,R]=l.useState(null),[H,N]=l.useState(null),[C,M]=l.useState(null),[y,b]=l.useState(Cs(e==null?void 0:e.provider)),[F,k]=l.useState(""),[S,v]=l.useState(()=>Ts()),[x,K]=l.useState(Lt),[$,J]=l.useState(!1),[re,G]=l.useState(0),j=l.useMemo(()=>{var _,ue,ce,je;const W=e==null?void 0:e.sessionId;if(!W)return!1;if(!a)return!0;const ee=(ue=(_=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:_.workspaceId)==null?void 0:ue.trim(),U=(je=(ce=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:ce.sourceWorkspaceId)==null?void 0:je.trim();return!ee||!U||ee===U?!1:o.some(Ne=>Ne.sessions.some(te=>te.sessionId===W)||Qr(Ne.childWorktrees,W))},[a,o,e==null?void 0:e.sessionId,(De=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:De.sourceWorkspaceId,(Pe=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:Pe.workspaceId]),{items:A}=xo(!!(e!=null&&e.sessionId&&j),a),O=Jr(),Q=l.useMemo(()=>A?ma(A):Zr,[A]),oe=A!==null&&Q.length===0,V=l.useMemo(()=>{var W;return((W=e==null?void 0:e.title)==null?void 0:W.trim())||null},[e==null?void 0:e.title]),Y=l.useMemo(()=>m?{workspaceId:m.workspaceId,project:m.project,session:m.session}:null,[m]),ae=(m==null?void 0:m.latestFollowUpTask)??null,le=(m==null?void 0:m.latestVerificationRun)??null,me=ae&&(ae.status==="active"||ae.status==="waiting_user")?ae:null,L=le&&(le.status==="queued"||le.status==="running")?le:null;l.useEffect(()=>{T(!1),J(!1),N(null),R(null),k(""),b(Cs(e==null?void 0:e.provider)),v(Ts()),K(Lt)},[e==null?void 0:e.sessionId]),l.useEffect(()=>{const W=Cs(e==null?void 0:e.provider,Q);(!y||!Q.includes(y))&&b(W)},[Q,y,e==null?void 0:e.provider]),l.useEffect(()=>{if(!(e!=null&&e.sessionId)||!j){g(!1),R(null),N(null);return}let W=!1;return g(!0),N(null),Po(e.sessionId,{targetHostId:a}).then(ee=>{W||R(ee.context)}).catch(ee=>{W||(R(null),N(ee instanceof Error?ee.message:c("conversation.butlerActionLoadFailed")))}).finally(()=>{W||g(!1)}),()=>{W=!0}},[re,a,e==null?void 0:e.sessionId,j]);function X(){w||G(W=>W+1)}function B(){!m&&!w&&X()}if(l.useEffect(()=>{t||s<=0||(T(!0),B())},[w,s,t,m]),!(e!=null&&e.sessionId)||!j)return null;async function he(){if(!Y){B();return}if(!y)return;const W=F.trim(),ee=S.trim();if(!W){n({title:c("conversation.butlerFollowUpObjectiveRequired"),tone:"warning"});return}if(!ee){n({title:c("conversation.butlerFollowUpCompletionCriteriaRequired"),tone:"warning"});return}M("follow-up");try{const U=await Ao({projectId:Y.project.id,butlerSessionId:Y.session.id,providerId:y,objective:W,completionCriteria:ee,maxAutoContinueCount:x},{targetHostId:a});R(_=>_&&{..._,latestFollowUpTask:U.task}),r(),n({title:c("conversation.butlerFollowUpStarted"),description:c("conversation.butlerFollowUpStartedDescription",{projectName:Y.project.name}),tone:"success"}),k(""),v(Ts()),K(Lt),T(!1)}catch(U){n({title:c("conversation.butlerFollowUpFailed"),description:U instanceof Error?U.message:void 0,tone:"error"})}finally{M(null)}}async function pe(){if(ae){M("follow-up");try{const W=await To(ae.id,{targetHostId:a});R(ee=>ee&&{...ee,latestFollowUpTask:W.task}),r(),n({title:c("conversation.butlerFollowUpStopped"),description:c("conversation.butlerFollowUpStoppedDescription"),tone:"success"}),T(!1)}catch(W){n({title:c("conversation.butlerFollowUpStopFailed"),description:W instanceof Error?W.message:void 0,tone:"error"})}finally{M(null)}}}async function Ee(){if(!Y){B();return}M("verification");try{const W=await Eo({projectId:Y.project.id,butlerSessionId:Y.session.id,verificationType:"browser",targetRef:V||Y.session.title||Y.project.name},{targetHostId:a});R(ee=>ee&&{...ee,latestVerificationRun:W.result.run}),r(),n({title:c("conversation.butlerVerificationStarted"),description:c("conversation.butlerVerificationStartedDescription",{projectName:Y.project.name}),tone:"success"}),T(!1)}catch(W){n({title:c("conversation.butlerVerificationFailed"),description:W instanceof Error?W.message:void 0,tone:"error"})}finally{M(null)}}async function Le(){if(le){M("verification");try{const W=await Co(le.projectId,le.id,{targetHostId:a});R(ee=>ee&&{...ee,latestVerificationRun:W.run}),r(),n({title:c("conversation.butlerVerificationStopped"),description:c("conversation.butlerVerificationStoppedDescription"),tone:"success"}),T(!1)}catch(W){n({title:c("conversation.butlerVerificationStopFailed"),description:W instanceof Error?W.message:void 0,tone:"error"})}finally{M(null)}}}return i.jsxs(i.Fragment,{children:[t?i.jsxs("div",{className:"conversation-butler-entry",onMouseEnter:()=>{J(!0),B()},onMouseLeave:()=>{J(!1)},children:[i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("conversation.butlerActionButton"),title:c("conversation.butlerActionButton"),onFocus:()=>{J(!0),B()},onBlur:()=>{J(!1)},onClick:()=>{T(!0),B()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Ro,{})})}),$?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")}):H?i.jsx("p",{children:H}):ae?i.jsxs(i.Fragment,{children:[i.jsxs("p",{children:[c("conversation.butlerAnalysisObjectiveLabel"),":",ae.objective]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisStatusLabel"),":",qn(ae.status)]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisSummaryLabel"),":",ae.lastAutomationSummary||ae.waitingReason||c("conversation.butlerAnalysisEmpty")]}),ae.waitingReason?i.jsxs("p",{children:[c("conversation.butlerAnalysisWaitingReasonLabel"),":",ae.waitingReason]}):null]}):i.jsx("p",{children:c("conversation.butlerAnalysisEmpty")})]}):null]}):null,i.jsx(aa,{open:I,title:c("conversation.butlerActionModalTitle"),description:c("conversation.butlerActionModalDescription"),className:"conversation-butler-modal-card",footer:!w&&!H&&Y?i.jsxs(gs,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:C!==null,onClick:()=>{Ee()},children:c("conversation.butlerVerificationAction")}),i.jsx("button",{type:"button",className:"primary-button",disabled:C!==null||oe||!y,onClick:()=>{he()},children:c("conversation.butlerFollowUpAction")})]}):void 0,onClose:()=>{C||T(!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&&H?i.jsx("p",{className:"conversation-butler-modal-error",children:H}):null,!w&&!H&&Y?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:Y.project.name})]}),i.jsxs("div",{className:"conversation-butler-target-card",children:[i.jsx("span",{children:c("conversation.butlerActionSessionLabel")}),i.jsx("strong",{children:Y.session.title||V||Y.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")})]}),oe?i.jsx("p",{className:"conversation-butler-modal-hint",children:c("conversation.butlerFollowUpProviderHint")}):i.jsx(ko,{workspaceId:Y.workspaceId,providers:Q,selectedProvider:y,disabled:C!==null,onSelect:W=>{ei(W)&&b(W)}})]}),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:x,disabled:C!==null,onChange:W=>{const ee=Number.parseInt(W.target.value,10);K(Number.isFinite(ee)?ee:Lt)}})]})]}),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:F,placeholder:c("conversation.butlerFollowUpObjectivePlaceholder"),disabled:C!==null,onChange:W=>{k(W.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:S,placeholder:c("conversation.butlerFollowUpCompletionCriteriaPlaceholder"),"aria-describedby":h,disabled:C!==null,onChange:W=>{v(W.target.value)}}),i.jsx("div",{className:"conversation-butler-preset-grid",role:"group","aria-label":c("conversation.butlerCompletionTemplateSectionLabel"),children:O.map(W=>i.jsxs("button",{type:"button",className:"conversation-butler-preset-card","data-selected":S.trim()===W.value,"aria-pressed":S.trim()===W.value,disabled:C!==null,onClick:()=>{v(W.value)},children:[i.jsx("strong",{children:W.label}),i.jsx("span",{children:W.description})]},W.id))})]}),me||L?i.jsxs("div",{className:"conversation-butler-meta-grid",children:[me?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:qn(me.status)}),i.jsx("small",{children:c("conversation.butlerCurrentFollowUpProgress",{current:me.autoContinueCount,max:me.maxAutoContinueCount??Lt})}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:C!==null,onClick:()=>{pe()},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:ga(L.status)}),i.jsx("small",{children:L.targetRef||L.verificationType}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:C!==null,onClick:()=>{Le()},children:c("conversation.butlerStopVerificationAction")})]}):null]}):null]}):null]})})]})}function qn(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 ga(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 va=340;function ba({session:e,onOpenBranchTree:t}){const s=vt(),n=nn(),r=l.useRef(null),a=l.useRef(null),[o,u]=l.useState(!1),[d,h]=l.useState(null),[f,I]=l.useState(null),[T,w]=l.useState(0);l.useEffect(()=>{u(!1),h(null)},[n.pathname,n.search]),l.useLayoutEffect(()=>{if(!o||!d||typeof window>"u"){I(null);return}const b=()=>{var v,x;const S=Tr(d,{width:((v=a.current)==null?void 0:v.offsetWidth)??0,height:((x=a.current)==null?void 0:x.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:va});I({position:"fixed",left:`${Math.round(S.left)}px`,top:`${Math.round(S.top)}px`,width:`${Math.round(S.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(S.maxHeight)}px`,transformOrigin:S.transformOrigin})},F=S=>{var x,K;const v=S.target;v&&!((x=a.current)!=null&&x.contains(v))&&!((K=r.current)!=null&&K.contains(v))&&m()},k=S=>{S.key==="Escape"&&m()};return b(),window.addEventListener("pointerdown",F),window.addEventListener("keydown",k),window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),()=>{window.removeEventListener("pointerdown",F),window.removeEventListener("keydown",k),window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0)}},[d,o]);function g(){var F;const b=(F=r.current)==null?void 0:F.getBoundingClientRect();b&&(h({x:b.right,y:b.bottom}),u(!0))}function m(){u(!1),h(null)}function R(b){s(b),m()}function H(b){const F=new URLSearchParams(n.search);F.set("toolPanel",b),R(`${n.pathname}?${F.toString()}`)}function N(){if(o){m();return}g()}function C(b){b.key!=="ContextMenu"&&!(b.shiftKey&&b.key==="F10")||(b.preventDefault(),b.stopPropagation(),g())}if(!e)return null;const M=[{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:()=>{H("files")}},{key:"git",label:c("shell.gitEntry"),onSelect:()=>{H("git")}},{key:"processes",label:c("shell.mobileConversationToolProcessesTab"),onSelect:()=>{H("processes")}}],y=o&&typeof document<"u"?St.createPortal(i.jsx("div",{ref:a,className:"session-action-menu mobile-conversation-action-menu surface-card",role:"menu","aria-label":c("conversation.moreSessionActions"),style:f??{position:"fixed",top:0,left:0,visibility:"hidden"},onClick:b=>b.stopPropagation(),children:M.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":o,onClick:N,onKeyDown:C,children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(_o,{})})}),i.jsx(ti,{session:e,showTrigger:!1,openRequestKey:T})]}),y]})}function si({items:e,deletingQueueItemId:t=null,steeringQueueItemId:s=null,canSteer:n=!1,onDelete:r,onSteer:a}){return e.length===0?null:i.jsxs("section",{className:"queued-message-list","aria-label":c("conversation.queueTitle"),children:[i.jsx("div",{className:"queued-message-list__header",children:i.jsx("h2",{children:`${c("conversation.queueTitle")} · ${e.length}`})}),i.jsx("div",{className:"queued-message-list__items",children:e.map((o,u)=>{const d=o.status==="queued"||o.status==="failed",h=n&&typeof a=="function"&&(o.status==="queued"||o.status==="failed");return i.jsxs("article",{className:"queued-message-item",children:[i.jsxs("div",{className:"queued-message-item__main",children:[i.jsx("span",{className:"queued-message-item__order","aria-hidden":"true",children:u+1}),i.jsx("p",{className:"queued-message-item__content",title:o.content||c("conversation.queueImageOnly"),children:o.content||c("conversation.queueImageOnly")}),i.jsx("span",{className:`queued-message-item__status queued-message-item__status--${o.status}`,children:o.status==="failed"?c("conversation.queueStatusFailed"):c("conversation.queueStatusQueued")}),i.jsxs("div",{className:"queued-message-item__actions",children:[h?i.jsx("button",{type:"button",className:"queued-message-item__action queued-message-item__action--steer",onClick:()=>void a(o.id),disabled:s===o.id,"aria-label":c("conversation.queueSteer"),title:c("conversation.queueSteer"),children:s===o.id?c("conversation.queueSteering"):c("conversation.queueSteer")}):null,d?i.jsx("button",{type:"button",className:"queued-message-item__action queued-message-item__action--delete",onClick:()=>void r(o.id),disabled:t===o.id,"aria-label":c("conversation.queueDelete"),title:c("conversation.queueDelete"),children:t===o.id?"…":"×"}):null]})]}),o.errorDetail?i.jsx("p",{className:"queued-message-item__error",children:o.errorDetail}):null]},o.id)})})]})}function wa(e){const{sending:t,setSending:s,session:n,runtimeHasActiveRun:r,runtimeCanInterrupt:a}=e,o=l.useRef(!1);l.useEffect(()=>{if(!t){o.current=!1;return}if(Ia(n,r,a)){o.current=!0;return}o.current&&(o.current=!1,s(!1))},[a,r,t,n,s])}function Ia(e,t,s){return t===!0||s===!0||(e==null?void 0:e.runningState)==="stale"||(e==null?void 0:e.runningState)==="unknown"?!0:Cr(e)}const Ma=30,Es=80,Ht=60,ni=600,Bn=300*1e3,Sa=600,ya=5e3,xa=1e4,Gs=120*1e3,ri=8,Pa=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/g;class Ra{constructor(t,s={}){xe(this,"state");xe(this,"authoritativeMessages",[]);xe(this,"runtimeOverlayMessages",[]);xe(this,"activeRuntimeOverlayKeys",[]);xe(this,"pendingMessages",[]);xe(this,"listeners",new Set);xe(this,"realtimeClient",null);xe(this,"historyBootstrapFallbackTimer",null);xe(this,"historyBootstrapEnvelopeReceived",!1);xe(this,"markSeenTimer",null);xe(this,"markSeenInFlight",!1);xe(this,"lastMarkSeenRequestAt",0);xe(this,"seenWatermark",null);xe(this,"runtimeRefreshTimer",null);xe(this,"runtimeRefreshMode",null);xe(this,"replaceSnapshotSeedOnBackfill",!1);xe(this,"olderHistoryPrefetchCursor",null);xe(this,"olderHistoryPrefetchPromise",null);xe(this,"prefetchedOlderHistoryPage",null);xe(this,"pendingReplyDebugTraces",[]);xe(this,"hasAuthoritativeBootstrapMessages");xe(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));xe(this,"getState",()=>this.state);var o;this.sessionId=t,this.options=s;const n=Pn(qs(t,s.targetHostId),Bn);this.hasAuthoritativeBootstrapMessages=(((o=s.bootstrapMessages)==null?void 0:o.length)??0)>0;const r=Zt(s.initialSession??null,(n==null?void 0:n.session)??null),a=Vn(ka(),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)<Ht&&((n==null?void 0:n.pagesLoaded)??0)<=1});this.authoritativeMessages=a.timeline.authoritativeMessages,this.runtimeOverlayMessages=a.timeline.runtimeOverlayMessages,this.activeRuntimeOverlayKeys=a.timeline.activeRuntimeOverlayKeys,this.pendingMessages=a.timeline.pendingMessages,this.replaceSnapshotSeedOnBackfill=a.timeline.replaceSnapshotSeedOnBackfill,this.state=jn({session:r,capabilities:(n==null?void 0:n.capabilities)??null,runtimeHasActiveRun:(n==null?void 0:n.runtimeHasActiveRun)??null,runtimeCanInterrupt:(n==null?void 0:n.runtimeCanInterrupt)??null,contextUsage:(n==null?void 0:n.contextUsage)??null,messages:a.messages,timelineItems:js(r,a.messages),permissionRequests:(n==null?void 0:n.permissionRequests)??[],queuedMessages:(n==null?void 0:n.queuedMessages)??[],olderCursor:(n==null?void 0:n.olderCursor)??null,hasOlderMessages:(n==null?void 0:n.hasOlderMessages)??!1,lastCursor:(n==null?void 0:n.lastCursor)??null,interruptSource:(n==null?void 0:n.interruptSource)??null,pagesLoaded:(n==null?void 0:n.pagesLoaded)??0}),this.seenWatermark=(r==null?void 0:r.lastSeenAt)??null}async initialize(){this.historyBootstrapEnvelopeReceived=!1,this.clearHistoryBootstrapFallbackTimer(),this.clearOlderHistoryPrefetch();const t=this.options.bootstrapMessages??[],s=this.applyTimelineEvent({type:"history.merge",source:"initialize_bootstrap",messages:t,replaceSnapshotSeed:!1}),n=this.hasAuthoritativeBootstrapMessages;this.patch({messages:s.messages,historyState:nl(this.state.session,n?this.authoritativeMessages.length:0),loadingOlderMessages:!1,olderCursor:n?null:this.state.olderCursor,hasOlderMessages:Pt({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=Pn(qs(this.sessionId,this.options.targetHostId),Bn),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)<Ht&&((t==null?void 0:t.pagesLoaded)??0)<=1});this.state=jn({session:Zt(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=Zt(this.state.session,t);s!==this.state.session&&this.patch({session:s,hasOlderMessages:Pt({session:s,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})})}async sendMessage(t,s){const n=tr();this.beginPendingReplyDebugTrace("send_live",n,t.length);const r=Er(this.sessionId,t,n,(s==null?void 0:s.attachmentMeta)??[],(s==null?void 0:s.attachments)??[],Ja(this.buildTimelineMessages("send_sequence"),this.state.session)),a=this.applyTimelineEvent({type:"pending.insert",source:"send_pending",pending:r});this.patch({messages:a.messages,session:ot(this.state.session,"running"),runtimeHasActiveRun:sr(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:nr(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt});try{const o=await this.sendMessageWithFallback(t,n,s);this.markPendingReplyDebugTraceResponseReady(n,{returnedMessageId:o.message.messageId,returnedProviderSessionId:o.message.providerSessionId}),this.resolvePendingMessage(o.message,n),this.patch({messages:this.buildTimelineMessages("send_resolved")})}catch(o){this.failPendingReplyDebugTrace(n,o);const u=this.applyTimelineEvent({type:"pending.fail",source:"send_failed",clientRequestId:n});throw this.patch({messages:u.messages,session:ot(this.state.session,"failed"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1}),o}}async retryMessage(t){const s=this.pendingMessages.find(r=>r.clientRequestId===t);if(!s)return;const n=this.applyTimelineEvent({type:"pending.retry",source:"retry_pending",clientRequestId:t});this.patch({messages:n.messages,runtimeHasActiveRun:sr(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:nr(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt}),this.beginPendingReplyDebugTrace("retry_live",t,s.content.length);try{const r=await this.sendMessageWithFallback(s.content,t,{attachments:s.attachmentPayloads??[],attachmentMeta:s.attachments});this.markPendingReplyDebugTraceResponseReady(t,{returnedMessageId:r.message.messageId,returnedProviderSessionId:r.message.providerSessionId}),this.resolvePendingMessage(r.message,t),this.patch({messages:this.buildTimelineMessages("retry_resolved")})}catch(r){this.failPendingReplyDebugTrace(t,r);const a=this.applyTimelineEvent({type:"pending.fail",source:"retry_failed",clientRequestId:t});throw this.patch({messages:a.messages,session:ot(this.state.session,"failed")}),r}}async enqueueMessage(t,s){const n=tr();try{const r=await jo(this.sessionId,{content:t,clientRequestId:n,model:(s==null?void 0:s.model)??null,reasoningLevel:(s==null?void 0:s.reasoningLevel)??null,permissionMode:It(),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:fl(this.state.queuedMessages,r)}),await this.refreshQueue()}catch(r){throw r}}async deleteQueuedMessage(t){await No(this.sessionId,t,{targetHostId:this.options.targetHostId}),await this.refreshQueue()}async steerQueuedMessage(t){await Oo(this.sessionId,t,{targetHostId:this.options.targetHostId}),await this.refreshRuntimeSnapshot("queue_steer")}async interrupt(){await Lo(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(a=>a.id===t)??null))return;const r=await Do(this.sessionId,t,s,{targetHostId:this.options.targetHostId});this.patch({permissionRequests:Bs(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,Es)))throw new Error("REALTIME_NOT_CONNECTED")}catch(s){const n=s instanceof Error?s.message:"unknown";this.patch({loadingOlderMessages:!1,errorCode:"HISTORY_LOAD_MORE_FAILED",errorDetail:n})}}}destroy(){var t;this.clearHistoryBootstrapFallbackTimer(),this.clearOlderHistoryPrefetch(),(t=this.realtimeClient)==null||t.close(),this.realtimeClient=null,this.pendingReplyDebugTraces.length=0,this.markSeenTimer!==null&&(window.clearTimeout(this.markSeenTimer),this.markSeenTimer=null),this.runtimeRefreshTimer!==null&&(window.clearTimeout(this.runtimeRefreshTimer),this.runtimeRefreshTimer=null),this.runtimeRefreshMode=null}startRealtime(){var s;if(!((s=Ss.getState().session)==null?void 0:s.accessToken)){Ss.clear();return}this.realtimeClient=new Ho({targetHostId:this.options.targetHostId,sessionId:this.sessionId,cursor:this.state.lastCursor,limit:Ht,onSubscribed:()=>{Se("session_send.realtime_subscribed",{sessionId:this.sessionId,lastCursor:this.state.lastCursor}),this.patch({connectionState:"connected",hasOlderMessages:Pt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})}),this.scheduleHistoryBootstrapFallback()},onConnectionChange:n=>{var a;const r=this.state.connectionState;if(this.patch({connectionState:n,session:n==="reconnecting"&&Je((a=this.state.session)==null?void 0:a.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:a,replacedSnapshotSeed:o}=this.mergeHistoryMessages(n.messages,r,n.type==="session.backfill"?"realtime_backfill":"realtime_delta");this.patch({messages:a,lastCursor:n.cursor,historyState:"ready",olderCursor:n.type==="session.backfill"&&!o&&this.state.pagesLoaded>1?this.state.olderCursor:n.olderCursor??this.state.olderCursor,hasOlderMessages:n.type==="session.backfill"?!o&&this.state.pagesLoaded>1?this.state.hasOlderMessages:!!n.olderCursor:Pt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),pagesLoaded:n.type==="session.backfill"?!o&&this.state.pagesLoaded>1?this.state.pagesLoaded:Math.max(this.state.pagesLoaded,this.authoritativeMessages.length>0?1:0):this.state.pagesLoaded,session:ot(this.state.session,Qn(n.type,(u=this.state.session)==null?void 0:u.runningState))}),(d=this.realtimeClient)==null||d.updateCursor(n.cursor),this.scheduleMarkSeen(),this.scheduleOlderHistoryPrefetch(n.type==="session.backfill"?"backfill":"delta"),this.state.queuedMessages.length>0&&this.refreshQueue()},onOlderHistory:n=>{this.applyOlderHistoryPage({messages:n.messages,nextCursor:n.olderCursor},"realtime")},onRuntimeMessage:n=>{this.handleRuntimeMessage(n)},onActivity:n=>{this.handleActivity(n)},onRuntimeStatus:n=>{this.handleRuntimeStatus(n)},onRuntimeError:n=>{this.handleRuntimeError(n)},onInterrupted:n=>{this.handleInterrupted(n)},onPermissionRequest:n=>{this.handlePermissionRequest(n)},onPermissionRequestResolved:n=>{this.handlePermissionRequestResolved(n)},onError:n=>{this.patch({loadingOlderMessages:!1,errorCode:n.error_code,errorDetail:n.detail})},onUnauthorized:()=>{Ss.clear()}}),this.realtimeClient.start()}patch(t){let s=t;Object.prototype.hasOwnProperty.call(t,"session")&&(this.syncSeenWatermark(t.session??null),s={...t,session:this.applySeenWatermark(t.session??null)}),(Object.prototype.hasOwnProperty.call(s,"session")||Object.prototype.hasOwnProperty.call(s,"messages"))&&(s={...s,timelineItems:js((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=Vn({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=Qa(s.previousMessages,s.messages,"assistant"),r=Ka(t);return(s.validationIssues.length>0||r.some(o=>o.role==="assistant")||n.length>0)&&rs("timeline.event",{sessionId:this.sessionId,eventType:t.type,source:t.source,replacedSnapshotSeed:s.replacedSnapshotSeed,validationIssues:s.validationIssues,authoritativeCount:this.authoritativeMessages.length,runtimeOverlayCount:this.runtimeOverlayMessages.length,pendingCount:this.pendingMessages.length,eventMessages:r.map(o=>gi(o)),assistantMoves:n,previousTail:Xn(s.previousMessages.slice(-6)),nextTail:Xn(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 Ks({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(Sa,s);this.markSeenTimer=window.setTimeout(()=>{this.markSeenTimer=null;const r=this.getTargetSeenAt();r!==null&&(Se("session_seen.start",{sessionId:this.sessionId,targetSeenAt:r,seenWatermark:this.seenWatermark}),this.markSeenInFlight=!0,this.lastMarkSeenRequestAt=Date.now(),qo(this.sessionId,{targetHostId:this.options.targetHostId}).then(()=>{var a,o;this.bumpSeenWatermark(r),this.patch({session:zn(this.state.session,r)}),(o=(a=this.options).onSeen)==null||o.call(a,this.sessionId,r),Se("session_seen.end",{sessionId:this.sessionId,seenWatermark:this.seenWatermark})}).catch(()=>{Se("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(ni,Math.max(Ht,this.authoritativeMessages.length,Ma)),s=await Us(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:Pt({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}),Se("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,Se("session.history_older.prefetch.start",{sessionId:this.sessionId,requestedCursor:t,reason:s,limit:Es});const n=Us(this.sessionId,t,Es,"backward",{targetHostId:this.options.targetHostId}).then(a=>(this.state.olderCursor===t&&(this.prefetchedOlderHistoryPage={requestedCursor:t,page:a}),Se("session.history_older.prefetch.end",{sessionId:this.sessionId,requestedCursor:t,messageCount:a.messages.length,nextCursor:a.nextCursor}),a)).catch(a=>(Se("session.history_older.prefetch.error",{sessionId:this.sessionId,requestedCursor:t,message:a instanceof Error?a.message:"unknown"}),null)).finally(()=>{this.olderHistoryPrefetchPromise===n&&(this.olderHistoryPrefetchPromise=null),this.olderHistoryPrefetchCursor===t&&(this.olderHistoryPrefetchCursor=null)});return this.olderHistoryPrefetchPromise=n,n}async takePrefetchedOlderHistoryPage(t){var s;if(((s=this.prefetchedOlderHistoryPage)==null?void 0:s.requestedCursor)===t){const n=this.prefetchedOlderHistoryPage.page;return this.prefetchedOlderHistoryPage=null,Se("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,Se("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,Se("session_runtime.refresh.schedule",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((r=this.state.session)==null?void 0:r.runningState)??null}),this.runtimeRefreshTimer=window.setTimeout(()=>{const a=this.runtimeRefreshMode??t;this.runtimeRefreshTimer=null,this.runtimeRefreshMode=null,this.refreshRuntimeState(a,s)},t==="poll"?xa:1200))}async refreshRuntimeState(t,s){var n,r,a,o,u;Se("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 Nn(this.sessionId,{targetHostId:this.options.targetHostId}),h=Ds(this.state.runtimeHasActiveRun,d.runningState,d.hasActiveRun),f=Hs(this.state.runtimeCanInterrupt,d.runningState,h,d.canInterrupt);this.patch({session:Yn(this.state.session,d),runtimeHasActiveRun:h,runtimeCanInterrupt:f,contextUsage:d.contextUsage,...Os(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);Se("session_runtime.refresh.end",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((a=this.state.session)==null?void 0:a.runningState)??null,continuePolling:I}),I&&this.scheduleRuntimeRefresh("poll","connection_poll")}catch(d){Se("session_runtime.refresh.error",{sessionId:this.sessionId,mode:t,reason:s,connectionState:this.state.connectionState,runningState:((o=this.state.session)==null?void 0:o.runningState)??null,message:d instanceof Error?d.message:"unknown"}),t==="poll"&&this.state.connectionState!=="connected"&&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(kr(this.sessionId,{targetHostId:this.options.targetHostId}).then(s=>{this.patch({session:Zt(s,this.state.session)})}).catch(()=>{})),Kn(this.state.capabilities)&&t.push(Bo(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 Fo(this.sessionId,{targetHostId:this.options.targetHostId});this.patch({permissionRequests:t.items})}catch{return}}shouldRefreshSessionDetail(){return this.state.session===null||Kn(this.state.capabilities)||this.state.session.runningState===null}shouldRefreshRuntimeSnapshot(){return this.state.contextUsage===null||hl(this.state.session,this.state.runtimeHasActiveRun,this.state.runtimeCanInterrupt)}async refreshRuntimeSnapshot(t){Se("session_runtime.snapshot.start",{sessionId:this.sessionId,reason:t});try{const s=await Nn(this.sessionId,{targetHostId:this.options.targetHostId}),n=Ds(this.state.runtimeHasActiveRun,s.runningState,s.hasActiveRun),r=Hs(this.state.runtimeCanInterrupt,s.runningState,n,s.canInterrupt);this.patch({session:Yn(this.state.session,s),runtimeHasActiveRun:n,runtimeCanInterrupt:r,contextUsage:s.contextUsage,...Os(s,this.state.interruptSource)}),await this.refreshQueue(),Se("session_runtime.snapshot.end",{sessionId:this.sessionId,reason:t,hasContextUsage:s.contextUsage!==null})}catch(s){Se("session_runtime.snapshot.error",{sessionId:this.sessionId,reason:t,message:s instanceof Error?s.message:"unknown"})}}async refreshQueue(){try{const t=await Wo(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:It(),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(a){if(!(a instanceof Ji)||a.status!==404&&a.status!==405||(((r=n==null?void 0:n.attachments)==null?void 0:r.length)??0)>0)throw a;return Se("session_send.live_fallback",{sessionId:this.sessionId,clientRequestId:s,reason:a.message}),Uo(this.sessionId,{content:t,clientRequestId:s,permissionMode:It()},{targetHostId:this.options.targetHostId})}}handleRuntimeStatus(t){var n;const s=Ns((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=Ds(this.state.runtimeHasActiveRun,t.runningState,t.hasActiveRun),n=Hs(this.state.runtimeCanInterrupt,t.runningState,s,t.canInterrupt);if(this.patch({session:il(this.state.session,t),runtimeHasActiveRun:s,runtimeCanInterrupt:n,...Os(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:Ar(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:Pt({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,Qn("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=Ns((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=Ns((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:Bs(this.state.permissionRequests,t.request)})}handlePermissionRequestResolved(t){this.patch({permissionRequests:Bs(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,ya-(Date.now()-this.lastMarkSeenRequestAt))}applySeenWatermark(t){return!t||!this.seenWatermark?t:zn(t,this.seenWatermark)}emit(){for(const t of this.listeners)t()}persistSnapshot(){eo(qs(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:rr(this.authoritativeMessages),timelineItems:js(this.state.session,rr(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),Se(`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(),Se(`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&&(Se(`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();Se(`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&&(Se(t,{sessionId:this.sessionId,clientRequestId:n.clientRequestId,durationMs:Math.round(performance.now()-n.startedAtMs),responseReady:n.responseReadyAtMs!==null,...s}),this.removePendingReplyDebugTrace(n.clientRequestId))}removePendingReplyDebugTrace(t){const s=this.pendingReplyDebugTraces.findIndex(n=>n.clientRequestId===t);s<0||this.pendingReplyDebugTraces.splice(s,1)}logCodexMergeDebug(t,s,n,r,a={}){const o=n.filter(al);if(o.length===0)return;const u=Jn(s),d=Jn(r);Qe("session.messages.merge",{sessionId:this.sessionId,source:t,beforeCount:s.length,incomingCount:n.length,afterCount:r.length,incoming:o.slice(0,5).map(cl),beforeDuplicateGroupCount:u.length,afterDuplicateGroupCount:d.length,afterDuplicateGroups:d.slice(0,3),...a})}}function ka(){return{authoritativeMessages:[],runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:!1}}function Ta(e,t){const s=new Map,n=new Set;for(const r of e)s.set(r.id,r),n.add(r.id);for(const r of t){const a=s.get(r.id)??null,o=fi(s,n,r,a);if(o){const h=s.get(o)??null;if(h){Qe("session.messages.runtime_overlay_authoritative_bridge",{mode:"prefer_equivalent",previous:ve(h),overlay:ve(r),replacedSameId:a?ve(a):null}),s.set(o,As(h,r));continue}}if(a){Qe("session.messages.runtime_overlay_authoritative_bridge",{mode:"same_id",previous:ve(a),overlay:ve(r)}),s.set(r.id,As(a,r));continue}const u=pn(s,n,r);if(u){const h=s.get(u)??null;if(h){Qe("session.messages.runtime_overlay_authoritative_bridge",{mode:"codex_compat",previous:ve(h),overlay:ve(r)}),s.set(u,As(h,r));continue}}const d=mn(s,r);if(d&&n.has(d)){const h=s.get(d)??null;if(h){if(Qe("session.messages.runtime_overlay_authoritative_bridge",{mode:"opencode_compat",previous:ve(h),overlay:ve(r)}),Is(h,r)){s.set(d,Fn(h,r));continue}s.set(d,Fn(h,r));continue}}Qe("session.messages.runtime_overlay_authoritative_bridge",{mode:"insert",overlay:ve(r)}),s.set(r.id,r)}return ja(Array.from(s.values()))}function As(e,t){return{...ii(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 ii(e,t){if(e.id!==t.id)return t;if(Wt(e,t)){const o=is(e.toolCall,t.toolCall),u=oi(e,t,o,os),d=as(e.attachments,t.attachments),h=ls(e,t);return{...Tt(e,t),kind:(o==null?void 0:o.status)==="running"?"tool_call":"tool_result",content:u,toolCall:o,attachments:d,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:h.rawRef,timestamp:h.timestamp,sequence:h.sequence}}if(e.role!==t.role||e.kind!==t.kind)return Tt(e,t);const s=is(e.toolCall,t.toolCall),n=os(e.content,t.content,e.timestamp,t.timestamp),r=as(e.attachments,t.attachments),a=ls(e,t);return{...Tt(e,t),content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:a.rawRef,timestamp:a.timestamp,sequence:a.sequence}}function Fn(e,t){if(Wt(e,t)){const o=is(e.toolCall,t.toolCall),u=oi(e,t,o,os),d=as(e.attachments,t.attachments),h=ls(e,t);return{...Tt(e,t),id:e.id,kind:(o==null?void 0:o.status)==="running"?"tool_call":"tool_result",content:u,toolCall:o,attachments:d,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:h.rawRef,timestamp:h.timestamp,sequence:h.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}if(e.role!==t.role||e.kind!==t.kind)return{...Tt(e,t),id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId};const s=is(e.toolCall,t.toolCall),n=os(e.content,t.content,e.timestamp,t.timestamp),r=as(e.attachments,t.attachments),a=ls(e,t);return{...Tt(e,t),id:e.id,content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:a.rawRef,timestamp:a.timestamp,sequence:a.sequence,clientRequestId:e.clientRequestId??t.clientRequestId}}function Wt(e,t){return Is(e,t)||Ms(e,t)}function oi(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 pn(e,t,s){if(!Ys(s))return null;for(const[n,r]of e.entries())if(!(n===s.id||!t.has(n)||!Ca(r,s)))return Qe("session.messages.codex_identity_bridge_match",{previous:ve(r),incoming:ve(s)}),n;return null}function Ca(e,t){if(!Oa(e,t))return!1;if(e.rawRef===t.rawRef)return!0;if(e.kind==="tool_call"||e.kind==="tool_result")return Ms(e,t);const s=us(e.rawRef),n=us(t.rawRef);if(!s||!n||s!==n)return!1;const r=Math.abs(e.sequence-t.sequence);return r>1?(Qe("session.messages.codex_identity_bridge_rejected",{reason:"sequence_distance",sequenceDistance:r,previous:ve(e),incoming:ve(t)}),!1):!0}function mn(e,t){if(!Un(t))return null;const s=cs(t.rawRef);if(s===null)return null;const n=At(t.timestamp);let r=null,a=Number.POSITIVE_INFINITY;for(const[o,u]of e.entries()){if(o===t.id||!Un(u)||u.role!==t.role)continue;if(Is(u,t))return o;if(u.kind!==t.kind||cs(u.rawRef)!==s)continue;const h=At(u.timestamp),f=Math.abs(h-n),T=Math.abs(u.sequence-t.sequence)*6e4+f;T<a&&(r=o,a=T)}return r}function Ea(e,t,s){if(!gn(t))return!1;const n=Xs(e.authoritativeMessages,t,"authoritative",s);if(n)return Qe("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"authoritative",matched:ve(n),incoming:ve(t)}),!0;const r=Xs(e.pendingMessages,t,"pending",s);return r?(Qe("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"pending",matched:ve(r),incoming:ve(t)}),!0):!1}function Xs(e,t,s,n){const r=At(t.timestamp),a=Ge(t.content),o=zs(t.content),u=ds(t.attachments);let d=null,h=Number.POSITIVE_INFINITY;const f=[];for(const I of e){if(!(s==="authoritative"?Na(I):li(I)))continue;const w=Ge(I.content),g=zs(I.content),m=w===a,R=g===o;if(!m&&!R)continue;const H=At(I.timestamp),N=Math.abs(H-r);if(N>300*1e3)continue;const C=Math.abs(I.sequence-t.sequence),M=ds(I.attachments),y=Da(M,u);if(f.push(qa(I,{strictTextMatches:m,relaxedTextMatches:R,attachmentCompatibility:y,distanceMs:N,sequenceDistance:C})),y==="conflict"&&(m||a.length===0))continue;const b=N+C*15e3+(m?0:500)+Ha(y);b<h&&(d=I,h=b)}return f.length>0&&Qe("session.messages.runtime_user_match",{sessionId:n,target:s,matchedId:(d==null?void 0:d.id)??null,matchedScore:Number.isFinite(h)?h:null,incoming:Ba(t,{relaxedContent:o,attachmentSignature:u}),candidates:f.slice(0,5)}),d}function Aa(e,t,s){for(const n of t){if(n.role!=="user"||n.kind!=="text")continue;const r=Ar(s,n,"sent",null);if(!Xs(e,r,"authoritative",s))return!0}return!1}function is(e,t){return e?t?{..._a(e,t),input:ai(e.input,t.input),output:Wn(e.output,t.output),error:Wn(e.error,t.error)}:e:t}function _a(e,t){const s=e.status==="running"?0:1,n=t.status==="running"?0:1;return n!==s?n>s?t:e:t}function os(e,t,s,n){const r=Ge(e),a=Ge(t);return r===a?e.length>=t.length?e:t:r.length>a.length&&r.includes(a)?e:a.length>r.length&&a.includes(r)||n.localeCompare(s)>=0?t:e}function as(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 ai(e,t){return t.length>e.length?t:e}function Wn(e,t){return e===null?t:t===null?e:ai(e,t)}function Tt(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 ls(e,t){return Vt(e,t)<=0?e:t}function Ge(e){return e.replace(Pa,"").replace(/\r\n/g,`
4
+ `).trimEnd()}function zs(e){return Ge(e).replace(/[ \t]+\n/g,`
5
+ `).replace(/\n{2,}/g,`
6
+ `).trim()}function ja(e){return[...e].sort((t,s)=>Vt(t,s))}function Ys(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("codex://")&&(e.role==="assistant"||e.role==="tool")}function gn(e){return e.role==="user"&&e.kind==="text"}function li(e){return gn(e)&&e.deliveryState!=="failed"&&(e.rawRef.startsWith("pending://")||e.rawRef.startsWith("synthetic://")||e.rawRef.includes("#synthetic"))}function Na(e){return gn(e)&&!li(e)}function Un(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 $n(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")&&e.toolCall!==null}function Is(e,t){var r,a;if(!$n(e)||!$n(t))return!1;const s=((r=e.toolCall)==null?void 0:r.callId.trim())??"",n=((a=t.toolCall)==null?void 0:a.callId.trim())??"";return s&&n?s===n:cs(e.rawRef)===cs(t.rawRef)}function cs(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 a=n.slice(0,r),o=new URLSearchParams(n.slice(r+1));if(!o.has("part"))return e;o.delete("part");const u=o.toString();return`${a}${u?`?${u}`:""}${s}`}function Oa(e,t){if(!Ys(e)||!Ys(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?Ms(e,t):Math.abs(e.sequence-t.sequence)>ri||!ui(e.timestamp,t.timestamp,Gs)?!1:t.kind==="text"||t.kind==="thinking"?ci(e,t,Gs):!1}function ci(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=Et(e.content),r=Et(t.content);return ui(e.timestamp,t.timestamp,s)&&Ge(n.text)===Ge(r.text)&&La(n.inlineImages,r.inlineImages)}function Ms(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 us(e){const t=e.match(/^codex:\/\/(.+?)(?:#|$)/);return(t==null?void 0:t[1])??null}function La(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 ui(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(Et(e.content).text).slice(0,160):Ge(e.content).slice(0,160)}}function ds(e){return(e??[]).map(t=>[t.kind,t.fileName.trim().toLowerCase(),t.mimeType.trim().toLowerCase(),String(t.fileSize)].join(":")).sort().join("|")}function Da(e,t){return!e&&!t?"same":!e||!t?"one_side_missing":e===t?"same":"conflict"}function Ha(e){switch(e){case"same":return 0;case"one_side_missing":return 2500;case"conflict":default:return 12e4}}function qa(e,t){return{...ve(e),comparableContent:zs(e.content).slice(0,160),attachmentSignature:ds(e.attachments),strictTextMatches:t.strictTextMatches,relaxedTextMatches:t.relaxedTextMatches,attachmentCompatibility:t.attachmentCompatibility,distanceMs:t.distanceMs,sequenceDistance:t.sequenceDistance}}function Ba(e,t){return{...ve(e),comparableContent:t.relaxedContent.slice(0,160),attachmentSignature:t.attachmentSignature}}function Ks(e){let t=Ta(e.authoritativeMessages,e.runtimeOverlayMessages);for(const s of e.pendingMessages)t=jr(t,s);return Ua(t,e.authoritativeMessages,e.runtimeOverlayMessages,e.activeRuntimeOverlayKeys)}function Vn(e,t,s){const n=Ks(e);let r=e,a=!1;switch(s.type){case"timeline.seed":{r={authoritativeMessages:xs(s.snapshotMessages,t,s.bootstrapMessages),runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:s.replaceSnapshotSeedOnBackfill};break}case"history.merge":{a=s.replaceSnapshotSeed&&e.replaceSnapshotSeedOnBackfill&&el(e.authoritativeMessages,s.messages);const u=a?[]:e.authoritativeMessages;r={...e,authoritativeMessages:xs(u,t,s.messages),activeRuntimeOverlayKeys:Aa(e.authoritativeMessages,s.messages,t)?[]:e.activeRuntimeOverlayKeys,replaceSnapshotSeedOnBackfill:a?!1:e.replaceSnapshotSeedOnBackfill};break}case"runtime.message":{if(Ea(e,s.message,t)){r=e;break}r={...e,runtimeOverlayMessages:$o(e.runtimeOverlayMessages,[s.message]),activeRuntimeOverlayKeys:$a(e,e.activeRuntimeOverlayKeys,s.message)};break}case"pending.insert":{r={...e,activeRuntimeOverlayKeys:s.pending.role==="user"?[]:e.activeRuntimeOverlayKeys,pendingMessages:jr(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:_r(e.pendingMessages,s.clientRequestId)};break}case"pending.resolve":{const u=e.pendingMessages.find(h=>h.clientRequestId===s.clientRequestId)??null;let d=xs(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:Wa(r.authoritativeMessages,r.runtimeOverlayMessages)},r={...r,activeRuntimeOverlayKeys:Ga(r.authoritativeMessages,r.runtimeOverlayMessages,r.activeRuntimeOverlayKeys)};const o=Ks(r);return{timeline:r,previousMessages:n,messages:o,replacedSnapshotSeed:a,validationIssues:Fa(e,r,s,n,o)}}function Fa(e,t,s,n,r){var f,I,T;const a=[],o=di(r,t.authoritativeMessages,t.runtimeOverlayMessages,t.activeRuntimeOverlayKeys),u=_s(r.map(w=>w.id));u.length>0&&a.push(`rendered_duplicate_ids:${u.join(",")}`);const d=_s(t.authoritativeMessages.map(w=>w.id));d.length>0&&a.push(`authoritative_duplicate_ids:${d.join(",")}`);const h=_s(t.pendingMessages.map(w=>w.clientRequestId).filter(w=>!!w));if(h.length>0&&a.push(`pending_duplicate_client_request_ids:${h.join(",")}`),Zs(r,o)||a.push("rendered_order_not_monotonic"),s.type==="pending.resolve"&&t.pendingMessages.some(g=>g.clientRequestId===s.clientRequestId)&&a.push(`pending_not_cleared:${s.clientRequestId}`),s.type==="runtime.message"&&!mi(e.authoritativeMessages,t.authoritativeMessages)&&a.push("runtime_message_mutated_authoritative_layer"),s.type==="history.merge"&&s.source.startsWith("older_history")&&!Ya(e.authoritativeMessages,t.authoritativeMessages)&&a.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)&&a.push("older_history_changed_rendered_tail"),o.length>0){const w=((T=r.at(-1))==null?void 0:T.id)??null;(!w||!o.includes(w))&&a.push("runtime_live_item_not_pinned_to_tail")}return a}function Wa(e,t){if(t.length===0)return t;const s=new Map(e.map(o=>[o.id,o])),n=new Set(s.keys()),r=e.at(-1)??null,a=t.filter(o=>{const u=Qs(s,n,o);if(!u)return!0;const d=hs(u,o);return!d&&hi(r,o)?(rs("timeline.runtime_overlay_stale_dropped",{overlay:ve(o),authoritativeMatch:ve(u),latestAuthoritative:r?ve(r):null}),!1):(!d&&pi(o)&&rs("timeline.runtime_overlay_not_absorbed",{overlay:ve(o),authoritativeMatch:ve(u)}),!d)});return a.length===t.length?t:a}function Ua(e,t,s,n){const r=di(e,t,s,n);if(r.length===0)return e;const a=new Set(r),o=[...e.filter(u=>!a.has(u.id)),...e.filter(u=>a.has(u.id))];return mi(e,o)?e:o}function di(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])),a=new Set(r.keys()),o=new Map(e.map(f=>[f.id,f])),u=new Set(o.keys()),d=new Map(s.map(f=>[on(f),f])),h=[];for(const f of n){const I=d.get(f)??null;if(!I||!vn(t,I))continue;const T=Qs(r,a,I);if(T&&hs(T,I))continue;const w=Qs(o,u,I);!w||h.includes(w.id)||h.push(w.id)}return h}function $a(e,t,s){if(!vn(e.authoritativeMessages,s))return t;const n=on(s);return t.includes(n)?t:[...t,n]}function vn(e,t){return pi(t)?!hi(e.at(-1)??null,t):!1}function hi(e,t){return!e||Wt(t,e)?!1:Va(t,e)<0}function Va(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 Ga(e,t,s){if(s.length===0)return s;const n=new Map(t.map(o=>[on(o),o])),r=e.at(-1)??null,a=s.filter(o=>{const u=n.get(o)??null;if(!u)return!1;const d=vn(e,u);return d||rs("timeline.runtime_overlay_tail_deactivated",{overlay:ve(u),latestAuthoritative:r?ve(r):null}),d});return a.length===s.length?s:a}function Qs(e,t,s){const n=e.get(s.id)??null,r=fi(e,t,s,n);if(r)return e.get(r)??null;if(n)return n;const a=pn(e,t,s);if(a)return e.get(a)??null;const o=mn(e,s);return o?e.get(o)??null:null}function fi(e,t,s,n){const r=Xa(e,t,s),a=pn(e,t,s),o=mn(e,s),u=r??a??o;if(!u)return null;if(!n)return u;const d=e.get(u)??null;return!d||!za(n,d,s)?null:u}function Xa(e,t,s){if(s.role!=="assistant"||s.kind!=="text"&&s.kind!=="thinking"||s.deliveryState!=="sent"||!s.rawRef.startsWith("codex://"))return null;const n=us(s.rawRef);if(!n)return null;for(const[r,a]of e.entries()){if(r===s.id||!t.has(r)||a.role!==s.role||a.kind!==s.kind||a.deliveryState!=="sent"||!a.rawRef.startsWith("codex://"))continue;const o=us(a.rawRef),u=Math.abs(a.sequence-s.sequence),d=o===n;if(!(!o||Vt(a,s)<0||!d&&u>ri||!ci(a,s,Gs)))return Qe("session.messages.codex_runtime_overlay_bridge_match",{bridgeMode:d?"same_store":"cross_store_sequence_window",sequenceDistance:u,previous:ve(a),incoming:ve(s)}),r}return null}function za(e,t,s){return!Wt(e,s)||!Wt(t,s)?!1:!hs(e,s)&&hs(t,s)}function pi(e){return e.role==="assistant"&&(e.kind==="text"||e.kind==="thinking")||e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")}function hs(e,t){if(e.role!==t.role||e.kind!==t.kind&&!(Is(e,t)||Ms(e,t)))return!1;const s=ii(e,{...t,id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId});return Gn(s)===Gn(e)}function Gn(e){const t=e.kind==="text"||e.kind==="thinking"?Ge(Et(e.content).text):Ge(e.content);return JSON.stringify({role:e.role,kind:e.kind,content:t,attachments:ds(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 _s(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 Zs(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(o=>!s.has(o.id));return e.slice(-n.length).some(o=>!s.has(o.id))?!1:Zs(r)&&Zs(n)}}for(let s=1;s<e.length;s+=1)if(Vt(e[s-1],e[s])>0)return!1;return!0}function mi(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 Ya(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 Ka(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 Qa(e,t,s){const n=new Map(e.map((h,f)=>[h.id,f])),r=new Map(t.map((h,f)=>[h.id,f])),a=new Map(e.map(h=>[h.id,h])),o=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=a.get(h)??null,I=o.get(h)??null,T=I??f;if(!T||T.role!==s)continue;const w=n.get(h)??null,g=r.get(h)??null;w!==g&&d.push({messageId:h,fromIndex:w,toIndex:g,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 gi(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:Za(e.content)}}function Xn(e){return e.map(t=>gi(t))}function Za(e){const t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}...`:t}function Fe(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 js(e,t){return Nr({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 vi(e){const t=e==null?void 0:e.messageCount;return typeof t=="number"&&Number.isFinite(t)?t:null}function Ja(e,t){const s=Vo(e),n=vi(t);return n===null?s:Math.max(s,n+1)}function el(e,t){const s=tl(t);if(!s)return!1;const n=sl(e);return n?bn(s.sequence,s.timestamp,n.sequence,n.timestamp)>=0:!0}function tl(e){let t=null;for(const s of e)(!t||bn(s.sequence,s.timestamp,t.sequence,t.timestamp)>0)&&(t=s);return t}function sl(e){let t=null;for(const s of e)s.deliveryState==="sent"&&(!t||bn(s.sequence,s.timestamp,t.sequence,t.timestamp)>0)&&(t=s);return t}function bn(e,t,s,n){return e!==s?e-s:t.localeCompare(n)}function nl(e,t){return t>0?"ready":"loading"}function rl(e,t){const s=vi(e);return s!==null?s>t:t>=Ht}function Pt(e){return e.olderCursor?!0:e.pagesLoaded>1?e.currentHasOlderMessages:rl(e.session,e.loadedMessageCount)}function ot(e,t){return e&&{...e,runningState:t,activityState:wi(e,t,e.completedAt??null,Je(t))}}function zn(e,t){return!e||e.lastSeenAt&&e.lastSeenAt>=t?e:{...e,lastSeenAt:t,activityState:e.activityState==="completed_unread"?"idle":e.activityState}}function Yn(e,t){return bi(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 il(e,t){return bi(e,t)}function bi(e,t){if(!e)return e;const s=ol(t.activityResolutionSource),n=Ut(t.runningState)?Ls(e.completedAt,t.updatedAt):null,r=t.runningState==="completed"||t.runningState==="interrupted"||t.runningState==="failed"?Ls(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:Ls(e.updatedAt,t.updatedAt)??t.updatedAt,activityState:wi(e,t.runningState,n,t.hasActiveRun)}}function wi(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 Kn(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 Qn(e,t){return e==="session.backfill"?t??"idle":t==="completed"||t==="interrupted"||t==="failed"?t:"running"}function Ns(e,t){return Ut(e)?e:t}function Os(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 ol(e){return e==="authoritative_runtime"||e==="authoritative_provider_event"?"runtime":e==="inferred_log"?"inferred":"none"}function al(e){return e.provider==="codex"&&(e.role==="assistant"||e.role==="tool")}function ll(e){return e.rawRef.startsWith("codex://")&&e.deliveryState==="sent"&&(e.role==="assistant"||e.role==="tool")}function cl(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:Ii(e.content,e.kind??"text")}}function Zn(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:Ii(e.content,e.kind)}}function Jn(e){const t=new Map;for(const n of e){if(!ll(n))continue;const r=ul(n),a=t.get(r);if(a){a.push(n);continue}t.set(r,[n])}const s=[];for(const[n,r]of t.entries()){const a=[...r].sort((u,d)=>u.sequence!==d.sequence?u.sequence-d.sequence:u.timestamp.localeCompare(d.timestamp));let o=[];for(const u of a){const d=o.at(-1)??null;if(!d||dl(d,u)){o.push(u);continue}o.length>1&&s.push({signature:n,messages:o.map(Zn)}),o=[u]}o.length>1&&s.push({signature:n,messages:o.map(Zn)})}return s}function ul(e){var r,a;if(e.kind==="tool_call"||e.kind==="tool_result")return[e.role,e.kind,((r=e.toolCall)==null?void 0:r.callId)??"",((a=e.toolCall)==null?void 0:a.name)??""].join(":");const t=Et(e.content),s=Js(t.text),n=t.inlineImages.map(o=>o.url).join("|");return[e.role,e.kind,s,n].join(":")}function dl(e,t){const s=er(e.timestamp),n=er(t.timestamp);return Math.abs(s-n)<=120*1e3&&Math.abs(e.sequence-t.sequence)<=8}function Ii(e,t){return t==="text"||t==="thinking"?Js(Et(e).text).slice(0,160):Js(e).slice(0,160)}function Js(e){return e.replace(/\r\n/g,`
7
+ `).trimEnd()}function er(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ls(e,t){return e?t?e>=t?e:t:e:t??null}function tr(){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 Mi(e,t){return t&&(!e||e.provider===t.provider)?t:null}function sr(e,t){const s=Mi(e,t);return s?!!s.canSendMessage:e?Or(e.provider):!1}function nr(e,t){const s=Mi(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 hl(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 Ds(e,t,s){return s?!0:e===!0&&Je(t)}function Hs(e,t,s,n){return n?!0:e===!0&&(s||Je(t))}function qs(e,t){const s=t==null?void 0:t.trim();return s?`session-runtime.snapshot.host.${encodeURIComponent(s)}.${e}`:`session-runtime.snapshot.${e}`}function rr(e){return e.filter(t=>t.deliveryState==="sent").slice(-ni)}function fl(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 Bs(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 Zt(e,t){if(!e)return t;if(!t||ir(e,t)||or(e,t))return e;if(ir(t,e)||or(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 ir(e,t){return ar(e)&&!ar(t)&&e.lastEventAt===t.lastEventAt&&e.lastMessageAt===t.lastMessageAt&&e.completedAt===t.completedAt}function or(e,t){if(!lr(e)||lr(t))return!1;const s=e.completedAt??e.lastEventAt??null;return s?(!t.lastEventAt||t.lastEventAt<=s)&&(!t.completedAt||t.completedAt<=s):!1}function ar(e){return e.activityState==="running"||Je(e.runningState)}function lr(e){return Ut(e.runningState)}const pl="workbench:focus-composer",ml=15e3,gl=320;function Si(){typeof window>"u"||window.dispatchEvent(new CustomEvent(pl))}function yi(e){var ke,ie,Ae,Xe;const t=l.useRef(null),s=l.useRef(null),n=l.useRef(null),[r,a]=l.useState(!1),[o,u]=l.useState(null),[d,h]=l.useState(null),[f,I]=l.useState(null),[T,w]=l.useState(null),g=gt(),{showToast:m}=g,R=g.dismissToast??(()=>{}),H=Go(E=>E.notificationPreferences.notifyOnPermissionRequest),N=_t(),C=an(),M=l.useRef(null),y=l.useRef(null),b=l.useRef(null),F=l.useRef(((ke=e.externalSession)==null?void 0:ke.runningState)??null),k=l.useRef(new Set),S=((ie=e.targetHostId)==null?void 0:ie.trim())||null;(!t.current||s.current!==e.sessionId||n.current!==S)&&((Ae=t.current)==null||Ae.destroy(),t.current=new Ra(e.sessionId,{targetHostId:S,initialSession:e.externalSession,bootstrapMessages:e.bootstrapMessages??[],onSeen:e.onSeen}),s.current=e.sessionId,n.current=S);const v=t.current,x=Fe(v,E=>E.session),K=Fe(v,E=>E.capabilities),$=Fe(v,E=>E.runtimeHasActiveRun),J=Fe(v,E=>E.runtimeCanInterrupt),re=Fe(v,E=>E.messages),G=Fe(v,E=>E.timelineItems),j=Fe(v,E=>E.permissionRequests),A=Fe(v,E=>E.queuedMessages),O=Fe(v,E=>E.contextUsage),Q=Fe(v,E=>E.historyState),oe=Fe(v,E=>E.errorCode),V=Fe(v,E=>E.errorDetail),Y=Fe(v,E=>E.interruptSource),ae=Fe(v,E=>E.loadingOlderMessages),le=Fe(v,E=>E.hasOlderMessages),me=Fe(v,E=>E.connectionState),L=Cr(x),X=r&&!T,B=L||$===!0||X?!0:$,he=J===!0||X?!0:J,pe=L||X,Ee=(x==null?void 0:x.provider)===(K==null?void 0:K.provider)&&Xo(K),Le=A.some(E=>E.status==="queued"||E.status==="dispatching"),De=x??e.externalSession??null,Pe=wl({sessionId:e.sessionId,provider:(x==null?void 0:x.provider)??null,runningState:(x==null?void 0:x.runningState)??null,activityState:(x==null?void 0:x.activityState)??null,runtimeHasActiveRun:$,messages:re}),W=e.enableThinkingPlaceholder===!1||!Pe?null:c("conversation.runtimeThinkingPlaceholder",{provider:c("conversation.providerCodex")}),ee=l.useMemo(()=>zo(G,W),[G,W]);wa({sending:r,setSending:a,session:x,runtimeHasActiveRun:$,runtimeCanInterrupt:J}),l.useEffect(()=>{v.applyNavigationSession(e.externalSession)},[e.externalSession,v]),l.useEffect(()=>(v.initialize(),()=>{v.destroy(),t.current===v&&(t.current=null)}),[v]),l.useEffect(()=>{w(null),k.current.clear()},[e.sessionId]),l.useEffect(()=>{if(e.onBindSessionWorkspace)return e.onBindSessionWorkspace(e.sessionId,(x==null?void 0:x.workspaceId)??null),()=>{var E;(E=e.onBindSessionWorkspace)==null||E.call(e,e.sessionId,null)}},[e.onBindSessionWorkspace,e.sessionId,x==null?void 0:x.workspaceId]),l.useEffect(()=>{if(e.enableCompletionHaptics===!1)return;const E=F.current,D=(x==null?void 0:x.runningState)??null;(E==="starting"||E==="running"||E==="reconnecting")&&D==="completed"&&C.trigger("success"),F.current=D},[C,e.enableCompletionHaptics,x==null?void 0:x.runningState]),l.useEffect(()=>{var _e;if((e.permissionRequestNotificationMode??"always")==="current_only"&&!e.isCurrent)return;const D=j.filter(ye=>ye.status==="pending"),be=(x==null?void 0:x.workspaceId)??((_e=e.externalSession)==null?void 0:_e.workspaceId)??null;for(const ye of D)k.current.has(ye.id)||(k.current.add(ye.id),H&&(m({id:`${e.permissionToastIdPrefix??"permission-request"}-${ye.id}`,title:c("conversation.permissionRequestToastTitle"),description:ye.title,tone:"warning",durationMs:8e3,action:be&&e.onNavigateToSession?{label:c("shell.contextOpenSession"),onClick:()=>{var ge;(ge=e.onNavigateToSession)==null||ge.call(e,be,e.sessionId)}}:void 0}),N.bridge.showNotification(c("conversation.permissionRequestToastTitle"),ye.title)))},[(Xe=e.externalSession)==null?void 0:Xe.workspaceId,e.isCurrent,e.onNavigateToSession,e.permissionRequestNotificationMode,e.permissionToastIdPrefix,e.sessionId,H,j,N.bridge,x==null?void 0:x.workspaceId,m]),l.useEffect(()=>{if(e.enableRuntimeErrorHandling!==!1)return()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)}},[e.enableRuntimeErrorHandling]),l.useEffect(()=>{var E;e.enableRuntimeErrorHandling!==!1&&(oe!=="SESSION_NOT_FOUND"&&oe!=="WORKSPACE_NOT_FOUND"||(R("conversation-runtime-error"),(E=e.onResolveMissingSession)==null||E.call(e)))},[R,e.enableRuntimeErrorHandling,e.onResolveMissingSession,oe]),l.useEffect(()=>{if(e.enableRuntimeErrorHandling===!1)return;if(oe==="SESSION_NOT_FOUND"||oe==="WORKSPACE_NOT_FOUND"){b.current!==null&&(window.clearTimeout(b.current),b.current=null),y.current=null,M.current=null,R("conversation-runtime-error");return}if(!oe||!V){b.current!==null&&(window.clearTimeout(b.current),b.current=null),y.current=null,M.current=null,R("conversation-runtime-error");return}const E=`${oe}:${V}`;if(!(M.current===E||y.current===E)){if(b.current!==null&&(window.clearTimeout(b.current),b.current=null),bl((x==null?void 0:x.provider)??null,oe,V)){y.current=E,b.current=window.setTimeout(()=>{y.current=null,b.current=null,M.current=E,m({id:"conversation-runtime-error",title:c("conversation.runtimeErrorTitle"),description:V,tone:"error",durationMs:null})},ml);return}y.current=null,M.current=E,m({id:"conversation-runtime-error",title:c("conversation.runtimeErrorTitle"),description:V,tone:"error",durationMs:null})}},[R,e.enableRuntimeErrorHandling,oe,V,x==null?void 0:x.provider,m]);const U=l.useCallback(async(E,D)=>{var ye,ge,Ie,fe,Ue,de,ze;const be=T;if(!be){await v.sendMessage(E,{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}),(ye=e.onRequestNavigationRefresh)==null||ye.call(e);return}let _e=null;try{_e=await Pr(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}),(ge=e.onUpsertNavigationSession)==null||ge.call(e,_e),await rn(_e.sessionId,{content:E,clientRequestId:vl(),model:be.targetModel,reasoningLevel:(D==null?void 0:D.reasoningLevel)??null,permissionMode:It(),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),(Ie=e.onRequestNavigationRefresh)==null||Ie.call(e),(fe=e.onNavigateToSession)==null||fe.call(e,_e.workspaceId,_e.sessionId),(Ue=e.onForkSuccess)==null||Ue.call(e,_e)}catch(He){throw _e&&((de=e.onUpsertNavigationSession)==null||de.call(e,_e),(ze=e.onRequestNavigationRefresh)==null||ze.call(e)),He}},[T,e,v]),_=l.useCallback(async(E,D)=>{a(!0);try{await U(E,D)}finally{a(!1)}},[U]),ue=l.useCallback(async(E,D)=>{a(!0);try{T?await U(E,D):await v.enqueueMessage(E,{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{a(!1)}},[T,U,v]),ce=l.useCallback(async(E,D)=>{u(E);try{await v.replyPermissionRequest(E,D)}catch(be){m({title:c("conversation.permissionRequestReplyFailed"),description:be instanceof Error?be.message:void 0,tone:"error"})}finally{u(null)}},[m,v]),je=l.useCallback(async E=>{h(E);try{await v.deleteQueuedMessage(E)}finally{h(null)}},[v]),Ne=l.useCallback(async E=>{var D;I(E);try{await v.steerQueuedMessage(E),(D=e.onRequestNavigationRefresh)==null||D.call(e)}finally{I(null)}},[e.onRequestNavigationRefresh,v]),te=l.useCallback(async()=>{var E;await v.interrupt(),(E=e.onRequestNavigationRefresh)==null||E.call(e)},[e.onRequestNavigationRefresh,v]);return{session:De,capabilities:K,runtimeHasActiveRun:$,runtimeCanInterrupt:J,messages:re,timelineItems:ee,permissionRequests:j,queuedMessages:A,contextUsage:O,historyState:Q,runtimeErrorCode:oe,runtimeErrorDetail:V,runtimeInterruptSource:Y,loadingOlderMessages:ae,hasOlderMessages:le,connectionState:me,sending:r,replyingPermissionRequestId:o,deletingQueueItemId:d,steeringQueueItemId:f,forkDraft:T,setForkDraft:w,composerHasActiveRun:B,composerCanInterrupt:he,composerIsRunning:pe,canSteerQueuedMessage:Ee,hasPendingQueuedMessages:Le,reconnect:v.reconnect.bind(v),loadOlderMessages:v.loadOlderMessages.bind(v),retryMessage:v.retryMessage.bind(v),send:_,queue:ue,interrupt:te,replyPermissionRequest:ce,deleteQueuedMessage:je,steerQueuedMessage:Ne}}function vl(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function bl(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 wl(e){const t=Il(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)},gl))},[t,s]),l.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),s}function Il(e){const{provider:t,runningState:s,activityState:n,runtimeHasActiveRun:r,messages:a}=e;if(t!=="codex")return"hide_immediately";const o=yl(a);return o<0||Sl(a,o)?"hide_immediately":Ml(s,n,r)?"show":"hide_deferred"}function Ml(e,t,s){return s===!0||t==="running"||e==="starting"||e==="running"||e==="reconnecting"}function Sl(e,t){return e.slice(t+1).some(s=>s.role==="assistant"&&(s.kind==="text"||s.kind==="thinking"))}function yl(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 xl=1.5,Pl=24,Rl=72,kl=296,Tl=16,cr={2:496,3:408,4:344};function xi(e){return cr[e]??cr[4]}function Cl({memberCount:e,currentWidth:t,monitorWidth:s}){if(e<2||t<=0||s<=0)return t;const n=kl,r=Math.max(0,e-1)*Tl,a=Math.max(0,(t-n-r)/e),o=xi(e);if(a>=o)return t;const u=n+r+e*o,d=Math.min(t*xl,Math.max(t,s-Rl)),h=Math.min(Math.max(t,u),d);return h<=t+Pl?t:h}const El=240,ur=920,dr=760,wn=360,In=320,Ve=16,hr=428,Al=404,ct=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)??wn,s),a=Math.min((t==null?void 0:t.minHeight)??In,n),o=Math.max(r,s),u=Math.max(a,n),d=Math.min(Math.max(e.width,r),o),h=Math.min(Math.max(e.height,a),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 _l(e){if(typeof window>"u")return{x:Ve,y:Ve,width:ur,height:dr};const t=Math.min(ur,Math.max(wn,window.innerWidth-Ve*2)),s=Math.min(dr,Math.max(In,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 jl(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(wn,e.width),minHeight:Math.min(In,e.height)})}function Nl(e){if(typeof window>"u")return{x:ct,y:ct,width:hr};const t=Math.min(hr,Math.max(Al,window.innerWidth-ct*2));return{x:Math.min(Math.max(((e==null?void 0:e.right)??window.innerWidth-ct)-t,ct),Math.max(ct,window.innerWidth-t-ct)),y:Math.max(ct,((e==null?void 0:e.bottom)??ct)+8),width:t}}function Ol({groupId:e,currentSessionId:t}){var ae,le,me;const s=vt(),n=_t(),r=Yo(n),{showToast:a}=gt(),{navigationGroups:o,requestNavigationRefresh:u,currentTargetHostId:d}=yt(),h=l.useMemo(()=>$t(o),[o]),f=l.useMemo(()=>new Map(h.map(L=>[L.session.sessionId,L])),[h]),I=l.useMemo(()=>vs(h),[h]),T=l.useMemo(()=>{const L=new Map,X=B=>{for(const he of B)L.set(he.item.session.sessionId,he),X(bs(he))};return X(I),L},[I]),w=l.useMemo(()=>ln(o),[o]),[g,m]=l.useState(null),[R,H]=l.useState(!0),[N,C]=l.useState(null),[M,y]=l.useState(null),[b,F]=l.useState(null),[k,S]=l.useState(null),[v,x]=l.useState(null),[K,$]=l.useState(!1),J=l.useRef(null),re=l.useRef(null);l.useEffect(()=>{let L=!1;async function X(){H(!0),C(null);try{const B=await Ko(e);if(L)return;m(B)}catch(B){if(L)return;C(B instanceof Error?B.message:c("shell.parallelGroupLoadFailed"))}finally{L||H(!1)}}return X(),()=>{L=!0}},[e]),l.useEffect(()=>{const L=no(e);L&&O(L)},[e]),l.useEffect(()=>()=>{re.current!==null&&window.clearTimeout(re.current)},[]);const G=l.useMemo(()=>g?g.members.slice().sort((L,X)=>L.member.ordinal-X.member.ordinal).map(L=>{const X=f.get(L.session.sessionId),B=(X==null?void 0:X.session)??L.session;return{session:B,workspaceId:(X==null?void 0:X.workspace.id)??ss(B,L.sessionIsolatedWorkspace),ordinal:L.member.ordinal,memberPrompt:L.member.memberPrompt,model:L.member.model,sessionIsolatedWorkspace:L.sessionIsolatedWorkspace,subagentTree:$l(B.sessionId,g.group.id,T)}}):[],[g,f,T]);l.useEffect(()=>{if(!n.isDesktop||n.ui.osFamily!=="macos"&&n.ui.osFamily!=="windows"||G.length<2)return;const L=`${e}:${G.length}`;if(J.current===L)return;J.current=L;let X=!1;async function B(){try{const he=await Rn(()=>import("./window-BVUB8gMK.js").then(ce=>ce.w),__vite__mapDeps([0,1])),pe=await Rn(()=>import("./window-BVUB8gMK.js").then(ce=>ce.d),__vite__mapDeps([0,1])),Ee=he.getCurrentWindow(),Le=await Ee.innerSize(),De=await Ee.scaleFactor(),Pe=await he.currentMonitor();if(X||De<=0)return;const W=Le.width/De,ee=Le.height/De,U=Pe?Pe.workArea.size.width/Pe.scaleFactor:W*1.5,_=Cl({memberCount:G.length,currentWidth:W,monitorWidth:U});if(_<=W+24)return;const ue=10;await new Promise(ce=>window.setTimeout(ce,56));for(let ce=1;ce<=ue;ce+=1){if(X)return;const je=ce/ue,Ne=1-Math.pow(1-je,3),te=W+(_-W)*Ne;await Ee.setSize(new pe.LogicalSize(te,ee)),await new Promise(ke=>window.setTimeout(ke,El/ue))}}catch{return}}return B(),()=>{X=!0}},[e,G.length,n.isDesktop,n.ui.osFamily]);async function j(L){F(L);try{const X=await Qo(L);await u(),m(B=>B&&{...B,members:B.members.map(he=>{var pe;return((pe=he.sessionIsolatedWorkspace)==null?void 0:pe.id)===L?{...he,sessionIsolatedWorkspace:{...he.sessionIsolatedWorkspace,workspaceId:X.workspace.id,lifecycleStatus:"promoted",promotedAt:X.record.promotedAt}}:he})}),a({title:c("shell.parallelWorkspacePromotedBadge"),tone:"success"})}catch(X){a({title:X instanceof Error?X.message:c("shell.parallelGroupLoadFailed"),tone:"error"})}finally{F(null)}}async function A(L){if(k)return;const X=L.trim();if(!X)return;const B=G.find(pe=>pe.session.sessionId!==X)??null,he=(g==null?void 0:g.group.workspaceId)??(B==null?void 0:B.workspaceId)??null;S(X);try{await Dr(X),Ws(X,null),y(pe=>pe===X?null:pe),m(pe=>pe&&{...pe,members:pe.members.filter(Ee=>Ee.session.sessionId!==X)}),await u(),t===X&&(B?s($e(B.workspaceId,B.session.sessionId)):he&&s(wt(he))),a({title:c("shell.deleteSessionSuccess"),tone:"success"})}catch(pe){a({title:pe instanceof Error?pe.message:c("shell.deleteSessionFailed"),tone:"error"})}finally{S(null)}}function O(L){x(L),re.current!==null&&window.clearTimeout(re.current),re.current=window.setTimeout(()=>{x(null),re.current=null},L.totalDurationMs)}if(R&&!g)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(N&&!g)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:N})]})});if(G.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 Q=((ae=w[(g==null?void 0:g.group.workspaceId)??""])==null?void 0:ae.displayName)??(g==null?void 0:g.group.workspaceId)??c("common.unknown"),oe=G.find(L=>L.session.sessionId===(g==null?void 0:g.group.anchorSessionId))??G[0]??null,V=G.length<4,Y={"--parallel-pane-min-width":`${xi(G.length)}px`,...v?{"--parallel-pane-enter-delay":`${v.paneEnterDelayMs}ms`,"--parallel-pane-enter-duration":`${v.paneEnterDurationMs}ms`,"--parallel-grid-reveal-delay":`${v.gridRevealDelayMs}ms`,"--parallel-grid-reveal-duration":`${v.gridRevealDurationMs}ms`,"--parallel-shell-expand-duration":`${v.shellExpandDurationMs}ms`,"--parallel-pane-stagger-delay":`${v.paneStaggerMs}ms`}:{}};return i.jsxs("main",{className:"workbench-page conversation-page-shell parallel-conversation-page","data-parallel-count":G.length,"data-parallel-entering":v?"true":void 0,style:Y,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:((le=g==null?void 0:g.group.sharedPrompt)==null?void 0:le.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:!V,onClick:()=>{V&&$(!0)},children:i.jsx("span",{"aria-hidden":"true",children:"+"})})]})}),i.jsx("div",{className:"parallel-conversation-grid",children:G.map(L=>{const X=w[L.workspaceId]??cn({id:L.workspaceId,name:L.session.workspaceId,path:L.session.workspaceId,repoRoot:L.session.workspaceId});return i.jsx(Ll,{entry:L,isCurrent:L.session.sessionId===t||Xt(L.subagentTree,t),routeCurrentSessionId:t,workspaceContext:X,infoOpen:M===L.session.sessionId,promotingWorkspaceId:b,onCloseInfo:()=>{y(null)},onToggleInfo:()=>{y(B=>B===L.session.sessionId?null:L.session.sessionId)},onPromoteWorkspace:j,onRemoveSession:A,removingSessionId:k},L.session.sessionId)})}),i.jsx($s,{open:K,source:g?{kind:"group",groupId:g.group.id,workspaceId:g.group.workspaceId,workspaceName:Q,sharedPrompt:((me=g.group.sharedPrompt)==null?void 0:me.trim())||"",currentMemberCount:G.length,defaultProvider:(oe==null?void 0:oe.session.provider)??"codex"}:null,targetHostId:d,onClose:()=>$(!1),onCreated:async L=>{m(L),$(!1),O(so("append")),await u(),a({title:c("shell.parallelAppendSucceeded"),tone:"success"})}})]})}function Ll({entry:e,isCurrent:t,routeCurrentSessionId:s,workspaceContext:n,infoOpen:r,onCloseInfo:a,onToggleInfo:o,onPromoteWorkspace:u,promotingWorkspaceId:d,onRemoveSession:h,removingSessionId:f}){var zt,Yt,jt,Nt,xt,Kt,Ot;const I=vt(),T=_t(),{showToast:w}=gt(),{navigationGroups:g,requestNavigationRefresh:m,setSessionWorkspace:R,upsertNavigationSession:H,markNavigationSessionSeen:N,selectWorkspace:C}=yt(),M=e.session.sessionId,[y,b]=l.useState(()=>Vl(e,s)),F=l.useMemo(()=>new Map($t(g).map(q=>[q.session.sessionId,q])),[g]),k=y===M?e.session:((zt=F.get(y))==null?void 0:zt.session)??Ri(e.subagentTree,y)??e.session,S=y===M?e.workspaceId:((Yt=F.get(y))==null?void 0:Yt.workspace.id)??ki(e.subagentTree,y)??e.workspaceId,v=k.sessionId,[x,K]=l.useState(!1),[$,J]=l.useState("files"),[re,G]=l.useState(!1),[j,A]=l.useState(null),[O,Q]=l.useState(null),oe=l.useRef(null),V=l.useRef(null),Y=l.useRef(null),ae=l.useRef(null),le=l.useRef(null),me=l.useRef(null),[L,X]=l.useState(()=>kn(M)),{session:B,capabilities:he,messages:pe,timelineItems:Ee,permissionRequests:Le,queuedMessages:De,contextUsage:Pe,historyState:W,runtimeInterruptSource:ee,loadingOlderMessages:U,hasOlderMessages:_,connectionState:ue,sending:ce,replyingPermissionRequestId:je,deletingQueueItemId:Ne,steeringQueueItemId:te,forkDraft:ke,setForkDraft:ie,composerHasActiveRun:Ae,composerCanInterrupt:Xe,composerIsRunning:E,canSteerQueuedMessage:D,hasPendingQueuedMessages:be,reconnect:_e,loadOlderMessages:ye,retryMessage:ge,send:Ie,queue:fe,interrupt:Ue,replyPermissionRequest:de,deleteQueuedMessage:ze,steerQueuedMessage:He}=yi({sessionId:v,externalSession:k,onSeen:(q,ne)=>{N(q,ne)},onRequestNavigationRefresh:m,onUpsertNavigationSession:H,onNavigateToSession:(q,ne)=>{C(q),I($e(q,ne))},onBindSessionWorkspace:y===M?R:void 0,onResolveMissingSession:()=>{m()},permissionRequestNotificationMode:"current_only",permissionToastIdPrefix:"parallel-permission-request",isCurrent:t,enableRuntimeErrorHandling:!0,enableCompletionHaptics:!1,enableThinkingPlaceholder:!0,enableForkTimelineSanitizer:!0}),dt=ro((B==null?void 0:B.parallelGroup)??e.session.parallelGroup),Ze=io({groupId:((jt=(B==null?void 0:B.parallelGroup)??e.session.parallelGroup)==null?void 0:jt.groupId)??"parallel-group",ordinal:e.ordinal,overrideColor:L}),ht=oo((B==null?void 0:B.parallelGroup)??e.session.parallelGroup),Te=(B==null?void 0:B.sessionIsolatedWorkspace)??e.sessionIsolatedWorkspace,ft=ao(Te),pt=((Nt=Pe==null?void 0:Pe.modelId)==null?void 0:Nt.trim())||((xt=e.model)==null?void 0:xt.trim())||c("shell.parallelPaneModelFallback"),at=((Kt=e.memberPrompt)==null?void 0:Kt.trim())||c("shell.parallelPanePromptFallback"),bt=S,Oe=Mr(B??k,Te),lt=Oe===bt?(n==null?void 0:n.displayName)??bt:ft??at,et=l.useMemo(()=>{var q;return((q=g.find(ne=>ne.workspace.id===Oe))==null?void 0:q.workspace.path)??null},[g,Oe]),p=f===v;async function z(q){await Ie(Object.entries(q.answers).map(([,ne])=>ne.filter(Boolean).join(" / ")).filter(Boolean).join(`
8
+ `))}const se=r&&O?{...qt(n)??{},...dt??{},...Ze,left:`${O.x}px`,top:`${O.y}px`,width:`${O.width}px`}:void 0,Me=x&&j?{...qt(n)??{},...dt??{},...Ze,left:`${j.x}px`,top:`${j.y}px`,width:`${j.width}px`,height:`${j.height}px`}:void 0;l.useEffect(()=>{X(kn(M)),K(!1),G(!1),A(null),Q(null),J("files")},[M]),l.useEffect(()=>{if(Xt(e.subagentTree,s)){b(s);return}if(s===M){b(M);return}b(q=>Gl(e,q)?q:M)},[e,M,s]),l.useEffect(()=>{if(!r)return;const q=ne=>{var Ye,nt,rt;const st=ne.target;st instanceof HTMLElement&&((Ye=V.current)!=null&&Ye.contains(st)||(nt=ae.current)!=null&&nt.contains(st)||(rt=le.current)!=null&&rt.contains(st)||a())};return window.addEventListener("pointerdown",q),()=>{window.removeEventListener("pointerdown",q)}},[r,a]),l.useEffect(()=>{if(!r){Q(null);return}const q=()=>{var ne;Q(Nl(((ne=Y.current)==null?void 0:ne.getBoundingClientRect())??null))};return q(),window.addEventListener("resize",q),window.addEventListener("scroll",q,!0),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0)}},[r]),l.useEffect(()=>{if(!x)return;const q=()=>{A(ne=>ne&&Bt(ne))};return window.addEventListener("resize",q),()=>{window.removeEventListener("resize",q)}},[x]);async function qe(){if(!T.isDesktop||!T.bridge.supported)return;if($==="files"){const ne=await Zo(T,{workspaceId:Oe,workspaceName:lt,sessionId:v,focusOwner:"file-context-panel"});ne.ok||w({title:ne.detail??c("conversation.filePanelOpenExternalFailed"),tone:"error"});return}if($==="git"){const ne=await Jo(T,{workspaceId:Oe,workspaceName:lt,focusOwner:"git-sidebar"});ne.ok||w({title:ne.detail??c("git.openExternalFailed"),tone:"error"});return}const q=await ea(T,{workspaceId:Oe,workspaceName:lt,focusOwner:"terminal-manager-panel"});q.ok||w({title:q.detail??c("terminalManager.openExternalFailed"),tone:"error"})}function We(){var q,ne;K(!0),A(jl(((q=oe.current)==null?void 0:q.getBoundingClientRect())??null)??_l(((ne=me.current)==null?void 0:ne.getBoundingClientRect())??null))}function Ce(q){if(q.button!==0||!j)return;q.preventDefault();const ne=q.clientX,st=q.clientY,Ye=j,nt=mt=>{A(Bt({...Ye,x:Ye.x+(mt.clientX-ne),y:Ye.y+(mt.clientY-st)}))},rt=()=>{window.removeEventListener("pointermove",nt),window.removeEventListener("pointerup",rt)};window.addEventListener("pointermove",nt),window.addEventListener("pointerup",rt)}function Be(q){if(q.button!==0||!j)return;q.preventDefault(),q.stopPropagation();const ne=q.clientX,st=q.clientY,Ye=j,nt=mt=>{A(Bt({...Ye,width:Ye.width+(mt.clientX-ne),height:Ye.height+(mt.clientY-st)}))},rt=()=>{window.removeEventListener("pointermove",nt),window.removeEventListener("pointerup",rt)};window.addEventListener("pointermove",nt),window.addEventListener("pointerup",rt)}const Re=x&&typeof document<"u"?St.createPortal(i.jsxs("div",{ref:le,className:"parallel-pane-tools-popover","data-parallel-pane-layer":v,"data-pinned":re?"true":void 0,"data-workspace-tone":(n==null?void 0:n.tone)??"root",style:Me,children:[i.jsxs("div",{className:"parallel-pane-tools-toolbar",children:[i.jsxs("div",{className:"parallel-pane-tools-drag-handle",onPointerDown:Ce,children:[i.jsx("span",{className:"parallel-pane-tools-drag-dots","aria-hidden":"true",children:i.jsx(ql,{})}),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"].map(q=>i.jsx("button",{type:"button",role:"tab","aria-selected":$===q,className:"parallel-pane-tools-tab",onClick:()=>{J(q)},children:q==="files"?c("shell.filesEntry"):q==="git"?c("shell.gitEntry"):c("shell.parallelPaneProcessesEntry")},q))}),i.jsxs("div",{className:"parallel-pane-tools-actions",children:[i.jsx("button",{type:"button",className:`conversation-header-ai-button${re?" active":""}`,"aria-label":c("shell.parallelPanePinAction"),title:c("shell.parallelPanePinAction"),"aria-pressed":re,onClick:()=>{G(q=>!q)},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Bl,{})})}),T.isDesktop&&T.bridge.supported?i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelPaneDetachAction"),title:c("shell.parallelPaneDetachAction"),onClick:()=>{qe()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Fl,{})})}):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(Wl,{})})})]})]}),i.jsx("div",{className:"parallel-pane-tools-body","data-panel":$,children:$==="files"?i.jsx(zr,{className:"parallel-pane-tools-surface",hideHeading:!0,sessionId:v,workspaceId:Oe}):$==="git"?i.jsx(Yr,{className:"parallel-pane-tools-surface",panelActive:!0,workspaceId:Oe}):i.jsx(Kr,{className:"parallel-pane-tools-surface parallel-pane-tools-process-panel",currentWorkspaceId:Oe,navigationGroups:g})}),i.jsx("button",{type:"button",className:"parallel-pane-tools-resize-handle","aria-label":c("shell.parallelPaneResizeAction"),title:c("shell.parallelPaneResizeAction"),onPointerDown:Be,children:i.jsx("span",{"aria-hidden":"true",children:i.jsx(Ul,{})})})]}),document.body):null,tt=r&&typeof document<"u"?St.createPortal(i.jsxs("div",{ref:ae,className:"parallel-pane-info-popover","data-parallel-pane-layer":v,"data-workspace-tone":(n==null?void 0:n.tone)??"root",style:se,children:[i.jsx("strong",{className:"parallel-pane-info-title",children:c("shell.parallelPaneInfoTitle")}),i.jsx(kt,{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((B??e.session).provider,"full")})]}),i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.parallelPaneModelFallback")}),i.jsx("dd",{children:pt})]}),i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.parallelPaneIsolatedWorkspaceTitle")}),i.jsx("dd",{children:ft??c("common.unknown")})]})]})}),i.jsx(kt,{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:()=>{Ws(M,null),X(null)},children:c("shell.parallelPaneColorPaletteReset")}),children:i.jsx("div",{className:"workbench-manage-color-palette parallel-pane-color-palette","aria-label":c("shell.parallelPaneColorPaletteLabel"),children:lo.map(q=>i.jsx("button",{type:"button",className:"workbench-manage-color-swatch","aria-label":c("shell.manageWorkspaceColorSelectSwatch",{color:q}),"aria-pressed":L===q,"data-selected":L===q,disabled:p,style:{backgroundColor:q},onClick:()=>{const ne=Ws(M,q);X(ne)}},q))})}),i.jsx(kt,{heading:c("shell.parallelPaneIsolatedWorkspaceTitle"),description:(Te==null?void 0:Te.lifecycleStatus)==="active"?c("shell.parallelPanePromoteDescription"):(Te==null?void 0:Te.lifecycleStatus)==="promoted"?c("shell.parallelPaneRemovePromotedDescription"):c("shell.parallelPaneRemoveDescription"),children:i.jsxs(gs,{align:"start",className:"parallel-pane-action-row",children:[(Te==null?void 0:Te.lifecycleStatus)==="active"?i.jsx("button",{type:"button",className:"secondary-button parallel-pane-promote-action",disabled:d===Te.id||p,onClick:()=>{const q=Te==null?void 0:Te.id;q&&u(q)},children:d===Te.id?c("shell.parallelPanePromoting"):c("shell.parallelPanePromoteAction")}):null,i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:p,onClick:()=>{h(v)},children:p?c("shell.parallelPaneRemoving"):c("shell.parallelPaneRemoveAction")})]})})]}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("article",{ref:oe,className:"parallel-conversation-pane","data-current":t?"true":void 0,"data-workspace-tone":(n==null?void 0:n.tone)??"root","data-parallel-role":((Ot=(B==null?void 0:B.parallelGroup)??e.session.parallelGroup)==null?void 0:Ot.role)??void 0,style:{"--parallel-pane-order":String(e.ordinal),...qt(n)??{},...dt??{},...Ze},children:[i.jsxs("header",{ref:V,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:[ht?i.jsx("span",{className:"session-parallel-badge",children:ht}):null,i.jsx("p",{className:"parallel-conversation-pane-subtitle",title:at,children:at}),i.jsxs("div",{className:"parallel-conversation-pane-meta",children:[i.jsx("span",{className:`session-provider-badge ${(B??e.session).provider}`,children:Ft((B??e.session).provider)}),i.jsx("span",{className:"parallel-conversation-pane-model",children:pt})]})]}),i.jsxs("div",{className:"parallel-conversation-pane-actions",children:[i.jsx("button",{ref:Y,type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelPaneInfoAction"),title:c("shell.parallelPaneInfoAction"),"aria-expanded":r,onClick:()=>{K(!1),o()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Dl,{})})}),i.jsx("button",{ref:me,type:"button",className:`conversation-header-ai-button${x?" active":""}`,"aria-label":c("shell.parallelPaneToolsAction"),title:c("shell.parallelPaneToolsAction"),"aria-expanded":x,onClick:()=>{a(),We()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Hl,{})})})]})]}),i.jsxs("div",{className:"parallel-conversation-pane-body",children:[i.jsx(fn,{connectionState:ue,onReconnect:_e}),i.jsx(Lr,{requests:Le,replyingRequestId:je,onReply:de}),i.jsx("div",{className:"parallel-conversation-pane-timeline",children:i.jsx(un,{sessionId:v,sessionSummary:B??e.session,workspaceId:Oe,workspacePath:et,items:Ee,historyState:W,loadingOlderMessages:U,hasOlderMessages:_,provider:(B==null?void 0:B.provider)??e.session.provider,interruptedSource:ee,followTailUpdates:!0,onLoadOlderMessages:ye,onRetryMessage:ge,onSubmitStructuredQuestion:z,onForkMessage:q=>{const ne=B??e.session;ie({sourceMessageId:q.id,sourceMessageSnapshot:{role:q.role,kind:q.kind??(q.role==="tool"?"tool_result":"text"),content:q.content},content:q.content,sourceProvider:ne.provider,workspaceId:ne.workspaceId,targetProvider:ne.provider,targetModel:null,targetProviderConfigMode:ne.providerConfigMode??"global-default",targetProviderPresetId:ne.providerPresetId??null}),Si()}})}),i.jsx(si,{items:De,deletingQueueItemId:Ne,steeringQueueItemId:te,canSteer:D,onDelete:ze,onSteer:He}),i.jsx(dn,{capabilities:he,draftStorageId:v,initialModel:e.model,workspaceId:(B??e.session).workspaceId,initialProviderConfigMode:(B??e.session).providerConfigMode??"global-default",initialProviderPresetId:(B??e.session).providerPresetId??null,forkDraft:ke,onClearForkDraft:()=>ie(null),onForkDraftChange:q=>ie(q),hasActiveRun:Ae,contextUsage:Pe,taskProvider:(B??e.session).provider,taskMessages:pe,hasPendingQueuedMessages:be,canInterrupt:Xe,isSubmitting:ce,isRunning:E,onInterrupt:Ue,onSend:Ie,onQueueSend:fe})]})]}),tt,Re]})}function Dl(){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 Hl(){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 ql(){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 Bl(){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 Fl(){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 Wl(){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 Ul(){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 $l(e,t,s){const n=s.get(e);return n?bs(n).flatMap(r=>Pi(r,t)):[]}function Pi(e,t){var r;const s=e.item.session;if(((r=s.parallelGroup)==null?void 0:r.groupId)===t)return[];const n=bs(e).flatMap(a=>Pi(a,t));return s.isSubagent!==!0?n:[{session:s,workspaceId:e.item.workspace.id,children:n}]}function Xt(e,t){const s=t.trim();return s?e.some(n=>n.session.sessionId===s||Xt(n.children,s)):!1}function Vl(e,t){return t===e.session.sessionId?e.session.sessionId:Xt(e.subagentTree,t)?t:e.session.sessionId}function Gl(e,t){const s=t.trim();return s?s===e.session.sessionId||Xt(e.subagentTree,s):!1}function Ri(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=Ri(n.children,s);if(r)return r}return null}function ki(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=ki(n.children,s);if(r)return r}return null}const Ct=196,Mt=82,fr=28,pr=24,Ti=34,en=18,Xl=332,Jt=360,fs=840,mr=18,zl=.22,Yl=2.4,Kl=6;function Ql(e,t){return(t.lastMessageAt??t.updatedAt).localeCompare(e.lastMessageAt??e.updatedAt)}function Ci(e,t,s){var w,g;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])),a=r.get(s)??null;if(!a)return null;const o=new Map;for(const m of n.sessions){const R=((w=m.parentSessionId)==null?void 0:w.trim())||null;if(!R)continue;const H=o.get(R)??[];o.set(R,[...H,m.sessionId])}const u=new Set,d=new Set;let h=a,f=a.sessionId;for(;h&&!d.has(h.sessionId);){u.add(h.sessionId),d.add(h.sessionId),f=h.sessionId;const m=((g=h.parentSessionId)==null?void 0:g.trim())||null;h=m?r.get(m)??null:null}const I=Ei(f,0,r,o,new Set),T=Jl(I);return{root:I,current:a,currentPathIds:u,relatedSessionIds:T,sessionsById:r}}function Zl(e){return((e==null?void 0:e.relatedSessionIds.size)??0)>1}function Ei(e,t,s,n,r){const a=s.get(e);if(!a)throw new Error(`Session ${e} not found`);const o=new Set(r);o.add(e);const u=[...n.get(e)??[]].filter(d=>!o.has(d)).sort((d,h)=>{const f=s.get(d),I=s.get(h);return!f||!I?0:Ql(f,I)});return{session:a,depth:t,children:u.map(d=>Ei(d,t+1,s,n,o))}}function Jl(e){const t=new Set;function s(n){t.add(n.session.sessionId),n.children.forEach(s)}return s(e),t}function Ai(e){const t=Wr(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 _i(e){return e.isArchived===!0}function ec(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 ji(e,t){return e<=0||t<=0?1:Math.min(1,e/t)}function tc(e,t,s,n){const r=ji(e,s),a=s*r,o=n*r,u=a<e?(e-a)/2:0;return{scale:r,offsetX:u,offsetY:0,shellWidth:Math.max(e,a),shellHeight:o}}function tn(e,t,s){return Math.min(s,Math.max(t,e))}function sc(e,t,s,n){if(e<=0||t<=0||s<=0||n<=0)return 1;const r=Math.max(1,e-mr*2),a=Math.max(1,t-mr*2);return Math.min(1,r/s,a/n)}function ps(e,t,s,n,r){const a=n*e.scale,o=r*e.scale,u=(t-a)/2,d=(s-o)/2,h=a<=t?u:tn(e.offsetX,t-a,0),f=o<=s?d:tn(e.offsetY,s-o,0);return{scale:e.scale,offsetX:h,offsetY:f}}function es(e,t,s,n){const r=sc(e,t,s,n);return ps({scale:r,offsetX:(e-s*r)/2,offsetY:(t-n*r)/2},e,t,s,n)}function nc(e,t,s,n,r,a,o,u){const d=(s-e.offsetX)/e.scale,h=(n-e.offsetY)/e.scale;return ps({scale:t,offsetX:s-d*t,offsetY:n-h*t},r,a,o,u)}function rc(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 ic(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 sn(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,Ct),Ct;const n=e.children.reduce((a,o,u)=>{const d=a+sn(o,t);return u===0?d:d+en},0),r=Math.max(Ct,n);return t.set(e.session.sessionId,r),r}function oc(e){const t=new Map,s=[],n=new Map;function r(u,d,h){const f=sn(u,t),I=d+f/2,T=pr+h*(Mt+Ti),w=I-Ct/2,g=u.children.reduce((N,C,M)=>{const y=N+sn(C,t);return M===0?y:y+en},0);let m=d+Math.max(0,(f-g)/2);const R=u.children.map(N=>{const C=r(N,m,h+1);return m+=C.subtreeWidth+en,C}),H={node:u,children:R,x:w,y:T,centerX:I,centerY:T+Mt/2,subtreeWidth:f};return s.push(H),n.set(u.session.sessionId,H),H}const a=r(e,fr,0),o=s.reduce((u,d)=>Math.max(u,d.y+Mt),0);return{root:a,nodes:s,bySessionId:n,width:a.subtreeWidth+fr*2,height:o+pr}}function ac(e){return Math.max(0,Math.min(255,Number.parseFloat(e)))}function lc(e){const t=e.trim();if(t.startsWith("#")){const n=t.slice(1);if(n.length===3){const[r,a,o]=n.split("").map(u=>Number.parseInt(u.repeat(2),16));return{r,g:a,b:o}}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,a]=s[1].split(",").map(o=>ac(o));return{r:n,g:r,b:a}}return null}function ut(e,t,s){const n=lc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:s}function cc(e,t,s,n,r,a){const o=e.getContext("2d");if(!o)return;const u=o,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",T=h.getPropertyValue("--bg-surface").trim()||"#ffffff";if(!a){const g=u.createLinearGradient(0,0,t.width,t.height);g.addColorStop(0,ut(T,.38,"rgba(255, 255, 255, 0.38)")),g.addColorStop(1,ut(f,.05,"rgba(59, 130, 246, 0.05)")),u.fillStyle=g,u.fillRect(0,0,t.width,t.height)}function w(g){for(const m of g.children){const R=n.has(g.node.session.sessionId)&&n.has(m.node.session.sessionId),H=g.node.session.sessionId===r||m.node.session.sessionId===r;u.beginPath(),u.moveTo(g.centerX,g.y+Mt-10);const N=g.y+Mt+Ti*.52;u.bezierCurveTo(g.centerX,N,m.centerX,N,m.centerX,m.y+10),u.lineWidth=H?3:R?2.5:1.5,u.strokeStyle=H?ut(f,.52,"rgba(59, 130, 246, 0.52)"):R?ut(f,.32,"rgba(59, 130, 246, 0.32)"):ut(I,.72,"rgba(148, 163, 184, 0.72)"),u.stroke(),u.beginPath(),u.arc(m.centerX,m.y,H?4.5:3.5,0,Math.PI*2),u.fillStyle=H?ut(f,.9,"rgba(59, 130, 246, 0.9)"):ut(I,.78,"rgba(148, 163, 184, 0.78)"),u.fill(),w(m)}}w(t.root);for(const g of t.nodes){const m=g.node.session.sessionId===s,R=g.node.session.sessionId===r,H=n.has(g.node.session.sessionId);if(!m&&!R&&!H)continue;const N=u.createRadialGradient(g.centerX,g.centerY,10,g.centerX,g.centerY,R?90:64);N.addColorStop(0,ut(f,R?.22:.14,"rgba(59, 130, 246, 0.22)")),N.addColorStop(1,"rgba(59, 130, 246, 0)"),u.fillStyle=N,u.beginPath(),u.ellipse(g.centerX,g.centerY,Ct*.72,Mt*.9,0,0,Math.PI*2),u.fill(),(R||m)&&(u.beginPath(),u.arc(g.centerX,g.y+12,R?6:5,0,Math.PI*2),u.fillStyle=ut(f,.94,"rgba(59, 130, 246, 0.94)"),u.fill())}}function uc(e,t,s){const n=Math.min(Xl,t-24),r=e.left+e.width/2-n/2,a=Math.max(12,Math.min(t-n-12,r)),d=s-e.bottom-12<220&&e.top>Jt?Math.max(12,e.top-Jt-12):Math.max(12,Math.min(s-Jt-12,e.bottom+12));return{width:n,left:a,top:d,maxHeight:Math.min(Jt,s-24)}}function dc({model:e,selectedSession:t,selectedTreeNode:s,previewEntry:n,onClose:r,onOpenSession:a}){const o=Gt(t.title,c("common.unknown")),u=t.sessionId===e.current.sessionId,d=_i(t),h=Hr(s.session),f=qr(s.session),I=Br(s.session),T=Fr(s.session);return i.jsxs("div",{className:"conversation-branch-preview-popover",role:"dialog","aria-label":`${c("conversation.branchTreePreviewTitle")} ${o.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:o.fullTitle,children:o.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:Ai(t)}),f&&h||T&&I?i.jsxs("div",{className:"conversation-branch-badge-row",children:[T&&I?i.jsx("span",{className:`session-fork-badge ${I}`,children:T}):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:ic(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:rc(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:()=>a(t),children:u?c("conversation.branchTreeCurrentAction"):c("conversation.branchTreeSwitchAction")})})]})}function hc({layout:e,model:t,selectedSessionId:s,onSelectSession:n,onBackgroundClick:r,stageScale:a,desktopStageLayout:o,transform:u,isMobileViewport:d,viewportRef:h,onRegisterNodeElement:f,onViewportTouchStart:I,onViewportTouchMove:T,onViewportTouchEnd:w}){const g=l.useRef(null);return l.useEffect(()=>{const m=g.current;m&&cc(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":a<.999,"data-mobile":d,onClick:m=>{m.target===m.currentTarget&&(r==null||r())},onTouchStart:I,onTouchMove:T,onTouchEnd:w,onTouchCancel:w,children:i.jsx("div",{className:"conversation-branch-canvas-stage-shell",style:{width:d?"100%":o.shellWidth,height:d?"100%":o.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(${o.offsetX}px, ${o.offsetY}px) scale(${o.scale})`,transformOrigin:"top left"},onClick:()=>{if(r){r();return}n(null)},children:[i.jsx("canvas",{ref:g,className:"conversation-branch-canvas",width:e.width,height:e.height,"aria-hidden":"true"}),e.nodes.map(m=>{const R=Gt(m.node.session.title,c("common.unknown")),H=Hr(m.node.session),N=qr(m.node.session),C=Br(m.node.session),M=Fr(m.node.session),y=m.node.session.sessionId===t.current.sessionId,b=m.node.session.sessionId===s,F=t.currentPathIds.has(m.node.session.sessionId),k=_i(m.node.session);return i.jsx("button",{ref:S=>f(m.node.session.sessionId,S),type:"button",className:"conversation-branch-smart-card conversation-branch-canvas-node","data-current":y,"data-selected":b,"data-current-path":F,"data-archived":k,style:{left:m.x,top:m.y,width:Ct,minHeight:Mt},"aria-pressed":b,onClick:S=>{S.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:R.fullTitle,children:R.displayTitle}),y?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:Ai(m.node.session)}),N&&H||M&&C?i.jsxs("div",{className:"conversation-branch-badge-row",children:[M&&C?i.jsx("span",{className:`session-fork-badge ${C}`,children:M}):null,N&&H?i.jsx("span",{className:`session-fork-badge ${H}`,children:N}):null]}):null]})},m.node.session.sessionId)})]})})})}function gr({model:e,onOpenSession:t,onClose:s}){const n=l.useMemo(()=>oc(e.root),[e.root]),r=l.useRef(null),a=l.useRef(new Map),[o,u]=l.useState(null),[d,h]=l.useState(0),[f,I]=l.useState(0),[T,w]=l.useState(null),[g,m]=l.useState({}),R=l.useRef(new Set),[H,N]=l.useState(typeof window<"u"?window.innerWidth<=fs:!1),[C,M]=l.useState(null),y=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 j=r.current;if(!j)return;const A=j;function O(){h(A.clientWidth),I(A.clientHeight),N(window.innerWidth<=fs)}if(O(),typeof ResizeObserver>"u")return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O);const Q=new ResizeObserver(O);return Q.observe(j),()=>Q.disconnect()},[]),l.useEffect(()=>{u(null)},[e.current.sessionId,e.root.session.sessionId]);const b=l.useMemo(()=>ji(d,n.width),[d,n.width]),F=l.useMemo(()=>tc(d,f,n.width,n.height),[f,d,n.height,n.width]);l.useEffect(()=>{if(!H||d<=0||f<=0){M(null);return}M(j=>j?ps(j,d,f,n.width,n.height):es(d,f,n.width,n.height))},[f,d,H,n.height,n.width]);const k=o?e.sessionsById.get(o)??null:null,S=k?n.bySessionId.get(k.sessionId)??null:null,v=k?g[k.sessionId]??{status:"idle",messages:[],error:null}:null,x=H&&!!s,K=!!s&&!x;l.useEffect(()=>{if(!o){w(null);return}const j=o;function A(){const O=a.current.get(j);if(!O){w(null);return}w(O.getBoundingClientRect())}return A(),window.addEventListener("resize",A),window.addEventListener("scroll",A,!0),()=>{window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0)}},[o,b]),l.useEffect(()=>{if(!H)return;const j=o;if(!j)return;const A=window.requestAnimationFrame(()=>{const O=a.current.get(j);O&&w(O.getBoundingClientRect())});return()=>window.cancelAnimationFrame(A)},[H,C,o]),l.useEffect(()=>{if(!(k!=null&&k.sessionId)||(v==null?void 0:v.status)==="ready"||R.current.has(k.sessionId))return;let j=!1;return R.current.add(k.sessionId),m(A=>{var O;return{...A,[k.sessionId]:{status:"loading",messages:((O=A[k.sessionId])==null?void 0:O.messages)??[],error:null}}}),Us(k.sessionId,null,6,"backward").then(A=>{R.current.delete(k.sessionId),!j&&m(O=>({...O,[k.sessionId]:{status:"ready",messages:ec(A.messages),error:null}}))}).catch(A=>{R.current.delete(k.sessionId),!j&&m(O=>{var Q;return{...O,[k.sessionId]:{status:"error",messages:((Q=O[k.sessionId])==null?void 0:Q.messages)??[],error:A instanceof Error?A.message:c("conversation.branchTreePreviewFailed")}}})}),()=>{j=!0}},[k==null?void 0:k.sessionId]);function $(j){!H||d<=0||f<=0||M(A=>{const O=A??es(d,f,n.width,n.height);return ps(j(O),d,f,n.width,n.height)})}function J(j){if(!H)return;const A=j.currentTarget.getBoundingClientRect();if(j.touches.length>=2){const oe=j.touches[0],V=j.touches[1],Y=Math.hypot(V.clientX-oe.clientX,V.clientY-oe.clientY),ae=(oe.clientX+V.clientX)/2-A.left,le=(oe.clientY+V.clientY)/2-A.top,me=C??es(d,f,n.width,n.height);y.current={mode:"pinch",startDistance:Y,startScale:me.scale,startOffsetX:me.offsetX,startOffsetY:me.offsetY,startTouchX:ae,startTouchY:le,anchorX:ae,anchorY:le,moved:!1};return}const O=j.touches[0],Q=C??es(d,f,n.width,n.height);y.current={mode:"pan",startDistance:0,startScale:Q.scale,startOffsetX:Q.offsetX,startOffsetY:Q.offsetY,startTouchX:O.clientX,startTouchY:O.clientY,anchorX:0,anchorY:0,moved:!1}}function re(j){if(!H)return;const A=y.current;if(j.touches.length>=2){const Y=j.currentTarget.getBoundingClientRect(),ae=j.touches[0],le=j.touches[1],me=Math.hypot(le.clientX-ae.clientX,le.clientY-ae.clientY);if(me<=0||A.startDistance<=0)return;j.preventDefault();const L=(ae.clientX+le.clientX)/2-Y.left,X=(ae.clientY+le.clientY)/2-Y.top,B=tn(A.startScale*(me/A.startDistance),zl,Yl);y.current={...A,mode:"pinch",moved:!0,anchorX:L,anchorY:X},$(he=>nc({...he,scale:A.startScale,offsetX:A.startOffsetX,offsetY:A.startOffsetY},B,L,X,d,f,n.width,n.height));return}if(A.mode!=="pan"||j.touches.length!==1)return;const O=j.touches[0],Q=O.clientX-A.startTouchX,oe=O.clientY-A.startTouchY;(A.moved||Math.hypot(Q,oe)>=Kl)&&(j.preventDefault(),y.current={...A,moved:!0},$(Y=>({...Y,offsetX:A.startOffsetX+Q,offsetY:A.startOffsetY+oe})))}function G(){y.current={mode:"idle",startDistance:0,startScale:(C==null?void 0:C.scale)??1,startOffsetX:(C==null?void 0:C.offsetX)??0,startOffsetY:(C==null?void 0:C.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":""}${x?" 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:[x?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,x?null:i.jsx("div",{className:"conversation-branch-canvas-tip",children:c("conversation.branchTreePreviewDescription")}),i.jsx(hc,{layout:n,model:e,selectedSessionId:o,onSelectSession:u,onBackgroundClick:x?s:void 0,stageScale:b,desktopStageLayout:F,transform:H?C:null,isMobileViewport:H,viewportRef:r,onRegisterNodeElement:(j,A)=>{if(A){a.current.set(j,A);return}a.current.delete(j)},onViewportTouchStart:J,onViewportTouchMove:re,onViewportTouchEnd:G})]})]}),k&&S&&v&&T&&typeof document<"u"?St.createPortal(i.jsx("div",{className:"conversation-branch-preview-floating",style:uc(T,window.innerWidth,window.innerHeight),children:i.jsx(dc,{model:e,selectedSession:k,selectedTreeNode:S.node,previewEntry:v,onClose:()=>u(null),onOpenSession:t})}),document.body):null]})}function fc({open:e,navigationGroups:t,workspaceId:s,sessionId:n,onClose:r,onOpenSession:a}){const o=l.useMemo(()=>Ci(t,s,n),[t,n,s]),[u,d]=l.useState(typeof window<"u"?window.innerWidth>fs:!0);return l.useEffect(()=>{if(typeof window>"u")return;function h(){d(window.innerWidth>fs)}return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]),!e||!o||typeof document>"u"?null:u?i.jsx(ms,{open:e,title:c("conversation.branchTreeMapTitle"),description:c("conversation.branchTreeMapDescription"),size:"regular",layout:"viewer",bodyClassName:"conversation-branch-modal-body",onClose:r,children:i.jsx(gr,{model:o,onOpenSession:a})}):St.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(gr,{model:o,onOpenSession:a,onClose:r})]}),document.body)}function pc(e,t,s){if(!t)return null;const n=e.find(o=>o.workspace.id===t);if(!n)return null;const r=$t([n]).filter(o=>!o.session.isArchived&&!hn(o.session)),a=r.findIndex(o=>o.session.sessionId===s);return a<0?null:r[a+1]??null}const vr=.6,Fs=.6,br=8,mc=36,gc=48,vc=96,bc=196;function iu(){const{sessionId:e="",workspaceId:t}=to(),s=nn(),n=vt(),r=l.useMemo(()=>new URLSearchParams(s.search),[s.search]),a=kc(r.get("toolPanel")),o=(t==null?void 0:t.trim())||null,u=l.useMemo(()=>xc(e,o,r),[o,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:a}):i.jsx(wc,{sessionId:e,bootstrapMessages:d,initialComposerModel:h.initialModel,initialComposerProviderConfigMode:h.providerConfigMode,initialComposerProviderPresetId:h.providerPresetId,initialToolPanel:a})}function wc(e){const{shellMode:t,navigationGroups:s,currentWorkspaceRef:n,currentTargetHostId:r}=yt(),a=vt(),o=l.useMemo(()=>$t(s),[s]),u=l.useMemo(()=>{var f;return((f=o.find(I=>I.session.sessionId===e.sessionId))==null?void 0:f.session)??null},[o,e.sessionId]),d=!zi(e.sessionId)&&e.bootstrapMessages.length===0&&o.length>0&&u===null,h=l.useMemo(()=>d?Dc({shellMode:t,navigationGroups:s,flattenedNavigationEntries:o,workspaceRef:n,targetHostId:r}):null,[r,n,o,d,s,t]);return l.useEffect(()=>{h&&a(h,{replace:!0})},[h,a]),h?null:i.jsx(Ic,{...e})}function Ic({sessionId:e,bootstrapMessages:t,initialComposerModel:s,initialComposerProviderConfigMode:n,initialComposerProviderPresetId:r,initialToolPanel:a}){var mt,Mn,Sn,yn;const{shellMode:o,navigationGroups:u,requestNavigationRefresh:d,selectWorkspace:h,setSessionWorkspace:f,markNavigationSessionSeen:I,favoriteSessions:T,toggleFavoriteSession:w,archiveSession:g,unarchiveSession:m,renameSession:R,startDraftSession:H,upsertNavigationSession:N,currentWorkspaceRef:C,currentTargetHostId:M}=yt(),y=vt(),[b,F]=l.useState(!1),[k,S]=l.useState(!1),[v,x]=l.useState(null),[K,$]=l.useState(!1),[J,re]=l.useState(!1),[G,j]=l.useState(!1),A=l.useMemo(()=>$t(u),[u]),O=l.useMemo(()=>{var P;return((P=A.find(Z=>Z.session.sessionId===e))==null?void 0:P.session)??null},[A,e]),{showToast:Q}=gt(),oe=()=>{var we;const P=(O==null?void 0:O.workspaceId)??((we=u[0])==null?void 0:we.workspace.id)??null,Z=(P?A.find(it=>it.workspace.id===P)??null:null)??A[0]??null;y(Z?$e(Z.workspace.id,Z.session.sessionId):P?wt(P):o==="mobile"?yr():"/landing",{replace:!0})},{session:V,capabilities:Y,messages:ae,timelineItems:le,permissionRequests:me,queuedMessages:L,contextUsage:X,historyState:B,runtimeInterruptSource:he,loadingOlderMessages:pe,hasOlderMessages:Ee,connectionState:Le,sending:De,replyingPermissionRequestId:Pe,deletingQueueItemId:W,steeringQueueItemId:ee,forkDraft:U,setForkDraft:_,composerHasActiveRun:ue,composerCanInterrupt:ce,composerIsRunning:je,canSteerQueuedMessage:Ne,hasPendingQueuedMessages:te,reconnect:ke,loadOlderMessages:ie,retryMessage:Ae,send:Xe,queue:E,interrupt:D,replyPermissionRequest:be,deleteQueuedMessage:_e,steerQueuedMessage:ye}=yi({sessionId:e,targetHostId:M,externalSession:O,bootstrapMessages:t,onSeen:(P,Z)=>{I(P,Z)},onRequestNavigationRefresh:d,onUpsertNavigationSession:N,onNavigateToSession:(P,Z)=>{const we=M?C:{hostId:"current",workspaceId:P};h(P,we),y($e(P,Z,we))},onBindSessionWorkspace:f,onResolveMissingSession:oe,onForkSuccess:()=>{Rt("preview"),Q({title:c("conversation.forkMessageSucceeded"),tone:"success"})},enableRuntimeErrorHandling:!0,enableCompletionHaptics:!0,enableThinkingPlaceholder:!0,enableForkTimelineSanitizer:!0}),ge=o!=="mobile",Ie=$i(!ge),fe=V??O??null,Ue=(V==null?void 0:V.sessionIsolatedWorkspace)??(O==null?void 0:O.sessionIsolatedWorkspace)??null,de=fe?ss(fe,Ue):null,ze=fe?Mr(fe,Ue):null,He=Wi({enabled:!ge,initialPanel:a,workspaceId:ze,suspendMainGesture:!ge&&Ie.isVisible}),dt=l.useMemo(()=>new Set(T.map(P=>P.session.sessionId)),[T]),Ze=l.useMemo(()=>u.map(P=>P.workspace),[u]),ht=l.useMemo(()=>Ur(u),[u]),Te=l.useMemo(()=>ln(u),[u]),ft=l.useMemo(()=>Li(u,de,dt),[dt,de,u]),pt=l.useMemo(()=>Di(T,u),[T,u]);async function at(P){await Xe(Mc(P.answers))}const[bt,Oe]=l.useState([]),lt=l.useMemo(()=>[...pt,...ft],[pt,ft]),et=l.useMemo(()=>de?Ze.find(P=>P.id===de)??null:null,[de,Ze]),p=(de?Te[de]??null:null)??(et?cn(et):null),z=l.useMemo(()=>ws(u,de),[de,u]),se=ht.find(P=>P.workspace.id===de)??(z?{workspace:z.workspace,label:z.workspace.name,subtitle:z.workspace.path}:null),Me=l.useMemo(()=>pc(u,de,e),[de,u,e]),qe=(V==null?void 0:V.provider)??(O==null?void 0:O.provider)??null,We=l.useMemo(()=>{var P;return Gt(((P=V??O)==null?void 0:P.title)??null,c("conversation.titleFallback"))},[O,V]),Ce=ge,Be=l.useMemo(()=>{var we;if(!Ce)return null;if(po(fe))return((we=fe==null?void 0:fe.parallelGroup)==null?void 0:we.groupId)??null;const P=vs(A);return Sc(P,e)},[fe,A,e,Ce]),Re=ge?null:Fi(Ie.mainGestureHandlers,He.mainGestureHandlers);l.useEffect(()=>{const P=Sr(lt,e,Z=>Z.session.sessionId);P.length!==0&&Oe(Z=>{const we=new Set(Z);let it=!1;for(const xn of P)we.has(xn)||(we.add(xn),it=!0);return it?Array.from(we):Z})},[lt,e]);const tt=(fe==null?void 0:fe.workspaceId)??(O==null?void 0:O.workspaceId)??null,zt=l.useMemo(()=>Ci(u,tt,e),[tt,u,e]),Yt=Zl(zt),jt=!!(fe&&tt&&Yt),Nt=()=>{re(!0)},xt=l.useMemo(()=>(z==null?void 0:z.sessions.filter(P=>$r(P)))??[],[z]),Kt=l.useRef(null),Ot=l.useRef(null),q=l.useRef(null),ne=l.useRef(null),[st,Ye]=l.useState(null),{composerPortalTarget:nt}=Vr();l.useEffect(()=>{re(!1)},[e]),qi(q,st,!ge,e),Bi(q,ne,!ge,e);function rt(P,Z){h(P,Z),y(wt(P,Z))}return ge&&Be?i.jsxs(i.Fragment,{children:[i.jsx(Ol,{groupId:Be,currentSessionId:e}),i.jsx($s,{open:G,source:fe?{kind:"session",sessionId:e,workspaceId:fe.workspaceId,workspaceName:(p==null?void 0:p.displayName)??fe.workspaceId,sessionTitle:fe.title,defaultProvider:fe.provider}:null,targetHostId:M,onClose:()=>j(!1),onCreated:async P=>{P.members.forEach(we=>{N(we.session)}),Tn(P.group.id),await d();const Z=P.members.find(we=>we.session.sessionId===P.group.anchorSessionId)??P.members[0]??null;if(Z){const we=ss(Z.session,Z.sessionIsolatedWorkspace),it=Ke(M,C);h(we,it),y($e(we,Z.session.sessionId,it))}j(!1),Q({title:c("shell.parallelCreateSucceeded"),tone:"success"})}})]}):i.jsxs(i.Fragment,{children:[i.jsxs("main",{ref:q,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!ge,"data-preview-mode":ge?void 0:Ie.displayMode,"data-preview-dragging":ge?void 0:Ie.isDragging,"data-workspace-tone":(p==null?void 0:p.tone)??"root","data-worktree-depth":(p==null?void 0:p.depth)??0,"data-tool-panel-open":ge?void 0:He.isOpen,style:{...ge?{}:Ie.pageStyle,...qt(p)??{}},children:[ge?i.jsx(Gr,{session:V??O,workspaceContext:p,actions:i.jsxs(i.Fragment,{children:[jt?i.jsx(Oc,{onOpenBranchTree:Nt}):null,fe?i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelCreateAction"),title:c("shell.parallelCreateAction"),onClick:()=>j(!0),children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Lc,{})})}):null,i.jsx(ti,{session:V??O})]})}):null,ge?null:i.jsx(Xr,{containerRef:ne,className:"mobile-conversation-page-header",gestureHandlers:Re??void 0,currentWorkspace:se?{id:se.workspace.id,name:se.label,path:se.subtitle}:Ze[0]??null,workspaces:Ze,workspaceOptions:ht,onSelectWorkspace:rt,heading:We.fullTitle,trailing:i.jsxs("div",{className:"mobile-conversation-toolbar-main",children:[i.jsx("span",{className:"mobile-conversation-toolbar-title",title:We.fullTitle,children:We.displayTitle}),i.jsx(ba,{session:V??O,onOpenBranchTree:jt?Nt:void 0})]})}),ge?null:i.jsx(Vi,{visible:!He.isOpen&&Ie.isVisible,widthPx:Ie.previewWidthPx,isDragging:Ie.isDragging,gestureHandlers:Ie.railGestureHandlers,activeSessionId:e,createSessionActionLabel:de&&qe?c("shell.createSession"):void 0,favoriteItems:pt,items:ft,expandedRootIds:bt,workspaceSectionLabel:(se==null?void 0:se.label)??c("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:de&&qe?()=>{H(de,qe)}:void 0,archiveCurrentActionLabel:c("shell.archiveCurrentSessionAction"),archiveFolderActionLabel:xt.length>0?c("shell.archiveFolderLabel"):void 0,onArchiveActiveSession:()=>{F(!0)},onOpenArchiveFolder:xt.length>0?()=>{S(!0)}:void 0,onToggleSubsessions:P=>{Oe(Z=>Z.includes(P)?Z.filter(we=>we!==P):[...Z,P])},onActivate:P=>{Ie.closePreview();const Z=Ke(M,C);h(P.workspace.id,Z),y($e(P.workspace.id,P.session.sessionId,Z))},onToggleFavoriteSession:P=>w(P),onArchiveSession:P=>g(P),onUnarchiveSession:P=>m(P),onRenameSession:(P,Z)=>R(P,Z),onDeleteSession:async P=>{if(await Dr(P,{targetHostId:M}),await d(),P===e){if(de){if(h(de,Ke(M,C)),Rt("preview"),Me){const Z=Ke(M,C);y($e(Me.workspace.id,Me.session.sessionId,Z));return}y(wt(de,Ke(M,C)));return}y("/workspaces")}}}),i.jsx("div",{className:"mobile-conversation-stage",...Re??{},children:i.jsxs("div",{ref:Kt,className:"mobile-conversation-main",children:[i.jsx(fn,{connectionState:Le,onReconnect:ke}),i.jsx(Lr,{requests:me,replyingRequestId:Pe,onReply:be}),i.jsx("div",{ref:Ot,className:"conversation-timeline-shell",children:i.jsx(un,{sessionId:e,sessionSummary:V??O??null,workspaceId:ze,workspacePath:(et==null?void 0:et.path)??null,items:le,historyState:B,loadingOlderMessages:pe,hasOlderMessages:Ee,provider:(V==null?void 0:V.provider)??null,interruptedSource:he,onLoadOlderMessages:ie,onRetryMessage:Ae,onSubmitStructuredQuestion:at,onForkMessage:P=>{V&&(_({sourceMessageId:P.id,sourceMessageSnapshot:{role:P.role,kind:P.kind??(P.role==="tool"?"tool_result":"text"),content:P.content},content:P.content,sourceProvider:V.provider,workspaceId:V.workspaceId,targetProvider:V.provider,targetModel:null,targetProviderConfigMode:V.providerConfigMode??"global-default",targetProviderPresetId:V.providerPresetId??null}),Si())}})}),i.jsx(pa,{containerRef:Ot,session:V??O??null,currentCapabilities:Y}),i.jsx(si,{items:L,deletingQueueItemId:W,steeringQueueItemId:ee,canSteer:Ne,onDelete:_e,onSteer:ye}),He.isOpen?null:i.jsx(dn,{capabilities:Y,draftStorageId:e,initialModel:s,workspaceId:((mt=V??O)==null?void 0:mt.workspaceId)??null,initialProviderConfigMode:n??((Mn=V??O)==null?void 0:Mn.providerConfigMode)??"global-default",initialProviderPresetId:r??((Sn=V??O)==null?void 0:Sn.providerPresetId)??null,forkDraft:U,onClearForkDraft:()=>_(null),onForkDraftChange:P=>_(P),panelRef:ge?void 0:Ye,portalContainer:ge?null:nt,hasActiveRun:ue,contextUsage:X,taskProvider:((yn=V??O)==null?void 0:yn.provider)??null,taskMessages:ae,hasPendingQueuedMessages:te,canInterrupt:ce,isSubmitting:De,isRunning:je,onInterrupt:D,onSend:Xe,onQueueSend:E})]})}),!ge&&ze?i.jsx(Ui,{activePanel:He.activePanel,open:He.isOpen,sessionId:e,workspaceId:ze,navigationGroups:u,onClose:()=>{He.closePanel()},onSelectPanel:P=>{He.selectPanel(P)},onSelectPanelBySwipe:P=>{if(P===null){He.closePanel();return}He.selectPanel(P)}}):null]}),i.jsx(fc,{open:J,navigationGroups:u,workspaceId:tt,sessionId:e,onClose:()=>re(!1),onOpenSession:P=>{re(!1);const Z=Ke(M,C);h(P.workspaceId,Z),Rt("preview"),y($e(P.workspaceId,P.sessionId,Z))}}),i.jsx(Nc,{open:b,busy:K,onClose:()=>{K||F(!1)},onConfirm:async()=>{if(!K){$(!0);try{if(await g(e),F(!1),Q({title:c("shell.archiveAdded"),tone:"success"}),de){if(h(de,Ke(M,C)),Rt("preview"),Me){const P=Ke(M,C);y($e(Me.workspace.id,Me.session.sessionId,P));return}y(wt(de,Ke(M,C)));return}y("/workspaces")}catch(P){Q({title:P instanceof Error?P.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{$(!1)}}}}),i.jsx(Xi,{open:k,workspaceName:(z==null?void 0:z.workspace.name)??null,sessions:xt,restoringSessionId:v,onClose:()=>{v||S(!1)},onRestore:async P=>{x(P);try{await m(P),Q({title:c("shell.archiveRestored"),tone:"success"})}catch(Z){Q({title:Z instanceof Error?Z.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{x(null)}}}),Ce?i.jsx($s,{open:G,source:fe?{kind:"session",sessionId:e,workspaceId:fe.workspaceId,workspaceName:(p==null?void 0:p.displayName)??fe.workspaceId,sessionTitle:fe.title,defaultProvider:fe.provider}:null,targetHostId:M,onClose:()=>j(!1),onCreated:async P=>{P.members.forEach(we=>{N(we.session)}),Tn(P.group.id),await d();const Z=P.members.find(we=>we.session.sessionId===P.group.anchorSessionId)??P.members[0]??null;if(Z){const we=ss(Z.session,Z.sessionIsolatedWorkspace),it=Ke(M,C);h(we,it),y($e(we,Z.session.sessionId,it))}j(!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=Ni(n,s,null);if(r)return r}return null}function Ni(e,t,s){var r,a;const n=((a=(r=e.item.session.parallelGroup)==null?void 0:r.groupId)==null?void 0:a.trim())||s;if(e.item.session.sessionId===t)return n;for(const o of bs(e)){const u=Ni(o,t,n);if(u)return u}return null}function yc({draft:e,navigate:t,initialToolPanel:s}){const{shellMode:n,navigationGroups:r,requestNavigationRefresh:a,selectWorkspace:o,setSessionWorkspace:u,upsertNavigationSession:d,favoriteSessions:h,unarchiveSession:f,startDraftSession:I,currentTargetHostId:T,currentWorkspaceRef:w}=yt(),[g,m]=l.useState(!1),[R,H]=l.useState([]),N=Pc(e,T,w),C=l.useMemo(()=>Dt(e.provider),[e.provider]),[M,y]=l.useState(C),b=n!=="mobile",{showToast:F}=gt(),k=l.useMemo(()=>Rc(e),[e]),S=$i(!b),v=Wi({enabled:!b,initialPanel:s,sessionId:e.sessionId,workspaceId:e.workspaceId,suspendMainGesture:!b&&S.isVisible}),x=l.useMemo(()=>new Set(h.map(U=>U.session.sessionId)),[h]),K=l.useMemo(()=>r.map(U=>U.workspace),[r]),$=l.useMemo(()=>Ur(r),[r]),J=l.useMemo(()=>ln(r),[r]),re=l.useMemo(()=>K.find(U=>U.id===e.workspaceId)??null,[e.workspaceId,K]),G=J[e.workspaceId]??(re?cn(re):null),j=l.useMemo(()=>Gt(k.title??null,c("conversation.titleFallback")),[k]),A=l.useMemo(()=>Li(r,e.workspaceId,x),[e.workspaceId,x,r]),O=l.useMemo(()=>Di(h,r),[h,r]),[Q,oe]=l.useState([]),V=l.useMemo(()=>[...O,...A],[O,A]),Y=l.useMemo(()=>ws(r,e.workspaceId),[e.workspaceId,r]),ae=l.useMemo(()=>(Y==null?void 0:Y.sessions.filter(U=>$r(U)))??[],[Y]),le=$.find(U=>U.workspace.id===e.workspaceId)??(Y?{workspace:Y.workspace,label:Y.workspace.name,subtitle:Y.workspace.path}:null),me=b?null:Fi(S.mainGestureHandlers,v.mainGestureHandlers),[L,X]=l.useState(!1),[B,he]=l.useState(null),pe=l.useRef(null),Ee=l.useRef(null),Le=l.useRef(null),[De,Pe]=l.useState(null),{composerPortalTarget:W}=Vr();l.useEffect(()=>{const U=Sr(V,e.sessionId,_=>_.session.sessionId);U.length!==0&&oe(_=>{const ue=new Set(_);let ce=!1;for(const je of U)ue.has(je)||(ue.add(je),ce=!0);return ce?Array.from(ue):_})},[e.sessionId,V]),l.useEffect(()=>(u(e.sessionId,e.workspaceId),()=>{u(e.sessionId,null)}),[e.sessionId,e.workspaceId,u]),l.useEffect(()=>{let U=!1;return y(C),xr(e.provider,N,void 0,{targetHostId:T}).then(_=>{U||y(_)}).catch(()=>{}),()=>{U=!0}},[T,e.provider,N,C]),qi(Ee,De,!b,e.sessionId),Bi(Ee,Le,!b,e.sessionId);function ee(U,_){o(U,_),t(wt(U,_))}return i.jsx(i.Fragment,{children:i.jsxs("main",{ref:Ee,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!b,"data-preview-mode":b?void 0:S.displayMode,"data-preview-dragging":b?void 0:S.isDragging,"data-workspace-tone":(G==null?void 0:G.tone)??"root","data-worktree-depth":(G==null?void 0:G.depth)??0,"data-tool-panel-open":b?void 0:v.isOpen,style:{...b?{}:S.pageStyle,...qt(G)??{}},children:[b?i.jsx(Gr,{session:k,workspaceContext:G}):null,b?null:i.jsx(Xr,{containerRef:Le,className:"mobile-conversation-page-header",gestureHandlers:me??void 0,currentWorkspace:le?{id:le.workspace.id,name:le.label,path:le.subtitle}:K[0]??null,workspaces:K,workspaceOptions:$,onSelectWorkspace:ee,heading:j.fullTitle,trailing:i.jsx("span",{className:"mobile-conversation-toolbar-title",title:j.fullTitle,children:j.displayTitle})}),b?null:i.jsx(Vi,{visible:!v.isOpen&&S.isVisible,widthPx:S.previewWidthPx,isDragging:S.isDragging,gestureHandlers:S.railGestureHandlers,activeSessionId:e.sessionId,createSessionActionLabel:c("shell.createSession"),favoriteItems:O,items:A,expandedRootIds:Q,workspaceSectionLabel:(le==null?void 0:le.label)??c("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:()=>{I(e.workspaceId,e.provider)},archiveFolderActionLabel:ae.length>0?c("shell.archiveFolderLabel"):void 0,onOpenArchiveFolder:ae.length>0?()=>{X(!0)}:void 0,onToggleSubsessions:U=>{oe(_=>_.includes(U)?_.filter(ue=>ue!==U):[..._,U])},onActivate:U=>{S.closePreview();const _=Ke(T,w);o(U.workspace.id,_),t($e(U.workspace.id,U.session.sessionId,_))},onToggleFavoriteSession:async()=>{},onArchiveSession:async()=>{},onUnarchiveSession:async()=>{},onRenameSession:async()=>k,onDeleteSession:async()=>{}}),i.jsx("div",{className:"mobile-conversation-stage",...me??{},children:i.jsxs("div",{ref:pe,className:"mobile-conversation-main",children:[i.jsx(fn,{connectionState:"closed",onReconnect:()=>{}}),i.jsx("div",{className:"conversation-timeline-shell",children:i.jsx(un,{sessionId:e.sessionId,sessionSummary:null,workspaceId:e.workspaceId,workspacePath:(re==null?void 0:re.path)??null,items:Nr({messages:R}),historyState:"ready",loadingOlderMessages:!1,hasOlderMessages:!1,provider:e.provider,onLoadOlderMessages:()=>{},onRetryMessage:()=>{}})}),v.isOpen?null:i.jsx(dn,{capabilities:M,draftStorageId:e.sessionId,workspaceId:e.workspaceId,panelRef:b?void 0:Pe,portalContainer:b?null:W,contextUsage:null,taskProvider:e.provider,taskMessages:R,isSubmitting:g,isRunning:!1,onSend:async(U,_)=>{var je,Ne,te,ke;const ue=Wc();H(ie=>[...ie,Er(e.sessionId,U,ue,(_==null?void 0:_.attachmentMeta)??[],(_==null?void 0:_.attachments)??[])]),m(!0);const ce=performance.now();Se("session_send.start_live.client_start",{draftSessionId:e.sessionId,workspaceId:N,provider:e.provider,clientRequestId:ue,contentLength:U.length});try{const ie=await Rr({workspaceId:N,provider:e.provider,content:U,clientRequestId:ue,model:(_==null?void 0:_.model)??null,reasoningLevel:(_==null?void 0:_.reasoningLevel)??null,permissionMode:It(),attachments:(_==null?void 0:_.attachments)??[],providerConfigMode:(_==null?void 0:_.providerConfigMode)??"global-default",providerPresetId:(_==null?void 0:_.providerPresetId)??null},{targetHostId:T});Se("session_send.start_live.client_response",{draftSessionId:e.sessionId,sessionId:ie.sessionId,workspaceId:((je=ie.session)==null?void 0:je.workspaceId)??N,provider:ie.provider,clientRequestId:ue,durationMs:Math.round(performance.now()-ce),returnedMessageId:((Ne=ie.message)==null?void 0:Ne.messageId)??null}),ie.session&&d(ie.session);const Ae=((ke=(te=ie.session)==null?void 0:te.workspaceId)==null?void 0:ke.trim())||N,Xe=Ke(T,w);u(ie.sessionId,Ae),Rt("preview"),t($e(Ae,ie.sessionId,Xe),{replace:!0,state:{composer:{sessionId:ie.sessionId,initialModel:(_==null?void 0:_.model)??null,providerConfigMode:(_==null?void 0:_.providerConfigMode)??"global-default",providerPresetId:(_==null?void 0:_.providerPresetId)??null},bootstrap:{sessionId:ie.sessionId,messages:[Hc({created:ie,provider:e.provider,content:U,clientRequestId:ue,attachments:(_==null?void 0:_.attachmentMeta)??[]})]}}}),a()}catch(ie){throw Se("session_send.start_live.client_error",{draftSessionId:e.sessionId,workspaceId:N,provider:e.provider,clientRequestId:ue,durationMs:Math.round(performance.now()-ce),error:ie instanceof Error?ie.message:String(ie)}),H(Ae=>_r(Ae,ue)),ie}finally{m(!1)}}})]})}),b?null:i.jsx(Ui,{activePanel:v.activePanel,open:v.isOpen,sessionId:e.sessionId,workspaceId:e.workspaceId,navigationGroups:r,onClose:()=>{v.closePanel()},onSelectPanel:U=>{v.selectPanel(U)},onSelectPanelBySwipe:U=>{if(U===null){v.closePanel();return}v.selectPanel(U)}}),i.jsx(Xi,{open:L,workspaceName:(Y==null?void 0:Y.workspace.name)??null,sessions:ae,restoringSessionId:B,onClose:()=>{B||X(!1)},onRestore:async U=>{he(U);try{await f(U),F({title:c("shell.archiveRestored"),tone:"success"})}catch(_){F({title:_ instanceof Error?_.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{he(null)}}})]})})}function xc(e,t,s,n=null){var d,h,f;if(!zi(e))return null;const r=((d=s.get("workspaceId"))==null?void 0:d.trim())||null,o=((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!o||!Or(u)?null:{sessionId:e,workspaceId:o,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 Oi(e){const t=new Map(e.map(r=>[r.sessionId,r])),s=new Map,n=r=>{const a=s.get(r.sessionId);if(typeof a=="boolean")return a;if(r.isArchived)return s.set(r.sessionId,!1),!1;const o=mo(r,{mode:"mobile"});if(!o)return s.set(r.sessionId,!0),!0;const u=t.get(o);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 Li(e,t,s){if(!t)return[];const n=ws(e,t);if(!n)return[];const r=Oi(n.sessions).map(o=>({session:o,workspace:n.workspace}));return vs(r,{mode:"mobile"}).filter(o=>!s.has(o.item.session.sessionId)&&!co(o.children,u=>s.has(u.session.sessionId)))}function Di(e,t){return e.filter(s=>!hn(s.session)).flatMap(s=>{const n=ws(t,s.workspace.id);if(!n)return[];const r=vs(Oi(n.sessions).map(o=>({session:o,workspace:n.workspace})),{mode:"mobile"}),a=Hi(r,s.session.sessionId);return a?[a]:[]})}function Hi(e,t){for(const s of e){if(s.item.session.sessionId===t)return s;const n=Hi(s.children,t);if(n)return n}return null}function qi(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 a=r,o=t;function u(){!e.current||!o.isConnected||a.style.setProperty("--mobile-conversation-composer-height",`${o.offsetHeight}px`)}u();const d=typeof ResizeObserver<"u"?new ResizeObserver(u):null;return d==null||d.observe(o),window.addEventListener("resize",u),()=>{d==null||d.disconnect(),window.removeEventListener("resize",u),r.style.removeProperty("--mobile-conversation-composer-height")}},[t,s,n,e])}function Bi(e,t,s,n){l.useEffect(()=>{const r=e.current,a=t.current;if(!s||!r){r&&r.style.removeProperty("--mobile-conversation-page-header-height");return}if(!a){r.style.removeProperty("--mobile-conversation-page-header-height");return}const o=r,u=a;function d(){!e.current||!u.isConnected||o.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 Fi(...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 Wi(e){const t=nn(),s=vt(),n=an(),r=_t(),a=l.useRef(null),o=l.useRef(!1),[u,d]=l.useState(()=>e.initialPanel??On()),h=e.initialPanel??u,f=e.enabled&&e.workspaceId!==null&&e.initialPanel!==null;l.useEffect(()=>{if(!e.enabled){a.current=null,o.current=!1;return}const M=e.initialPanel??On();d(M),Ln(M)},[e.enabled,e.initialPanel]),l.useEffect(()=>{if(!f){o.current=!1;return}if(r.platform!=="android"||!Tc(t.state)||o.current||typeof window>"u"||window.location.pathname!==t.pathname)return;const M=new URLSearchParams(t.search);M.delete("toolPanel");const y=M.toString(),b=`${t.pathname}${y?`?${y}`:""}${t.hash}`,F=`${t.pathname}${t.search}${t.hash}`;window.history.replaceState(window.history.state,"",b),window.history.pushState(window.history.state,"",F),o.current=!0},[f,t.hash,t.pathname,t.search,t.state,r.platform]);function I(M,y){const b=new URLSearchParams(t.search);M?(b.set("toolPanel",M),d(M),Ln(M)):b.delete("toolPanel");const F=b.toString();s({pathname:t.pathname,search:F?`?${F}`:""},{replace:(y==null?void 0:y.replace)??!1})}function T(M){n.trigger("selection"),I(M,{replace:f})}function w(){if(f){if(n.trigger("gesture"),o.current&&typeof window<"u"){o.current=!1,window.history.back();return}I(null,{replace:!0})}}function g(M){if(!e.enabled||!e.workspaceId)return;const y=M??h;n.trigger("gesture"),I(y)}function m(M){if(!e.enabled||M.changedTouches.length!==1){a.current=null;return}if(Cc(M.target)){a.current=null;return}const y=M.changedTouches[0];a.current={x:y.clientX,y:y.clientY}}function R(M){const y=a.current;if(a.current=null,!y||M.changedTouches.length!==1||f||e.suspendMainGesture)return;const b=M.changedTouches[0],F=b.clientX-y.x,k=b.clientY-y.y;F>-56||Math.abs(F)<=Math.abs(k)*1.15||g()}function H(M){const y=a.current;if(a.current=null,!y||M.changedTouches.length!==1||!f)return;const b=M.changedTouches[0],F=b.clientX-y.x,k=b.clientY-y.y;F<56||Math.abs(F)<=Math.abs(k)*1.15||w()}return{activePanel:h,closePanel:w,isOpen:f,mainGestureHandlers:{onTouchStart:m,onTouchMove:()=>{},onTouchEnd:R,onTouchCancel:()=>{a.current=null}},openPanel:g,panelGestureHandlers:{onTouchStart:m,onTouchMove:()=>{},onTouchEnd:H,onTouchCancel:()=>{a.current=null}},selectPanel:T}}function Ui(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 a=r.changedTouches[0];t.current={x:a.clientX,y:a.clientY}}function n(r){const a=t.current;if(t.current=null,!a||r.changedTouches.length!==1)return;const o=r.changedTouches[0],u=o.clientX-a.x,d=o.clientY-a.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(zr,{className:"mobile-conversation-tool-surface",hideHeading:!0,sessionId:e.sessionId,workspaceId:e.workspaceId}):e.activePanel==="git"?i.jsx(Yr,{className:"mobile-conversation-tool-surface",panelActive:!0,workspaceId:e.workspaceId}):i.jsx(Kr,{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 $i(e){const t=an(),[s,n]=l.useState(()=>e?Ps():"immersive"),[r,a]=l.useState(()=>wr()),[o,u]=l.useState(()=>e&&Ps()==="preview"?"default":"closed"),d=l.useRef(o),h=l.useRef(null);l.useEffect(()=>{d.current=o},[o]),l.useEffect(()=>{if(!e){h.current=null,d.current="closed",u("closed"),n("immersive");return}const k=Ps();n(k),u(k==="preview"?"default":"closed")},[e]),l.useEffect(()=>{e&&Rt(s)},[e,s]),l.useEffect(()=>{if(typeof window>"u")return;function k(){a(wr())}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 T(){f("closed"),n("immersive")}function w(){f("expanded"),n("preview")}function g(){if(d.current!=="closed"){t.trigger("gesture"),T();return}t.trigger("gesture"),I()}function m(k,S){const v=S.touches[0]??S.changedTouches[0];if(!e||!v){h.current=null;return}if(_c(S.target)){h.current=null;return}if(k==="main"){if(d.current==="closed"&&v.clientX>vc){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:v.clientX,startY:v.clientY,lastX:v.clientX,lastY:v.clientY,horizontalLocked:!1}}function R(k){const S=h.current,v=k.touches[0];if(!e||!S||!v)return;const x=v.clientX-S.startX,K=v.clientY-S.startY;if(S.lastX=v.clientX,S.lastY=v.clientY,!S.horizontalLocked){if(Math.abs(x)<br&&Math.abs(K)<br)return;if(Math.abs(x)<=Math.abs(K)){h.current=null;return}if(S.intent==="open"&&x<=0){h.current=null;return}if(S.intent==="close"&&x>=0){h.current=null;return}S.horizontalLocked=!0}}function H(k){var K;const S=h.current;if(h.current=null,!(S!=null&&S.horizontalLocked))return;const v=(K=k==null?void 0:k.changedTouches)==null?void 0:K[0];v&&(S.lastX=v.clientX,S.lastY=v.clientY);const x=S.lastX-S.startX;if(S.intent==="open"){x>=mc&&(t.trigger("gesture"),I("default"));return}if(S.intent==="close"){x<=-34&&(t.trigger("gesture"),T());return}if(x<=-34){t.trigger("gesture"),T();return}x>=gc&&d.current==="default"&&(t.trigger("gesture"),w())}const N=o==="expanded"?Fs:o==="default"?vr:0,C=Math.round(r*N*100)/100,M=N===0?0:N/Fs,y={"--mobile-conversation-preview-default-width":`${Math.round(r*vr*100)/100}px`,"--mobile-conversation-preview-max-width":`${Math.round(r*Fs*100)/100}px`,"--mobile-conversation-preview-width":`${C}px`,"--mobile-conversation-preview-progress":M.toFixed(4)};return{closePreview:T,displayMode:o==="closed"?"immersive":"preview",isDragging:!1,isVisible:o!=="closed",mainGestureHandlers:{onTouchStart:k=>m("main",k),onTouchMove:R,onTouchEnd:H,onTouchCancel:H},pageStyle:y,previewWidthPx:C,railGestureHandlers:{onTouchStart:k=>m("rail",k),onTouchMove:R,onTouchEnd:H,onTouchCancel:H},togglePreview:g}}function Vi({visible:e,widthPx:t,isDragging:s,gestureHandlers:n,activeSessionId:r,createSessionActionLabel:a,favoriteItems:o,items:u,expandedRootIds:d,workspaceSectionLabel:h,onCreateSession:f,archiveCurrentActionLabel:I,archiveFolderActionLabel:T,onArchiveActiveSession:w,onOpenArchiveFolder:g,onToggleSubsessions:m,onActivate:R,onToggleFavoriteSession:H,onArchiveSession:N,onUnarchiveSession:C,onRenameSession:M,onDeleteSession:y}){if(!e)return null;function b(F,k){const{workspaceName:S,ancestorExpanded:v=!1,ancestorHasNextSiblings:x=[],hasNextSibling:K=!1,isFirstSibling:$=!1}=k??{},J=F.item.session.sessionId,re=F.children,G=F.depth===0&&re.length>0,j=v||G&&d.includes(J),A=F.depth>0?[...x,K]:[...x];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":F.depth},children:[F.depth>0?i.jsxs("div",{className:"mobile-conversation-preview-guides","aria-hidden":"true",children:[x.map((O,Q)=>O?i.jsx("span",{className:"mobile-conversation-preview-guide-column",style:{"--mobile-preview-tree-level":Q+1}},`${J}:ancestor:${Q}`):null),i.jsx("span",{className:"mobile-conversation-preview-guide-branch","data-continue":K,"data-first":$,style:{"--mobile-preview-tree-level":F.depth},children:i.jsx("span",{className:"mobile-conversation-preview-guide-branch-horizontal"})})]}):null,i.jsx(Ac,{entry:F.item,activeSessionId:r,hasSubsessions:G,subsessionsExpanded:j,workspaceName:S,isFavorite:!!F.item.session.isFavorite,onToggleSubsessions:G?()=>{m(J)}:void 0,onActivate:R,onToggleFavoriteSession:H,onArchiveSession:N,onUnarchiveSession:C,onRenameSession:M,onDeleteSession:y})]}),re.length>0&&j?i.jsx("div",{className:"mobile-conversation-preview-children",children:re.map((O,Q)=>b(O,{workspaceName:S,ancestorExpanded:!0,ancestorHasNextSiblings:A,hasNextSibling:Q<re.length-1,isFirstSibling:Q===0}))}):null]},`${F.item.workspace.id}:${J}`)}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:[a&&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:a})]})}):null,i.jsxs("div",{className:"mobile-conversation-preview-body terminal-mobile-list-body",children:[o.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:o.length})]}),i.jsx("div",{className:"mobile-conversation-preview-list mobile-conversation-preview-list-static terminal-mobile-session-list",children:o.map(F=>i.jsx("div",{children:b(F,{workspaceName:F.item.workspace.name})},`favorite:${F.item.workspace.id}:${F.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(F=>b(F))})]})]}),I&&w||T&&g?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,T&&g?i.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:g,children:T}):null]}):null]})}function Ac({entry:e,activeSessionId:t,isFavorite:s,hasSubsessions:n=!1,subsessionsExpanded:r=!1,onActivate:a,onToggleSubsessions:o,workspaceName:u,onToggleFavoriteSession:d,onArchiveSession:h,onUnarchiveSession:f,onRenameSession:I,onDeleteSession:T}){const w=_t(),g=e.session.sessionId===t,[m,R]=l.useState(!1),[H,N]=l.useState(null),[C,M]=l.useState(null),y=l.useRef(null);l.useLayoutEffect(()=>{if(!m||!C||typeof window>"u"){N(null);return}const $=()=>{var j,A;const G=Tr(C,{width:((j=y.current)==null?void 0:j.offsetWidth)??0,height:((A=y.current)==null?void 0:A.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:bc});N({position:"fixed",left:`${Math.round(G.left)}px`,top:`${Math.round(G.top)}px`,width:`${Math.round(G.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(G.maxHeight)}px`,transformOrigin:G.transformOrigin})},J=G=>{var A;const j=G.target;j&&!((A=y.current)!=null&&A.contains(j))&&F()},re=G=>{G.key==="Escape"&&F()};return $(),window.addEventListener("pointerdown",J),window.addEventListener("keydown",re),window.addEventListener("resize",$),window.addEventListener("scroll",$,!0),()=>{window.removeEventListener("pointerdown",J),window.removeEventListener("keydown",re),window.removeEventListener("resize",$),window.removeEventListener("scroll",$,!0)}},[C,m]);function b($){M($),R(!0)}function F(){R(!1),M(null)}async function k(){const $=e.session.title||c("common.unknown"),J=window.prompt(c("shell.renameModalDescription"),$);J!=null&&J.trim()&&(await I(e.session.sessionId,J.trim()),F())}async function S(){if(e.session.isArchived){await f(e.session.sessionId),F();return}await h(e.session.sessionId),F()}async function v(){await T(e.session.sessionId),F()}function x($){if($.key!=="ContextMenu"&&!($.shiftKey&&$.key==="F10"))return;$.preventDefault(),$.stopPropagation();const J=$.currentTarget.getBoundingClientRect();b({x:J.right,y:J.bottom})}const K=!w.isDesktop&&m&&typeof document<"u"?St.createPortal(i.jsxs("div",{ref:y,className:"workbench-session-menu",role:"menu","aria-label":c("shell.sessionMoreAction"),style:H??{position:"fixed",top:0,left:0,visibility:"hidden"},onClick:$=>$.stopPropagation(),children:[i.jsx("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{k()},children:i.jsx("span",{children:c("shell.renameAction")})}),i.jsx("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{d(e.session.sessionId).then(()=>{F()})},children:i.jsx("span",{children:s?c("shell.unfavoriteAction"):c("shell.favoriteAction")})}),i.jsx("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{S()},children:i.jsx("span",{children:e.session.isArchived?c("shell.unarchiveAction"):c("shell.archiveAction")})}),i.jsx("button",{type:"button",className:"workbench-session-menu-item",onClick:()=>{v()},children:i.jsx("span",{children:c("shell.deleteSessionAction")})})]}),document.body):null;return i.jsxs("article",{className:"mobile-conversation-preview-entry terminal-mobile-session-card","data-active":g,onContextMenu:$=>{$.preventDefault(),$.stopPropagation(),b({x:$.clientX,y:$.clientY})},children:[n?i.jsx("button",{type:"button",className:"mobile-conversation-preview-toggle","aria-label":r?c("shell.subagentCollapse"):c("shell.subagentExpand"),title:r?c("shell.subagentCollapse"):c("shell.subagentExpand"),"aria-expanded":r,onClick:$=>{$.stopPropagation(),o==null||o()},children:i.jsx("span",{className:Ir(e.session,{isActive:g,hasSubsessions:n}),"aria-hidden":"true"})}):i.jsx("span",{className:Ir(e.session,{isActive:g,hasSubsessions:n}),"aria-hidden":"true"}),i.jsx("button",{type:"button",className:"mobile-conversation-preview-item terminal-mobile-session-primary","data-active":g,onClick:()=>a(e),onKeyDown:x,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:Gi(e.session,u)})]})}),K]})}function wr(){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 Ir(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 Gi(e,t){const s=Wr(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(ms,{open:e,title:c("shell.archiveConfirmTitle"),description:c("shell.archiveConfirmDescription"),size:"narrow",layout:"confirm",dismissible:!t,showCloseButton:!1,footer:i.jsxs(gs,{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 Xi({open:e,workspaceName:t,sessions:s,restoringSessionId:n,onClose:r,onRestore:a}){const{searchOpen:o,searchKeyword:u,filteredSessions:d,summaryLoading:h,summaryError:f,summaryBySessionId:I,setSearchKeyword:T,toggleSearch:w}=sa(e,s),g=l.useId(),m=s.length>0&&u.trim().length>0?c("shell.archiveSearchEmpty"):c("shell.archiveEmpty");return i.jsxs(ms,{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":o,onClick:w,children:c("shell.archiveSearchAction")}):void 0,showCloseButton:!1,onClose:r,children:[o?i.jsxs("div",{className:"workbench-archive-search-panel",children:[i.jsx(ts,{label:c("shell.archiveSearchLabel"),htmlFor:g,children:i.jsx("input",{id:g,type:"text",value:u,placeholder:c("shell.archiveSearchPlaceholder"),autoFocus:!0,onChange:R=>T(R.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(uo,{className:"workbench-archive-list",children:d.map(R=>{var M;const H=Gt(R.title,c("common.unknown")),N=((M=I[R.sessionId])==null?void 0:M.trim())??"",C=na(R);return i.jsx(ho,{className:"workbench-archive-item",trailing:i.jsx("button",{type:"button",className:"secondary-button",disabled:n===R.sessionId,onClick:()=>{a(R.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:H.fullTitle,children:H.displayTitle}),C?i.jsx("span",{className:"session-fork-badge archive-child",children:C}):null]}),i.jsx("p",{children:Gi(R)}),o&&N?i.jsx("p",{className:"workbench-archive-item-summary",children:N}):null]})},R.sessionId)})}):i.jsx(fo,{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 zi(e){return e.startsWith("draft-")}function Dc(e){var n,r,a;const t=((n=e.navigationGroups[0])==null?void 0:n.workspace.id)??null,s=(t?e.flattenedNavigationEntries.find(o=>o.workspace.id===t)??null:null)??e.flattenedNavigationEntries[0]??null;if(s){const o=e.targetHostId?(r=e.workspaceRef)!=null&&r.workspaceId?{hostId:e.targetHostId,workspaceId:e.workspaceRef.workspaceId}:null:e.workspaceRef??null;return $e(s.workspace.id,s.session.sessionId,o)}if(t){const o=e.targetHostId?(a=e.workspaceRef)!=null&&a.workspaceId?{hostId:e.targetHostId,workspaceId:e.workspaceRef.workspaceId}:null:e.workspaceRef??null;return wt(t,o)}return e.shellMode==="mobile"?yr():"/landing"}function Ke(e,t){return!e||!(t!=null&&t.workspaceId)?null:{hostId:e,workspaceId:t.workspaceId}}function Hc(e){var a,o,u,d,h,f;const t=((o=(a=e.created.message)==null?void 0:a.providerSessionId)==null?void 0:o.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,a=s.providerConfigMode,o=s.providerPresetId;if(n!==e)return{initialModel:null,providerConfigMode:"global-default",providerPresetId:null};const u=typeof r=="string"&&r.trim()||null,d=typeof o=="string"&&o.trim()||null,h=a==="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-FOhyOpGY.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
+ import{b as d,j as e}from"./index-BilHJjYU.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-FOhyOpGY.js";import{g as L}from"./App-Dl-mcdqy.js";function C(){return e.jsx("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true",children:e.jsx("path",{d:"M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"})})}function O({className:a,"aria-label":r,...o}){return e.jsx("button",{type:"button",className:a?`workbench-modal-close ${a}`:"workbench-modal-close","aria-label":r??j("common.close"),...o,children:e.jsx(C,{})})}function R({open:a,title:r,description:o,hideHeader:l=!1,size:c="compact",layout:s="form",dismissible:n=!0,closeOnBackdrop:v=!0,closeOnEscape:y=!0,backdropVisible:E=!0,className:i,bodyClassName:u,titleClassName:N,titleRef:D,titleProps:I,headerActions:m,beforeCloseButton:M,footer:b,showCloseButton:h=!0,onClose:t,children:g}){const k=d.useId(),f=d.useId(),x=n&&v,w=n&&y,$=!n;return d.useEffect(()=>{if(!a||!w)return;function p(B){B.key==="Escape"&&t()}return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p)}},[w,t,a]),!a||typeof document>"u"?null:L.createPortal(e.jsxs("div",{className:"workbench-modal-layer desktop-modal-layer","data-fullscreen":c==="full"?"true":void 0,"data-layout":s,"data-backdrop-visible":E?"true":"false",children:[e.jsx("button",{type:"button",className:"workbench-modal-backdrop","aria-label":j("common.close"),disabled:!x,onClick:()=>{x&&t()}}),e.jsxs("section",{className:`workbench-modal-card surface-card desktop-modal-card${i?` ${i}`:""}`,"data-size":c,"data-layout":s,role:"dialog","aria-modal":"true","aria-labelledby":l?void 0:k,"aria-label":l?r:void 0,"aria-describedby":!l&&o?f:void 0,children:[l?null:e.jsxs("div",{className:"workbench-modal-header",children:[e.jsxs("div",{className:"workbench-modal-title-wrap",children:[e.jsx("h2",{id:k,className:N,ref:D,...I,children:r}),o?e.jsx("p",{id:f,children:o}):null]}),m||h?e.jsxs("div",{className:"workbench-modal-header-actions",children:[m,M,h?e.jsx(O,{disabled:$,onClick:()=>{n&&t()}}):null]}):null]}),e.jsx("div",{className:u?`workbench-modal-body ${u}`:"workbench-modal-body",children:g}),b?e.jsx("div",{className:"workbench-modal-footer",children:b}):null]})]}),document.body)}export{R as D,O as M};
1
+ import{j as e,t as j,b as d}from"./index-BilHJjYU.js";import{g as L}from"./App-CHsm-VrM.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-BilHJjYU.js";import{r as O,u as C,W as _,m as N,F as $,T as A,g as U}from"./WorkbenchLayout-Bo2BbMY6.js";import{FileContextPanel as V}from"./FileContextPanel-DzMUQvE5.js";import{GitSidebar as z}from"./GitSidebar-C8IC18GH.js";import{TerminalManagerPanel as B}from"./TerminalManagerPanel-wVnoRA8u.js";import{b as H,a as K}from"./workbench-navigation-ED0157V-.js";import{c as J,u as Q,e as X,N as W}from"./App-CHsm-VrM.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./host-alias-Zb2xyVrf.js";import"./DesktopModal-Csj5AdAN.js";import"./relay-entry-Cmc8vTlE.js";import"./WorkbenchModal-YsyEdJ_m.js";import"./MobileSheet-Co-qPMBD.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};