@jingyi0605/codingns 1.0.0-beta.2 → 1.0.0-beta.3

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 (75) hide show
  1. package/dist/public/assets/{AdaptiveButlerPage-BHUAx_24.js → AdaptiveButlerPage-CLHLiZSY.js} +1 -1
  2. package/dist/public/assets/{App-D5hc6KuU.js → App-FYuZfAoO.js} +3 -3
  3. package/dist/public/assets/{BootstrapPage-C2sMZMJa.js → BootstrapPage-3xpnsG-A.js} +1 -1
  4. package/dist/public/assets/ConversationPage-C5_ZqhU3.js +9 -0
  5. package/dist/public/assets/{DesktopDetachPreviewPage-D9Abm5NU.js → DesktopDetachPreviewPage-B77MG82y.js} +1 -1
  6. package/dist/public/assets/{DesktopModal-BCVZq_PQ.js → DesktopModal-K5bEcj38.js} +1 -1
  7. package/dist/public/assets/{DesktopWindowPage-Cotl5fte.js → DesktopWindowPage-DbG-RBAf.js} +1 -1
  8. package/dist/public/assets/{FileContextPanel-DbPOq5w-.js → FileContextPanel-C-1yOton.js} +1 -1
  9. package/dist/public/assets/{GitSidebar-Cuxi2R93.js → GitSidebar-DFHAPT3S.js} +1 -1
  10. package/dist/public/assets/{MobileCreateSessionSheet-DYqarJqO.js → MobileCreateSessionSheet-gOyAZ857.js} +1 -1
  11. package/dist/public/assets/{MobileSheet-DPYtp5Ze.js → MobileSheet-D0MfNkTv.js} +1 -1
  12. package/dist/public/assets/{PluginAccessOverview-CiVzb_NI.js → PluginAccessOverview-IrYIPLg3.js} +1 -1
  13. package/dist/public/assets/{PluginContainerPage-BfZ3E41c.js → PluginContainerPage-b9LQVuqG.js} +1 -1
  14. package/dist/public/assets/{PluginDetailPage-DQQAg_ba.js → PluginDetailPage-BX7gohai.js} +1 -1
  15. package/dist/public/assets/{PluginsListPage-bF1NmA_r.js → PluginsListPage-R0SibHMi.js} +1 -1
  16. package/dist/public/assets/{PureConversationPage-CWji-ARJ.js → PureConversationPage-CcakFvo0.js} +1 -1
  17. package/dist/public/assets/{RelayConnectEntryPage-D4-3Fher.js → RelayConnectEntryPage-cAVq_kNM.js} +1 -1
  18. package/dist/public/assets/{ServerSettingsModal-BUY1Y3g6.js → ServerSettingsModal-BJwYHdKD.js} +1 -1
  19. package/dist/public/assets/{SessionIndexPage-zVB9jnzP.js → SessionIndexPage-CJKRHB_F.js} +1 -1
  20. package/dist/public/assets/{SettingsPage-DeqR2p7d.js → SettingsPage-Csp7wEBC.js} +1 -1
  21. package/dist/public/assets/{TerminalManagerPanel-BjnC70ga.js → TerminalManagerPanel-2HG-NyfR.js} +1 -1
  22. package/dist/public/assets/{ToolFilesPage-BZseQqvZ.js → ToolFilesPage-BAZdjNaF.js} +1 -1
  23. package/dist/public/assets/{ToolGitPage-SrOO8Ftz.js → ToolGitPage-CGkPmgsz.js} +1 -1
  24. package/dist/public/assets/{ToolProcessesPage-Dbzlqjdy.js → ToolProcessesPage-BHpS7-VH.js} +1 -1
  25. package/dist/public/assets/{ToolsHomePage-BBilUc0P.js → ToolsHomePage-DDGqYwYU.js} +1 -1
  26. package/dist/public/assets/{WorkbenchLandingPage-FdsBC8WN.js → WorkbenchLandingPage-B4aooEYJ.js} +1 -1
  27. package/dist/public/assets/{WorkbenchLayout-yGxGKcG1.js → WorkbenchLayout-DrAvGjGK.js} +81 -79
  28. package/dist/public/assets/{WorkbenchModal-Cm-ciXO9.js → WorkbenchModal-BK5ix8YI.js} +1 -1
  29. package/dist/public/assets/WorkbenchShellRoute-p1FvkoPN.js +1 -0
  30. package/dist/public/assets/{WorkspaceDebugDetailPage-CZtpOiY0.js → WorkspaceDebugDetailPage-CPgAe8dd.js} +1 -1
  31. package/dist/public/assets/{WorkspaceDetailPage-CbbgUz1H.js → WorkspaceDetailPage-YM85dTGg.js} +1 -1
  32. package/dist/public/assets/{WorkspaceHomePage-DMNJKAYe.js → WorkspaceHomePage-DPPvwM93.js} +1 -1
  33. package/dist/public/assets/{client-runtime-manager-tsFkLtO_.js → client-runtime-manager-Clq-8rWh.js} +1 -1
  34. package/dist/public/assets/{host-alias-df5bYDlE.js → host-alias-BxzpRYrt.js} +1 -1
  35. package/dist/public/assets/{index-CILPuSCp.js → index-BArTKWXk.js} +3 -3
  36. package/dist/public/assets/index-CqKepLbu.css +1 -0
  37. package/dist/public/assets/{login-direct-candidate-resolver-pkfXrMJy.js → login-direct-candidate-resolver-BiWwFKnk.js} +1 -1
  38. package/dist/public/assets/{peer-host-config-sync-nS_66OLg.js → peer-host-config-sync-kTom1_pp.js} +1 -1
  39. package/dist/public/assets/{plugin-permission-copy-LDy-lW7h.js → plugin-permission-copy-1_1wViri.js} +1 -1
  40. package/dist/public/assets/{plugins-api-BGF9OybZ.js → plugins-api-C0JqR2-W.js} +1 -1
  41. package/dist/public/assets/{preferences-service-BC25oxA_.js → preferences-service-DWeLWZST.js} +1 -1
  42. package/dist/public/assets/{relay-entry-ErQKnI7B.js → relay-entry-ClEd3cjN.js} +1 -1
  43. package/dist/public/assets/{useRegisteredDebugTemplates-BTr3ATCZ.js → useRegisteredDebugTemplates-wJGOYam9.js} +1 -1
  44. package/dist/public/assets/{workbench-navigation-hwM28xIb.js → workbench-navigation-vIWt3Rv_.js} +1 -1
  45. package/dist/public/index.html +2 -2
  46. package/dist/server/modules/sessions/codex-app-server-helper-process.js +84 -20
  47. package/dist/server/modules/sessions/codex-app-server-helper-process.js.map +1 -1
  48. package/dist/server/modules/sessions/session-controller.js +2 -1
  49. package/dist/server/modules/sessions/session-controller.js.map +1 -1
  50. package/dist/server/modules/sessions/session-live-runtime-service.d.ts +14 -0
  51. package/dist/server/modules/sessions/session-live-runtime-service.js +103 -4
  52. package/dist/server/modules/sessions/session-live-runtime-service.js.map +1 -1
  53. package/dist/server/modules/sessions/session-permission-request-service.d.ts +1 -0
  54. package/dist/server/modules/sessions/session-permission-request-service.js +27 -5
  55. package/dist/server/modules/sessions/session-permission-request-service.js.map +1 -1
  56. package/dist/server/modules/sessions/session-provider-config-service.js +1 -0
  57. package/dist/server/modules/sessions/session-provider-config-service.js.map +1 -1
  58. package/dist/server/modules/sessions/workspace-session-runtime-context-service.js +5 -1
  59. package/dist/server/modules/sessions/workspace-session-runtime-context-service.js.map +1 -1
  60. package/dist/server/storage/repositories/session-send-queue-repository.d.ts +1 -0
  61. package/dist/server/storage/repositories/session-send-queue-repository.js +23 -0
  62. package/dist/server/storage/repositories/session-send-queue-repository.js.map +1 -1
  63. package/node_modules/@codingns/session-sync-core/dist/index.d.ts +1 -0
  64. package/node_modules/@codingns/session-sync-core/dist/index.js +1 -0
  65. package/node_modules/@codingns/session-sync-core/dist/index.js.map +1 -1
  66. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-permissions.d.ts +27 -1
  67. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-permissions.js +48 -4
  68. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-permissions.js.map +1 -1
  69. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js +53 -15
  70. package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js.map +1 -1
  71. package/package.json +2 -1
  72. package/scripts/claude-hook-bridge.cjs +167 -0
  73. package/dist/public/assets/ConversationPage-CDpyEOUA.js +0 -9
  74. package/dist/public/assets/WorkbenchShellRoute-CijuAd9-.js +0 -1
  75. package/dist/public/assets/index-CSlwKnM4.css +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 Qi=Object.defineProperty;var Zi=(e,t,s)=>t in e?Qi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Se=(e,t,s)=>Zi(e,typeof t!="symbol"?t+"":t,s);import{t as c,b as l,u as Ji,G as eo,j as i,E as Rn,o as ys,B as to,F as so,_ as kn}from"./index-BArTKWXk.js";import{f as ft,u as pt,e as jt,g as St,h as rn,c as no}from"./App-FYuZfAoO.js";import{D as gs}from"./DesktopModal-K5bEcj38.js";import{w as vs,M as Tt,s as ss,c as $e,x as Vt,n as bs,y as ns,z as ro,p as ws,A as io,B as Tn,l as oo,C as ao,r as lo,D as co,E as Sr,P as uo,F as Us,b as wt,q as yr,G as ho,t as fo,u as po,H as mo,I as xr,J as go,K as Cn,m as vo}from"./workbench-navigation-vIWt3Rv_.js";import{P as bo,Q as wo,b as yt,R as En,U as Io,V as rs,X as Zt,Y as An,Z as Mo,_ as So,$ as xs,a0 as Ht,a1 as _n,a2 as yo,a3 as Pr,a4 as xo,d as Wt,a5 as Po,j as jn,a6 as Rr,a7 as on,a8 as It,a9 as kr,aa as Tr,ab as Ro,ac as ko,ad as To,S as Co,ae as Eo,af as Ao,ag as _o,ah as jo,ai as No,L as Cr,i as Er,aj as Nn,ak as Ar,al as Oo,am as Lo,an as Do,ao as Ho,ap as qo,aq as Bo,ar as Me,as as is,at as Fo,au as $s,av as On,aw as Wo,ax as Uo,ay as $o,az as Vo,aA as _r,aB as Ke,aC as Ps,aD as jr,aE as Nr,aF as Go,aG as Or,aH as Xo,aI as Lr,aJ as an,aK as At,aL as Gt,u as zo,I as ln,aM as Yo,aN as Ko,r as Qo,O as cn,aO as un,aP as Vs,aQ as Zo,aR as Bt,aS as Dr,aT as dn,aU as hn,aV as Hr,aW as Jo,aX as ea,aY as ta,aZ as sa,w as Xt,a_ as qr,a$ as Br,b0 as Fr,b1 as Wr,J as Ur,k as fn,f as $r,c as Is,y as Vr,b2 as Gr,b3 as Xr,M as zr,b4 as na,b5 as ra,x as ia,b6 as oa,N as aa}from"./WorkbenchLayout-DrAvGjGK.js";import{M as la}from"./MobileSheet-D0MfNkTv.js";import{FileContextPanel as Yr}from"./FileContextPanel-C-1yOton.js";import{GitSidebar as Kr}from"./GitSidebar-DFHAPT3S.js";import{W as ca}from"./WorkbenchModal-BK5ix8YI.js";import{TerminalManagerPanel as Qr}from"./TerminalManagerPanel-2HG-NyfR.js";import{w as kt,r as Rs,a as Ln,b as Dn}from"./styles-DwSuZo1w.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./host-alias-BxzpRYrt.js";import"./relay-entry-ClEd3cjN.js";function pn({connectionState:e,onReconnect:t}){const{showToast:s,dismissToast:n}=ft(),r=bo(),a=r?c(wo(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 ua=48;function da(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 ha(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(!da(e))throw new Error(c("conversation.copyContentFailed"))}}function Hn(e,t,s){return Math.min(Math.max(e,t),s)}function ks(e,t=rs){return e&&t.includes(e)?e:t[0]??"codex"}function fa(e){return rs.includes(e)}function pa(e,t){const s=e.flatMap(n=>fa(n)?[n]:[]);return s.length>0?s:t?[t]:[]}function Gs(e){return e?e.nodeType===Node.ELEMENT_NODE?e:e.parentElement:null}function qn(e){var s,n;const t=Gs(e);return((n=(s=t==null?void 0:t.closest("[data-message-id]"))==null?void 0:s.getAttribute("data-message-id"))==null?void 0:n.trim())||null}function ma(e,t){return[t.trim()||c("conversation.selectionActionDefaultPrompt"),"",c("conversation.selectionActionQuotedLabel"),"```text",e.trim(),"```"].join(`
3
+ `)}function Ts(e){if(typeof window>"u")return null;const t=window.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return null;const s=t.getRangeAt(0),n=Gs(s.startContainer),r=Gs(s.endContainer);if(!n||!r||!e.contains(n)||!e.contains(r))return null;const a=t.toString().trim();if(!a)return null;const o=s.getBoundingClientRect();if(!o.width&&!o.height)return null;const u=qn(s.startContainer),d=qn(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 ga({containerRef:e,session:t,currentCapabilities:s}){const n=pt(),r=jt(),{showToast:a}=ft(),{shellMode:o,requestNavigationRefresh:u,selectWorkspace:d,upsertNavigationSession:h,currentTargetHostId:f,currentWorkspaceRef:M}=yt(),T=Ji(m=>m.profile.providers),w=l.useMemo(()=>En(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,p]=l.useState(null),[R,H]=l.useState(null),[O,E]=l.useState(!1),{visibleProviders:I}=Io(rs,O,f),[y,b]=l.useState(""),[F,k]=l.useState(!1),[S,v]=l.useState(ks(t==null?void 0:t.provider)),[P,Q]=l.useState(Zt),[V,te]=l.useState(w.providerConfigMode),[ie,X]=l.useState(w.providerPresetId),[N,j]=l.useState({}),[L,Z]=l.useState(!1),[ge,U]=l.useState(null),[G,le]=l.useState({}),[ce,pe]=l.useState(!1),[q,Y]=l.useState(!1),[D,fe]=l.useState(!1),[me,Ce]=l.useState(0),[Le,qe]=l.useState(null),[ye,W]=l.useState(()=>({width:typeof window>"u"?0:window.innerWidth,height:typeof window>"u"?0:window.innerHeight})),J=l.useRef(!1),$=l.useRef(!1),A=l.useRef(!1),ue=l.useRef(null),de=l.useRef(null),Ee=o==="mobile"||r.isMobile,Oe=l.useMemo(()=>m=>{var z,se;return(eo(m)?(se=(z=T[m])==null?void 0:z.defaultModel)==null?void 0:se.trim():null)||Zt},[T]),re=l.useMemo(()=>En(V,ie),[V,ie]),Ae=l.useMemo(()=>pa(I,S),[S,I]),oe=l.useMemo(()=>An(S),[S]),_e=l.useMemo(()=>oe?N[oe]??null:null,[N,oe]),ze=l.useMemo(()=>Mo(_e),[_e]),Ue=l.useMemo(()=>So(_e),[_e]),st=re.providerConfigMode==="cc-switch-preset"?re.providerPresetId??xs:xs,C=l.useMemo(()=>Ue.find(m=>m.value===st)??Ue[0]??null,[Ue,st]),_=l.useMemo(()=>S===(t==null?void 0:t.provider)&&re.providerConfigMode===w.providerConfigMode&&re.providerPresetId===w.providerPresetId&&s?s:ge??Ht(S),[s,ge,S,re.providerConfigMode,re.providerPresetId,t==null?void 0:t.provider,w.providerConfigMode,w.providerPresetId]),he=l.useMemo(()=>{var z;const m=Ht(S).modelOptions??[];return(z=_.modelOptions)!=null&&z.length?_.modelOptions:m},[_.modelOptions,S]),Re=l.useMemo(()=>he.map(m=>({value:m.id,label:_n(m)?c("conversation.modelUseCliDefault"):m.name})),[he]),K=l.useMemo(()=>he.find(m=>m.id===P)??he[0]??null,[he,P]),ke=l.useMemo(()=>{const m=K?_n(K)?c("conversation.modelUseCliDefault"):K.name:c("conversation.modelUseCliDefault");return ze?`${(C==null?void 0:C.label)??c("conversation.deploymentDefaultPreset")} · ${m}`:m},[K,C,ze]),ae=l.useCallback(m=>{if(v(m),Q(Oe(m)),t&&m===t.provider&&An(m)){te(w.providerConfigMode),X(w.providerPresetId);return}te("global-default"),X(null)},[Oe,t,w.providerConfigMode,w.providerPresetId]),Be=l.useMemo(()=>{const m=G[S]??(S===(t==null?void 0:t.provider)&&re.providerConfigMode===w.providerConfigMode&&re.providerPresetId===w.providerPresetId?s:ge);return!m||m.canStartSession!==!1?null:m.limitations[0]??c("conversation.capabilityDenied")},[s,ge,G,S,re.providerConfigMode,re.providerPresetId,t==null?void 0:t.provider,w.providerConfigMode,w.providerPresetId]),ve=l.useMemo(()=>{var Te;if(!g||typeof window>"u")return null;const m=(Te=e.current)==null?void 0:Te.getBoundingClientRect(),z=m?Math.max(80,m.left+80):96,se=m?Math.min(ye.width-80,m.right-80):ye.width-96,we=m?Math.max(12,m.top+12):12,Ne=m?Math.max(we,m.bottom-48):Math.max(12,ye.height-48),We=g.rect.left+g.rect.width/2;return{left:Hn(We,z,Math.max(z,se)),top:Hn(g.rect.top-48,we,Ne)}},[e,g,ye.height,ye.width]);l.useEffect(()=>{if(typeof window>"u")return;const m=()=>{W({width:window.innerWidth,height:window.innerHeight})};return m(),window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m)}},[]),l.useEffect(()=>{if(!t){de.current!==null&&typeof window<"u"&&(window.clearTimeout(de.current),de.current=null),ue.current=null,A.current=!1,p(null),H(null),E(!1);return}const m=ks(t.provider);ae(m)},[ae,t]),l.useEffect(()=>{if(!O){Z(!1);return}if(!oe){Z(!1);return}let m=!1;return Z(!0),yo({targetHostId:f}).then(z=>{m||j(Object.fromEntries(z.items.map(se=>[se.app,se])))}).catch(()=>{m||j({})}).finally(()=>{m||Z(!1)}),()=>{m=!0}},[O,f,oe]),l.useEffect(()=>{!oe||re.providerConfigMode!=="cc-switch-preset"||!re.providerPresetId||L||!_e||_e.options.some(m=>m.id===re.providerPresetId)||(te("global-default"),X(null))},[L,_e,oe,re.providerConfigMode,re.providerPresetId]),l.useEffect(()=>{if(!t||!e.current||typeof window>"u"){de.current!==null&&(window.clearTimeout(de.current),de.current=null),ue.current=null,A.current=!1,p(null),H(null);return}const m=e.current,z=xe=>{J.current||(ue.current=xe,p(xe),xe||E(!1))},se=()=>{de.current!==null&&(window.clearTimeout(de.current),de.current=null)},we=(xe,ht)=>{if(ue.current=xe,se(),ht!=null&&ht.immediate){z(xe);return}de.current=window.setTimeout(()=>{de.current=null,z(ue.current)},ua)},Ne=()=>{const xe=Ts(m);if(A.current){ue.current=xe;return}we(xe)},We=()=>{const xe=Ts(m);if(A.current){ue.current=xe;return}we(xe,{immediate:!0})},Te=xe=>{!(xe.target instanceof Node)||!m.contains(xe.target)||(A.current=!0,se())},De=()=>{A.current&&(A.current=!1,we(Ts(m)))};return document.addEventListener("pointerdown",Te),document.addEventListener("selectionchange",Ne),window.addEventListener("pointerup",De),window.addEventListener("pointercancel",De),window.addEventListener("mouseup",De),window.addEventListener("touchend",De),window.addEventListener("resize",We),window.addEventListener("scroll",We,!0),()=>{se(),document.removeEventListener("pointerdown",Te),document.removeEventListener("selectionchange",Ne),window.removeEventListener("pointerup",De),window.removeEventListener("pointercancel",De),window.removeEventListener("mouseup",De),window.removeEventListener("touchend",De),window.removeEventListener("resize",We),window.removeEventListener("scroll",We,!0)}},[e,t]),l.useEffect(()=>{(!O||!(R!=null&&R.sourceMessageId))&&k(!1)},[O,R==null?void 0:R.sourceMessageId]),l.useEffect(()=>{if(!O||!t)return;let m=!1;return S===t.provider&&re.providerConfigMode===w.providerConfigMode&&re.providerPresetId===w.providerPresetId&&s?(pe(!1),U(s),()=>{m=!0}):(pe(!0),U(Ht(S)),Pr(S,t.workspaceId,oe?{providerConfigMode:re.providerConfigMode,providerPresetId:re.providerPresetId}:void 0,{targetHostId:f}).then(z=>{m||U(z)}).catch(()=>{m||U(Ht(S))}).finally(()=>{m||pe(!1)}),()=>{m=!0})},[O,f,s,oe,S,re.providerConfigMode,re.providerPresetId,t,w.providerConfigMode,w.providerPresetId]),l.useEffect(()=>{if(!O||!t){le({});return}let m=!1;return xo(Ae,t.workspaceId,{targetHostId:f}).then(z=>{m||le(z)}),()=>{m=!0}},[O,f,t,Ae]),l.useEffect(()=>{if(!O||!t)return;const m=Ae.filter(se=>{const we=G[se];return!we||we.canStartSession!==!1});if(m.length===0||m.includes(S))return;const z=m[0];ae(z)},[O,ae,G,S,t,Ae]),l.useEffect(()=>{var z;const m=Oe(S);if(!he.some(se=>se.id===P)){if(he.some(se=>se.id===m)){Q(m);return}Q(((z=he[0])==null?void 0:z.id)??Zt)}},[he,Oe,P,S]),l.useEffect(()=>{if(!O){J.current=!1;return}J.current=!0},[O]),l.useEffect(()=>{if(typeof window>"u")return;const m=z=>{z.key==="Escape"&&(E(!1),H(null),p(null),J.current=!1)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);async function Qe(){var z,se;if(!g)return;const m=g.text;p(null),typeof window<"u"&&((se=(z=window.getSelection())==null?void 0:z.removeAllRanges)==null||se.call(z));try{await ha(m,r),a({title:c("conversation.copyContentSuccess"),tone:"success"})}catch(we){a({title:we instanceof Error?we.message:c("conversation.copyContentFailed"),tone:"error"})}}function je(){g&&(qe({title:"",content:g.text}),Ce(m=>m+1),fe(!0),E(!1),H(null),p(null),J.current=!1)}function Ze(){var se,we;if(!g||!t)return;const m=g,z=ks(t.provider,Ae.length>0?Ae:rs);ae(z),b(""),k(!1),H(m),p(null),E(!0),typeof window<"u"&&((we=(se=window.getSelection())==null?void 0:se.removeAllRanges)==null||we.call(se))}function nt(m){m.preventDefault(),J.current=!0}function Pe(){$.current=!0,Ze()}function xt(){if($.current){$.current=!1;return}Ze()}async function dt(){var m,z,se,we;if(!(!R||!t)){if(Be){a({title:Be,tone:"error"});return}Y(!0);try{const Ne=ma(R.text,y),We=(K==null?void 0:K.id)===Zt?null:(K==null?void 0:K.id)??null;let Te=null;if(F&&R.sourceMessageId)Te=await Rr(t.sessionId,{sourceType:"message",sourceMessageId:R.sourceMessageId,strategy:"auto",targetProvider:S,providerConfigMode:re.providerConfigMode,providerPresetId:re.providerPresetId,sessionKind:"annotation",annotationSourceMessageId:R.sourceMessageId,annotationSourceText:R.text},{targetHostId:f}),h(Te),await on(Te.sessionId,{content:Ne,clientRequestId:((z=(m=globalThis.crypto)==null?void 0:m.randomUUID)==null?void 0:z.call(m))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:We,permissionMode:It(),providerConfigMode:re.providerConfigMode,providerPresetId:re.providerPresetId},{targetHostId:f});else{const xe=await kr({workspaceId:t.workspaceId,provider:S,content:Ne,clientRequestId:((we=(se=globalThis.crypto)==null?void 0:se.randomUUID)==null?void 0:we.call(se))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:We,permissionMode:It(),providerConfigMode:re.providerConfigMode,providerPresetId:re.providerPresetId,parentSessionId:t.sessionId,sessionKind:"annotation",annotationSourceMessageId:R.sourceMessageId??null,annotationSourceText:R.text},{targetHostId:f});Te=xe.session??await Tr(xe.sessionId,{targetHostId:f})}h(Te),u();const De=f&&M?{hostId:f,workspaceId:M.workspaceId}:M;d(Te.workspaceId,De),n($e(Te.workspaceId,Te.sessionId,De)),E(!1),H(null),p(null),J.current=!1}catch(Ne){a({title:Ne instanceof Error?Ne.message:c("conversation.selectionActionFailed"),tone:"error"})}finally{Y(!1)}}}function Je(m=!1){E(!1),H(null),J.current=!1,m&&p(null)}const mt=!!(!O&&g&&ve),Fe=!!(O&&R),lt=i.jsxs(vs,{children:[i.jsx("button",{type:"button",className:"secondary-button",onClick:()=>Je(!1),children:c("common.cancel")}),i.jsx("button",{type:"button",className:"primary-button",disabled:q||!!Be||Ae.length===0,onClick:()=>void dt(),children:q?c("conversation.sendingState"):c("conversation.selectionActionSubmit")})]}),gt=R?i.jsxs(i.Fragment,{children:[i.jsx(Tt,{className:"conversation-selection-preview-section",heading:c("conversation.selectionActionPreviewLabel"),children:i.jsx("div",{className:"conversation-selection-action-dialog-quote",children:R.text})}),i.jsxs(Tt,{className:"conversation-selection-request-section",children:[i.jsx(ss,{className:"conversation-selection-field conversation-selection-prompt-field",label:c("conversation.selectionActionPromptLabel"),children:i.jsx("textarea",{value:y,rows:4,placeholder:c("conversation.selectionActionPromptPlaceholder"),onChange:m=>b(m.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:m=>k(m.target.checked)}),i.jsx("span",{children:c("conversation.selectionActionIncludeContext")})]}),R.sourceMessageId?null:i.jsx("p",{className:"conversation-selection-hint",children:c("conversation.selectionActionContextUnavailable")}),Be?i.jsx("p",{className:"conversation-selection-hint",children:Be}):null]})]}),i.jsx(Tt,{className:"conversation-selection-target-section",heading:c("conversation.selectionActionTargetLabel"),children:i.jsxs("div",{className:"conversation-selection-grid",children:[i.jsx(ss,{className:"conversation-selection-field",label:c("conversation.forkTargetProviderLabel"),children:i.jsx("select",{value:S,onChange:m=>{ae(m.target.value)},children:Ae.map(m=>{var z;return i.jsx("option",{value:m,disabled:((z=G[m])==null?void 0:z.canStartSession)===!1,children:Wt(m,"full")},m)})})}),i.jsx(ss,{className:"conversation-selection-field",label:c("conversation.forkTargetModelLabel"),children:oe?i.jsx("div",{className:"conversation-selection-deployment-select",children:i.jsx(Po,{ariaLabel:c("conversation.forkTargetModelLabel"),triggerLabel:ke,presetOptions:Ue,selectedPresetValue:st,selectedPresetSummary:(C==null?void 0:C.summary)??null,onSelectPreset:m=>{if(m===xs){te("global-default"),X(null);return}te("cc-switch-preset"),X(m)},modelOptions:Re,selectedModelValue:P,onSelectModel:Q,loadingPresets:L,loadingModels:ce,modelColumnDisabled:ce||!!Be,showPresetColumn:ze,modelEmptyText:c("conversation.deploymentModelEmpty")})}):i.jsx("select",{value:P,disabled:ce||!!Be,onChange:m=>Q(m.target.value),children:he.map(m=>i.jsx("option",{value:m.id,children:m.name},m.id))})})]})})]}):null;return!t||!mt&&!Fe||typeof document>"u"?i.jsx(jn,{open:D,preferredWorkspaceId:(t==null?void 0:t.workspaceId)??null,preferredSessionId:(t==null?void 0:t.sessionId)??null,creationRequestId:me,initialDraft:Le,onClose:()=>fe(!1)}):i.jsxs(i.Fragment,{children:[St.createPortal(mt?i.jsxs("div",{className:"conversation-selection-toolbar",style:ve??void 0,onMouseDown:m=>m.preventDefault(),children:[i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:()=>void Qe(),children:c("conversation.copyAction")}),i.jsx("button",{type:"button",className:"conversation-selection-action",onClick:je,children:c("conversation.selectionTodoAction")}),i.jsx("button",{type:"button",className:"conversation-selection-action is-primary",onPointerDown:nt,onMouseDown:nt,onPointerUp:Pe,onClick:xt,children:c("conversation.selectionActionButton")})]}):null,document.body),Ee?i.jsx(la,{open:Fe,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:()=>Je(!1),children:gt}):i.jsx(gs,{open:Fe,title:c("conversation.selectionActionButton"),size:"compact",layout:"form",className:"conversation-selection-action-dialog",bodyClassName:"conversation-selection-action-dialog-body",footer:lt,onClose:()=>Je(!1),children:gt}),i.jsx(jn,{open:D,preferredWorkspaceId:t.workspaceId,preferredSessionId:t.sessionId,creationRequestId:me,initialDraft:Le,onClose:()=>fe(!1)})]})}function Zr(e,t){return Array.isArray(e)?e.some(s=>s.sessions.some(n=>n.sessionId===t)||Zr(s.children,t)):!1}const Dt=5,Jr=["codex","claude-code"];function ei(){return[{id:"recommended",label:c("conversation.butlerCompletionTemplateRecommendedLabel"),description:c("conversation.butlerCompletionTemplateRecommendedDescription"),value:c("conversation.butlerCompletionTemplateRecommendedValue")},{id:"spec-finish",label:c("conversation.butlerCompletionTemplateSpecLabel"),description:c("conversation.butlerCompletionTemplateSpecDescription"),value:c("conversation.butlerCompletionTemplateSpecValue")},{id:"bugfix",label:c("conversation.butlerCompletionTemplateBugfixLabel"),description:c("conversation.butlerCompletionTemplateBugfixDescription"),value:c("conversation.butlerCompletionTemplateBugfixValue")}]}function Cs(){var e;return((e=ei()[0])==null?void 0:e.value)??""}function Es(e,t=Jr){return e==="claude-code"&&t.includes("claude-code")?"claude-code":t.includes("codex")?"codex":t[0]??null}function ti(e){return e==="codex"||e==="claude-code"}function va(e){return e.flatMap(t=>!t.enabled||!ti(t.provider)?[]:[t.provider])}function si({session:e,showTrigger:t=!0,openRequestKey:s=0}){var qe,ye;const{showToast:n}=ft(),{requestNavigationRefresh:r,currentTargetHostId:a,navigationGroups:o}=yt(),u=l.useId(),d=l.useId(),h=l.useId(),f=l.useId(),[M,T]=l.useState(!1),[w,g]=l.useState(!1),[p,R]=l.useState(null),[H,O]=l.useState(null),[E,I]=l.useState(null),[y,b]=l.useState(Es(e==null?void 0:e.provider)),[F,k]=l.useState(""),[S,v]=l.useState(()=>Cs()),[P,Q]=l.useState(Dt),[V,te]=l.useState(!1),[ie,X]=l.useState(0),N=l.useMemo(()=>{var A,ue,de,Ee;const W=e==null?void 0:e.sessionId;if(!W)return!1;if(!a)return!0;const J=(ue=(A=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:A.workspaceId)==null?void 0:ue.trim(),$=(Ee=(de=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:de.sourceWorkspaceId)==null?void 0:Ee.trim();return!J||!$||J===$?!1:o.some(Oe=>Oe.sessions.some(re=>re.sessionId===W)||Zr(Oe.childWorktrees,W))},[a,o,e==null?void 0:e.sessionId,(qe=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:qe.sourceWorkspaceId,(ye=e==null?void 0:e.sessionIsolatedWorkspace)==null?void 0:ye.workspaceId]),{items:j}=Ro(!!(e!=null&&e.sessionId&&N),a),L=ei(),Z=l.useMemo(()=>j?va(j):Jr,[j]),ge=j!==null&&Z.length===0,U=l.useMemo(()=>{var W;return((W=e==null?void 0:e.title)==null?void 0:W.trim())||null},[e==null?void 0:e.title]),G=l.useMemo(()=>p?{workspaceId:p.workspaceId,project:p.project,session:p.session}:null,[p]),le=(p==null?void 0:p.latestFollowUpTask)??null,ce=(p==null?void 0:p.latestVerificationRun)??null,pe=le&&(le.status==="active"||le.status==="waiting_user")?le:null,q=ce&&(ce.status==="queued"||ce.status==="running")?ce:null;l.useEffect(()=>{T(!1),te(!1),O(null),R(null),k(""),b(Es(e==null?void 0:e.provider)),v(Cs()),Q(Dt)},[e==null?void 0:e.sessionId]),l.useEffect(()=>{const W=Es(e==null?void 0:e.provider,Z);(!y||!Z.includes(y))&&b(W)},[Z,y,e==null?void 0:e.provider]),l.useEffect(()=>{if(!(e!=null&&e.sessionId)||!N){g(!1),R(null),O(null);return}let W=!1;return g(!0),O(null),ko(e.sessionId,{targetHostId:a}).then(J=>{W||R(J.context)}).catch(J=>{W||(R(null),O(J instanceof Error?J.message:c("conversation.butlerActionLoadFailed")))}).finally(()=>{W||g(!1)}),()=>{W=!0}},[ie,a,e==null?void 0:e.sessionId,N]);function Y(){w||X(W=>W+1)}function D(){!p&&!w&&Y()}if(l.useEffect(()=>{t||s<=0||(T(!0),D())},[w,s,t,p]),!(e!=null&&e.sessionId)||!N)return null;async function fe(){if(!G){D();return}if(!y)return;const W=F.trim(),J=S.trim();if(!W){n({title:c("conversation.butlerFollowUpObjectiveRequired"),tone:"warning"});return}if(!J){n({title:c("conversation.butlerFollowUpCompletionCriteriaRequired"),tone:"warning"});return}I("follow-up");try{const $=await jo({projectId:G.project.id,butlerSessionId:G.session.id,providerId:y,objective:W,completionCriteria:J,maxAutoContinueCount:P},{targetHostId:a});R(A=>A&&{...A,latestFollowUpTask:$.task}),r(),n({title:c("conversation.butlerFollowUpStarted"),description:c("conversation.butlerFollowUpStartedDescription",{projectName:G.project.name}),tone:"success"}),k(""),v(Cs()),Q(Dt),T(!1)}catch($){n({title:c("conversation.butlerFollowUpFailed"),description:$ instanceof Error?$.message:void 0,tone:"error"})}finally{I(null)}}async function me(){if(le){I("follow-up");try{const W=await Eo(le.id,{targetHostId:a});R(J=>J&&{...J,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{I(null)}}}async function Ce(){if(!G){D();return}I("verification");try{const W=await _o({projectId:G.project.id,butlerSessionId:G.session.id,verificationType:"browser",targetRef:U||G.session.title||G.project.name},{targetHostId:a});R(J=>J&&{...J,latestVerificationRun:W.result.run}),r(),n({title:c("conversation.butlerVerificationStarted"),description:c("conversation.butlerVerificationStartedDescription",{projectName:G.project.name}),tone:"success"}),T(!1)}catch(W){n({title:c("conversation.butlerVerificationFailed"),description:W instanceof Error?W.message:void 0,tone:"error"})}finally{I(null)}}async function Le(){if(ce){I("verification");try{const W=await Ao(ce.projectId,ce.id,{targetHostId:a});R(J=>J&&{...J,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{I(null)}}}return i.jsxs(i.Fragment,{children:[t?i.jsxs("div",{className:"conversation-butler-entry",onMouseEnter:()=>{te(!0),D()},onMouseLeave:()=>{te(!1)},children:[i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("conversation.butlerActionButton"),title:c("conversation.butlerActionButton"),onFocus:()=>{te(!0),D()},onBlur:()=>{te(!1)},onClick:()=>{T(!0),D()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(To,{})})}),V?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}):le?i.jsxs(i.Fragment,{children:[i.jsxs("p",{children:[c("conversation.butlerAnalysisObjectiveLabel"),":",le.objective]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisStatusLabel"),":",Bn(le.status)]}),i.jsxs("p",{children:[c("conversation.butlerAnalysisSummaryLabel"),":",le.lastAutomationSummary||le.waitingReason||c("conversation.butlerAnalysisEmpty")]}),le.waitingReason?i.jsxs("p",{children:[c("conversation.butlerAnalysisWaitingReasonLabel"),":",le.waitingReason]}):null]}):i.jsx("p",{children:c("conversation.butlerAnalysisEmpty")})]}):null]}):null,i.jsx(ca,{open:M,title:c("conversation.butlerActionModalTitle"),description:c("conversation.butlerActionModalDescription"),className:"conversation-butler-modal-card",footer:!w&&!H&&G?i.jsxs(vs,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:E!==null,onClick:()=>{Ce()},children:c("conversation.butlerVerificationAction")}),i.jsx("button",{type:"button",className:"primary-button",disabled:E!==null||ge||!y,onClick:()=>{fe()},children:c("conversation.butlerFollowUpAction")})]}):void 0,onClose:()=>{E||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&&G?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:G.project.name})]}),i.jsxs("div",{className:"conversation-butler-target-card",children:[i.jsx("span",{children:c("conversation.butlerActionSessionLabel")}),i.jsx("strong",{children:G.session.title||U||G.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")})]}),ge?i.jsx("p",{className:"conversation-butler-modal-hint",children:c("conversation.butlerFollowUpProviderHint")}):i.jsx(Co,{workspaceId:G.workspaceId,providers:Z,selectedProvider:y,disabled:E!==null,onSelect:W=>{ti(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:P,disabled:E!==null,onChange:W=>{const J=Number.parseInt(W.target.value,10);Q(Number.isFinite(J)?J:Dt)}})]})]}),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:E!==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:E!==null,onChange:W=>{v(W.target.value)}}),i.jsx("div",{className:"conversation-butler-preset-grid",role:"group","aria-label":c("conversation.butlerCompletionTemplateSectionLabel"),children:L.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:E!==null,onClick:()=>{v(W.value)},children:[i.jsx("strong",{children:W.label}),i.jsx("span",{children:W.description})]},W.id))})]}),pe||q?i.jsxs("div",{className:"conversation-butler-meta-grid",children:[pe?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:Bn(pe.status)}),i.jsx("small",{children:c("conversation.butlerCurrentFollowUpProgress",{current:pe.autoContinueCount,max:pe.maxAutoContinueCount??Dt})}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:E!==null,onClick:()=>{me()},children:c("conversation.butlerStopFollowUpAction")})]}):null,q?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:ba(q.status)}),i.jsx("small",{children:q.targetRef||q.verificationType}),i.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:E!==null,onClick:()=>{Le()},children:c("conversation.butlerStopVerificationAction")})]}):null]}):null]}):null]})})]})}function Bn(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 ba(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 wa=340;function Ia({session:e,onOpenBranchTree:t}){const s=pt(),n=rn(),r=l.useRef(null),a=l.useRef(null),[o,u]=l.useState(!1),[d,h]=l.useState(null),[f,M]=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"){M(null);return}const b=()=>{var v,P;const S=Cr(d,{width:((v=a.current)==null?void 0:v.offsetWidth)??0,height:((P=a.current)==null?void 0:P.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:wa});M({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 P,Q;const v=S.target;v&&!((P=a.current)!=null&&P.contains(v))&&!((Q=r.current)!=null&&Q.contains(v))&&p()},k=S=>{S.key==="Escape"&&p()};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 p(){u(!1),h(null)}function R(b){s(b),p()}function H(b){const F=new URLSearchParams(n.search);F.set("toolPanel",b),R(`${n.pathname}?${F.toString()}`)}function O(){if(o){p();return}g()}function E(b){b.key!=="ContextMenu"&&!(b.shiftKey&&b.key==="F10")||(b.preventDefault(),b.stopPropagation(),g())}if(!e)return null;const I=[{key:"assistant",label:c("shell.butlerEntry"),onSelect:()=>{w(b=>b+1),p()}},...t?[{key:"branch",label:c("conversation.branchAction"),onSelect:()=>{t(),p()}}]:[],{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:I.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:O,onKeyDown:E,children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(No,{})})}),i.jsx(si,{session:e,showTrigger:!1,openRequestKey:T})]}),y]})}function ni({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 Ma(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(Sa(n,r,a)){o.current=!0;return}o.current&&(o.current=!1,s(!1))},[a,r,t,n,s])}function Sa(e,t,s){return t===!0||s===!0||(e==null?void 0:e.runningState)==="stale"||(e==null?void 0:e.runningState)==="unknown"?!0:Er(e)}const ya=30,As=80,qt=60,ri=600,Fn=300*1e3,xa=600,Pa=5e3,Ra=1e4,Xs=120*1e3,ii=8,ka=/\[\[CODINGNS_IMAGE_ATTACHMENTS\]\][\s\S]*?\[\[\/CODINGNS_IMAGE_ATTACHMENTS\]\]/g;class Ta{constructor(t,s={}){Se(this,"state");Se(this,"authoritativeMessages",[]);Se(this,"runtimeOverlayMessages",[]);Se(this,"activeRuntimeOverlayKeys",[]);Se(this,"pendingMessages",[]);Se(this,"listeners",new Set);Se(this,"realtimeClient",null);Se(this,"historyBootstrapFallbackTimer",null);Se(this,"historyBootstrapEnvelopeReceived",!1);Se(this,"markSeenTimer",null);Se(this,"markSeenInFlight",!1);Se(this,"lastMarkSeenRequestAt",0);Se(this,"seenWatermark",null);Se(this,"runtimeRefreshTimer",null);Se(this,"runtimeRefreshMode",null);Se(this,"replaceSnapshotSeedOnBackfill",!1);Se(this,"olderHistoryPrefetchCursor",null);Se(this,"olderHistoryPrefetchPromise",null);Se(this,"prefetchedOlderHistoryPage",null);Se(this,"pendingReplyDebugTraces",[]);Se(this,"hasAuthoritativeBootstrapMessages");Se(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));Se(this,"getState",()=>this.state);var o;this.sessionId=t,this.options=s;const n=Rn(Bs(t,s.targetHostId),Fn);this.hasAuthoritativeBootstrapMessages=(((o=s.bootstrapMessages)==null?void 0:o.length)??0)>0;const r=Jt(s.initialSession??null,(n==null?void 0:n.session)??null),a=Gn(Ca(),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)<qt&&((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=Nn({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,permissionStatus:(n==null?void 0:n.permissionStatus)??null,messages:a.messages,timelineItems:Ns(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:il(this.state.session,n?this.authoritativeMessages.length:0),loadingOlderMessages:!1,olderCursor:n?null:this.state.olderCursor,hasOlderMessages:Rt({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=Rn(Bs(this.sessionId,this.options.targetHostId),Fn),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)<qt&&((t==null?void 0:t.pagesLoaded)??0)<=1});this.state=Nn({session:Jt(this.options.initialSession??null,(t==null?void 0:t.session)??null),capabilities:(t==null?void 0:t.capabilities)??null,runtimeHasActiveRun:(t==null?void 0:t.runtimeHasActiveRun)??null,runtimeCanInterrupt:(t==null?void 0:t.runtimeCanInterrupt)??null,contextUsage:(t==null?void 0:t.contextUsage)??null,permissionStatus:(t==null?void 0:t.permissionStatus)??null,messages:s.messages,permissionRequests:(t==null?void 0:t.permissionRequests)??[],queuedMessages:(t==null?void 0:t.queuedMessages)??[],olderCursor:(t==null?void 0:t.olderCursor)??null,hasOlderMessages:(t==null?void 0:t.hasOlderMessages)??!1,lastCursor:(t==null?void 0:t.lastCursor)??null,pagesLoaded:(t==null?void 0:t.pagesLoaded)??0}),this.seenWatermark=((r=this.state.session)==null?void 0:r.lastSeenAt)??null,this.emit(),await this.initialize()}applyNavigationSession(t){if(!t||t.sessionId!==this.sessionId)return;const s=Jt(this.state.session,t);s!==this.state.session&&this.patch({session:s,hasOlderMessages:Rt({session:s,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})})}async sendMessage(t,s){const n=sr();this.beginPendingReplyDebugTrace("send_live",n,t.length);const r=Ar(this.sessionId,t,n,(s==null?void 0:s.attachmentMeta)??[],(s==null?void 0:s.attachments)??[],tl(this.buildTimelineMessages("send_sequence"),this.state.session)),a=this.applyTimelineEvent({type:"pending.insert",source:"send_pending",pending:r});this.patch({messages:a.messages,session:at(this.state.session,"running"),runtimeHasActiveRun:nr(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:rr(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:at(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:nr(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:rr(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:at(this.state.session,"failed")}),r}}async enqueueMessage(t,s){const n=sr();try{const r=await Oo(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:ml(this.state.queuedMessages,r)}),await this.refreshQueue()}catch(r){throw r}}async deleteQueuedMessage(t){await Lo(this.sessionId,t,{targetHostId:this.options.targetHostId}),await this.refreshQueue()}async steerQueuedMessage(t){await Do(this.sessionId,t,{targetHostId:this.options.targetHostId}),await this.refreshRuntimeSnapshot("queue_steer")}async interrupt(){await Ho(this.sessionId,{targetHostId:this.options.targetHostId}),this.patch({session:at(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 qo(this.sessionId,t,s,{targetHostId:this.options.targetHostId});this.patch({permissionRequests:Fs(this.state.permissionRequests,r)})}reconnect(){var t;(t=this.realtimeClient)==null||t.reconnectNow()}async loadOlderMessages(){var t;if(!(this.state.historyState!=="ready"||this.state.loadingOlderMessages||!this.state.olderCursor)){this.patch({loadingOlderMessages:!0,errorCode:null,errorDetail:null});try{const s=this.state.olderCursor,n=await this.takePrefetchedOlderHistoryPage(s);if(n&&this.state.olderCursor===s){this.applyOlderHistoryPage(n,"prefetch_cache");return}if(!((t=this.realtimeClient)==null?void 0:t.requestOlderMessages(s,As)))throw new Error("REALTIME_NOT_CONNECTED")}catch(s){const n=s instanceof Error?s.message:"unknown";this.patch({loadingOlderMessages:!1,errorCode:"HISTORY_LOAD_MORE_FAILED",errorDetail:n})}}}destroy(){var t;this.clearHistoryBootstrapFallbackTimer(),this.clearOlderHistoryPrefetch(),(t=this.realtimeClient)==null||t.close(),this.realtimeClient=null,this.pendingReplyDebugTraces.length=0,this.markSeenTimer!==null&&(window.clearTimeout(this.markSeenTimer),this.markSeenTimer=null),this.runtimeRefreshTimer!==null&&(window.clearTimeout(this.runtimeRefreshTimer),this.runtimeRefreshTimer=null),this.runtimeRefreshMode=null}startRealtime(){var s;if(!((s=ys.getState().session)==null?void 0:s.accessToken)){ys.clear();return}this.realtimeClient=new Bo({targetHostId:this.options.targetHostId,sessionId:this.sessionId,cursor:this.state.lastCursor,limit:qt,onSubscribed:()=>{Me("session_send.realtime_subscribed",{sessionId:this.sessionId,lastCursor:this.state.lastCursor}),this.patch({connectionState:"connected",hasOlderMessages:Rt({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"&&tt((a=this.state.session)==null?void 0:a.runningState)?at(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:Rt({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:at(this.state.session,Zn(n.type,(u=this.state.session)==null?void 0:u.runningState))}),(d=this.realtimeClient)==null||d.updateCursor(n.cursor),this.scheduleMarkSeen(),this.scheduleOlderHistoryPrefetch(n.type==="session.backfill"?"backfill":"delta"),this.state.queuedMessages.length>0&&this.refreshQueue()},onOlderHistory:n=>{this.applyOlderHistoryPage({messages:n.messages,nextCursor:n.olderCursor},"realtime")},onRuntimeMessage:n=>{this.handleRuntimeMessage(n)},onActivity:n=>{this.handleActivity(n)},onRuntimeStatus:n=>{this.handleRuntimeStatus(n)},onRuntimeError:n=>{this.handleRuntimeError(n)},onInterrupted:n=>{this.handleInterrupted(n)},onPermissionRequest:n=>{this.handlePermissionRequest(n)},onPermissionRequestResolved:n=>{this.handlePermissionRequestResolved(n)},onError:n=>{this.patch({loadingOlderMessages:!1,errorCode:n.error_code,errorDetail:n.detail})},onUnauthorized:()=>{ys.clear()}}),this.realtimeClient.start()}patch(t){let s=t;Object.prototype.hasOwnProperty.call(t,"session")&&(this.syncSeenWatermark(t.session??null),s={...t,session:this.applySeenWatermark(t.session??null)}),(Object.prototype.hasOwnProperty.call(s,"session")||Object.prototype.hasOwnProperty.call(s,"messages"))&&(s={...s,timelineItems:Ns((Object.prototype.hasOwnProperty.call(s,"session")?s.session:this.state.session)??null,(Object.prototype.hasOwnProperty.call(s,"messages")?s.messages:this.state.messages)??[])}),this.state={...this.state,...s},(Object.prototype.hasOwnProperty.call(s,"session")||Object.prototype.hasOwnProperty.call(s,"capabilities")||Object.prototype.hasOwnProperty.call(s,"contextUsage")||Object.prototype.hasOwnProperty.call(s,"messages")||Object.prototype.hasOwnProperty.call(s,"timelineItems")||Object.prototype.hasOwnProperty.call(s,"permissionRequests")||Object.prototype.hasOwnProperty.call(s,"queuedMessages"))&&this.persistSnapshot(),this.emit()}applyTimelineEvent(t){const s=Gn({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=Ja(s.previousMessages,s.messages,"assistant"),r=Za(t);return(s.validationIssues.length>0||r.some(o=>o.role==="assistant")||n.length>0)&&is("timeline.event",{sessionId:this.sessionId,eventType:t.type,source:t.source,replacedSnapshotSeed:s.replacedSnapshotSeed,validationIssues:s.validationIssues,authoritativeCount:this.authoritativeMessages.length,runtimeOverlayCount:this.runtimeOverlayMessages.length,pendingCount:this.pendingMessages.length,eventMessages:r.map(o=>vi(o)),assistantMoves:n,previousTail:zn(s.previousMessages.slice(-6)),nextTail:zn(s.messages.slice(-6))}),s}mergeHistoryMessages(t,s,n){const r=this.applyTimelineEvent({type:"history.merge",source:n,messages:t,replaceSnapshotSeed:s});return this.logCodexMergeDebug(n,r.previousMessages,t,r.messages,{replacedSnapshotSeedAttempted:s,replacedSnapshotSeed:r.replacedSnapshotSeed,baseMessageCount:r.replacedSnapshotSeed?0:r.previousMessages.length}),{messages:r.messages,replacedSnapshotSeed:r.replacedSnapshotSeed}}buildTimelineMessages(t){return Qs({authoritativeMessages:this.authoritativeMessages,runtimeOverlayMessages:this.runtimeOverlayMessages,activeRuntimeOverlayKeys:this.activeRuntimeOverlayKeys,pendingMessages:this.pendingMessages,replaceSnapshotSeedOnBackfill:this.replaceSnapshotSeedOnBackfill})}clearActiveRuntimeTail(t){if(this.activeRuntimeOverlayKeys.length===0)return;this.activeRuntimeOverlayKeys=[];const s=this.buildTimelineMessages(t);this.patch({messages:s})}resolvePendingMessage(t,s){this.applyTimelineEvent({type:"pending.resolve",source:"pending_resolved",clientRequestId:s,message:t})}handleError(t){this.clearHistoryBootstrapFallbackTimer();const s=t instanceof Error?t.message:"unknown";this.patch({historyState:"error",errorCode:"RUNTIME_INIT_FAILED",errorDetail:s})}scheduleMarkSeen(){if(this.markSeenTimer!==null)return;const t=this.getTargetSeenAt();if(this.markSeenInFlight||t===null)return;const s=this.getMarkSeenThrottleDelayMs(),n=Math.max(xa,s);this.markSeenTimer=window.setTimeout(()=>{this.markSeenTimer=null;const r=this.getTargetSeenAt();r!==null&&(Me("session_seen.start",{sessionId:this.sessionId,targetSeenAt:r,seenWatermark:this.seenWatermark}),this.markSeenInFlight=!0,this.lastMarkSeenRequestAt=Date.now(),Fo(this.sessionId,{targetHostId:this.options.targetHostId}).then(()=>{var a,o;this.bumpSeenWatermark(r),this.patch({session:Yn(this.state.session,r)}),(o=(a=this.options).onSeen)==null||o.call(a,this.sessionId,r),Me("session_seen.end",{sessionId:this.sessionId,seenWatermark:this.seenWatermark})}).catch(()=>{Me("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(ri,Math.max(qt,this.authoritativeMessages.length,ya)),s=await $s(this.sessionId,null,t,"backward",{targetHostId:this.options.targetHostId});if(this.historyBootstrapEnvelopeReceived)return;this.historyBootstrapEnvelopeReceived=!0;const{messages:n,replacedSnapshotSeed:r}=this.mergeHistoryMessages(s.messages,this.replaceSnapshotSeedOnBackfill,"http_bootstrap_fallback");this.patch({messages:n,historyState:"ready",olderCursor:!r&&this.state.pagesLoaded>1?this.state.olderCursor:s.nextCursor,hasOlderMessages:!r&&this.state.pagesLoaded>1?this.state.hasOlderMessages:Rt({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}),Me("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,Me("session.history_older.prefetch.start",{sessionId:this.sessionId,requestedCursor:t,reason:s,limit:As});const n=$s(this.sessionId,t,As,"backward",{targetHostId:this.options.targetHostId}).then(a=>(this.state.olderCursor===t&&(this.prefetchedOlderHistoryPage={requestedCursor:t,page:a}),Me("session.history_older.prefetch.end",{sessionId:this.sessionId,requestedCursor:t,messageCount:a.messages.length,nextCursor:a.nextCursor}),a)).catch(a=>(Me("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,Me("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,Me("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(!tt((n=this.state.session)==null?void 0:n.runningState)){this.clearRuntimeRefreshTimer();return}t==="poll"&&this.state.connectionState==="connected"||(this.clearRuntimeRefreshTimer(),this.runtimeRefreshMode=t,Me("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"?Ra:1200))}async refreshRuntimeState(t,s){var n,r,a,o,u;Me("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 On(this.sessionId,{targetHostId:this.options.targetHostId}),h=Hs(this.state.runtimeHasActiveRun,d.runningState,d.hasActiveRun),f=qs(this.state.runtimeCanInterrupt,d.runningState,h,d.canInterrupt);this.patch({session:Kn(this.state.session,d),runtimeHasActiveRun:h,runtimeCanInterrupt:f,contextUsage:d.contextUsage,permissionStatus:d.permissionStatus,...Ls(d,this.state.interruptSource)}),await this.refreshQueue();const M=t==="poll"&&this.state.connectionState!=="connected"&&tt((r=this.state.session)==null?void 0:r.runningState);Me("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:M}),M&&this.scheduleRuntimeRefresh("poll","connection_poll")}catch(d){Me("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"&&tt((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(Tr(this.sessionId,{targetHostId:this.options.targetHostId}).then(s=>{this.patch({session:Jt(s,this.state.session)})}).catch(()=>{})),Qn(this.state.capabilities)&&t.push(Wo(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 Uo(this.sessionId,{targetHostId:this.options.targetHostId});this.patch({permissionRequests:t.items})}catch{return}}shouldRefreshSessionDetail(){return this.state.session===null||Qn(this.state.capabilities)||this.state.session.runningState===null}shouldRefreshRuntimeSnapshot(){return this.state.contextUsage===null||pl(this.state.session,this.state.runtimeHasActiveRun,this.state.runtimeCanInterrupt)}async refreshRuntimeSnapshot(t){Me("session_runtime.snapshot.start",{sessionId:this.sessionId,reason:t});try{const s=await On(this.sessionId,{targetHostId:this.options.targetHostId}),n=Hs(this.state.runtimeHasActiveRun,s.runningState,s.hasActiveRun),r=qs(this.state.runtimeCanInterrupt,s.runningState,n,s.canInterrupt);this.patch({session:Kn(this.state.session,s),runtimeHasActiveRun:n,runtimeCanInterrupt:r,contextUsage:s.contextUsage,permissionStatus:s.permissionStatus,...Ls(s,this.state.interruptSource)}),await this.refreshQueue(),Me("session_runtime.snapshot.end",{sessionId:this.sessionId,reason:t,hasContextUsage:s.contextUsage!==null})}catch(s){Me("session_runtime.snapshot.error",{sessionId:this.sessionId,reason:t,message:s instanceof Error?s.message:"unknown"})}}async refreshQueue(){try{const t=await $o(this.sessionId,{targetHostId:this.options.targetHostId});this.patch({queuedMessages:t.items})}catch{return}}async sendMessageWithFallback(t,s,n){var r;try{return await on(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 to)||a.status!==404&&a.status!==405||(((r=n==null?void 0:n.attachments)==null?void 0:r.length)??0)>0)throw a;return Me("session_send.live_fallback",{sessionId:this.sessionId,clientRequestId:s,reason:a.message}),Vo(this.sessionId,{content:t,clientRequestId:s,permissionMode:It()},{targetHostId:this.options.targetHostId})}}handleRuntimeStatus(t){var n;const s=Os((n=this.state.session)==null?void 0:n.runningState,t.status);this.patch({session:at(this.state.session,s),runtimeHasActiveRun:tt(s)?this.state.runtimeHasActiveRun??!0:!1,runtimeCanInterrupt:tt(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}),$t(s)&&(this.clearActiveRuntimeTail("runtime_status_terminal"),this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_terminal_before_message",{status:t.status,detail:t.detail}),this.clearRuntimeRefreshTimer(),this.refreshQueue(),this.refreshRuntimeSnapshot("runtime_terminal"))}handleActivity(t){const s=Hs(this.state.runtimeHasActiveRun,t.runningState,t.hasActiveRun),n=qs(this.state.runtimeCanInterrupt,t.runningState,s,t.canInterrupt);if(this.patch({session:al(this.state.session,t),runtimeHasActiveRun:s,runtimeCanInterrupt:n,...Ls(t,this.state.interruptSource)}),$t(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:_r(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:Rt({session:this.state.session,loadedMessageCount:this.authoritativeMessages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),session:at(this.state.session,Zn("session.delta",(r=this.state.session)==null?void 0:r.runningState))}),this.scheduleMarkSeen(),this.state.queuedMessages.length>0&&this.refreshQueue()}handleRuntimeError(t){var n;const s=Os((n=this.state.session)==null?void 0:n.runningState,"failed");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_runtime_error",{errorCode:t.error_code,detail:t.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:at(this.state.session,s),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:null,errorCode:s==="failed"?t.error_code:this.state.errorCode,errorDetail:s==="failed"?t.detail:this.state.errorDetail}),this.refreshQueue()}handleInterrupted(t){var n;const s=Os((n=this.state.session)==null?void 0:n.runningState,"interrupted");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_interrupted",{detail:t.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:at(this.state.session,s),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:s==="interrupted"?t.interruptSource??this.state.interruptSource:this.state.interruptSource,errorCode:s==="interrupted"?null:this.state.errorCode,errorDetail:s==="interrupted"?t.detail:this.state.errorDetail}),this.refreshQueue()}handlePermissionRequest(t){this.patch({permissionRequests:Fs(this.state.permissionRequests,t.request)})}handlePermissionRequestResolved(t){this.patch({permissionRequests:Fs(this.state.permissionRequests,t.request)})}shouldMarkSeen(){return this.getTargetSeenAt()!==null}getTargetSeenAt(){const t=[...this.state.messages].reverse().find(n=>n.role!=="user");if(!t)return null;const s=this.seenWatermark;return s?t.timestamp>s?t.timestamp:null:t.timestamp}syncSeenWatermark(t){t!=null&&t.lastSeenAt&&this.bumpSeenWatermark(t.lastSeenAt)}bumpSeenWatermark(t){this.seenWatermark&&this.seenWatermark>=t||(this.seenWatermark=t)}getMarkSeenThrottleDelayMs(){return this.lastMarkSeenRequestAt<=0?0:Math.max(0,Pa-(Date.now()-this.lastMarkSeenRequestAt))}applySeenWatermark(t){return!t||!this.seenWatermark?t:Yn(t,this.seenWatermark)}emit(){for(const t of this.listeners)t()}persistSnapshot(){so(Bs(this.sessionId,this.options.targetHostId),{session:this.state.session,capabilities:this.state.capabilities,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage,permissionStatus:this.state.permissionStatus,messages:ir(this.authoritativeMessages),timelineItems:Ns(this.state.session,ir(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),Me(`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(),Me(`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&&(Me(`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();Me(`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&&(Me(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(cl);if(o.length===0)return;const u=er(s),d=er(r);Ke("session.messages.merge",{sessionId:this.sessionId,source:t,beforeCount:s.length,incomingCount:n.length,afterCount:r.length,incoming:o.slice(0,5).map(dl),beforeDuplicateGroupCount:u.length,afterDuplicateGroupCount:d.length,afterDuplicateGroups:d.slice(0,3),...a})}}function Ca(){return{authoritativeMessages:[],runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:!1}}function Ea(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=pi(s,n,r,a);if(o){const h=s.get(o)??null;if(h){Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"prefer_equivalent",previous:be(h),overlay:be(r),replacedSameId:a?be(a):null}),s.set(o,_s(h,r));continue}}if(a){Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"same_id",previous:be(a),overlay:be(r)}),s.set(r.id,_s(a,r));continue}const u=mn(s,n,r);if(u){const h=s.get(u)??null;if(h){Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"codex_compat",previous:be(h),overlay:be(r)}),s.set(u,_s(h,r));continue}}const d=gn(s,r);if(d&&n.has(d)){const h=s.get(d)??null;if(h){if(Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"opencode_compat",previous:be(h),overlay:be(r)}),Ms(h,r)){s.set(d,Wn(h,r));continue}s.set(d,Wn(h,r));continue}}Ke("session.messages.runtime_overlay_authoritative_bridge",{mode:"insert",overlay:be(r)}),s.set(r.id,r)}return Oa(Array.from(s.values()))}function _s(e,t){return{...oi(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 oi(e,t){if(e.id!==t.id)return t;if(Ut(e,t)){const o=os(e.toolCall,t.toolCall),u=ai(e,t,o,as),d=ls(e.attachments,t.attachments),h=cs(e,t);return{...Ct(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 Ct(e,t);const s=os(e.toolCall,t.toolCall),n=as(e.content,t.content,e.timestamp,t.timestamp),r=ls(e.attachments,t.attachments),a=cs(e,t);return{...Ct(e,t),content:n,toolCall:s,attachments:r,attachmentPayloads:e.attachmentPayloads??t.attachmentPayloads??null,rawRef:a.rawRef,timestamp:a.timestamp,sequence:a.sequence}}function Wn(e,t){if(Ut(e,t)){const o=os(e.toolCall,t.toolCall),u=ai(e,t,o,as),d=ls(e.attachments,t.attachments),h=cs(e,t);return{...Ct(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{...Ct(e,t),id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId};const s=os(e.toolCall,t.toolCall),n=as(e.content,t.content,e.timestamp,t.timestamp),r=ls(e.attachments,t.attachments),a=cs(e,t);return{...Ct(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 Ut(e,t){return Ms(e,t)||Ss(e,t)}function ai(e,t,s,n){if((s==null?void 0:s.status)==="running"){if(t.kind==="tool_call"&&t.content)return t.content;if(e.kind==="tool_call"&&e.content)return e.content}else{if(t.kind==="tool_result"&&t.content)return t.content;if(e.kind==="tool_result"&&e.content)return e.content;if(s!=null&&s.output)return s.output}return n(e.content,t.content,e.timestamp,t.timestamp)}function mn(e,t,s){if(!Ks(s))return null;for(const[n,r]of e.entries())if(!(n===s.id||!t.has(n)||!Aa(r,s)))return Ke("session.messages.codex_identity_bridge_match",{previous:be(r),incoming:be(s)}),n;return null}function Aa(e,t){if(!Da(e,t))return!1;if(e.rawRef===t.rawRef)return!0;if(e.kind==="tool_call"||e.kind==="tool_result")return Ss(e,t);const s=ds(e.rawRef),n=ds(t.rawRef);if(!s||!n||s!==n)return!1;const r=Math.abs(e.sequence-t.sequence);return r>1?(Ke("session.messages.codex_identity_bridge_rejected",{reason:"sequence_distance",sequenceDistance:r,previous:be(e),incoming:be(t)}),!1):!0}function gn(e,t){if(!$n(t))return null;const s=us(t.rawRef);if(s===null)return null;const n=_t(t.timestamp);let r=null,a=Number.POSITIVE_INFINITY;for(const[o,u]of e.entries()){if(o===t.id||!$n(u)||u.role!==t.role)continue;if(Ms(u,t))return o;if(u.kind!==t.kind||us(u.rawRef)!==s)continue;const h=_t(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 _a(e,t,s){if(!vn(t))return!1;const n=zs(e.authoritativeMessages,t,"authoritative",s);if(n)return Ke("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"authoritative",matched:be(n),incoming:be(t)}),!0;const r=zs(e.pendingMessages,t,"pending",s);return r?(Ke("session.messages.runtime_user_echo_suppressed",{sessionId:s,target:"pending",matched:be(r),incoming:be(t)}),!0):!1}function zs(e,t,s,n){const r=_t(t.timestamp),a=Ge(t.content),o=Ys(t.content),u=hs(t.attachments);let d=null,h=Number.POSITIVE_INFINITY;const f=[];for(const M of e){if(!(s==="authoritative"?La(M):ci(M)))continue;const w=Ge(M.content),g=Ys(M.content),p=w===a,R=g===o;if(!p&&!R)continue;const H=_t(M.timestamp),O=Math.abs(H-r);if(O>300*1e3)continue;const E=Math.abs(M.sequence-t.sequence),I=hs(M.attachments),y=qa(I,u);if(f.push(Fa(M,{strictTextMatches:p,relaxedTextMatches:R,attachmentCompatibility:y,distanceMs:O,sequenceDistance:E})),y==="conflict"&&(p||a.length===0))continue;const b=O+E*15e3+(p?0:500)+Ba(y);b<h&&(d=M,h=b)}return f.length>0&&Ke("session.messages.runtime_user_match",{sessionId:n,target:s,matchedId:(d==null?void 0:d.id)??null,matchedScore:Number.isFinite(h)?h:null,incoming:Wa(t,{relaxedContent:o,attachmentSignature:u}),candidates:f.slice(0,5)}),d}function ja(e,t,s){for(const n of t){if(n.role!=="user"||n.kind!=="text")continue;const r=_r(s,n,"sent",null);if(!zs(e,r,"authoritative",s))return!0}return!1}function os(e,t){return e?t?{...Na(e,t),input:li(e.input,t.input),output:Un(e.output,t.output),error:Un(e.error,t.error)}:e:t}function Na(e,t){const s=e.status==="running"?0:1,n=t.status==="running"?0:1;return n!==s?n>s?t:e:t}function as(e,t,s,n){const r=Ge(e),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 ls(e,t){const s=(e==null?void 0:e.length)??0,n=(t==null?void 0:t.length)??0;return n!==s?n>s?t:e:t??e}function li(e,t){return t.length>e.length?t:e}function Un(e,t){return e===null?t:t===null?e:li(e,t)}function Ct(e,t){return t.timestamp!==e.timestamp?t.timestamp.localeCompare(e.timestamp)>=0?t:e:t.sequence!==e.sequence?t.sequence>=e.sequence?t:e:t}function cs(e,t){return Gt(e,t)<=0?e:t}function Ge(e){return e.replace(ka,"").replace(/\r\n/g,`
4
+ `).trimEnd()}function Ys(e){return Ge(e).replace(/[ \t]+\n/g,`
5
+ `).replace(/\n{2,}/g,`
6
+ `).trim()}function Oa(e){return[...e].sort((t,s)=>Gt(t,s))}function Ks(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("codex://")&&(e.role==="assistant"||e.role==="tool")}function vn(e){return e.role==="user"&&e.kind==="text"}function ci(e){return vn(e)&&e.deliveryState!=="failed"&&(e.rawRef.startsWith("pending://")||e.rawRef.startsWith("synthetic://")||e.rawRef.includes("#synthetic"))}function La(e){return vn(e)&&!ci(e)}function $n(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 Vn(e){return e.deliveryState==="sent"&&e.rawRef.startsWith("opencode://")&&e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")&&e.toolCall!==null}function Ms(e,t){var r,a;if(!Vn(e)||!Vn(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:us(e.rawRef)===us(t.rawRef)}function us(e){if(!e.startsWith("opencode://"))return null;const t=e.indexOf("#"),s=t>=0?e.slice(t):"",n=t>=0?e.slice(0,t):e,r=n.indexOf("?");if(r<0)return e;const 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 Da(e,t){if(!Ks(e)||!Ks(t)||e.role!==t.role)return!1;const s=(e.kind==="tool_call"||e.kind==="tool_result")&&(t.kind==="tool_call"||t.kind==="tool_result");return!s&&e.kind!==t.kind?!1:s?Ss(e,t):Math.abs(e.sequence-t.sequence)>ii||!di(e.timestamp,t.timestamp,Xs)?!1:t.kind==="text"||t.kind==="thinking"?ui(e,t,Xs):!1}function ui(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=At(e.content),r=At(t.content);return di(e.timestamp,t.timestamp,s)&&Ge(n.text)===Ge(r.text)&&Ha(n.inlineImages,r.inlineImages)}function Ss(e,t){if(e.deliveryState!=="sent"||t.deliveryState!=="sent"||!e.rawRef.startsWith("codex://")||!t.rawRef.startsWith("codex://")||e.role!=="tool"||t.role!=="tool"||e.kind!=="tool_call"&&e.kind!=="tool_result"||t.kind!=="tool_call"&&t.kind!=="tool_result"||e.toolCall===null||t.toolCall===null)return!1;const s=e.toolCall.callId.trim(),n=t.toolCall.callId.trim();return s.length>0&&s===n}function ds(e){const t=e.match(/^codex:\/\/(.+?)(?:#|$)/);return(t==null?void 0:t[1])??null}function Ha(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 di(e,t,s){return Math.abs(_t(e)-_t(t))<=s}function _t(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function be(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(At(e.content).text).slice(0,160):Ge(e.content).slice(0,160)}}function hs(e){return(e??[]).map(t=>[t.kind,t.fileName.trim().toLowerCase(),t.mimeType.trim().toLowerCase(),String(t.fileSize)].join(":")).sort().join("|")}function qa(e,t){return!e&&!t?"same":!e||!t?"one_side_missing":e===t?"same":"conflict"}function Ba(e){switch(e){case"same":return 0;case"one_side_missing":return 2500;case"conflict":default:return 12e4}}function Fa(e,t){return{...be(e),comparableContent:Ys(e.content).slice(0,160),attachmentSignature:hs(e.attachments),strictTextMatches:t.strictTextMatches,relaxedTextMatches:t.relaxedTextMatches,attachmentCompatibility:t.attachmentCompatibility,distanceMs:t.distanceMs,sequenceDistance:t.sequenceDistance}}function Wa(e,t){return{...be(e),comparableContent:t.relaxedContent.slice(0,160),attachmentSignature:t.attachmentSignature}}function Qs(e){let t=Ea(e.authoritativeMessages,e.runtimeOverlayMessages);for(const s of e.pendingMessages)t=Nr(t,s);return Va(t,e.authoritativeMessages,e.runtimeOverlayMessages,e.activeRuntimeOverlayKeys)}function Gn(e,t,s){const n=Qs(e);let r=e,a=!1;switch(s.type){case"timeline.seed":{r={authoritativeMessages:Ps(s.snapshotMessages,t,s.bootstrapMessages),runtimeOverlayMessages:[],activeRuntimeOverlayKeys:[],pendingMessages:[],replaceSnapshotSeedOnBackfill:s.replaceSnapshotSeedOnBackfill};break}case"history.merge":{a=s.replaceSnapshotSeed&&e.replaceSnapshotSeedOnBackfill&&sl(e.authoritativeMessages,s.messages);const u=a?[]:e.authoritativeMessages;r={...e,authoritativeMessages:Ps(u,t,s.messages),activeRuntimeOverlayKeys:ja(e.authoritativeMessages,s.messages,t)?[]:e.activeRuntimeOverlayKeys,replaceSnapshotSeedOnBackfill:a?!1:e.replaceSnapshotSeedOnBackfill};break}case"runtime.message":{if(_a(e,s.message,t)){r=e;break}r={...e,runtimeOverlayMessages:Go(e.runtimeOverlayMessages,[s.message]),activeRuntimeOverlayKeys:Ga(e,e.activeRuntimeOverlayKeys,s.message)};break}case"pending.insert":{r={...e,activeRuntimeOverlayKeys:s.pending.role==="user"?[]:e.activeRuntimeOverlayKeys,pendingMessages:Nr(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:jr(e.pendingMessages,s.clientRequestId)};break}case"pending.resolve":{const u=e.pendingMessages.find(h=>h.clientRequestId===s.clientRequestId)??null;let d=Ps(e.authoritativeMessages,t,[s.message]);u&&(d=d.map(h=>{if(h.id!==s.message.messageId)return h;const f=h.attachments??[];return{...h,attachments:f.length>0?f:u.attachments??[],attachmentPayloads:u.attachmentPayloads??h.attachmentPayloads??null,clientRequestId:s.clientRequestId}})),r={...e,authoritativeMessages:d,activeRuntimeOverlayKeys:s.message.role==="user"?[]:e.activeRuntimeOverlayKeys,pendingMessages:e.pendingMessages.filter(h=>h.clientRequestId!==s.clientRequestId)};break}}r={...r,runtimeOverlayMessages:$a(r.authoritativeMessages,r.runtimeOverlayMessages)},r={...r,activeRuntimeOverlayKeys:za(r.authoritativeMessages,r.runtimeOverlayMessages,r.activeRuntimeOverlayKeys)};const o=Qs(r);return{timeline:r,previousMessages:n,messages:o,replacedSnapshotSeed:a,validationIssues:Ua(e,r,s,n,o)}}function Ua(e,t,s,n,r){var f,M,T;const a=[],o=hi(r,t.authoritativeMessages,t.runtimeOverlayMessages,t.activeRuntimeOverlayKeys),u=js(r.map(w=>w.id));u.length>0&&a.push(`rendered_duplicate_ids:${u.join(",")}`);const d=js(t.authoritativeMessages.map(w=>w.id));d.length>0&&a.push(`authoritative_duplicate_ids:${d.join(",")}`);const h=js(t.pendingMessages.map(w=>w.clientRequestId).filter(w=>!!w));if(h.length>0&&a.push(`pending_duplicate_client_request_ids:${h.join(",")}`),Js(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"&&!gi(e.authoritativeMessages,t.authoritativeMessages)&&a.push("runtime_message_mutated_authoritative_layer"),s.type==="history.merge"&&s.source.startsWith("older_history")&&!Qa(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)!==((M=r.at(-1))==null?void 0:M.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 $a(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=Zs(s,n,o);if(!u)return!0;const d=fs(u,o);return!d&&fi(r,o)?(is("timeline.runtime_overlay_stale_dropped",{overlay:be(o),authoritativeMatch:be(u),latestAuthoritative:r?be(r):null}),!1):(!d&&mi(o)&&is("timeline.runtime_overlay_not_absorbed",{overlay:be(o),authoritativeMatch:be(u)}),!d)});return a.length===t.length?t:a}function Va(e,t,s,n){const r=hi(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 gi(e,o)?e:o}function hi(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=>[an(f),f])),h=[];for(const f of n){const M=d.get(f)??null;if(!M||!bn(t,M))continue;const T=Zs(r,a,M);if(T&&fs(T,M))continue;const w=Zs(o,u,M);!w||h.includes(w.id)||h.push(w.id)}return h}function Ga(e,t,s){if(!bn(e.authoritativeMessages,s))return t;const n=an(s);return t.includes(n)?t:[...t,n]}function bn(e,t){return mi(t)?!fi(e.at(-1)??null,t):!1}function fi(e,t){return!e||Ut(t,e)?!1:Xa(t,e)<0}function Xa(e,t){const s=e.timestamp.localeCompare(t.timestamp);return s!==0?s:e.sequence!==t.sequence?e.sequence-t.sequence:Gt(e,t)}function za(e,t,s){if(s.length===0)return s;const n=new Map(t.map(o=>[an(o),o])),r=e.at(-1)??null,a=s.filter(o=>{const u=n.get(o)??null;if(!u)return!1;const d=bn(e,u);return d||is("timeline.runtime_overlay_tail_deactivated",{overlay:be(u),latestAuthoritative:r?be(r):null}),d});return a.length===s.length?s:a}function Zs(e,t,s){const n=e.get(s.id)??null,r=pi(e,t,s,n);if(r)return e.get(r)??null;if(n)return n;const a=mn(e,t,s);if(a)return e.get(a)??null;const o=gn(e,s);return o?e.get(o)??null:null}function pi(e,t,s,n){const r=Ya(e,t,s),a=mn(e,t,s),o=gn(e,s),u=r??a??o;if(!u)return null;if(!n)return u;const d=e.get(u)??null;return!d||!Ka(n,d,s)?null:u}function Ya(e,t,s){if(s.role!=="assistant"||s.kind!=="text"&&s.kind!=="thinking"||s.deliveryState!=="sent"||!s.rawRef.startsWith("codex://"))return null;const n=ds(s.rawRef);if(!n)return null;for(const[r,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=ds(a.rawRef),u=Math.abs(a.sequence-s.sequence),d=o===n;if(!(!o||Gt(a,s)<0||!d&&u>ii||!ui(a,s,Xs)))return Ke("session.messages.codex_runtime_overlay_bridge_match",{bridgeMode:d?"same_store":"cross_store_sequence_window",sequenceDistance:u,previous:be(a),incoming:be(s)}),r}return null}function Ka(e,t,s){return!Ut(e,s)||!Ut(t,s)?!1:!fs(e,s)&&fs(t,s)}function mi(e){return e.role==="assistant"&&(e.kind==="text"||e.kind==="thinking")||e.role==="tool"&&(e.kind==="tool_call"||e.kind==="tool_result")}function fs(e,t){if(e.role!==t.role||e.kind!==t.kind&&!(Ms(e,t)||Ss(e,t)))return!1;const s=oi(e,{...t,id:e.id,clientRequestId:e.clientRequestId??t.clientRequestId});return Xn(s)===Xn(e)}function Xn(e){const t=e.kind==="text"||e.kind==="thinking"?Ge(At(e.content).text):Ge(e.content);return JSON.stringify({role:e.role,kind:e.kind,content:t,attachments:hs(e.attachments),toolCall:e.toolCall===null?null:{callId:e.toolCall.callId,name:e.toolCall.name,status:e.toolCall.status,input:Ge(e.toolCall.input),output:Ge(e.toolCall.output??""),error:Ge(e.toolCall.error??"")}})}function js(e){const t=new Map;for(const s of e)t.set(s,(t.get(s)??0)+1);return Array.from(t.entries()).filter(([,s])=>s>1).map(([s])=>s)}function Js(e,t=[]){if(t.length>0){const s=new Set(t),n=e.filter(r=>s.has(r.id));if(n.length>0){const r=e.filter(o=>!s.has(o.id));return e.slice(-n.length).some(o=>!s.has(o.id))?!1:Js(r)&&Js(n)}}for(let s=1;s<e.length;s+=1)if(Gt(e[s-1],e[s])>0)return!1;return!0}function gi(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 Qa(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 Za(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 Ja(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,M=o.get(h)??null,T=M??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:(M==null?void 0:M.sequence)??null,fromRawRef:(f==null?void 0:f.rawRef)??null,toRawRef:(M==null?void 0:M.rawRef)??null,anchorChanged:(f==null?void 0:f.sequence)!==(M==null?void 0:M.sequence)||(f==null?void 0:f.timestamp)!==(M==null?void 0:M.timestamp)||(f==null?void 0:f.rawRef)!==(M==null?void 0:M.rawRef)})}return d.slice(0,8)}function vi(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:el(e.content)}}function zn(e){return e.map(t=>vi(t))}function el(e){const t=e.replace(/\s+/g," ").trim();return t.length>80?`${t.slice(0,80)}...`:t}function He(e,t){const[s,n]=l.useState(()=>t(e.getState()));return l.useEffect(()=>(n(t(e.getState())),e.subscribe(()=>{n(t(e.getState()))})),[t,e]),s}function Ns(e,t){return Or({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,sessionDetail:(e==null?void 0:e.detail)??null})}function bi(e){const t=e==null?void 0:e.messageCount;return typeof t=="number"&&Number.isFinite(t)?t:null}function tl(e,t){const s=Xo(e),n=bi(t);return n===null?s:Math.max(s,n+1)}function sl(e,t){const s=nl(t);if(!s)return!1;const n=rl(e);return n?wn(s.sequence,s.timestamp,n.sequence,n.timestamp)>=0:!0}function nl(e){let t=null;for(const s of e)(!t||wn(s.sequence,s.timestamp,t.sequence,t.timestamp)>0)&&(t=s);return t}function rl(e){let t=null;for(const s of e)s.deliveryState==="sent"&&(!t||wn(s.sequence,s.timestamp,t.sequence,t.timestamp)>0)&&(t=s);return t}function wn(e,t,s,n){return e!==s?e-s:t.localeCompare(n)}function il(e,t){return t>0?"ready":"loading"}function ol(e,t){const s=bi(e);return s!==null?s>t:t>=qt}function Rt(e){return e.olderCursor?!0:e.pagesLoaded>1?e.currentHasOlderMessages:ol(e.session,e.loadedMessageCount)}function at(e,t){return e&&{...e,runningState:t,activityState:Ii(e,t,e.completedAt??null,tt(t))}}function Yn(e,t){return!e||e.lastSeenAt&&e.lastSeenAt>=t?e:{...e,lastSeenAt:t,activityState:e.activityState==="completed_unread"?"idle":e.activityState}}function Kn(e,t){return wi(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 al(e,t){return wi(e,t)}function wi(e,t){if(!e)return e;const s=ll(t.activityResolutionSource),n=$t(t.runningState)?Ds(e.completedAt,t.updatedAt):null,r=t.runningState==="completed"||t.runningState==="interrupted"||t.runningState==="failed"?Ds(e.lastEventAt,t.updatedAt):t.updatedAt;return{...e,runningState:t.runningState,activitySource:s,activityResolutionSource:t.activityResolutionSource,activityConfidence:t.activityConfidence,runId:t.runId,lastEventAt:r,completedAt:n,lastErrorCode:t.runningState==="failed"?t.errorCode??e.lastErrorCode:null,lastErrorDetail:t.runningState==="failed"?t.errorDetail??t.detail??e.lastErrorDetail:null,watchdogTriggeredAt:t.watchdogTriggeredAt,updatedAt:Ds(e.updatedAt,t.updatedAt)??t.updatedAt,activityState:Ii(e,t.runningState,n,t.hasActiveRun)}}function Ii(e,t,s,n){return n||tt(t)?"running":s&&(!e.lastSeenAt||s>e.lastSeenAt)?"completed_unread":e.activityState==="running"||e.activityState==="completed_unread"?"idle":e.activityState??"idle"}function tt(e){return e==="starting"||e==="running"||e==="reconnecting"}function $t(e){return e==="completed"||e==="interrupted"||e==="failed"}function Qn(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 Zn(e,t){return e==="session.backfill"?t??"idle":t==="completed"||t==="interrupted"||t==="failed"?t:"running"}function Os(e,t){return $t(e)&&(t==="completed"||t==="interrupted"||t==="failed")?e:t}function Ls(e,t){return e.runningState==="failed"?{interruptSource:null,errorCode:e.errorCode,errorDetail:e.errorDetail??e.detail}:e.runningState==="interrupted"?{interruptSource:e.interruptSource??null,errorCode:null,errorDetail:e.detail}:e.runningState==="completed"?{interruptSource:null,errorCode:null,errorDetail:e.detail}:{interruptSource:t,errorCode:null,errorDetail:null}}function ll(e){return e==="authoritative_runtime"||e==="authoritative_provider_event"?"runtime":e==="inferred_log"?"inferred":"none"}function cl(e){return e.provider==="codex"&&(e.role==="assistant"||e.role==="tool")}function ul(e){return e.rawRef.startsWith("codex://")&&e.deliveryState==="sent"&&(e.role==="assistant"||e.role==="tool")}function dl(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:Mi(e.content,e.kind??"text")}}function Jn(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:Mi(e.content,e.kind)}}function er(e){const t=new Map;for(const n of e){if(!ul(n))continue;const r=hl(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||fl(d,u)){o.push(u);continue}o.length>1&&s.push({signature:n,messages:o.map(Jn)}),o=[u]}o.length>1&&s.push({signature:n,messages:o.map(Jn)})}return s}function hl(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=At(e.content),s=en(t.text),n=t.inlineImages.map(o=>o.url).join("|");return[e.role,e.kind,s,n].join(":")}function fl(e,t){const s=tr(e.timestamp),n=tr(t.timestamp);return Math.abs(s-n)<=120*1e3&&Math.abs(e.sequence-t.sequence)<=8}function Mi(e,t){return t==="text"||t==="thinking"?en(At(e).text).slice(0,160):en(e).slice(0,160)}function en(e){return e.replace(/\r\n/g,`
7
+ `).trimEnd()}function tr(e){const t=Date.parse(e);return Number.isFinite(t)?t:0}function Ds(e,t){return e?t?e>=t?e:t:e:t??null}function sr(){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 Si(e,t){return t&&(!e||e.provider===t.provider)?t:null}function nr(e,t){const s=Si(e,t);return s?!!s.canSendMessage:e?Lr(e.provider):!1}function rr(e,t){const s=Si(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 pl(e,t,s){return t===!0||s===!0?!0:e?e.activityState==="running"||e.runningState==="starting"||e.runningState==="running"||e.runningState==="reconnecting"||e.runningState==="stale"||e.runningState==="unknown":!1}function Hs(e,t,s){return s?!0:e===!0&&tt(t)}function qs(e,t,s,n){return n?!0:e===!0&&(s||tt(t))}function Bs(e,t){const s=t==null?void 0:t.trim();return s?`session-runtime.snapshot.host.${encodeURIComponent(s)}.${e}`:`session-runtime.snapshot.${e}`}function ir(e){return e.filter(t=>t.deliveryState==="sent").slice(-ri)}function ml(e,t){const s=e.filter(n=>n.id!==t.id);return s.push(t),s.sort((n,r)=>n.orderIndex-r.orderIndex),s}function Fs(e,t){const s=e.filter(n=>n.id!==t.id);return s.push(t),s.sort((n,r)=>n.status!==r.status?n.status==="pending"?-1:1:r.createdAt.localeCompare(n.createdAt)),s}function Jt(e,t){if(!e)return t;if(!t||or(e,t)||ar(e,t))return e;if(or(t,e)||ar(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 or(e,t){return lr(e)&&!lr(t)&&e.lastEventAt===t.lastEventAt&&e.lastMessageAt===t.lastMessageAt&&e.completedAt===t.completedAt}function ar(e,t){if(!cr(e)||cr(t))return!1;const s=e.completedAt??e.lastEventAt??null;return s?(!t.lastEventAt||t.lastEventAt<=s)&&(!t.completedAt||t.completedAt<=s):!1}function lr(e){return e.activityState==="running"||tt(e.runningState)}function cr(e){return $t(e.runningState)}const gl="workbench:focus-composer",vl=15e3,bl=320;function yi(){typeof window>"u"||window.dispatchEvent(new CustomEvent(gl))}function xi(e){var oe,_e,ze,Ue,st;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,M]=l.useState(null),[T,w]=l.useState(null),g=ft(),{showToast:p}=g,R=g.dismissToast??(()=>{}),H=zo(C=>C.notificationPreferences.notifyOnPermissionRequest),O=jt(),E=ln(),I=l.useRef(null),y=l.useRef(null),b=l.useRef(null),F=l.useRef(((oe=e.externalSession)==null?void 0:oe.runningState)??null),k=l.useRef(new Set),S=((_e=e.targetHostId)==null?void 0:_e.trim())||null;(!t.current||s.current!==e.sessionId||n.current!==S)&&((ze=t.current)==null||ze.destroy(),t.current=new Ta(e.sessionId,{targetHostId:S,initialSession:e.externalSession,bootstrapMessages:e.bootstrapMessages??[],onSeen:e.onSeen}),s.current=e.sessionId,n.current=S);const v=t.current,P=He(v,C=>C.session),Q=He(v,C=>C.capabilities),V=He(v,C=>C.runtimeHasActiveRun),te=He(v,C=>C.runtimeCanInterrupt),ie=He(v,C=>C.messages),X=He(v,C=>C.timelineItems),N=He(v,C=>C.permissionRequests),j=He(v,C=>C.queuedMessages),L=He(v,C=>C.contextUsage),Z=He(v,C=>C.permissionStatus),ge=He(v,C=>C.historyState),U=He(v,C=>C.errorCode),G=He(v,C=>C.errorDetail),le=He(v,C=>C.interruptSource),ce=He(v,C=>C.loadingOlderMessages),pe=He(v,C=>C.hasOlderMessages),q=He(v,C=>C.connectionState),Y=Er(P),D=r&&!T,fe=Y||V===!0||D?!0:V,me=te===!0||D?!0:te,Ce=Y||D,Le=(P==null?void 0:P.provider)===(Q==null?void 0:Q.provider)&&Yo(Q),qe=j.some(C=>C.status==="queued"||C.status==="dispatching"),ye=P??e.externalSession??null,W=Sl({sessionId:e.sessionId,provider:(P==null?void 0:P.provider)??null,runningState:(P==null?void 0:P.runningState)??null,activityState:(P==null?void 0:P.activityState)??null,runtimeHasActiveRun:V,messages:ie}),J=e.enableThinkingPlaceholder===!1||!W?null:c("conversation.runtimeThinkingPlaceholder",{provider:c("conversation.providerCodex")}),$=l.useMemo(()=>Ko(X,J),[X,J]);Ma({sending:r,setSending:a,session:P,runtimeHasActiveRun:V,runtimeCanInterrupt:te}),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(()=>{var _,he,Re;if(!e.onBindSessionWorkspace)return;const C=((_=P==null?void 0:P.workspaceId)==null?void 0:_.trim())||((Re=(he=e.externalSession)==null?void 0:he.workspaceId)==null?void 0:Re.trim())||null;if(C)return e.onBindSessionWorkspace(e.sessionId,C),()=>{var K;(K=e.onBindSessionWorkspace)==null||K.call(e,e.sessionId,null)}},[(Ue=e.externalSession)==null?void 0:Ue.workspaceId,e.onBindSessionWorkspace,e.sessionId,P==null?void 0:P.workspaceId]),l.useEffect(()=>{if(e.enableCompletionHaptics===!1)return;const C=F.current,_=(P==null?void 0:P.runningState)??null;(C==="starting"||C==="running"||C==="reconnecting")&&_==="completed"&&E.trigger("success"),F.current=_},[E,e.enableCompletionHaptics,P==null?void 0:P.runningState]),l.useEffect(()=>{var Re;if((e.permissionRequestNotificationMode??"always")==="current_only"&&!e.isCurrent)return;const _=N.filter(K=>K.status==="pending"),he=(P==null?void 0:P.workspaceId)??((Re=e.externalSession)==null?void 0:Re.workspaceId)??null;for(const K of _){if(k.current.has(K.id)||(k.current.add(K.id),!H))continue;const ke=wl(K.kind);p({id:`${e.permissionToastIdPrefix??"permission-request"}-${K.id}`,title:ke,description:K.title,tone:"warning",durationMs:8e3,action:he&&e.onNavigateToSession?{label:c("shell.contextOpenSession"),onClick:()=>{var ae;(ae=e.onNavigateToSession)==null||ae.call(e,he,e.sessionId)}}:void 0}),O.bridge.showNotification(ke,K.title)}},[(st=e.externalSession)==null?void 0:st.workspaceId,e.isCurrent,e.onNavigateToSession,e.permissionRequestNotificationMode,e.permissionToastIdPrefix,e.sessionId,H,N,O.bridge,P==null?void 0:P.workspaceId,p]),l.useEffect(()=>{if(e.enableRuntimeErrorHandling!==!1)return()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)}},[e.enableRuntimeErrorHandling]),l.useEffect(()=>{var C;e.enableRuntimeErrorHandling!==!1&&(U!=="SESSION_NOT_FOUND"&&U!=="WORKSPACE_NOT_FOUND"||(R("conversation-runtime-error"),(C=e.onResolveMissingSession)==null||C.call(e)))},[R,e.enableRuntimeErrorHandling,e.onResolveMissingSession,U]),l.useEffect(()=>{if(e.enableRuntimeErrorHandling===!1)return;if(U==="SESSION_NOT_FOUND"||U==="WORKSPACE_NOT_FOUND"){b.current!==null&&(window.clearTimeout(b.current),b.current=null),y.current=null,I.current=null,R("conversation-runtime-error");return}if(!U||!G){b.current!==null&&(window.clearTimeout(b.current),b.current=null),y.current=null,I.current=null,R("conversation-runtime-error");return}const C=`${U}:${G}`;if(!(I.current===C||y.current===C)){if(b.current!==null&&(window.clearTimeout(b.current),b.current=null),Ml((P==null?void 0:P.provider)??null,U,G)){y.current=C,b.current=window.setTimeout(()=>{y.current=null,b.current=null,I.current=C,p({id:"conversation-runtime-error",title:c("conversation.runtimeErrorTitle"),description:G,tone:"error",durationMs:null})},vl);return}y.current=null,I.current=C,p({id:"conversation-runtime-error",title:c("conversation.runtimeErrorTitle"),description:G,tone:"error",durationMs:null})}},[R,e.enableRuntimeErrorHandling,U,G,P==null?void 0:P.provider,p]);const A=l.useCallback(async(C,_)=>{var K,ke,ae,Be,ve,Qe,je;const he=T;if(!he){await v.sendMessage(C,{model:_==null?void 0:_.model,reasoningLevel:_==null?void 0:_.reasoningLevel,providerConfigMode:_==null?void 0:_.providerConfigMode,providerPresetId:(_==null?void 0:_.providerPresetId)??null,attachments:_==null?void 0:_.attachments,attachmentMeta:_==null?void 0:_.attachmentMeta}),(K=e.onRequestNavigationRefresh)==null||K.call(e);return}let Re=null;try{Re=await Rr(e.sessionId,{sourceType:"message",sourceMessageId:he.sourceMessageId,sourceMessageSnapshot:he.sourceMessageSnapshot,strategy:"auto",targetProvider:he.targetProvider,providerConfigMode:he.targetProviderConfigMode??(_==null?void 0:_.providerConfigMode),providerPresetId:he.targetProviderPresetId??(_==null?void 0:_.providerPresetId)??null}),(ke=e.onUpsertNavigationSession)==null||ke.call(e,Re),await on(Re.sessionId,{content:C,clientRequestId:Il(),model:he.targetModel,reasoningLevel:(_==null?void 0:_.reasoningLevel)??null,permissionMode:It(),attachments:(_==null?void 0:_.attachments)??[],providerConfigMode:he.targetProviderConfigMode??(_==null?void 0:_.providerConfigMode),providerPresetId:he.targetProviderPresetId??(_==null?void 0:_.providerPresetId)??null}),w(null),(ae=e.onRequestNavigationRefresh)==null||ae.call(e),(Be=e.onNavigateToSession)==null||Be.call(e,Re.workspaceId,Re.sessionId),(ve=e.onForkSuccess)==null||ve.call(e,Re)}catch(Ze){throw Re&&((Qe=e.onUpsertNavigationSession)==null||Qe.call(e,Re),(je=e.onRequestNavigationRefresh)==null||je.call(e)),Ze}},[T,e,v]),ue=l.useCallback(async(C,_)=>{a(!0);try{await A(C,_)}finally{a(!1)}},[A]),de=l.useCallback(async(C,_)=>{a(!0);try{T?await A(C,_):await v.enqueueMessage(C,{model:_==null?void 0:_.model,reasoningLevel:_==null?void 0:_.reasoningLevel,providerConfigMode:_==null?void 0:_.providerConfigMode,providerPresetId:(_==null?void 0:_.providerPresetId)??null,attachments:_==null?void 0:_.attachments,attachmentMeta:_==null?void 0:_.attachmentMeta})}finally{a(!1)}},[T,A,v]),Ee=l.useCallback(async(C,_)=>{u(C);try{await v.replyPermissionRequest(C,_)}catch(he){p({title:c("conversation.permissionRequestReplyFailed"),description:he instanceof Error?he.message:void 0,tone:"error"})}finally{u(null)}},[p,v]),Oe=l.useCallback(async C=>{h(C);try{await v.deleteQueuedMessage(C)}finally{h(null)}},[v]),re=l.useCallback(async C=>{var _;M(C);try{await v.steerQueuedMessage(C),(_=e.onRequestNavigationRefresh)==null||_.call(e)}finally{M(null)}},[e.onRequestNavigationRefresh,v]),Ae=l.useCallback(async()=>{var C;await v.interrupt(),(C=e.onRequestNavigationRefresh)==null||C.call(e)},[e.onRequestNavigationRefresh,v]);return{session:ye,capabilities:Q,runtimeHasActiveRun:V,runtimeCanInterrupt:te,messages:ie,timelineItems:$,permissionRequests:N,queuedMessages:j,contextUsage:L,permissionStatus:Z,historyState:ge,runtimeErrorCode:U,runtimeErrorDetail:G,runtimeInterruptSource:le,loadingOlderMessages:ce,hasOlderMessages:pe,connectionState:q,sending:r,replyingPermissionRequestId:o,deletingQueueItemId:d,steeringQueueItemId:f,forkDraft:T,setForkDraft:w,composerHasActiveRun:fe,composerCanInterrupt:me,composerIsRunning:Ce,canSteerQueuedMessage:Le,hasPendingQueuedMessages:qe,reconnect:v.reconnect.bind(v),loadOlderMessages:v.loadOlderMessages.bind(v),retryMessage:v.retryMessage.bind(v),send:ue,queue:de,interrupt:Ae,replyPermissionRequest:Ee,deleteQueuedMessage:Oe,steerQueuedMessage:re}}function wl(e){return e==="user_input"?c("conversation.permissionQuestionToastTitle"):c("conversation.permissionRequestToastTitle")}function Il(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function Ml(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 Sl(e){const t=yl(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)},bl))},[t,s]),l.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),s}function yl(e){const{provider:t,runningState:s,activityState:n,runtimeHasActiveRun:r,messages:a}=e;if(t!=="codex")return"hide_immediately";const o=Rl(a);return o<0||Pl(a,o)?"hide_immediately":xl(s,n,r)?"show":"hide_deferred"}function xl(e,t,s){return s===!0||t==="running"||e==="starting"||e==="running"||e==="reconnecting"}function Pl(e,t){return e.slice(t+1).some(s=>s.role==="assistant"&&(s.kind==="text"||s.kind==="thinking"))}function Rl(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 kl=1.5,Tl=24,Cl=72,El=296,Al=16,ur={2:496,3:408,4:344};function Pi(e){return ur[e]??ur[4]}function _l({memberCount:e,currentWidth:t,monitorWidth:s}){if(e<2||t<=0||s<=0)return t;const n=El,r=Math.max(0,e-1)*Al,a=Math.max(0,(t-n-r)/e),o=Pi(e);if(a>=o)return t;const u=n+r+e*o,d=Math.min(t*kl,Math.max(t,s-Cl)),h=Math.min(Math.max(t,u),d);return h<=t+Tl?t:h}const jl=240,dr=920,hr=760,In=360,Mn=320,Ve=16,fr=428,Nl=404,ct=12;function Ft(e,t){if(typeof window>"u")return e;const s=Math.max(0,window.innerWidth-Ve*2),n=Math.max(0,window.innerHeight-Ve*2),r=Math.min((t==null?void 0:t.minWidth)??In,s),a=Math.min((t==null?void 0:t.minHeight)??Mn,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)),M=Math.min(Math.max(e.y,Ve),Math.max(Ve,window.innerHeight-h-Ve));return{x:f,y:M,width:d,height:h}}function Ol(e){if(typeof window>"u")return{x:Ve,y:Ve,width:dr,height:hr};const t=Math.min(dr,Math.max(In,window.innerWidth-Ve*2)),s=Math.min(hr,Math.max(Mn,window.innerHeight-Ve*2));return Ft({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 Ll(e){return!e||e.width<=0||e.height<=0?null:Ft({x:e.left,y:e.top,width:e.width,height:e.height},{minWidth:Math.min(In,e.width),minHeight:Math.min(Mn,e.height)})}function Dl(e){if(typeof window>"u")return{x:ct,y:ct,width:fr};const t=Math.min(fr,Math.max(Nl,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 Hl({groupId:e,currentSessionId:t}){var le,ce,pe;const s=pt(),n=jt(),r=Qo(n),{showToast:a}=ft(),{navigationGroups:o,requestNavigationRefresh:u,currentTargetHostId:d}=yt(),h=l.useMemo(()=>Vt(o),[o]),f=l.useMemo(()=>new Map(h.map(q=>[q.session.sessionId,q])),[h]),M=l.useMemo(()=>bs(h),[h]),T=l.useMemo(()=>{const q=new Map,Y=D=>{for(const fe of D)q.set(fe.item.session.sessionId,fe),Y(ws(fe))};return Y(M),q},[M]),w=l.useMemo(()=>cn(o),[o]),[g,p]=l.useState(null),[R,H]=l.useState(!0),[O,E]=l.useState(null),[I,y]=l.useState(null),[b,F]=l.useState(null),[k,S]=l.useState(null),[v,P]=l.useState(null),[Q,V]=l.useState(!1),te=l.useRef(null),ie=l.useRef(null);l.useEffect(()=>{let q=!1;async function Y(){H(!0),E(null);try{const D=await Zo(e);if(q)return;p(D)}catch(D){if(q)return;E(D instanceof Error?D.message:c("shell.parallelGroupLoadFailed"))}finally{q||H(!1)}}return Y(),()=>{q=!0}},[e]),l.useEffect(()=>{const q=io(e);q&&L(q)},[e]),l.useEffect(()=>()=>{ie.current!==null&&window.clearTimeout(ie.current)},[]);const X=l.useMemo(()=>g?g.members.slice().sort((q,Y)=>q.member.ordinal-Y.member.ordinal).map(q=>{const Y=f.get(q.session.sessionId),D=(Y==null?void 0:Y.session)??q.session;return{session:D,workspaceId:(Y==null?void 0:Y.workspace.id)??ns(D,q.sessionIsolatedWorkspace),ordinal:q.member.ordinal,memberPrompt:q.member.memberPrompt,model:q.member.model,sessionIsolatedWorkspace:q.sessionIsolatedWorkspace,subagentTree:Xl(D.sessionId,g.group.id,T)}}):[],[g,f,T]);l.useEffect(()=>{if(!n.isDesktop||n.ui.osFamily!=="macos"&&n.ui.osFamily!=="windows"||X.length<2)return;const q=`${e}:${X.length}`;if(te.current===q)return;te.current=q;let Y=!1;async function D(){try{const fe=await kn(()=>import("./window-BVUB8gMK.js").then(de=>de.w),__vite__mapDeps([0,1])),me=await kn(()=>import("./window-BVUB8gMK.js").then(de=>de.d),__vite__mapDeps([0,1])),Ce=fe.getCurrentWindow(),Le=await Ce.innerSize(),qe=await Ce.scaleFactor(),ye=await fe.currentMonitor();if(Y||qe<=0)return;const W=Le.width/qe,J=Le.height/qe,$=ye?ye.workArea.size.width/ye.scaleFactor:W*1.5,A=_l({memberCount:X.length,currentWidth:W,monitorWidth:$});if(A<=W+24)return;const ue=10;await new Promise(de=>window.setTimeout(de,56));for(let de=1;de<=ue;de+=1){if(Y)return;const Ee=de/ue,Oe=1-Math.pow(1-Ee,3),re=W+(A-W)*Oe;await Ce.setSize(new me.LogicalSize(re,J)),await new Promise(Ae=>window.setTimeout(Ae,jl/ue))}}catch{return}}return D(),()=>{Y=!0}},[e,X.length,n.isDesktop,n.ui.osFamily]);async function N(q){F(q);try{const Y=await Jo(q);await u(),p(D=>D&&{...D,members:D.members.map(fe=>{var me;return((me=fe.sessionIsolatedWorkspace)==null?void 0:me.id)===q?{...fe,sessionIsolatedWorkspace:{...fe.sessionIsolatedWorkspace,workspaceId:Y.workspace.id,lifecycleStatus:"promoted",promotedAt:Y.record.promotedAt}}:fe})}),a({title:c("shell.parallelWorkspacePromotedBadge"),tone:"success"})}catch(Y){a({title:Y instanceof Error?Y.message:c("shell.parallelGroupLoadFailed"),tone:"error"})}finally{F(null)}}async function j(q){if(k)return;const Y=q.trim();if(!Y)return;const D=X.find(me=>me.session.sessionId!==Y)??null,fe=(g==null?void 0:g.group.workspaceId)??(D==null?void 0:D.workspaceId)??null;S(Y);try{await Hr(Y),Us(Y,null),y(me=>me===Y?null:me),p(me=>me&&{...me,members:me.members.filter(Ce=>Ce.session.sessionId!==Y)}),await u(),t===Y&&(D?s($e(D.workspaceId,D.session.sessionId)):fe&&s(wt(fe))),a({title:c("shell.deleteSessionSuccess"),tone:"success"})}catch(me){a({title:me instanceof Error?me.message:c("shell.deleteSessionFailed"),tone:"error"})}finally{S(null)}}function L(q){P(q),ie.current!==null&&window.clearTimeout(ie.current),ie.current=window.setTimeout(()=>{P(null),ie.current=null},q.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(O&&!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:O})]})});if(X.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 Z=((le=w[(g==null?void 0:g.group.workspaceId)??""])==null?void 0:le.displayName)??(g==null?void 0:g.group.workspaceId)??c("common.unknown"),ge=X.find(q=>q.session.sessionId===(g==null?void 0:g.group.anchorSessionId))??X[0]??null,U=X.length<4,G={"--parallel-pane-min-width":`${Pi(X.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":X.length,"data-parallel-entering":v?"true":void 0,style:G,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:((ce=g==null?void 0:g.group.sharedPrompt)==null?void 0:ce.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:!U,onClick:()=>{U&&V(!0)},children:i.jsx("span",{"aria-hidden":"true",children:"+"})})]})}),i.jsx("div",{className:"parallel-conversation-grid",children:X.map(q=>{const Y=w[q.workspaceId]??un({id:q.workspaceId,name:q.session.workspaceId,path:q.session.workspaceId,repoRoot:q.session.workspaceId});return i.jsx(ql,{entry:q,isCurrent:q.session.sessionId===t||zt(q.subagentTree,t),routeCurrentSessionId:t,workspaceContext:Y,infoOpen:I===q.session.sessionId,promotingWorkspaceId:b,onCloseInfo:()=>{y(null)},onToggleInfo:()=>{y(D=>D===q.session.sessionId?null:q.session.sessionId)},onPromoteWorkspace:N,onRemoveSession:j,removingSessionId:k},q.session.sessionId)})}),i.jsx(Vs,{open:Q,source:g?{kind:"group",groupId:g.group.id,workspaceId:g.group.workspaceId,workspaceName:Z,sharedPrompt:((pe=g.group.sharedPrompt)==null?void 0:pe.trim())||"",currentMemberCount:X.length,defaultProvider:(ge==null?void 0:ge.session.provider)??"codex"}:null,targetHostId:d,onClose:()=>V(!1),onCreated:async q=>{p(q),V(!1),L(ro("append")),await u(),a({title:c("shell.parallelAppendSucceeded"),tone:"success"})}})]})}function ql({entry:e,isCurrent:t,routeCurrentSessionId:s,workspaceContext:n,infoOpen:r,onCloseInfo:a,onToggleInfo:o,onPromoteWorkspace:u,promotingWorkspaceId:d,onRemoveSession:h,removingSessionId:f}){var vt,Yt,Kt,Nt,Ot,Pt,Qt;const M=pt(),T=jt(),{showToast:w}=ft(),{navigationGroups:g,requestNavigationRefresh:p,setSessionWorkspace:R,upsertNavigationSession:H,markNavigationSessionSeen:O,selectWorkspace:E}=yt(),I=e.session.sessionId,[y,b]=l.useState(()=>zl(e,s)),F=l.useMemo(()=>new Map(Vt(g).map(B=>[B.session.sessionId,B])),[g]),k=y===I?e.session:((vt=F.get(y))==null?void 0:vt.session)??ki(e.subagentTree,y)??e.session,S=y===I?e.workspaceId:((Yt=F.get(y))==null?void 0:Yt.workspace.id)??Ti(e.subagentTree,y)??e.workspaceId,v=k.sessionId,[P,Q]=l.useState(!1),[V,te]=l.useState("files"),[ie,X]=l.useState(!1),[N,j]=l.useState(null),[L,Z]=l.useState(null),ge=l.useRef(null),U=l.useRef(null),G=l.useRef(null),le=l.useRef(null),ce=l.useRef(null),pe=l.useRef(null),[q,Y]=l.useState(()=>Tn(I)),{session:D,capabilities:fe,messages:me,timelineItems:Ce,permissionRequests:Le,queuedMessages:qe,contextUsage:ye,historyState:W,runtimeInterruptSource:J,loadingOlderMessages:$,hasOlderMessages:A,connectionState:ue,sending:de,replyingPermissionRequestId:Ee,deletingQueueItemId:Oe,steeringQueueItemId:re,forkDraft:Ae,setForkDraft:oe,composerHasActiveRun:_e,composerCanInterrupt:ze,composerIsRunning:Ue,canSteerQueuedMessage:st,hasPendingQueuedMessages:C,reconnect:_,loadOlderMessages:he,retryMessage:Re,send:K,queue:ke,interrupt:ae,replyPermissionRequest:Be,deleteQueuedMessage:ve,steerQueuedMessage:Qe}=xi({sessionId:v,externalSession:k,onSeen:(B,ne)=>{O(B,ne)},onRequestNavigationRefresh:p,onUpsertNavigationSession:H,onNavigateToSession:(B,ne)=>{E(B),M($e(B,ne))},onBindSessionWorkspace:y===I?R:void 0,onResolveMissingSession:()=>{p()},permissionRequestNotificationMode:"current_only",permissionToastIdPrefix:"parallel-permission-request",isCurrent:t,enableRuntimeErrorHandling:!0,enableCompletionHaptics:!1,enableThinkingPlaceholder:!0,enableForkTimelineSanitizer:!0}),je=oo((D==null?void 0:D.parallelGroup)??e.session.parallelGroup),Ze=ao({groupId:((Kt=(D==null?void 0:D.parallelGroup)??e.session.parallelGroup)==null?void 0:Kt.groupId)??"parallel-group",ordinal:e.ordinal,overrideColor:q}),nt=lo((D==null?void 0:D.parallelGroup)??e.session.parallelGroup),Pe=(D==null?void 0:D.sessionIsolatedWorkspace)??e.sessionIsolatedWorkspace,xt=co(Pe),dt=((Nt=ye==null?void 0:ye.modelId)==null?void 0:Nt.trim())||((Ot=e.model)==null?void 0:Ot.trim())||c("shell.parallelPaneModelFallback"),Je=((Pt=e.memberPrompt)==null?void 0:Pt.trim())||c("shell.parallelPanePromptFallback"),mt=S,Fe=Sr(D??k,Pe),lt=Fe===mt?(n==null?void 0:n.displayName)??mt:xt??Je,gt=l.useMemo(()=>{var B;return((B=g.find(ne=>ne.workspace.id===Fe))==null?void 0:B.workspace.path)??null},[g,Fe]),m=f===v;async function z(B){await K(Object.entries(B.answers).map(([,ne])=>ne.filter(Boolean).join(" / ")).filter(Boolean).join(`
8
+ `))}const se=r&&L?{...Bt(n)??{},...je??{},...Ze,left:`${L.x}px`,top:`${L.y}px`,width:`${L.width}px`}:void 0,we=P&&N?{...Bt(n)??{},...je??{},...Ze,left:`${N.x}px`,top:`${N.y}px`,width:`${N.width}px`,height:`${N.height}px`}:void 0;l.useEffect(()=>{Y(Tn(I)),Q(!1),X(!1),j(null),Z(null),te("files")},[I]),l.useEffect(()=>{if(zt(e.subagentTree,s)){b(s);return}if(s===I){b(I);return}b(B=>Yl(e,B)?B:I)},[e,I,s]),l.useEffect(()=>{if(!r)return;const B=ne=>{var Ye,rt,it;const et=ne.target;et instanceof HTMLElement&&((Ye=U.current)!=null&&Ye.contains(et)||(rt=le.current)!=null&&rt.contains(et)||(it=ce.current)!=null&&it.contains(et)||a())};return window.addEventListener("pointerdown",B),()=>{window.removeEventListener("pointerdown",B)}},[r,a]),l.useEffect(()=>{if(!r){Z(null);return}const B=()=>{var ne;Z(Dl(((ne=G.current)==null?void 0:ne.getBoundingClientRect())??null))};return B(),window.addEventListener("resize",B),window.addEventListener("scroll",B,!0),()=>{window.removeEventListener("resize",B),window.removeEventListener("scroll",B,!0)}},[r]),l.useEffect(()=>{if(!P)return;const B=()=>{j(ne=>ne&&Ft(ne))};return window.addEventListener("resize",B),()=>{window.removeEventListener("resize",B)}},[P]);async function Ne(){if(!T.isDesktop||!T.bridge.supported)return;if(V==="files"){const ne=await ea(T,{workspaceId:Fe,workspaceName:lt,sessionId:v,focusOwner:"file-context-panel"});ne.ok||w({title:ne.detail??c("conversation.filePanelOpenExternalFailed"),tone:"error"});return}if(V==="git"){const ne=await ta(T,{workspaceId:Fe,workspaceName:lt,focusOwner:"git-sidebar"});ne.ok||w({title:ne.detail??c("git.openExternalFailed"),tone:"error"});return}const B=await sa(T,{workspaceId:Fe,workspaceName:lt,focusOwner:"terminal-manager-panel"});B.ok||w({title:B.detail??c("terminalManager.openExternalFailed"),tone:"error"})}function We(){var B,ne;Q(!0),j(Ll(((B=ge.current)==null?void 0:B.getBoundingClientRect())??null)??Ol(((ne=pe.current)==null?void 0:ne.getBoundingClientRect())??null))}function Te(B){if(B.button!==0||!N)return;B.preventDefault();const ne=B.clientX,et=B.clientY,Ye=N,rt=bt=>{j(Ft({...Ye,x:Ye.x+(bt.clientX-ne),y:Ye.y+(bt.clientY-et)}))},it=()=>{window.removeEventListener("pointermove",rt),window.removeEventListener("pointerup",it)};window.addEventListener("pointermove",rt),window.addEventListener("pointerup",it)}function De(B){if(B.button!==0||!N)return;B.preventDefault(),B.stopPropagation();const ne=B.clientX,et=B.clientY,Ye=N,rt=bt=>{j(Ft({...Ye,width:Ye.width+(bt.clientX-ne),height:Ye.height+(bt.clientY-et)}))},it=()=>{window.removeEventListener("pointermove",rt),window.removeEventListener("pointerup",it)};window.addEventListener("pointermove",rt),window.addEventListener("pointerup",it)}const xe=P&&typeof document<"u"?St.createPortal(i.jsxs("div",{ref:ce,className:"parallel-pane-tools-popover","data-parallel-pane-layer":v,"data-pinned":ie?"true":void 0,"data-workspace-tone":(n==null?void 0:n.tone)??"root",style:we,children:[i.jsxs("div",{className:"parallel-pane-tools-toolbar",children:[i.jsxs("div",{className:"parallel-pane-tools-drag-handle",onPointerDown:Te,children:[i.jsx("span",{className:"parallel-pane-tools-drag-dots","aria-hidden":"true",children:i.jsx(Wl,{})}),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(B=>i.jsx("button",{type:"button",role:"tab","aria-selected":V===B,className:"parallel-pane-tools-tab",onClick:()=>{te(B)},children:B==="files"?c("shell.filesEntry"):B==="git"?c("shell.gitEntry"):c("shell.parallelPaneProcessesEntry")},B))}),i.jsxs("div",{className:"parallel-pane-tools-actions",children:[i.jsx("button",{type:"button",className:`conversation-header-ai-button${ie?" active":""}`,"aria-label":c("shell.parallelPanePinAction"),title:c("shell.parallelPanePinAction"),"aria-pressed":ie,onClick:()=>{X(B=>!B)},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Ul,{})})}),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:()=>{Ne()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx($l,{})})}):null,i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("common.close"),title:c("common.close"),onClick:()=>{Q(!1)},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Vl,{})})})]})]}),i.jsx("div",{className:"parallel-pane-tools-body","data-panel":V,children:V==="files"?i.jsx(Yr,{className:"parallel-pane-tools-surface",hideHeading:!0,sessionId:v,workspaceId:Fe}):V==="git"?i.jsx(Kr,{className:"parallel-pane-tools-surface",panelActive:!0,workspaceId:Fe}):i.jsx(Qr,{className:"parallel-pane-tools-surface parallel-pane-tools-process-panel",currentWorkspaceId:Fe,navigationGroups:g})}),i.jsx("button",{type:"button",className:"parallel-pane-tools-resize-handle","aria-label":c("shell.parallelPaneResizeAction"),title:c("shell.parallelPaneResizeAction"),onPointerDown:De,children:i.jsx("span",{"aria-hidden":"true",children:i.jsx(Gl,{})})})]}),document.body):null,ht=r&&typeof document<"u"?St.createPortal(i.jsxs("div",{ref:le,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(Tt,{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:Wt((D??e.session).provider,"full")})]}),i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.parallelPaneModelFallback")}),i.jsx("dd",{children:dt})]}),i.jsxs("div",{children:[i.jsx("dt",{children:c("shell.parallelPaneIsolatedWorkspaceTitle")}),i.jsx("dd",{children:xt??c("common.unknown")})]})]})}),i.jsx(Tt,{heading:c("shell.parallelPaneColorPaletteLabel"),description:c("shell.parallelPaneColorPaletteDescription"),actions:i.jsx("button",{type:"button",className:"ghost-button parallel-pane-color-reset",disabled:!q||m,onClick:()=>{Us(I,null),Y(null)},children:c("shell.parallelPaneColorPaletteReset")}),children:i.jsx("div",{className:"workbench-manage-color-palette parallel-pane-color-palette","aria-label":c("shell.parallelPaneColorPaletteLabel"),children:uo.map(B=>i.jsx("button",{type:"button",className:"workbench-manage-color-swatch","aria-label":c("shell.manageWorkspaceColorSelectSwatch",{color:B}),"aria-pressed":q===B,"data-selected":q===B,disabled:m,style:{backgroundColor:B},onClick:()=>{const ne=Us(I,B);Y(ne)}},B))})}),i.jsx(Tt,{heading:c("shell.parallelPaneIsolatedWorkspaceTitle"),description:(Pe==null?void 0:Pe.lifecycleStatus)==="active"?c("shell.parallelPanePromoteDescription"):(Pe==null?void 0:Pe.lifecycleStatus)==="promoted"?c("shell.parallelPaneRemovePromotedDescription"):c("shell.parallelPaneRemoveDescription"),children:i.jsxs(vs,{align:"start",className:"parallel-pane-action-row",children:[(Pe==null?void 0:Pe.lifecycleStatus)==="active"?i.jsx("button",{type:"button",className:"secondary-button parallel-pane-promote-action",disabled:d===Pe.id||m,onClick:()=>{const B=Pe==null?void 0:Pe.id;B&&u(B)},children:d===Pe.id?c("shell.parallelPanePromoting"):c("shell.parallelPanePromoteAction")}):null,i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:m,onClick:()=>{h(v)},children:m?c("shell.parallelPaneRemoving"):c("shell.parallelPaneRemoveAction")})]})})]}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("article",{ref:ge,className:"parallel-conversation-pane","data-current":t?"true":void 0,"data-workspace-tone":(n==null?void 0:n.tone)??"root","data-parallel-role":((Qt=(D==null?void 0:D.parallelGroup)??e.session.parallelGroup)==null?void 0:Qt.role)??void 0,style:{"--parallel-pane-order":String(e.ordinal),...Bt(n)??{},...je??{},...Ze},children:[i.jsxs("header",{ref:U,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:[nt?i.jsx("span",{className:"session-parallel-badge",children:nt}):null,i.jsx("p",{className:"parallel-conversation-pane-subtitle",title:Je,children:Je}),i.jsxs("div",{className:"parallel-conversation-pane-meta",children:[i.jsx("span",{className:`session-provider-badge ${(D??e.session).provider}`,children:Wt((D??e.session).provider)}),i.jsx("span",{className:"parallel-conversation-pane-model",children:dt})]})]}),i.jsxs("div",{className:"parallel-conversation-pane-actions",children:[i.jsx("button",{ref:G,type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelPaneInfoAction"),title:c("shell.parallelPaneInfoAction"),"aria-expanded":r,onClick:()=>{Q(!1),o()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Bl,{})})}),i.jsx("button",{ref:pe,type:"button",className:`conversation-header-ai-button${P?" active":""}`,"aria-label":c("shell.parallelPaneToolsAction"),title:c("shell.parallelPaneToolsAction"),"aria-expanded":P,onClick:()=>{a(),We()},children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(Fl,{})})})]})]}),i.jsxs("div",{className:"parallel-conversation-pane-body",children:[i.jsx(pn,{connectionState:ue,onReconnect:_}),i.jsx(Dr,{requests:Le,replyingRequestId:Ee,onReply:Be}),i.jsx("div",{className:"parallel-conversation-pane-timeline",children:i.jsx(dn,{sessionId:v,sessionSummary:D??e.session,workspaceId:Fe,workspacePath:gt,items:Ce,historyState:W,loadingOlderMessages:$,hasOlderMessages:A,provider:(D==null?void 0:D.provider)??e.session.provider,interruptedSource:J,followTailUpdates:!0,onLoadOlderMessages:he,onRetryMessage:Re,onSubmitStructuredQuestion:z,permissionRequests:Le,replyingPermissionRequestId:Ee,onReplyPermissionRequest:Be,onForkMessage:B=>{const ne=D??e.session;oe({sourceMessageId:B.id,sourceMessageSnapshot:{role:B.role,kind:B.kind??(B.role==="tool"?"tool_result":"text"),content:B.content},content:B.content,sourceProvider:ne.provider,workspaceId:ne.workspaceId,targetProvider:ne.provider,targetModel:null,targetProviderConfigMode:ne.providerConfigMode??"global-default",targetProviderPresetId:ne.providerPresetId??null}),yi()}})}),i.jsx(ni,{items:qe,deletingQueueItemId:Oe,steeringQueueItemId:re,canSteer:st,onDelete:ve,onSteer:Qe}),i.jsx(hn,{capabilities:fe,draftStorageId:v,initialModel:e.model,workspaceId:(D??e.session).workspaceId,initialProviderConfigMode:(D??e.session).providerConfigMode??"global-default",initialProviderPresetId:(D??e.session).providerPresetId??null,forkDraft:Ae,onClearForkDraft:()=>oe(null),onForkDraftChange:B=>oe(B),hasActiveRun:_e,contextUsage:ye,taskProvider:(D??e.session).provider,taskMessages:me,hasPendingQueuedMessages:C,canInterrupt:ze,isSubmitting:de,isRunning:Ue,onInterrupt:ae,onSend:K,onQueueSend:ke})]})]}),ht,xe]})}function Bl(){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 Fl(){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 Wl(){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 Ul(){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 $l(){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 Vl(){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 Gl(){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 Xl(e,t,s){const n=s.get(e);return n?ws(n).flatMap(r=>Ri(r,t)):[]}function Ri(e,t){var r;const s=e.item.session;if(((r=s.parallelGroup)==null?void 0:r.groupId)===t)return[];const n=ws(e).flatMap(a=>Ri(a,t));return s.isSubagent!==!0?n:[{session:s,workspaceId:e.item.workspace.id,children:n}]}function zt(e,t){const s=t.trim();return s?e.some(n=>n.session.sessionId===s||zt(n.children,s)):!1}function zl(e,t){return t===e.session.sessionId?e.session.sessionId:zt(e.subagentTree,t)?t:e.session.sessionId}function Yl(e,t){const s=t.trim();return s?s===e.session.sessionId||zt(e.subagentTree,s):!1}function ki(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=ki(n.children,s);if(r)return r}return null}function Ti(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=Ti(n.children,s);if(r)return r}return null}const Et=196,Mt=82,pr=28,mr=24,Ci=34,tn=18,Kl=332,es=360,ps=840,gr=18,Ql=.22,Zl=2.4,Jl=6;function ec(e,t){return(t.lastMessageAt??t.updatedAt).localeCompare(e.lastMessageAt??e.updatedAt)}function Ei(e,t,s){var w,g;if(!t)return null;const n=e.find(p=>p.workspace.id===t);if(!n)return null;const r=new Map(n.sessions.map(p=>[p.sessionId,p])),a=r.get(s)??null;if(!a)return null;const o=new Map;for(const p of n.sessions){const R=((w=p.parentSessionId)==null?void 0:w.trim())||null;if(!R)continue;const H=o.get(R)??[];o.set(R,[...H,p.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 p=((g=h.parentSessionId)==null?void 0:g.trim())||null;h=p?r.get(p)??null:null}const M=Ai(f,0,r,o,new Set),T=sc(M);return{root:M,current:a,currentPathIds:u,relatedSessionIds:T,sessionsById:r}}function tc(e){return((e==null?void 0:e.relatedSessionIds.size)??0)>1}function Ai(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),M=s.get(h);return!f||!M?0:ec(f,M)});return{session:a,depth:t,children:u.map(d=>Ai(d,t+1,s,n,o))}}function sc(e){const t=new Set;function s(n){t.add(n.session.sessionId),n.children.forEach(s)}return s(e),t}function _i(e){const t=Ur(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[Wt(e.provider),n,t].filter(Boolean).join(" · ")}function ji(e){return e.isArchived===!0}function nc(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 Ni(e,t){return e<=0||t<=0?1:Math.min(1,e/t)}function rc(e,t,s,n){const r=Ni(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 sn(e,t,s){return Math.min(s,Math.max(t,e))}function ic(e,t,s,n){if(e<=0||t<=0||s<=0||n<=0)return 1;const r=Math.max(1,e-gr*2),a=Math.max(1,t-gr*2);return Math.min(1,r/s,a/n)}function ms(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:sn(e.offsetX,t-a,0),f=o<=s?d:sn(e.offsetY,s-o,0);return{scale:e.scale,offsetX:h,offsetY:f}}function ts(e,t,s,n){const r=ic(e,t,s,n);return ms({scale:r,offsetX:(e-s*r)/2,offsetY:(t-n*r)/2},e,t,s,n)}function oc(e,t,s,n,r,a,o,u){const d=(s-e.offsetX)/e.scale,h=(n-e.offsetY)/e.scale;return ms({scale:t,offsetX:s-d*t,offsetY:n-h*t},r,a,o,u)}function ac(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 lc(e){switch(e.role){case"assistant":return c("conversation.roleAssistant");case"system":return c("conversation.roleSystem");case"tool":return c("conversation.roleTool");case"user":default:return c("conversation.roleUser")}}function nn(e,t){const s=t.get(e.session.sessionId);if(s!==void 0)return s;if(e.children.length===0)return t.set(e.session.sessionId,Et),Et;const n=e.children.reduce((a,o,u)=>{const d=a+nn(o,t);return u===0?d:d+tn},0),r=Math.max(Et,n);return t.set(e.session.sessionId,r),r}function cc(e){const t=new Map,s=[],n=new Map;function r(u,d,h){const f=nn(u,t),M=d+f/2,T=mr+h*(Mt+Ci),w=M-Et/2,g=u.children.reduce((O,E,I)=>{const y=O+nn(E,t);return I===0?y:y+tn},0);let p=d+Math.max(0,(f-g)/2);const R=u.children.map(O=>{const E=r(O,p,h+1);return p+=E.subtreeWidth+tn,E}),H={node:u,children:R,x:w,y:T,centerX:M,centerY:T+Mt/2,subtreeWidth:f};return s.push(H),n.set(u.session.sessionId,H),H}const a=r(e,pr,0),o=s.reduce((u,d)=>Math.max(u,d.y+Mt),0);return{root:a,nodes:s,bySessionId:n,width:a.subtreeWidth+pr*2,height:o+mr}}function uc(e){return Math.max(0,Math.min(255,Number.parseFloat(e)))}function dc(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=>uc(o));return{r:n,g:r,b:a}}return null}function ut(e,t,s){const n=dc(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:s}function hc(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",M=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 p of g.children){const R=n.has(g.node.session.sessionId)&&n.has(p.node.session.sessionId),H=g.node.session.sessionId===r||p.node.session.sessionId===r;u.beginPath(),u.moveTo(g.centerX,g.y+Mt-10);const O=g.y+Mt+Ci*.52;u.bezierCurveTo(g.centerX,O,p.centerX,O,p.centerX,p.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(M,.72,"rgba(148, 163, 184, 0.72)"),u.stroke(),u.beginPath(),u.arc(p.centerX,p.y,H?4.5:3.5,0,Math.PI*2),u.fillStyle=H?ut(f,.9,"rgba(59, 130, 246, 0.9)"):ut(M,.78,"rgba(148, 163, 184, 0.78)"),u.fill(),w(p)}}w(t.root);for(const g of t.nodes){const p=g.node.session.sessionId===s,R=g.node.session.sessionId===r,H=n.has(g.node.session.sessionId);if(!p&&!R&&!H)continue;const O=u.createRadialGradient(g.centerX,g.centerY,10,g.centerX,g.centerY,R?90:64);O.addColorStop(0,ut(f,R?.22:.14,"rgba(59, 130, 246, 0.22)")),O.addColorStop(1,"rgba(59, 130, 246, 0)"),u.fillStyle=O,u.beginPath(),u.ellipse(g.centerX,g.centerY,Et*.72,Mt*.9,0,0,Math.PI*2),u.fill(),(R||p)&&(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 fc(e,t,s){const n=Math.min(Kl,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>es?Math.max(12,e.top-es-12):Math.max(12,Math.min(s-es-12,e.bottom+12));return{width:n,left:a,top:d,maxHeight:Math.min(es,s-24)}}function pc({model:e,selectedSession:t,selectedTreeNode:s,previewEntry:n,onClose:r,onOpenSession:a}){const o=Xt(t.title,c("common.unknown")),u=t.sessionId===e.current.sessionId,d=ji(t),h=qr(s.session),f=Br(s.session),M=Fr(s.session),T=Wr(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:_i(t)}),f&&h||T&&M?i.jsxs("div",{className:"conversation-branch-badge-row",children:[T&&M?i.jsx("span",{className:`session-fork-badge ${M}`,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:lc(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:ac(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 mc({layout:e,model:t,selectedSessionId:s,onSelectSession:n,onBackgroundClick:r,stageScale:a,desktopStageLayout:o,transform:u,isMobileViewport:d,viewportRef:h,onRegisterNodeElement:f,onViewportTouchStart:M,onViewportTouchMove:T,onViewportTouchEnd:w}){const g=l.useRef(null);return l.useEffect(()=>{const p=g.current;p&&hc(p,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:p=>{p.target===p.currentTarget&&(r==null||r())},onTouchStart:M,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:p=>{p.target===p.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(p=>{const R=Xt(p.node.session.title,c("common.unknown")),H=qr(p.node.session),O=Br(p.node.session),E=Fr(p.node.session),I=Wr(p.node.session),y=p.node.session.sessionId===t.current.sessionId,b=p.node.session.sessionId===s,F=t.currentPathIds.has(p.node.session.sessionId),k=ji(p.node.session);return i.jsx("button",{ref:S=>f(p.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:p.x,top:p.y,width:Et,minHeight:Mt},"aria-pressed":b,onClick:S=>{S.stopPropagation(),n(p.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:_i(p.node.session)}),O&&H||I&&E?i.jsxs("div",{className:"conversation-branch-badge-row",children:[I&&E?i.jsx("span",{className:`session-fork-badge ${E}`,children:I}):null,O&&H?i.jsx("span",{className:`session-fork-badge ${H}`,children:O}):null]}):null]})},p.node.session.sessionId)})]})})})}function vr({model:e,onOpenSession:t,onClose:s}){const n=l.useMemo(()=>cc(e.root),[e.root]),r=l.useRef(null),a=l.useRef(new Map),[o,u]=l.useState(null),[d,h]=l.useState(0),[f,M]=l.useState(0),[T,w]=l.useState(null),[g,p]=l.useState({}),R=l.useRef(new Set),[H,O]=l.useState(typeof window<"u"?window.innerWidth<=ps:!1),[E,I]=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 N=r.current;if(!N)return;const j=N;function L(){h(j.clientWidth),M(j.clientHeight),O(window.innerWidth<=ps)}if(L(),typeof ResizeObserver>"u")return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L);const Z=new ResizeObserver(L);return Z.observe(N),()=>Z.disconnect()},[]),l.useEffect(()=>{u(null)},[e.current.sessionId,e.root.session.sessionId]);const b=l.useMemo(()=>Ni(d,n.width),[d,n.width]),F=l.useMemo(()=>rc(d,f,n.width,n.height),[f,d,n.height,n.width]);l.useEffect(()=>{if(!H||d<=0||f<=0){I(null);return}I(N=>N?ms(N,d,f,n.width,n.height):ts(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,P=H&&!!s,Q=!!s&&!P;l.useEffect(()=>{if(!o){w(null);return}const N=o;function j(){const L=a.current.get(N);if(!L){w(null);return}w(L.getBoundingClientRect())}return j(),window.addEventListener("resize",j),window.addEventListener("scroll",j,!0),()=>{window.removeEventListener("resize",j),window.removeEventListener("scroll",j,!0)}},[o,b]),l.useEffect(()=>{if(!H)return;const N=o;if(!N)return;const j=window.requestAnimationFrame(()=>{const L=a.current.get(N);L&&w(L.getBoundingClientRect())});return()=>window.cancelAnimationFrame(j)},[H,E,o]),l.useEffect(()=>{if(!(k!=null&&k.sessionId)||(v==null?void 0:v.status)==="ready"||R.current.has(k.sessionId))return;let N=!1;return R.current.add(k.sessionId),p(j=>{var L;return{...j,[k.sessionId]:{status:"loading",messages:((L=j[k.sessionId])==null?void 0:L.messages)??[],error:null}}}),$s(k.sessionId,null,6,"backward").then(j=>{R.current.delete(k.sessionId),!N&&p(L=>({...L,[k.sessionId]:{status:"ready",messages:nc(j.messages),error:null}}))}).catch(j=>{R.current.delete(k.sessionId),!N&&p(L=>{var Z;return{...L,[k.sessionId]:{status:"error",messages:((Z=L[k.sessionId])==null?void 0:Z.messages)??[],error:j instanceof Error?j.message:c("conversation.branchTreePreviewFailed")}}})}),()=>{N=!0}},[k==null?void 0:k.sessionId]);function V(N){!H||d<=0||f<=0||I(j=>{const L=j??ts(d,f,n.width,n.height);return ms(N(L),d,f,n.width,n.height)})}function te(N){if(!H)return;const j=N.currentTarget.getBoundingClientRect();if(N.touches.length>=2){const ge=N.touches[0],U=N.touches[1],G=Math.hypot(U.clientX-ge.clientX,U.clientY-ge.clientY),le=(ge.clientX+U.clientX)/2-j.left,ce=(ge.clientY+U.clientY)/2-j.top,pe=E??ts(d,f,n.width,n.height);y.current={mode:"pinch",startDistance:G,startScale:pe.scale,startOffsetX:pe.offsetX,startOffsetY:pe.offsetY,startTouchX:le,startTouchY:ce,anchorX:le,anchorY:ce,moved:!1};return}const L=N.touches[0],Z=E??ts(d,f,n.width,n.height);y.current={mode:"pan",startDistance:0,startScale:Z.scale,startOffsetX:Z.offsetX,startOffsetY:Z.offsetY,startTouchX:L.clientX,startTouchY:L.clientY,anchorX:0,anchorY:0,moved:!1}}function ie(N){if(!H)return;const j=y.current;if(N.touches.length>=2){const G=N.currentTarget.getBoundingClientRect(),le=N.touches[0],ce=N.touches[1],pe=Math.hypot(ce.clientX-le.clientX,ce.clientY-le.clientY);if(pe<=0||j.startDistance<=0)return;N.preventDefault();const q=(le.clientX+ce.clientX)/2-G.left,Y=(le.clientY+ce.clientY)/2-G.top,D=sn(j.startScale*(pe/j.startDistance),Ql,Zl);y.current={...j,mode:"pinch",moved:!0,anchorX:q,anchorY:Y},V(fe=>oc({...fe,scale:j.startScale,offsetX:j.startOffsetX,offsetY:j.startOffsetY},D,q,Y,d,f,n.width,n.height));return}if(j.mode!=="pan"||N.touches.length!==1)return;const L=N.touches[0],Z=L.clientX-j.startTouchX,ge=L.clientY-j.startTouchY;(j.moved||Math.hypot(Z,ge)>=Jl)&&(N.preventDefault(),y.current={...j,moved:!0},V(G=>({...G,offsetX:j.startOffsetX+Z,offsetY:j.startOffsetY+ge})))}function X(){y.current={mode:"idle",startDistance:0,startScale:(E==null?void 0:E.scale)??1,startOffsetX:(E==null?void 0:E.offsetX)??0,startOffsetY:(E==null?void 0:E.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":""}${P?" 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:[Q?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:[P?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,P?null:i.jsx("div",{className:"conversation-branch-canvas-tip",children:c("conversation.branchTreePreviewDescription")}),i.jsx(mc,{layout:n,model:e,selectedSessionId:o,onSelectSession:u,onBackgroundClick:P?s:void 0,stageScale:b,desktopStageLayout:F,transform:H?E:null,isMobileViewport:H,viewportRef:r,onRegisterNodeElement:(N,j)=>{if(j){a.current.set(N,j);return}a.current.delete(N)},onViewportTouchStart:te,onViewportTouchMove:ie,onViewportTouchEnd:X})]})]}),k&&S&&v&&T&&typeof document<"u"?St.createPortal(i.jsx("div",{className:"conversation-branch-preview-floating",style:fc(T,window.innerWidth,window.innerHeight),children:i.jsx(pc,{model:e,selectedSession:k,selectedTreeNode:S.node,previewEntry:v,onClose:()=>u(null),onOpenSession:t})}),document.body):null]})}function gc({open:e,navigationGroups:t,workspaceId:s,sessionId:n,onClose:r,onOpenSession:a}){const o=l.useMemo(()=>Ei(t,s,n),[t,n,s]),[u,d]=l.useState(typeof window<"u"?window.innerWidth>ps:!0);return l.useEffect(()=>{if(typeof window>"u")return;function h(){d(window.innerWidth>ps)}return h(),window.addEventListener("resize",h),()=>window.removeEventListener("resize",h)},[]),!e||!o||typeof document>"u"?null:u?i.jsx(gs,{open:e,title:c("conversation.branchTreeMapTitle"),description:c("conversation.branchTreeMapDescription"),size:"regular",layout:"viewer",bodyClassName:"conversation-branch-modal-body",onClose:r,children:i.jsx(vr,{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(vr,{model:o,onOpenSession:a,onClose:r})]}),document.body)}function vc(e,t,s){if(!t)return null;const n=e.find(o=>o.workspace.id===t);if(!n)return null;const r=Vt([n]).filter(o=>!o.session.isArchived&&!fn(o.session)),a=r.findIndex(o=>o.session.sessionId===s);return a<0?null:r[a+1]??null}const br=.6,Ws=.6,wr=8,bc=36,wc=48,Ic=96,Mc=196;function lu(){const{sessionId:e="",workspaceId:t}=no(),s=rn(),n=pt(),r=l.useMemo(()=>new URLSearchParams(s.search),[s.search]),a=Ec(r.get("toolPanel")),o=(t==null?void 0:t.trim())||null,u=l.useMemo(()=>kc(e,o,r),[o,r,e]),d=l.useMemo(()=>Wc(e,s.state),[s.state,e]),h=l.useMemo(()=>Uc(e,s.state),[s.state,e]);return u?i.jsx(Rc,{draft:u,navigate:n,initialToolPanel:a}):i.jsx(Sc,{sessionId:e,bootstrapMessages:d,initialComposerModel:h.initialModel,initialComposerProviderConfigMode:h.providerConfigMode,initialComposerProviderPresetId:h.providerPresetId,initialToolPanel:a})}function Sc(e){const{shellMode:t,navigationGroups:s,currentWorkspaceRef:n,currentTargetHostId:r}=yt(),a=pt(),o=l.useMemo(()=>Vt(s),[s]),u=l.useMemo(()=>{var f;return((f=o.find(M=>M.session.sessionId===e.sessionId))==null?void 0:f.session)??null},[o,e.sessionId]),d=!Yi(e.sessionId)&&e.bootstrapMessages.length===0&&o.length>0&&u===null,h=l.useMemo(()=>d?Bc({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})},[r,n,h,a,e.sessionId]),h?null:i.jsx(yc,{...e})}function yc({sessionId:e,bootstrapMessages:t,initialComposerModel:s,initialComposerProviderConfigMode:n,initialComposerProviderPresetId:r,initialToolPanel:a}){var Sn,yn,xn,Pn;const{shellMode:o,navigationGroups:u,requestNavigationRefresh:d,selectWorkspace:h,setSessionWorkspace:f,markNavigationSessionSeen:M,favoriteSessions:T,toggleFavoriteSession:w,archiveSession:g,unarchiveSession:p,renameSession:R,startDraftSession:H,upsertNavigationSession:O,currentWorkspaceRef:E,currentTargetHostId:I}=yt(),y=pt(),[b,F]=l.useState(!1),[k,S]=l.useState(!1),[v,P]=l.useState(null),[Q,V]=l.useState(!1),[te,ie]=l.useState(!1),[X,N]=l.useState(!1),j=l.useMemo(()=>Vt(u),[u]),L=l.useMemo(()=>{var x;return((x=j.find(ee=>ee.session.sessionId===e))==null?void 0:x.session)??null},[j,e]),{showToast:Z}=ft(),ge=()=>{var Lt;const x=(L==null?void 0:L.workspaceId)??((Lt=u[0])==null?void 0:Lt.workspace.id)??null,ee=(x?j.find(Ki=>Ki.workspace.id===x)??null:null)??j[0]??null,Ie=Xe(I,E,x),ot=ee?$e(ee.workspace.id,ee.session.sessionId,Ie):x?wt(x,Ie):o==="mobile"?xr():"/landing";y(ot,{replace:!0})},{session:U,capabilities:G,messages:le,timelineItems:ce,permissionRequests:pe,queuedMessages:q,contextUsage:Y,permissionStatus:D,historyState:fe,runtimeInterruptSource:me,loadingOlderMessages:Ce,hasOlderMessages:Le,connectionState:qe,sending:ye,replyingPermissionRequestId:W,deletingQueueItemId:J,steeringQueueItemId:$,forkDraft:A,setForkDraft:ue,composerHasActiveRun:de,composerCanInterrupt:Ee,composerIsRunning:Oe,canSteerQueuedMessage:re,hasPendingQueuedMessages:Ae,reconnect:oe,loadOlderMessages:_e,retryMessage:ze,send:Ue,queue:st,interrupt:C,replyPermissionRequest:_,deleteQueuedMessage:he,steerQueuedMessage:Re}=xi({sessionId:e,targetHostId:I,externalSession:L,bootstrapMessages:t,onSeen:(x,ee)=>{M(x,ee)},onRequestNavigationRefresh:d,onUpsertNavigationSession:O,onNavigateToSession:(x,ee)=>{const Ie=I?E:{hostId:"current",workspaceId:x};h(x,Ie),y($e(x,ee,Ie))},onBindSessionWorkspace:f,onResolveMissingSession:ge,onForkSuccess:()=>{kt("preview"),Z({title:c("conversation.forkMessageSucceeded"),tone:"success"})},enableRuntimeErrorHandling:!0,enableCompletionHaptics:!0,enableThinkingPlaceholder:!0,enableForkTimelineSanitizer:!0}),K=o!=="mobile",ke=Vi(!K),ae=U??L??null,Be=(U==null?void 0:U.sessionIsolatedWorkspace)??(L==null?void 0:L.sessionIsolatedWorkspace)??null,ve=ae?ns(ae,Be):null,Qe=ae?Sr(ae,Be):null,je=Ui({enabled:!K,initialPanel:a,workspaceId:Qe,suspendMainGesture:!K&&ke.isVisible}),Ze=l.useMemo(()=>new Set(T.map(x=>x.session.sessionId)),[T]),nt=l.useMemo(()=>u.map(x=>x.workspace),[u]),Pe=l.useMemo(()=>$r(u),[u]),xt=l.useMemo(()=>cn(u),[u]),dt=l.useMemo(()=>Di(u,ve,Ze),[Ze,ve,u]),Je=l.useMemo(()=>Hi(T,u),[T,u]);async function mt(x){await Ue(xc(x.answers))}const[Fe,lt]=l.useState([]),gt=l.useMemo(()=>[...Je,...dt],[Je,dt]),m=l.useMemo(()=>ve?nt.find(x=>x.id===ve)??null:null,[ve,nt]),z=(ve?xt[ve]??null:null)??(m?un(m):null),se=l.useMemo(()=>Is(u,ve),[ve,u]),we=Pe.find(x=>x.workspace.id===ve)??(se?{workspace:se.workspace,label:se.workspace.name,subtitle:se.workspace.path}:null),Ne=l.useMemo(()=>vc(u,ve,e),[ve,u,e]),We=(U==null?void 0:U.provider)??(L==null?void 0:L.provider)??null,Te=l.useMemo(()=>{var x;return Xt(((x=U??L)==null?void 0:x.title)??null,c("conversation.titleFallback"))},[L,U]),De=K,xe=l.useMemo(()=>{var Ie;if(!De)return null;if(go(ae))return((Ie=ae==null?void 0:ae.parallelGroup)==null?void 0:Ie.groupId)??null;const x=bs(j);return Pc(x,e)},[ae,j,e,De]),ht=K?null:Wi(ke.mainGestureHandlers,je.mainGestureHandlers);l.useEffect(()=>{const x=yr(gt,e,ee=>ee.session.sessionId);x.length!==0&&lt(ee=>{const Ie=new Set(ee);let ot=!1;for(const Lt of x)Ie.has(Lt)||(Ie.add(Lt),ot=!0);return ot?Array.from(Ie):ee})},[gt,e]);const vt=(ae==null?void 0:ae.workspaceId)??(L==null?void 0:L.workspaceId)??null,Yt=l.useMemo(()=>Ei(u,vt,e),[vt,u,e]),Kt=tc(Yt),Nt=!!(ae&&vt&&Kt),Ot=()=>{ie(!0)},Pt=l.useMemo(()=>(se==null?void 0:se.sessions.filter(x=>Vr(x)))??[],[se]),Qt=l.useRef(null),B=l.useRef(null),ne=l.useRef(null),et=l.useRef(null),[Ye,rt]=l.useState(null),{composerPortalTarget:it}=Gr();l.useEffect(()=>{ie(!1)},[e]),Bi(ne,Ye,!K,e),Fi(ne,et,!K,e);function bt(x,ee){h(x,ee),y(wt(x,ee))}return K&&xe?i.jsxs(i.Fragment,{children:[i.jsx(Hl,{groupId:xe,currentSessionId:e}),i.jsx(Vs,{open:X,source:ae?{kind:"session",sessionId:e,workspaceId:ae.workspaceId,workspaceName:(z==null?void 0:z.displayName)??ae.workspaceId,sessionTitle:ae.title,defaultProvider:ae.provider}:null,targetHostId:I,onClose:()=>N(!1),onCreated:async x=>{x.members.forEach(Ie=>{O(Ie.session)}),Cn(x.group.id),await d();const ee=x.members.find(Ie=>Ie.session.sessionId===x.group.anchorSessionId)??x.members[0]??null;if(ee){const Ie=ns(ee.session,ee.sessionIsolatedWorkspace),ot=Xe(I,E);h(Ie,ot),y($e(Ie,ee.session.sessionId,ot))}N(!1),Z({title:c("shell.parallelCreateSucceeded"),tone:"success"})}})]}):i.jsxs(i.Fragment,{children:[i.jsxs("main",{ref:ne,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!K,"data-preview-mode":K?void 0:ke.displayMode,"data-preview-dragging":K?void 0:ke.isDragging,"data-workspace-tone":(z==null?void 0:z.tone)??"root","data-worktree-depth":(z==null?void 0:z.depth)??0,"data-tool-panel-open":K?void 0:je.isOpen,style:{...K?{}:ke.pageStyle,...Bt(z)??{}},children:[K?i.jsx(Xr,{session:U??L,workspaceContext:z,actions:i.jsxs(i.Fragment,{children:[Nt?i.jsx(Hc,{onOpenBranchTree:Ot}):null,ae?i.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":c("shell.parallelCreateAction"),title:c("shell.parallelCreateAction"),onClick:()=>N(!0),children:i.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:i.jsx(qc,{})})}):null,i.jsx(si,{session:U??L})]})}):null,K?null:i.jsx(zr,{containerRef:et,className:"mobile-conversation-page-header",gestureHandlers:ht??void 0,currentWorkspace:we?{id:we.workspace.id,name:we.label,path:we.subtitle}:nt[0]??null,workspaces:nt,workspaceOptions:Pe,onSelectWorkspace:bt,heading:Te.fullTitle,trailing:i.jsxs("div",{className:"mobile-conversation-toolbar-main",children:[i.jsx("span",{className:"mobile-conversation-toolbar-title",title:Te.fullTitle,children:Te.displayTitle}),i.jsx(Ia,{session:U??L,onOpenBranchTree:Nt?Ot:void 0})]})}),K?null:i.jsx(Gi,{visible:!je.isOpen&&ke.isVisible,widthPx:ke.previewWidthPx,isDragging:ke.isDragging,gestureHandlers:ke.railGestureHandlers,activeSessionId:e,createSessionActionLabel:ve&&We?c("shell.createSession"):void 0,favoriteItems:Je,items:dt,expandedRootIds:Fe,workspaceSectionLabel:(we==null?void 0:we.label)??c("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:ve&&We?()=>{H(ve,We)}:void 0,archiveCurrentActionLabel:c("shell.archiveCurrentSessionAction"),archiveFolderActionLabel:Pt.length>0?c("shell.archiveFolderLabel"):void 0,onArchiveActiveSession:()=>{F(!0)},onOpenArchiveFolder:Pt.length>0?()=>{S(!0)}:void 0,onToggleSubsessions:x=>{lt(ee=>ee.includes(x)?ee.filter(Ie=>Ie!==x):[...ee,x])},onActivate:x=>{ke.closePreview();const ee=Xe(I,E);h(x.workspace.id,ee),y($e(x.workspace.id,x.session.sessionId,ee))},onToggleFavoriteSession:x=>w(x),onArchiveSession:x=>g(x),onUnarchiveSession:x=>p(x),onRenameSession:(x,ee)=>R(x,ee),onDeleteSession:async x=>{if(await Hr(x,{targetHostId:I}),await d(),x===e){if(ve){if(h(ve,Xe(I,E)),kt("preview"),Ne){const ee=Xe(I,E);y($e(Ne.workspace.id,Ne.session.sessionId,ee));return}y(wt(ve,Xe(I,E)));return}y("/workspaces")}}}),i.jsx("div",{className:"mobile-conversation-stage",...ht??{},children:i.jsxs("div",{ref:Qt,className:"mobile-conversation-main",children:[i.jsx(pn,{connectionState:qe,onReconnect:oe}),i.jsx(Dr,{requests:pe,replyingRequestId:W,onReply:_}),i.jsx("div",{ref:B,className:"conversation-timeline-shell",children:i.jsx(dn,{sessionId:e,sessionSummary:U??L??null,workspaceId:Qe,workspacePath:(m==null?void 0:m.path)??null,items:ce,historyState:fe,loadingOlderMessages:Ce,hasOlderMessages:Le,provider:(U==null?void 0:U.provider)??null,interruptedSource:me,onLoadOlderMessages:_e,onRetryMessage:ze,onSubmitStructuredQuestion:mt,permissionRequests:pe,replyingPermissionRequestId:W,onReplyPermissionRequest:_,onForkMessage:x=>{U&&(ue({sourceMessageId:x.id,sourceMessageSnapshot:{role:x.role,kind:x.kind??(x.role==="tool"?"tool_result":"text"),content:x.content},content:x.content,sourceProvider:U.provider,workspaceId:U.workspaceId,targetProvider:U.provider,targetModel:null,targetProviderConfigMode:U.providerConfigMode??"global-default",targetProviderPresetId:U.providerPresetId??null}),yi())}})}),i.jsx(ga,{containerRef:B,session:U??L??null,currentCapabilities:G}),i.jsx(ni,{items:q,deletingQueueItemId:J,steeringQueueItemId:$,canSteer:re,onDelete:he,onSteer:Re}),je.isOpen?null:i.jsx(hn,{capabilities:G,draftStorageId:e,initialModel:s,workspaceId:((Sn=U??L)==null?void 0:Sn.workspaceId)??null,initialProviderConfigMode:n??((yn=U??L)==null?void 0:yn.providerConfigMode)??"global-default",initialProviderPresetId:r??((xn=U??L)==null?void 0:xn.providerPresetId)??null,forkDraft:A,onClearForkDraft:()=>ue(null),onForkDraftChange:x=>ue(x),panelRef:K?void 0:rt,portalContainer:K?null:it,hasActiveRun:de,contextUsage:Y,permissionStatus:D,taskProvider:((Pn=U??L)==null?void 0:Pn.provider)??null,taskMessages:le,hasPendingQueuedMessages:Ae,canInterrupt:Ee,isSubmitting:ye,isRunning:Oe,onInterrupt:C,onSend:Ue,onQueueSend:st})]})}),!K&&Qe?i.jsx($i,{activePanel:je.activePanel,open:je.isOpen,sessionId:e,workspaceId:Qe,navigationGroups:u,onClose:()=>{je.closePanel()},onSelectPanel:x=>{je.selectPanel(x)},onSelectPanelBySwipe:x=>{if(x===null){je.closePanel();return}je.selectPanel(x)}}):null]}),i.jsx(gc,{open:te,navigationGroups:u,workspaceId:vt,sessionId:e,onClose:()=>ie(!1),onOpenSession:x=>{ie(!1);const ee=Xe(I,E);h(x.workspaceId,ee),kt("preview"),y($e(x.workspaceId,x.sessionId,ee))}}),i.jsx(Dc,{open:b,busy:Q,onClose:()=>{Q||F(!1)},onConfirm:async()=>{if(!Q){V(!0);try{if(await g(e),F(!1),Z({title:c("shell.archiveAdded"),tone:"success"}),ve){if(h(ve,Xe(I,E)),kt("preview"),Ne){const x=Xe(I,E);y($e(Ne.workspace.id,Ne.session.sessionId,x));return}y(wt(ve,Xe(I,E)));return}y("/workspaces")}catch(x){Z({title:x instanceof Error?x.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{V(!1)}}}}),i.jsx(zi,{open:k,workspaceName:(se==null?void 0:se.workspace.name)??null,sessions:Pt,restoringSessionId:v,onClose:()=>{v||S(!1)},onRestore:async x=>{P(x);try{await p(x),Z({title:c("shell.archiveRestored"),tone:"success"})}catch(ee){Z({title:ee instanceof Error?ee.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{P(null)}}}),De?i.jsx(Vs,{open:X,source:ae?{kind:"session",sessionId:e,workspaceId:ae.workspaceId,workspaceName:(z==null?void 0:z.displayName)??ae.workspaceId,sessionTitle:ae.title,defaultProvider:ae.provider}:null,targetHostId:I,onClose:()=>N(!1),onCreated:async x=>{x.members.forEach(Ie=>{O(Ie.session)}),Cn(x.group.id),await d();const ee=x.members.find(Ie=>Ie.session.sessionId===x.group.anchorSessionId)??x.members[0]??null;if(ee){const Ie=ns(ee.session,ee.sessionIsolatedWorkspace),ot=Xe(I,E);h(Ie,ot),y($e(Ie,ee.session.sessionId,ot))}N(!1),Z({title:c("shell.parallelCreateSucceeded"),tone:"success"})}}):null]})}function xc(e){return Object.entries(e).map(([,t])=>t.filter(Boolean).join(" / ")).filter(Boolean).join(`
9
+ `)}function Pc(e,t){const s=t.trim();if(!s)return null;for(const n of e){const r=Oi(n,s,null);if(r)return r}return null}function Oi(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 ws(e)){const u=Oi(o,t,n);if(u)return u}return null}function Rc({draft:e,navigate:t,initialToolPanel:s}){const{shellMode:n,navigationGroups:r,requestNavigationRefresh:a,selectWorkspace:o,setSessionWorkspace:u,upsertNavigationSession:d,favoriteSessions:h,unarchiveSession:f,startDraftSession:M,currentTargetHostId:T,currentWorkspaceRef:w}=yt(),[g,p]=l.useState(!1),[R,H]=l.useState([]),O=Tc(e,T,w),E=l.useMemo(()=>Ht(e.provider),[e.provider]),[I,y]=l.useState(E),b=n!=="mobile",{showToast:F}=ft(),k=l.useMemo(()=>Cc(e),[e]),S=Vi(!b),v=Ui({enabled:!b,initialPanel:s,sessionId:e.sessionId,workspaceId:e.workspaceId,suspendMainGesture:!b&&S.isVisible}),P=l.useMemo(()=>new Set(h.map($=>$.session.sessionId)),[h]),Q=l.useMemo(()=>r.map($=>$.workspace),[r]),V=l.useMemo(()=>$r(r),[r]),te=l.useMemo(()=>cn(r),[r]),ie=l.useMemo(()=>Q.find($=>$.id===e.workspaceId)??null,[e.workspaceId,Q]),X=te[e.workspaceId]??(ie?un(ie):null),N=l.useMemo(()=>Xt(k.title??null,c("conversation.titleFallback")),[k]),j=l.useMemo(()=>Di(r,e.workspaceId,P),[e.workspaceId,P,r]),L=l.useMemo(()=>Hi(h,r),[h,r]),[Z,ge]=l.useState([]),U=l.useMemo(()=>[...L,...j],[L,j]),G=l.useMemo(()=>Is(r,e.workspaceId),[e.workspaceId,r]),le=l.useMemo(()=>(G==null?void 0:G.sessions.filter($=>Vr($)))??[],[G]),ce=V.find($=>$.workspace.id===e.workspaceId)??(G?{workspace:G.workspace,label:G.workspace.name,subtitle:G.workspace.path}:null),pe=b?null:Wi(S.mainGestureHandlers,v.mainGestureHandlers),[q,Y]=l.useState(!1),[D,fe]=l.useState(null),me=l.useRef(null),Ce=l.useRef(null),Le=l.useRef(null),[qe,ye]=l.useState(null),{composerPortalTarget:W}=Gr();l.useEffect(()=>{const $=yr(U,e.sessionId,A=>A.session.sessionId);$.length!==0&&ge(A=>{const ue=new Set(A);let de=!1;for(const Ee of $)ue.has(Ee)||(ue.add(Ee),de=!0);return de?Array.from(ue):A})},[e.sessionId,U]),l.useEffect(()=>(u(e.sessionId,e.workspaceId),()=>{u(e.sessionId,null)}),[e.sessionId,e.workspaceId,u]),l.useEffect(()=>{let $=!1;return y(E),Pr(e.provider,O,void 0,{targetHostId:T}).then(A=>{$||y(A)}).catch(()=>{}),()=>{$=!0}},[T,e.provider,O,E]),Bi(Ce,qe,!b,e.sessionId),Fi(Ce,Le,!b,e.sessionId);function J($,A){o($,A),t(wt($,A))}return i.jsx(i.Fragment,{children:i.jsxs("main",{ref:Ce,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":(X==null?void 0:X.tone)??"root","data-worktree-depth":(X==null?void 0:X.depth)??0,"data-tool-panel-open":b?void 0:v.isOpen,style:{...b?{}:S.pageStyle,...Bt(X)??{}},children:[b?i.jsx(Xr,{session:k,workspaceContext:X}):null,b?null:i.jsx(zr,{containerRef:Le,className:"mobile-conversation-page-header",gestureHandlers:pe??void 0,currentWorkspace:ce?{id:ce.workspace.id,name:ce.label,path:ce.subtitle}:Q[0]??null,workspaces:Q,workspaceOptions:V,onSelectWorkspace:J,heading:N.fullTitle,trailing:i.jsx("span",{className:"mobile-conversation-toolbar-title",title:N.fullTitle,children:N.displayTitle})}),b?null:i.jsx(Gi,{visible:!v.isOpen&&S.isVisible,widthPx:S.previewWidthPx,isDragging:S.isDragging,gestureHandlers:S.railGestureHandlers,activeSessionId:e.sessionId,createSessionActionLabel:c("shell.createSession"),favoriteItems:L,items:j,expandedRootIds:Z,workspaceSectionLabel:(ce==null?void 0:ce.label)??c("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:()=>{M(e.workspaceId,e.provider)},archiveFolderActionLabel:le.length>0?c("shell.archiveFolderLabel"):void 0,onOpenArchiveFolder:le.length>0?()=>{Y(!0)}:void 0,onToggleSubsessions:$=>{ge(A=>A.includes($)?A.filter(ue=>ue!==$):[...A,$])},onActivate:$=>{S.closePreview();const A=Xe(T,w);o($.workspace.id,A),t($e($.workspace.id,$.session.sessionId,A))},onToggleFavoriteSession:async()=>{},onArchiveSession:async()=>{},onUnarchiveSession:async()=>{},onRenameSession:async()=>k,onDeleteSession:async()=>{}}),i.jsx("div",{className:"mobile-conversation-stage",...pe??{},children:i.jsxs("div",{ref:me,className:"mobile-conversation-main",children:[i.jsx(pn,{connectionState:"closed",onReconnect:()=>{}}),i.jsx("div",{className:"conversation-timeline-shell",children:i.jsx(dn,{sessionId:e.sessionId,sessionSummary:null,workspaceId:e.workspaceId,workspacePath:(ie==null?void 0:ie.path)??null,items:Or({messages:R}),historyState:"ready",loadingOlderMessages:!1,hasOlderMessages:!1,provider:e.provider,onLoadOlderMessages:()=>{},onRetryMessage:()=>{}})}),v.isOpen?null:i.jsx(hn,{capabilities:I,draftStorageId:e.sessionId,workspaceId:e.workspaceId,panelRef:b?void 0:ye,portalContainer:b?null:W,contextUsage:null,permissionStatus:null,taskProvider:e.provider,taskMessages:R,isSubmitting:g,isRunning:!1,onSend:async($,A)=>{var Ee,Oe,re,Ae;const ue=Vc();H(oe=>[...oe,Ar(e.sessionId,$,ue,(A==null?void 0:A.attachmentMeta)??[],(A==null?void 0:A.attachments)??[])]),p(!0);const de=performance.now();Me("session_send.start_live.client_start",{draftSessionId:e.sessionId,workspaceId:O,provider:e.provider,clientRequestId:ue,contentLength:$.length});try{const oe=await kr({workspaceId:O,provider:e.provider,content:$,clientRequestId:ue,model:(A==null?void 0:A.model)??null,reasoningLevel:(A==null?void 0:A.reasoningLevel)??null,permissionMode:It(),attachments:(A==null?void 0:A.attachments)??[],providerConfigMode:(A==null?void 0:A.providerConfigMode)??"global-default",providerPresetId:(A==null?void 0:A.providerPresetId)??null},{targetHostId:T});Me("session_send.start_live.client_response",{draftSessionId:e.sessionId,sessionId:oe.sessionId,workspaceId:((Ee=oe.session)==null?void 0:Ee.workspaceId)??O,provider:oe.provider,clientRequestId:ue,durationMs:Math.round(performance.now()-de),returnedMessageId:((Oe=oe.message)==null?void 0:Oe.messageId)??null}),oe.session&&d(oe.session);const _e=((Ae=(re=oe.session)==null?void 0:re.workspaceId)==null?void 0:Ae.trim())||O,ze=Xe(T,w),Ue=e.routeWorkspaceId||_e;u(oe.sessionId,_e),kt("preview"),t($e(Ue,oe.sessionId,ze),{replace:!0,state:{composer:{sessionId:oe.sessionId,initialModel:(A==null?void 0:A.model)??null,providerConfigMode:(A==null?void 0:A.providerConfigMode)??"global-default",providerPresetId:(A==null?void 0:A.providerPresetId)??null},bootstrap:{sessionId:oe.sessionId,messages:[Fc({created:oe,provider:e.provider,content:$,clientRequestId:ue,attachments:(A==null?void 0:A.attachmentMeta)??[]})]}}}),a()}catch(oe){throw Me("session_send.start_live.client_error",{draftSessionId:e.sessionId,workspaceId:O,provider:e.provider,clientRequestId:ue,durationMs:Math.round(performance.now()-de),error:oe instanceof Error?oe.message:String(oe)}),H(_e=>jr(_e,ue)),oe}finally{p(!1)}}})]})}),b?null:i.jsx($i,{activePanel:v.activePanel,open:v.isOpen,sessionId:e.sessionId,workspaceId:e.workspaceId,navigationGroups:r,onClose:()=>{v.closePanel()},onSelectPanel:$=>{v.selectPanel($)},onSelectPanelBySwipe:$=>{if($===null){v.closePanel();return}v.selectPanel($)}}),i.jsx(zi,{open:q,workspaceName:(G==null?void 0:G.workspace.name)??null,sessions:le,restoringSessionId:D,onClose:()=>{D||Y(!1)},onRestore:async $=>{fe($);try{await f($),F({title:c("shell.archiveRestored"),tone:"success"})}catch(A){F({title:A instanceof Error?A.message:c("shell.navigationLoadFailed"),tone:"error"})}finally{fe(null)}}})]})})}function kc(e,t,s,n=null){var d,h,f;if(!Yi(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||!Lr(u)?null:{sessionId:e,workspaceId:o,routeWorkspaceId:t,provider:u}}function Tc(e,t,s){return t&&(s==null?void 0:s.hostId)===t&&s.workspaceId.trim()?s.workspaceId.trim():e.workspaceId}function Cc(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:na(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 Li(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=vo(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=!fn(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 Di(e,t,s){if(!t)return[];const n=Is(e,t);if(!n)return[];const r=Li(n.sessions).map(o=>({session:o,workspace:n.workspace}));return bs(r,{mode:"mobile"}).filter(o=>!s.has(o.item.session.sessionId)&&!ho(o.children,u=>s.has(u.session.sessionId)))}function Hi(e,t){return e.filter(s=>!fn(s.session)).flatMap(s=>{const n=Is(t,s.workspace.id);if(!n)return[];const r=bs(Li(n.sessions).map(o=>({session:o,workspace:n.workspace})),{mode:"mobile"}),a=qi(r,s.session.sessionId);return a?[a]:[]})}function qi(e,t){for(const s of e){if(s.item.session.sessionId===t)return s;const n=qi(s.children,t);if(n)return n}return null}function Bi(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 Fi(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 Ec(e){return e==="files"||e==="git"||e==="processes"?e:null}function Wi(...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 Ui(e){const t=rn(),s=pt(),n=ln(),r=jt(),a=l.useRef(null),o=l.useRef(!1),[u,d]=l.useState(()=>e.initialPanel??Ln()),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 I=e.initialPanel??Ln();d(I),Dn(I)},[e.enabled,e.initialPanel]),l.useEffect(()=>{if(!f){o.current=!1;return}if(r.platform!=="android"||!Ac(t.state)||o.current||typeof window>"u"||window.location.pathname!==t.pathname)return;const I=new URLSearchParams(t.search);I.delete("toolPanel");const y=I.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 M(I,y){const b=new URLSearchParams(t.search);I?(b.set("toolPanel",I),d(I),Dn(I)):b.delete("toolPanel");const F=b.toString();s({pathname:t.pathname,search:F?`?${F}`:""},{replace:(y==null?void 0:y.replace)??!1})}function T(I){n.trigger("selection"),M(I,{replace:f})}function w(){if(f){if(n.trigger("gesture"),o.current&&typeof window<"u"){o.current=!1,window.history.back();return}M(null,{replace:!0})}}function g(I){if(!e.enabled||!e.workspaceId)return;const y=I??h;n.trigger("gesture"),M(y)}function p(I){if(!e.enabled||I.changedTouches.length!==1){a.current=null;return}if(_c(I.target)){a.current=null;return}const y=I.changedTouches[0];a.current={x:y.clientX,y:y.clientY}}function R(I){const y=a.current;if(a.current=null,!y||I.changedTouches.length!==1||f||e.suspendMainGesture)return;const b=I.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(I){const y=a.current;if(a.current=null,!y||I.changedTouches.length!==1||!f)return;const b=I.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:p,onTouchMove:()=>{},onTouchEnd:R,onTouchCancel:()=>{a.current=null}},openPanel:g,panelGestureHandlers:{onTouchStart:p,onTouchMove:()=>{},onTouchEnd:H,onTouchCancel:()=>{a.current=null}},selectPanel:T}}function $i(e){const t=l.useRef(null);if(!e.open)return null;function s(r){if(r.changedTouches.length!==1){t.current=null;return}if(jc(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(Yr,{className:"mobile-conversation-tool-surface",hideHeading:!0,sessionId:e.sessionId,workspaceId:e.workspaceId}):e.activePanel==="git"?i.jsx(Kr,{className:"mobile-conversation-tool-surface",panelActive:!0,workspaceId:e.workspaceId}):i.jsx(Qr,{className:"mobile-conversation-tool-surface mobile-tool-native-panel mobile-tool-process-panel",currentWorkspaceId:e.workspaceId,navigationGroups:e.navigationGroups})})]})}function Ac(e){return typeof e=="object"&&e!==null&&"mobileToolPanelRouteRedirect"in e&&e.mobileToolPanelRouteRedirect===!0}function _c(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function jc(e){return e instanceof Element?!!e.closest("input, textarea, select, option, [contenteditable='true']"):!1}function Vi(e){const t=ln(),[s,n]=l.useState(()=>e?Rs():"immersive"),[r,a]=l.useState(()=>Ir()),[o,u]=l.useState(()=>e&&Rs()==="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=Rs();n(k),u(k==="preview"?"default":"closed")},[e]),l.useEffect(()=>{e&&kt(s)},[e,s]),l.useEffect(()=>{if(typeof window>"u")return;function k(){a(Ir())}return k(),window.addEventListener("resize",k),()=>{window.removeEventListener("resize",k)}},[]);function f(k){d.current=k,u(k)}function M(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"),M()}function p(k,S){const v=S.touches[0]??S.changedTouches[0];if(!e||!v){h.current=null;return}if(Oc(S.target)){h.current=null;return}if(k==="main"){if(d.current==="closed"&&v.clientX>Ic){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 P=v.clientX-S.startX,Q=v.clientY-S.startY;if(S.lastX=v.clientX,S.lastY=v.clientY,!S.horizontalLocked){if(Math.abs(P)<wr&&Math.abs(Q)<wr)return;if(Math.abs(P)<=Math.abs(Q)){h.current=null;return}if(S.intent==="open"&&P<=0){h.current=null;return}if(S.intent==="close"&&P>=0){h.current=null;return}S.horizontalLocked=!0}}function H(k){var Q;const S=h.current;if(h.current=null,!(S!=null&&S.horizontalLocked))return;const v=(Q=k==null?void 0:k.changedTouches)==null?void 0:Q[0];v&&(S.lastX=v.clientX,S.lastY=v.clientY);const P=S.lastX-S.startX;if(S.intent==="open"){P>=bc&&(t.trigger("gesture"),M("default"));return}if(S.intent==="close"){P<=-34&&(t.trigger("gesture"),T());return}if(P<=-34){t.trigger("gesture"),T();return}P>=wc&&d.current==="default"&&(t.trigger("gesture"),w())}const O=o==="expanded"?Ws:o==="default"?br:0,E=Math.round(r*O*100)/100,I=O===0?0:O/Ws,y={"--mobile-conversation-preview-default-width":`${Math.round(r*br*100)/100}px`,"--mobile-conversation-preview-max-width":`${Math.round(r*Ws*100)/100}px`,"--mobile-conversation-preview-width":`${E}px`,"--mobile-conversation-preview-progress":I.toFixed(4)};return{closePreview:T,displayMode:o==="closed"?"immersive":"preview",isDragging:!1,isVisible:o!=="closed",mainGestureHandlers:{onTouchStart:k=>p("main",k),onTouchMove:R,onTouchEnd:H,onTouchCancel:H},pageStyle:y,previewWidthPx:E,railGestureHandlers:{onTouchStart:k=>p("rail",k),onTouchMove:R,onTouchEnd:H,onTouchCancel:H},togglePreview:g}}function Gi({visible:e,widthPx:t,isDragging:s,gestureHandlers:n,activeSessionId:r,createSessionActionLabel:a,favoriteItems:o,items:u,expandedRootIds:d,workspaceSectionLabel:h,onCreateSession:f,archiveCurrentActionLabel:M,archiveFolderActionLabel:T,onArchiveActiveSession:w,onOpenArchiveFolder:g,onToggleSubsessions:p,onActivate:R,onToggleFavoriteSession:H,onArchiveSession:O,onUnarchiveSession:E,onRenameSession:I,onDeleteSession:y}){if(!e)return null;function b(F,k){const{workspaceName:S,ancestorExpanded:v=!1,ancestorHasNextSiblings:P=[],hasNextSibling:Q=!1,isFirstSibling:V=!1}=k??{},te=F.item.session.sessionId,ie=F.children,X=F.depth===0&&ie.length>0,N=v||X&&d.includes(te),j=F.depth>0?[...P,Q]:[...P];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:[P.map((L,Z)=>L?i.jsx("span",{className:"mobile-conversation-preview-guide-column",style:{"--mobile-preview-tree-level":Z+1}},`${te}:ancestor:${Z}`):null),i.jsx("span",{className:"mobile-conversation-preview-guide-branch","data-continue":Q,"data-first":V,style:{"--mobile-preview-tree-level":F.depth},children:i.jsx("span",{className:"mobile-conversation-preview-guide-branch-horizontal"})})]}):null,i.jsx(Nc,{entry:F.item,activeSessionId:r,hasSubsessions:X,subsessionsExpanded:N,workspaceName:S,isFavorite:!!F.item.session.isFavorite,onToggleSubsessions:X?()=>{p(te)}:void 0,onActivate:R,onToggleFavoriteSession:H,onArchiveSession:O,onUnarchiveSession:E,onRenameSession:I,onDeleteSession:y})]}),ie.length>0&&N?i.jsx("div",{className:"mobile-conversation-preview-children",children:ie.map((L,Z)=>b(L,{workspaceName:S,ancestorExpanded:!0,ancestorHasNextSiblings:j,hasNextSibling:Z<ie.length-1,isFirstSibling:Z===0}))}):null]},`${F.item.workspace.id}:${te}`)}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))})]})]}),M&&w||T&&g?i.jsxs("div",{className:"mobile-conversation-preview-actions terminal-mobile-list-footer",children:[M&&w?i.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:()=>{w()},children:M}):null,T&&g?i.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:g,children:T}):null]}):null]})}function Nc({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:M,onDeleteSession:T}){const w=jt(),g=e.session.sessionId===t,[p,R]=l.useState(!1),[H,O]=l.useState(null),[E,I]=l.useState(null),y=l.useRef(null);l.useLayoutEffect(()=>{if(!p||!E||typeof window>"u"){O(null);return}const V=()=>{var N,j;const X=Cr(E,{width:((N=y.current)==null?void 0:N.offsetWidth)??0,height:((j=y.current)==null?void 0:j.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:Mc});O({position:"fixed",left:`${Math.round(X.left)}px`,top:`${Math.round(X.top)}px`,width:`${Math.round(X.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(X.maxHeight)}px`,transformOrigin:X.transformOrigin})},te=X=>{var j;const N=X.target;N&&!((j=y.current)!=null&&j.contains(N))&&F()},ie=X=>{X.key==="Escape"&&F()};return V(),window.addEventListener("pointerdown",te),window.addEventListener("keydown",ie),window.addEventListener("resize",V),window.addEventListener("scroll",V,!0),()=>{window.removeEventListener("pointerdown",te),window.removeEventListener("keydown",ie),window.removeEventListener("resize",V),window.removeEventListener("scroll",V,!0)}},[E,p]);function b(V){I(V),R(!0)}function F(){R(!1),I(null)}async function k(){const V=e.session.title||c("common.unknown"),te=window.prompt(c("shell.renameModalDescription"),V);te!=null&&te.trim()&&(await M(e.session.sessionId,te.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 P(V){if(V.key!=="ContextMenu"&&!(V.shiftKey&&V.key==="F10"))return;V.preventDefault(),V.stopPropagation();const te=V.currentTarget.getBoundingClientRect();b({x:te.right,y:te.bottom})}const Q=!w.isDesktop&&p&&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:V=>V.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:V=>{V.preventDefault(),V.stopPropagation(),b({x:V.clientX,y:V.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:V=>{V.stopPropagation(),o==null||o()},children:i.jsx("span",{className:Mr(e.session,{isActive:g,hasSubsessions:n}),"aria-hidden":"true"})}):i.jsx("span",{className:Mr(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:P,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:Xi(e.session,u)})]})}),Q]})}function Ir(){return typeof window>"u"?390:Math.max(window.innerWidth||390,320)}function Oc(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function Mr(e,t){const s=aa("mobile-conversation-preview-indicator",e,{hasSubagents:t.hasSubsessions});return s.endsWith(" is-idle")&&t.isActive?"mobile-conversation-preview-indicator is-active":s}function Xi(e,t){const s=Ur(e);return[t??null,Wt(e.provider),Lc(e.lastMessageAt??e.updatedAt),s].filter(Boolean).join(" · ")}function Lc(e){return e?new Date(e).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):c("common.unknown")}function Dc({open:e,busy:t,onClose:s,onConfirm:n}){return i.jsx(gs,{open:e,title:c("shell.archiveConfirmTitle"),description:c("shell.archiveConfirmDescription"),size:"narrow",layout:"confirm",dismissible:!t,showCloseButton:!1,footer:i.jsxs(vs,{children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:t,onClick:s,children:c("common.cancel")}),i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:t,onClick:()=>{n()},children:c("shell.archiveAction")})]}),onClose:s,children:i.jsx(i.Fragment,{})})}function zi({open:e,workspaceName:t,sessions:s,restoringSessionId:n,onClose:r,onRestore:a}){const{searchOpen:o,searchKeyword:u,filteredSessions:d,summaryLoading:h,summaryError:f,summaryBySessionId:M,setSearchKeyword:T,toggleSearch:w}=ra(e,s),g=l.useId(),p=s.length>0&&u.trim().length>0?c("shell.archiveSearchEmpty"):c("shell.archiveEmpty");return i.jsxs(gs,{open:e,title:c("shell.archiveModalTitle"),description:t?`${t} · ${c("shell.archiveModalDescription")}`:c("shell.archiveModalDescription"),size:"regular",layout:"list",dismissible:!n,headerActions:s.length>0?i.jsx("button",{type:"button",className:"secondary-button","aria-pressed":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(ss,{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(fo,{className:"workbench-archive-list",children:d.map(R=>{var I;const H=Xt(R.title,c("common.unknown")),O=((I=M[R.sessionId])==null?void 0:I.trim())??"",E=ia(R);return i.jsx(po,{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}),E?i.jsx("span",{className:"session-fork-badge archive-child",children:E}):null]}),i.jsx("p",{children:Xi(R)}),o&&O?i.jsx("p",{className:"workbench-archive-item-summary",children:O}):null]})},R.sessionId)})}):i.jsx(mo,{title:p,compact:!0,className:"workbench-section-empty"})]})}function Hc(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(oa,{})})})}function qc(){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 Yi(e){return e.startsWith("draft-")}function Bc(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"?xr():"/landing"}function Xe(e,t,s){var r;if(!e)return null;const n=((r=t==null?void 0:t.workspaceId)==null?void 0:r.trim())||(s==null?void 0:s.trim())||null;return n?{hostId:e,workspaceId:n}:null}function Fc(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 Wc(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($c)}function Uc(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 $c(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 Vc(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}export{lu as ConversationPage};
@@ -1 +1 @@
1
- import{b as d,j as e}from"./index-CILPuSCp.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-BArTKWXk.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-CILPuSCp.js";import{g as L}from"./App-D5hc6KuU.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-BArTKWXk.js";import{g as L}from"./App-FYuZfAoO.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};