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