@jingyi0605/codingns 0.5.1 → 0.5.5
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-SffCV4Vb.js → AdaptiveButlerPage-CUyNL98E.js} +1 -1
- package/dist/public/assets/App-BFP7LCSC.js +30 -0
- package/dist/public/assets/{BootstrapPage--zExdgfM.js → BootstrapPage-G74dX2Us.js} +1 -1
- package/dist/public/assets/ConversationPage-Bz0_tvvM.js +2 -0
- package/dist/public/assets/{DesktopDetachPreviewPage-DvI9CIKi.js → DesktopDetachPreviewPage-IV7oEdOX.js} +1 -1
- package/dist/public/assets/DesktopWindowPage-BBmHyRg5.js +2 -0
- package/dist/public/assets/FileContextPanel--FVTxDrq.js +1 -0
- package/dist/public/assets/GitSidebar-DAiSi9oc.js +6 -0
- package/dist/public/assets/{MobileCreateSessionSheet-CXSKMnYn.js → MobileCreateSessionSheet-DqVwz_Hp.js} +1 -1
- package/dist/public/assets/MobileSheet-D1lMrcvD.js +1 -0
- package/dist/public/assets/{MobileTopHeaderFrame-BWorAJ1C.js → MobileTopHeaderFrame-COTc7cRr.js} +1 -1
- package/dist/public/assets/{MobileWorkspaceSwitcherHeader-DOr4pTUq.js → MobileWorkspaceSwitcherHeader-DJPV9ym2.js} +1 -1
- package/dist/public/assets/RelayConnectEntryPage-dSwU8VzK.js +1 -0
- package/dist/public/assets/{ServerSettingsModal-BYB0GvTl.js → ServerSettingsModal-B34ms3ze.js} +1 -1
- package/dist/public/assets/{SessionIndexPage-CR3IARXX.js → SessionIndexPage-D3tG1gmM.js} +1 -1
- package/dist/public/assets/SettingsPage-B3-6-5GL.js +1 -0
- package/dist/public/assets/{TerminalManagerPanel-PQ-EM64j.js → TerminalManagerPanel-DhuTEdzV.js} +1 -1
- package/dist/public/assets/{TerminalPage-CvnHXBhw.js → TerminalPage-DpsvQQVR.js} +19 -19
- package/dist/public/assets/{TerminalRuntimeFallbackModal-D7Aq186N.js → TerminalRuntimeFallbackModal-CNzOt5v5.js} +1 -1
- package/dist/public/assets/{ToolFilesPage-Qzkc6K2I.js → ToolFilesPage-BX9QDi9Y.js} +1 -1
- package/dist/public/assets/{ToolGitPage-BdNDN-cV.js → ToolGitPage-4VtFox3p.js} +1 -1
- package/dist/public/assets/{ToolProcessesPage-EXJ9DHWI.js → ToolProcessesPage-DZJC6Qnt.js} +1 -1
- package/dist/public/assets/{ToolsHomePage-CjF3CWzR.js → ToolsHomePage-D7JbrAWv.js} +1 -1
- package/dist/public/assets/{WorkbenchLandingPage-DZPk4SmX.js → WorkbenchLandingPage-C0yqnzqh.js} +1 -1
- package/dist/public/assets/WorkbenchLayout-Brlj8K3i.js +3 -0
- package/dist/public/assets/{WorkbenchModal-B09hC9b5.js → WorkbenchModal-CbDxaCOR.js} +1 -1
- package/dist/public/assets/{WorkbenchShellRoute-DsW4mBTX.css → WorkbenchShellRoute-BMcnFadA.css} +1 -1
- package/dist/public/assets/WorkbenchShellRoute-puGpdDFY.js +1 -0
- package/dist/public/assets/{WorkspaceDebugDetailPage-Bcq8s-Ma.js → WorkspaceDebugDetailPage-fTGweC9N.js} +1 -1
- package/dist/public/assets/{WorkspaceDetailPage-DNAa8pKr.js → WorkspaceDetailPage-BtaIzSDB.js} +1 -1
- package/dist/public/assets/{WorkspaceHomePage-BoiLuACV.js → WorkspaceHomePage-CUmmYDrM.js} +1 -1
- package/dist/public/assets/{client-runtime-manager-CRQ-F5d2.js → client-runtime-manager-RHFa_iWo.js} +1 -1
- package/dist/public/assets/{default-session-permission-mode-D0wZ9Jek.js → default-session-permission-mode-Cu5SreTG.js} +1 -1
- package/dist/public/assets/file-tree-icon-BMKuc5pw.js +31 -0
- package/dist/public/assets/index-Cq3ue0za.css +1 -0
- package/dist/public/assets/index-DEbFT-Aq.js +42 -0
- package/dist/public/assets/{preferences-service-gOt2ZjKZ.js → preferences-service-gv_9vGKz.js} +1 -1
- package/dist/public/assets/session-runtime-machine-Bfnxkk9B.js +17 -0
- package/dist/public/assets/{terminal-runtime-meta-BMT-rSEe.js → terminal-runtime-meta-B9xJGY__.js} +1 -1
- package/dist/public/assets/{useRegisteredDebugTemplates-zMcEOGca.js → useRegisteredDebugTemplates-CDfl54Wt.js} +1 -1
- package/dist/public/index.html +2 -2
- package/dist/server/config/env.d.ts +1 -0
- package/dist/server/config/env.js +36 -0
- package/dist/server/config/env.js.map +1 -1
- package/dist/server/modules/relay-tunnel/crypto/relay-tunnel-packets.d.ts +16 -1
- package/dist/server/modules/relay-tunnel/crypto/relay-tunnel-packets.js.map +1 -1
- package/dist/server/modules/relay-tunnel/crypto/relay-tunnel-protocol.d.ts +2 -1
- package/dist/server/modules/relay-tunnel/crypto/relay-tunnel-protocol.js +18 -0
- package/dist/server/modules/relay-tunnel/crypto/relay-tunnel-protocol.js.map +1 -1
- package/dist/server/modules/relay-tunnel/relay-tunnel-client-context.d.ts +13 -0
- package/dist/server/modules/relay-tunnel/relay-tunnel-client-context.js +2 -0
- package/dist/server/modules/relay-tunnel/relay-tunnel-client-context.js.map +1 -0
- package/dist/server/modules/relay-tunnel/relay-tunnel-gateway-service.d.ts +6 -0
- package/dist/server/modules/relay-tunnel/relay-tunnel-gateway-service.js +110 -10
- package/dist/server/modules/relay-tunnel/relay-tunnel-gateway-service.js.map +1 -1
- package/dist/server/modules/relay-tunnel/relay-tunnel-runtime-adapter.d.ts +16 -4
- package/dist/server/modules/relay-tunnel/relay-tunnel-runtime-adapter.js +216 -101
- package/dist/server/modules/relay-tunnel/relay-tunnel-runtime-adapter.js.map +1 -1
- package/dist/server/modules/relay-tunnel/relay-tunnel-service.d.ts +4 -1
- package/dist/server/modules/relay-tunnel/relay-tunnel-service.js +256 -34
- package/dist/server/modules/relay-tunnel/relay-tunnel-service.js.map +1 -1
- package/dist/server/modules/sessions/session-activity-inspector.js +6 -8
- package/dist/server/modules/sessions/session-activity-inspector.js.map +1 -1
- package/dist/server/modules/sessions/session-history-service.d.ts +1 -0
- package/dist/server/modules/sessions/session-history-service.js +62 -7
- package/dist/server/modules/sessions/session-history-service.js.map +1 -1
- package/dist/server/modules/workbench/workbench-service.d.ts +32 -2
- package/dist/server/modules/workbench/workbench-service.js +36 -2
- package/dist/server/modules/workbench/workbench-service.js.map +1 -1
- package/dist/server/server/create-server.js +10 -5
- package/dist/server/server/create-server.js.map +1 -1
- package/dist/server/ws/workbench-ws-hub.js +166 -16
- package/dist/server/ws/workbench-ws-hub.js.map +1 -1
- package/dist/server/ws/ws-server.js +141 -8
- package/dist/server/ws/ws-server.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/providers/codex.js +33 -6
- package/node_modules/@codingns/session-sync-core/dist/providers/codex.js.map +1 -1
- package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js +78 -36
- package/node_modules/@codingns/session-sync-core/dist/runtime/codex-runtime.js.map +1 -1
- package/package.json +1 -1
- package/dist/public/assets/App-WOLwMld_.js +0 -30
- package/dist/public/assets/ConversationPage-D9pzRmOg.js +0 -2
- package/dist/public/assets/DesktopWindowPage-D8FpOSLE.js +0 -2
- package/dist/public/assets/FileContextPanel-C8T7oqRN.js +0 -1
- package/dist/public/assets/GitSidebar-Bze7DNnc.js +0 -6
- package/dist/public/assets/MobileSheet-Gzc14EpR.js +0 -1
- package/dist/public/assets/SettingsPage-B_BQtnwE.js +0 -1
- package/dist/public/assets/WorkbenchLayout-rwQib5In.js +0 -3
- package/dist/public/assets/WorkbenchShellRoute-Cerk5uK7.js +0 -1
- package/dist/public/assets/file-tree-icon-Dp_xhVfD.js +0 -31
- package/dist/public/assets/index-C2G8Gmf1.js +0 -42
- package/dist/public/assets/index-CpPTUeA3.css +0 -1
- package/dist/public/assets/session-runtime-machine-Dq3pW-UF.js +0 -17
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var $n=Object.defineProperty;var Yn=(t,e,n)=>e in t?$n(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var de=(t,e,n)=>Yn(t,typeof e!="symbol"?e+"":e,n);import{t as o,b as a,u as Gn,j as r,l as It,A as zn}from"./index-C2G8Gmf1.js";import{W as Qn,D as Ht}from"./WorkbenchModal-B09hC9b5.js";import{l as Kn,m as Jn,n as Xe,o as Ds,p as Zn,q as nt,a as qt,s as Bs,t as Ut,v as Fs,w as Hs,S as er,x as qs,y as Us,z as tr,A as sr,B as nr,C as rr,D as ir,E as or,F as ls,G as ar,H as lr,I as cr,J as ur,K as Ws,u as dr,e as Wt,L as hr,N as mr,i as fr,j as pr,O as gr}from"./MobileSheet-Gzc14EpR.js";import{g as _e}from"./default-session-permission-mode-D0wZ9Jek.js";import{e as Ye,u as Ge,d as Xt,f as lt,g as Vt,c as vr}from"./App-WOLwMld_.js";import{u as ct,e as cs,b as ke,L as br,M as wr,N as Sr,O as Mr,P as Ir,E as xr,z as He,Q as Xs,R as Vs,S as $s,T as Ys,A as Gs,U as yr,V as $t,r as us,X as ie,w as Rr,Y as zs,i as ut,G as Qs,Z as Ks,_ as Js,K as Zs,j as rt,$ as Tr,H as en,a0 as Cr,F as kr}from"./WorkbenchLayout-rwQib5In.js";import{B as Er,M as Ar,m as Ue,c as ds,a as tn,g as Pr,r as hs,b as Lt,R as jr,d as sn,C as nn,P as Nr,e as _r}from"./session-runtime-machine-Dq3pW-UF.js";import{FileContextPanel as Lr}from"./FileContextPanel-C8T7oqRN.js";import{GitSidebar as Or}from"./GitSidebar-Bze7DNnc.js";import{TerminalManagerPanel as Dr}from"./TerminalManagerPanel-PQ-EM64j.js";import{f as rn,a as dt,M as on}from"./MobileWorkspaceSwitcherHeader-DOr4pTUq.js";import{w as $e,r as xt,a as ms,b as fs}from"./styles-CSUx5LGe.js";import"./window-BWqRixxq.js";import"./event-DvH9tcej.js";import"./file-tree-icon-Dp_xhVfD.js";import"./terminal-runtime-meta-BMT-rSEe.js";import"./TerminalRuntimeFallbackModal-D7Aq186N.js";import"./MobileTopHeaderFrame-BWorAJ1C.js";function an({connectionState:t,onReconnect:e}){const{showToast:n,dismissToast:s}=Ye(),i=Kn(),c=i?o(Jn(i.kind)):null;return a.useEffect(()=>{if(t==="connected"||t==="closed"){s("conversation-connection-state");return}if(t==="reconnect_failed"){n({id:"conversation-connection-state",title:o("conversation.connectionReconnectFailed"),description:c?o("conversation.reconnectFailedExplainWithRoute",{route:c}):o("conversation.reconnectFailedExplain"),tone:"warning",durationMs:null,action:{label:o("conversation.reconnectButton"),onClick:e}});return}n({id:"conversation-connection-state",title:o("conversation.connectionReconnecting"),description:c?o("conversation.reconnectExplainWithRoute",{route:c}):o("conversation.reconnectExplain"),tone:"info",durationMs:3200})},[c,t,s,e,n]),null}const Je="provider-default",Br=420,Fr=520,Hr=32,qr=48;function Ur(t){if(typeof document>"u")return!1;const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly","true"),e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.focus(),e.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(e)}}async function Wr(t,e){var n;if(!(e.isDesktop&&(await e.bridge.writeClipboardText(t)).ok)){if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(t);return}catch{}if(!Ur(t))throw new Error(o("conversation.copyContentFailed"))}}function Ze(t,e,n){return Math.min(Math.max(t,e),n)}function yt(t){return t&&nt.includes(t)?t:"codex"}function Ot(t){return t?t.nodeType===Node.ELEMENT_NODE?t:t.parentElement:null}function ps(t){var n,s;const e=Ot(t);return((s=(n=e==null?void 0:e.closest("[data-message-id]"))==null?void 0:n.getAttribute("data-message-id"))==null?void 0:s.trim())||null}function Xr(t,e){return[e.trim()||o("conversation.selectionActionDefaultPrompt"),"",o("conversation.selectionActionQuotedLabel"),"```text",t.trim(),"```"].join(`
|
|
2
|
-
`)}function Rt(t){if(typeof window>"u")return null;const e=window.getSelection();if(!e||e.rangeCount===0||e.isCollapsed)return null;const n=e.getRangeAt(0),s=Ot(n.startContainer),i=Ot(n.endContainer);if(!s||!i||!t.contains(s)||!t.contains(i))return null;const c=e.toString().trim();if(!c)return null;const l=n.getBoundingClientRect();if(!l.width&&!l.height)return null;const u=ps(n.startContainer),h=ps(n.endContainer);return{text:c,sourceMessageId:u&&u===h?u:null,rect:{left:l.left,top:l.top,right:l.right,bottom:l.bottom,width:l.width,height:l.height}}}function Vr({containerRef:t,session:e,currentCapabilities:n}){const s=Ge(),i=Xt(),{showToast:c}=Ye(),{shellMode:l,requestNavigationRefresh:u,selectWorkspace:h,upsertNavigationSession:b}=ct(),R=Gn(m=>m.profile.providers),[S,N]=a.useState(null),[C,x]=a.useState(!1),[w,_]=a.useState(""),[E,M]=a.useState(!1),[g,D]=a.useState(yt(e==null?void 0:e.provider)),[O,T]=a.useState(Je),[F,y]=a.useState(null),[k,j]=a.useState({}),[X,$]=a.useState(!1),[te,oe]=a.useState(!1),[Z,le]=a.useState(!1),[p,v]=a.useState(0),[P,H]=a.useState(null),[q,se]=a.useState(()=>({width:typeof window>"u"?0:window.innerWidth,height:typeof window>"u"?0:window.innerHeight})),Y=a.useRef(!1),K=a.useRef(!1),G=a.useRef(null),U=a.useRef(null),ge=l==="mobile"||i.isMobile,A=a.useMemo(()=>m=>{var B,z;return((z=(B=R[m])==null?void 0:B.defaultModel)==null?void 0:z.trim())||Je},[R]),f=a.useMemo(()=>g===(e==null?void 0:e.provider)&&n?n:F??Xe(g),[n,F,g,e==null?void 0:e.provider]),J=a.useMemo(()=>{var B;const m=Xe(g).modelOptions??[];return(B=f.modelOptions)!=null&&B.length?f.modelOptions:m},[f.modelOptions,g]),he=a.useMemo(()=>J.find(m=>m.id===O)??J[0]??null,[J,O]),Se=a.useMemo(()=>{const m=k[g]??(g===(e==null?void 0:e.provider)?n:F);return!m||m.canStartSession!==!1?null:m.limitations[0]??o("conversation.capabilityDenied")},[n,F,k,g,e==null?void 0:e.provider]),Te=a.useMemo(()=>{var ee;if(!S||typeof window>"u")return null;const m=(ee=t.current)==null?void 0:ee.getBoundingClientRect(),B=m?Math.max(80,m.left+80):96,z=m?Math.min(q.width-80,m.right-80):q.width-96,W=m?Math.max(12,m.top+12):12,ne=m?Math.max(W,m.bottom-48):Math.max(12,q.height-48),be=S.rect.left+S.rect.width/2;return{left:Ze(be,B,Math.max(B,z)),top:Ze(S.rect.top-48,W,ne)}},[t,S,q.height,q.width]),Ee=a.useMemo(()=>{var ze;if(!S||typeof window>"u")return null;const m=(ze=t.current)==null?void 0:ze.getBoundingClientRect(),B=(m==null?void 0:m.left)??0,z=(m==null?void 0:m.right)??q.width,W=(m==null?void 0:m.top)??0,ne=(m==null?void 0:m.bottom)??q.height;if(ge)return{left:q.width/2,top:q.height/2,width:Math.min(420,Math.max(280,q.width-24)),maxHeight:Math.max(260,q.height-Hr),transform:"translate(-50%, -50%)"};const be=Math.max(280,Math.min(q.width-24,z-B-24)),ee=Math.min(420,be),pe=S.rect.left+S.rect.width/2,re=Math.max(12,B+12),Pe=Math.max(re,Math.min(q.width-ee-12,z-ee-12)),qe=Math.min(Fr,Math.max(280,ne-W-24),Math.max(280,q.height-24)),Oe=Math.max(12,W+12),ht=Math.max(Oe,Math.min(q.height-qe-12,ne-qe-12)),mt=S.rect.top-Br-18;return{left:Ze(pe-ee/2,re,Pe),top:Ze(mt,Oe,ht),width:ee,maxHeight:qe}},[t,ge,S,q.height,q.width]);a.useEffect(()=>{if(typeof window>"u")return;const m=()=>{se({width:window.innerWidth,height:window.innerHeight})};return m(),window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m)}},[]),a.useEffect(()=>{if(!e){U.current!==null&&typeof window<"u"&&(window.clearTimeout(U.current),U.current=null),G.current=null,K.current=!1,N(null),x(!1);return}const m=yt(e.provider);D(m),T(A(m))},[A,e]),a.useEffect(()=>{if(!e||!t.current||typeof window>"u"){U.current!==null&&(window.clearTimeout(U.current),U.current=null),G.current=null,K.current=!1,N(null);return}const m=t.current,B=re=>{Y.current||(G.current=re,N(re),re||x(!1))},z=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},W=(re,Pe)=>{if(G.current=re,z(),Pe!=null&&Pe.immediate){B(re);return}U.current=window.setTimeout(()=>{U.current=null,B(G.current)},qr)},ne=()=>{const re=Rt(m);if(K.current){G.current=re;return}W(re)},be=()=>{const re=Rt(m);if(K.current){G.current=re;return}W(re,{immediate:!0})},ee=re=>{!(re.target instanceof Node)||!m.contains(re.target)||(K.current=!0,z())},pe=()=>{K.current&&(K.current=!1,W(Rt(m)))};return document.addEventListener("pointerdown",ee),document.addEventListener("selectionchange",ne),window.addEventListener("pointerup",pe),window.addEventListener("pointercancel",pe),window.addEventListener("mouseup",pe),window.addEventListener("touchend",pe),window.addEventListener("resize",be),window.addEventListener("scroll",be,!0),()=>{z(),document.removeEventListener("pointerdown",ee),document.removeEventListener("selectionchange",ne),window.removeEventListener("pointerup",pe),window.removeEventListener("pointercancel",pe),window.removeEventListener("mouseup",pe),window.removeEventListener("touchend",pe),window.removeEventListener("resize",be),window.removeEventListener("scroll",be,!0)}},[t,e]),a.useEffect(()=>{(!C||!(S!=null&&S.sourceMessageId))&&M(!1)},[C,S==null?void 0:S.sourceMessageId]),a.useEffect(()=>{if(!C||!e)return;let m=!1;return g===e.provider&&n?($(!1),y(n),()=>{m=!0}):($(!0),y(Xe(g)),Ds(g,e.workspaceId).then(B=>{m||y(B)}).catch(()=>{m||y(Xe(g))}).finally(()=>{m||$(!1)}),()=>{m=!0})},[C,n,g,e]),a.useEffect(()=>{if(!C||!e){j({});return}let m=!1;return Zn(nt,e.workspaceId).then(B=>{m||j(B)}),()=>{m=!0}},[C,e]),a.useEffect(()=>{if(!C||!e)return;const m=nt.filter(z=>{const W=k[z];return!W||W.canStartSession!==!1});if(m.length===0||m.includes(g))return;const B=m[0];D(B),T(A(B))},[C,A,k,g,e]),a.useEffect(()=>{var B;const m=A(g);if(!J.some(z=>z.id===O)){if(J.some(z=>z.id===m)){T(m);return}T(((B=J[0])==null?void 0:B.id)??Je)}},[J,A,O,g]),a.useEffect(()=>{if(!C){Y.current=!1;return}Y.current=!0},[C]),a.useEffect(()=>{if(typeof window>"u")return;const m=B=>{B.key==="Escape"&&(x(!1),N(null),Y.current=!1)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);async function L(){if(S)try{await Wr(S.text,i),c({title:o("conversation.copyContentSuccess"),tone:"success"})}catch(m){c({title:m instanceof Error?m.message:o("conversation.copyContentFailed"),tone:"error"})}}function V(){S&&(H({title:"",content:S.text}),v(m=>m+1),le(!0),x(!1),N(null),Y.current=!1)}function me(){if(!S||!e)return;const m=yt(e.provider);D(m),T(A(m)),_(""),M(!1),x(!0)}async function ce(){var m,B,z,W;if(!(!S||!e)){if(Se){c({title:Se,tone:"error"});return}oe(!0);try{const ne=Xr(S.text,w),be=(he==null?void 0:he.id)===Je?null:(he==null?void 0:he.id)??null;let ee=null;if(E&&S.sourceMessageId)ee=await Bs(e.sessionId,{sourceType:"message",sourceMessageId:S.sourceMessageId,strategy:"auto",targetProvider:g,sessionKind:"annotation",annotationSourceMessageId:S.sourceMessageId,annotationSourceText:S.text}),b(ee),await Ut(ee.sessionId,{content:ne,clientRequestId:((B=(m=globalThis.crypto)==null?void 0:m.randomUUID)==null?void 0:B.call(m))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:be,permissionMode:_e()});else{const pe=await Fs({workspaceId:e.workspaceId,provider:g,content:ne,clientRequestId:((W=(z=globalThis.crypto)==null?void 0:z.randomUUID)==null?void 0:W.call(z))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:be,permissionMode:_e(),parentSessionId:e.sessionId,sessionKind:"annotation",annotationSourceMessageId:S.sourceMessageId??null,annotationSourceText:S.text});ee=pe.session??await Hs(pe.sessionId)}b(ee),u(),h(ee.workspaceId),s(ke(ee.workspaceId,ee.sessionId)),x(!1),N(null),Y.current=!1}catch(ne){c({title:ne instanceof Error?ne.message:o("conversation.selectionActionFailed"),tone:"error"})}finally{oe(!1)}}}function fe(m=!1){x(!1),Y.current=!1,m&&N(null)}return!e||!S||!Te||typeof document>"u"?r.jsx(cs,{open:Z,preferredWorkspaceId:(e==null?void 0:e.workspaceId)??null,preferredSessionId:(e==null?void 0:e.sessionId)??null,creationRequestId:p,initialDraft:P,onClose:()=>le(!1)}):r.jsxs(r.Fragment,{children:[lt.createPortal(r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"conversation-selection-toolbar",style:Te,onMouseDown:m=>m.preventDefault(),children:[r.jsx("button",{type:"button",className:"conversation-selection-action",onClick:()=>void L(),children:o("conversation.copyAction")}),r.jsx("button",{type:"button",className:"conversation-selection-action",onClick:V,children:o("conversation.selectionTodoAction")}),r.jsx("button",{type:"button",className:"conversation-selection-action is-primary",onClick:me,children:o("conversation.selectionActionButton")})]}),C&&Ee?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`conversation-selection-dialog-backdrop${ge?" is-mobile":""}`,onMouseDown:()=>fe(!1)}),r.jsxs("div",{className:`conversation-selection-action-dialog workbench-modal-card surface-card${ge?" is-centered":""}`,style:Ee,role:"dialog","aria-modal":"true","aria-label":o("conversation.selectionActionButton"),onMouseDown:m=>m.stopPropagation(),children:[r.jsxs("div",{className:"conversation-selection-action-dialog-header workbench-modal-header",children:[r.jsx("div",{className:"workbench-modal-title-wrap",children:r.jsx("h2",{children:o("conversation.selectionActionButton")})}),r.jsx("button",{type:"button",className:"conversation-selection-action-dialog-close workbench-modal-close","aria-label":o("common.close"),onClick:()=>fe(!1),children:"×"})]}),r.jsx("p",{className:"conversation-selection-action-dialog-quote",children:S.text}),r.jsxs("label",{className:"conversation-selection-field workbench-modal-field",children:[r.jsx("span",{children:o("conversation.selectionActionPromptLabel")}),r.jsx("textarea",{value:w,rows:4,placeholder:o("conversation.selectionActionPromptPlaceholder"),onChange:m=>_(m.target.value)})]}),r.jsxs("label",{className:"conversation-selection-checkbox",children:[r.jsx("input",{type:"checkbox",checked:E,disabled:!S.sourceMessageId,onChange:m=>M(m.target.checked)}),r.jsx("span",{children:o("conversation.selectionActionIncludeContext")})]}),S.sourceMessageId?null:r.jsx("p",{className:"conversation-selection-hint",children:o("conversation.selectionActionContextUnavailable")}),Se?r.jsx("p",{className:"conversation-selection-hint",children:Se}):null,r.jsxs("div",{className:"conversation-selection-grid",children:[r.jsxs("label",{className:"conversation-selection-field workbench-modal-field",children:[r.jsx("span",{children:o("conversation.forkTargetProviderLabel")}),r.jsx("select",{value:g,onChange:m=>{const B=m.target.value;D(B),T(A(B))},children:nt.map(m=>{var B;return r.jsx("option",{value:m,disabled:((B=k[m])==null?void 0:B.canStartSession)===!1,children:qt(m,"full")},m)})})]}),r.jsxs("label",{className:"conversation-selection-field workbench-modal-field",children:[r.jsx("span",{children:o("conversation.forkTargetModelLabel")}),r.jsx("select",{value:O,disabled:X||!!Se,onChange:m=>T(m.target.value),children:J.map(m=>r.jsx("option",{value:m.id,children:m.name},m.id))})]})]}),r.jsxs("div",{className:"conversation-selection-actions",children:[r.jsx("button",{type:"button",className:"secondary-button",onClick:()=>fe(!1),children:o("common.cancel")}),r.jsx("button",{type:"button",className:"primary-button",disabled:te||!!Se,onClick:()=>void ce(),children:te?o("conversation.sendingState"):o("conversation.selectionActionSubmit")})]})]})]}):null]}),document.body),r.jsx(cs,{open:Z,preferredWorkspaceId:e.workspaceId,preferredSessionId:e.sessionId,creationRequestId:p,initialDraft:P,onClose:()=>le(!1)})]})}const We=5,$r=["codex","claude-code"];function ln(){return[{id:"recommended",label:o("conversation.butlerCompletionTemplateRecommendedLabel"),description:o("conversation.butlerCompletionTemplateRecommendedDescription"),value:o("conversation.butlerCompletionTemplateRecommendedValue")},{id:"spec-finish",label:o("conversation.butlerCompletionTemplateSpecLabel"),description:o("conversation.butlerCompletionTemplateSpecDescription"),value:o("conversation.butlerCompletionTemplateSpecValue")},{id:"bugfix",label:o("conversation.butlerCompletionTemplateBugfixLabel"),description:o("conversation.butlerCompletionTemplateBugfixDescription"),value:o("conversation.butlerCompletionTemplateBugfixValue")}]}function Tt(){var t;return((t=ln()[0])==null?void 0:t.value)??""}function gs(t){return t==="claude-code"?"claude-code":"codex"}function Yr(t){return t==="codex"||t==="claude-code"}function cn({session:t,showTrigger:e=!0,openRequestKey:n=0}){const{showToast:s}=Ye(),{requestNavigationRefresh:i}=ct(),c=a.useId(),l=a.useId(),u=a.useId(),h=a.useId(),[b,R]=a.useState(!1),[S,N]=a.useState(!1),[C,x]=a.useState(null),[w,_]=a.useState(null),[E,M]=a.useState(null),[g,D]=a.useState(gs(t==null?void 0:t.provider)),[O,T]=a.useState(""),[F,y]=a.useState(()=>Tt()),[k,j]=a.useState(We),[X,$]=a.useState(!1),[te,oe]=a.useState(0),Z=ln(),le=a.useMemo(()=>{var A;return((A=t==null?void 0:t.title)==null?void 0:A.trim())||null},[t==null?void 0:t.title]),p=a.useMemo(()=>C?{workspaceId:C.workspaceId,project:C.project,session:C.session}:null,[C]),v=(C==null?void 0:C.latestFollowUpTask)??null,P=(C==null?void 0:C.latestVerificationRun)??null,H=v&&(v.status==="active"||v.status==="waiting_user")?v:null,q=P&&(P.status==="queued"||P.status==="running")?P:null;if(a.useEffect(()=>{R(!1),$(!1),_(null),x(null),T(""),D(gs(t==null?void 0:t.provider)),y(Tt()),j(We)},[t==null?void 0:t.sessionId]),a.useEffect(()=>{if(!(t!=null&&t.sessionId)){N(!1);return}let A=!1;return N(!0),_(null),br(t.sessionId).then(f=>{A||x(f.context)}).catch(f=>{A||(x(null),_(f instanceof Error?f.message:o("conversation.butlerActionLoadFailed")))}).finally(()=>{A||N(!1)}),()=>{A=!0}},[te,t==null?void 0:t.sessionId]),!(t!=null&&t.sessionId))return null;function se(){S||oe(A=>A+1)}function Y(){!C&&!S&&se()}a.useEffect(()=>{e||n<=0||(R(!0),Y())},[S,n,e,C]);async function K(){if(!p){Y();return}const A=O.trim(),f=F.trim();if(!A){s({title:o("conversation.butlerFollowUpObjectiveRequired"),tone:"warning"});return}if(!f){s({title:o("conversation.butlerFollowUpCompletionCriteriaRequired"),tone:"warning"});return}M("follow-up");try{const J=await Ir({projectId:p.project.id,butlerSessionId:p.session.id,providerId:g,objective:A,completionCriteria:f,maxAutoContinueCount:k});x(he=>he&&{...he,latestFollowUpTask:J.task}),i(),s({title:o("conversation.butlerFollowUpStarted"),description:o("conversation.butlerFollowUpStartedDescription",{projectName:p.project.name}),tone:"success"}),T(""),y(Tt()),j(We),R(!1)}catch(J){s({title:o("conversation.butlerFollowUpFailed"),description:J instanceof Error?J.message:void 0,tone:"error"})}finally{M(null)}}async function G(){if(v){M("follow-up");try{const A=await wr(v.id);x(f=>f&&{...f,latestFollowUpTask:A.task}),i(),s({title:o("conversation.butlerFollowUpStopped"),description:o("conversation.butlerFollowUpStoppedDescription"),tone:"success"}),R(!1)}catch(A){s({title:o("conversation.butlerFollowUpStopFailed"),description:A instanceof Error?A.message:void 0,tone:"error"})}finally{M(null)}}}async function U(){if(!p){Y();return}M("verification");try{const A=await Mr({projectId:p.project.id,butlerSessionId:p.session.id,verificationType:"browser",targetRef:le||p.session.title||p.project.name});x(f=>f&&{...f,latestVerificationRun:A.result.run}),i(),s({title:o("conversation.butlerVerificationStarted"),description:o("conversation.butlerVerificationStartedDescription",{projectName:p.project.name}),tone:"success"}),R(!1)}catch(A){s({title:o("conversation.butlerVerificationFailed"),description:A instanceof Error?A.message:void 0,tone:"error"})}finally{M(null)}}async function ge(){if(P){M("verification");try{const A=await Sr(P.projectId,P.id);x(f=>f&&{...f,latestVerificationRun:A.run}),i(),s({title:o("conversation.butlerVerificationStopped"),description:o("conversation.butlerVerificationStoppedDescription"),tone:"success"}),R(!1)}catch(A){s({title:o("conversation.butlerVerificationStopFailed"),description:A instanceof Error?A.message:void 0,tone:"error"})}finally{M(null)}}}return r.jsxs(r.Fragment,{children:[e?r.jsxs("div",{className:"conversation-butler-entry",onMouseEnter:()=>{$(!0),Y()},onMouseLeave:()=>{$(!1)},children:[r.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":o("conversation.butlerActionButton"),title:o("conversation.butlerActionButton"),onFocus:()=>{$(!0),Y()},onBlur:()=>{$(!1)},onClick:()=>{R(!0),Y()},children:r.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:r.jsx(Er,{})})}),X?r.jsxs("div",{className:"conversation-butler-analysis-popover",role:"status","aria-live":"polite",children:[r.jsx("strong",{children:o("conversation.butlerAnalysisTitle")}),S?r.jsx("p",{children:o("conversation.butlerActionLoading")}):w?r.jsx("p",{children:w}):v?r.jsxs(r.Fragment,{children:[r.jsxs("p",{children:[o("conversation.butlerAnalysisObjectiveLabel"),":",v.objective]}),r.jsxs("p",{children:[o("conversation.butlerAnalysisStatusLabel"),":",vs(v.status)]}),r.jsxs("p",{children:[o("conversation.butlerAnalysisSummaryLabel"),":",v.lastAutomationSummary||v.waitingReason||o("conversation.butlerAnalysisEmpty")]}),v.waitingReason?r.jsxs("p",{children:[o("conversation.butlerAnalysisWaitingReasonLabel"),":",v.waitingReason]}):null]}):r.jsx("p",{children:o("conversation.butlerAnalysisEmpty")})]}):null]}):null,r.jsx(Qn,{open:b,title:o("conversation.butlerActionModalTitle"),description:o("conversation.butlerActionModalDescription"),className:"conversation-butler-modal-card",footer:!S&&!w&&p?r.jsxs(qs,{children:[r.jsx("button",{type:"button",className:"secondary-button",disabled:E!==null,onClick:()=>{U()},children:o("conversation.butlerVerificationAction")}),r.jsx("button",{type:"button",className:"primary-button",disabled:E!==null,onClick:()=>{K()},children:o("conversation.butlerFollowUpAction")})]}):void 0,onClose:()=>{E||R(!1)},children:r.jsxs("div",{className:"conversation-butler-modal",children:[S?r.jsx("p",{className:"conversation-butler-modal-hint",children:o("conversation.butlerActionLoading")}):null,!S&&w?r.jsx("p",{className:"conversation-butler-modal-error",children:w}):null,!S&&!w&&p?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"conversation-butler-target-grid",children:[r.jsxs("div",{className:"conversation-butler-target-card",children:[r.jsx("span",{children:o("conversation.butlerActionProjectLabel")}),r.jsx("strong",{children:p.project.name})]}),r.jsxs("div",{className:"conversation-butler-target-card",children:[r.jsx("span",{children:o("conversation.butlerActionSessionLabel")}),r.jsx("strong",{children:p.session.title||le||p.session.sessionId})]})]}),r.jsxs("div",{className:"conversation-butler-follow-up-grid",children:[r.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[r.jsxs("div",{className:"conversation-butler-field-heading",children:[r.jsx("label",{children:o("conversation.butlerFollowUpProviderLabel")}),r.jsx("small",{children:o("conversation.butlerFollowUpProviderHint")})]}),r.jsx(er,{workspaceId:p.workspaceId,providers:$r,selectedProvider:g,disabled:E!==null,onSelect:A=>{Yr(A)&&D(A)}})]}),r.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field conversation-butler-round-limit-field",children:[r.jsxs("div",{className:"conversation-butler-field-heading",children:[r.jsx("label",{htmlFor:h,children:o("conversation.butlerFollowUpRoundLimitLabel")}),r.jsx("small",{children:o("conversation.butlerFollowUpRoundLimitHint")})]}),r.jsx("input",{id:h,type:"number",min:1,max:20,value:k,disabled:E!==null,onChange:A=>{const f=Number.parseInt(A.target.value,10);j(Number.isFinite(f)?f:We)}})]})]}),r.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[r.jsx("label",{htmlFor:c,children:o("conversation.butlerFollowUpObjectiveLabel")}),r.jsx("textarea",{id:c,rows:3,value:O,placeholder:o("conversation.butlerFollowUpObjectivePlaceholder"),disabled:E!==null,onChange:A=>{T(A.target.value)}})]}),r.jsxs("div",{className:"workbench-modal-field conversation-butler-modal-field",children:[r.jsxs("div",{className:"conversation-butler-field-heading",children:[r.jsx("label",{htmlFor:l,children:o("conversation.butlerFollowUpCompletionCriteriaLabel")}),r.jsx("small",{id:u,children:o("conversation.butlerCompletionTemplateSectionHint")})]}),r.jsx("textarea",{id:l,rows:3,value:F,placeholder:o("conversation.butlerFollowUpCompletionCriteriaPlaceholder"),"aria-describedby":u,disabled:E!==null,onChange:A=>{y(A.target.value)}}),r.jsx("div",{className:"conversation-butler-preset-grid",role:"group","aria-label":o("conversation.butlerCompletionTemplateSectionLabel"),children:Z.map(A=>r.jsxs("button",{type:"button",className:"conversation-butler-preset-card","data-selected":F.trim()===A.value,"aria-pressed":F.trim()===A.value,disabled:E!==null,onClick:()=>{y(A.value)},children:[r.jsx("strong",{children:A.label}),r.jsx("span",{children:A.description})]},A.id))})]}),H||q?r.jsxs("div",{className:"conversation-butler-meta-grid",children:[H?r.jsxs("div",{className:"conversation-butler-target-card conversation-butler-current-task-card",children:[r.jsx("span",{children:o("conversation.butlerCurrentFollowUpLabel")}),r.jsx("strong",{children:vs(H.status)}),r.jsx("small",{children:o("conversation.butlerCurrentFollowUpProgress",{current:H.autoContinueCount,max:H.maxAutoContinueCount??We})}),r.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:E!==null,onClick:()=>{G()},children:o("conversation.butlerStopFollowUpAction")})]}):null,q?r.jsxs("div",{className:"conversation-butler-target-card conversation-butler-current-task-card",children:[r.jsx("span",{children:o("conversation.butlerCurrentVerificationLabel")}),r.jsx("strong",{children:Gr(q.status)}),r.jsx("small",{children:q.targetRef||q.verificationType}),r.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:E!==null,onClick:()=>{ge()},children:o("conversation.butlerStopVerificationAction")})]}):null]}):null]}):null]})})]})}function vs(t){switch(t){case"waiting_user":return o("shell.butlerAutomationStatusWaitingUser");case"completed":return o("shell.butlerAutomationStatusCompleted");case"failed":return o("shell.butlerAutomationStatusFailed");case"cancelled":return o("shell.butlerAutomationStatusCancelled");case"active":default:return o("shell.butlerAutomationStatusActive")}}function Gr(t){switch(t){case"queued":case"running":return o("shell.butlerAutomationStatusActive");case"passed":case"skipped":return o("shell.butlerAutomationStatusCompleted");case"failed":return o("shell.butlerAutomationStatusFailed");case"cancelled":default:return o("shell.butlerAutomationStatusCancelled")}}const zr=340;function Qr({session:t,onOpenBranchTree:e}){const n=Ge(),s=Vt(),i=a.useRef(null),c=a.useRef(null),[l,u]=a.useState(!1),[h,b]=a.useState(null),[R,S]=a.useState(null),[N,C]=a.useState(0);a.useEffect(()=>{u(!1),b(null)},[s.pathname,s.search]),a.useLayoutEffect(()=>{if(!l||!h||typeof window>"u"){S(null);return}const T=()=>{var j,X;const k=xr(h,{width:((j=c.current)==null?void 0:j.offsetWidth)??0,height:((X=c.current)==null?void 0:X.offsetHeight)??0},{width:window.innerWidth,height:window.innerHeight},{estimatedHeightPx:zr});S({position:"fixed",left:`${Math.round(k.left)}px`,top:`${Math.round(k.top)}px`,width:`${Math.round(k.width)}px`,maxWidth:"calc(100vw - 24px)",maxHeight:`${Math.round(k.maxHeight)}px`,transformOrigin:k.transformOrigin})},F=k=>{var X,$;const j=k.target;j&&!((X=c.current)!=null&&X.contains(j))&&!(($=i.current)!=null&&$.contains(j))&&w()},y=k=>{k.key==="Escape"&&w()};return T(),window.addEventListener("pointerdown",F),window.addEventListener("keydown",y),window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),()=>{window.removeEventListener("pointerdown",F),window.removeEventListener("keydown",y),window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0)}},[h,l]);function x(){var F;const T=(F=i.current)==null?void 0:F.getBoundingClientRect();T&&(b({x:T.right,y:T.bottom}),u(!0))}function w(){u(!1),b(null)}function _(T){n(T),w()}function E(T){const F=new URLSearchParams(s.search);F.set("toolPanel",T),_(`${s.pathname}?${F.toString()}`)}function M(){if(l){w();return}x()}function g(T){T.key!=="ContextMenu"&&!(T.shiftKey&&T.key==="F10")||(T.preventDefault(),T.stopPropagation(),x())}if(!t)return null;const D=[{key:"assistant",label:o("shell.butlerEntry"),onSelect:()=>{C(T=>T+1),w()}},...e?[{key:"branch",label:o("conversation.branchAction"),onSelect:()=>{e(),w()}}]:[],{key:"files",label:o("shell.filesEntry"),onSelect:()=>{E("files")}},{key:"git",label:o("shell.gitEntry"),onSelect:()=>{E("git")}},{key:"processes",label:o("shell.mobileConversationToolProcessesTab"),onSelect:()=>{E("processes")}}],O=l&&typeof document<"u"?lt.createPortal(r.jsx("div",{ref:c,className:"session-action-menu mobile-conversation-action-menu surface-card",role:"menu","aria-label":o("conversation.moreSessionActions"),style:R??{position:"fixed",top:0,left:0,visibility:"hidden"},onClick:T=>T.stopPropagation(),children:D.map(T=>r.jsx("button",{type:"button",className:"session-action-menu-item mobile-conversation-action-menu-item",role:"menuitem",onClick:T.onSelect,children:T.label},T.key))}),document.body):null;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"mobile-conversation-session-actions",children:[r.jsx("button",{ref:i,type:"button",className:"conversation-header-ai-button mobile-conversation-more-button","aria-label":o("conversation.moreSessionActions"),title:o("conversation.moreSessionActions"),"aria-haspopup":"menu","aria-expanded":l,onClick:M,onKeyDown:g,children:r.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:r.jsx(Ar,{})})}),r.jsx(cn,{session:t,showTrigger:!1,openRequestKey:N})]}),O]})}function Kr({items:t,deletingQueueItemId:e=null,steeringQueueItemId:n=null,canSteer:s=!1,onDelete:i,onSteer:c}){return t.length===0?null:r.jsxs("section",{className:"queued-message-list","aria-label":o("conversation.queueTitle"),children:[r.jsx("div",{className:"queued-message-list__header",children:r.jsx("h2",{children:`${o("conversation.queueTitle")} · ${t.length}`})}),r.jsx("div",{className:"queued-message-list__items",children:t.map((l,u)=>{const h=l.status==="queued"||l.status==="failed",b=s&&typeof c=="function"&&(l.status==="queued"||l.status==="failed");return r.jsxs("article",{className:"queued-message-item",children:[r.jsxs("div",{className:"queued-message-item__main",children:[r.jsx("span",{className:"queued-message-item__order","aria-hidden":"true",children:u+1}),r.jsx("p",{className:"queued-message-item__content",title:l.content||o("conversation.queueImageOnly"),children:l.content||o("conversation.queueImageOnly")}),r.jsx("span",{className:`queued-message-item__status queued-message-item__status--${l.status}`,children:l.status==="failed"?o("conversation.queueStatusFailed"):o("conversation.queueStatusQueued")}),r.jsxs("div",{className:"queued-message-item__actions",children:[b?r.jsx("button",{type:"button",className:"queued-message-item__action queued-message-item__action--steer",onClick:()=>void c(l.id),disabled:n===l.id,"aria-label":o("conversation.queueSteer"),title:o("conversation.queueSteer"),children:n===l.id?o("conversation.queueSteering"):o("conversation.queueSteer")}):null,h?r.jsx("button",{type:"button",className:"queued-message-item__action queued-message-item__action--delete",onClick:()=>void i(l.id),disabled:e===l.id,"aria-label":o("conversation.queueDelete"),title:o("conversation.queueDelete"),children:e===l.id?"…":"×"}):null]})]}),l.errorDetail?r.jsx("p",{className:"queued-message-item__error",children:l.errorDetail}):null]},l.id)})})]})}const Fe=196,Le=82,bs=28,ws=24,un=34,Dt=18,Jr=332,et=360,it=840,Ss=18,Zr=.22,ei=2.4,ti=6;function si(t,e){return(e.lastMessageAt??e.updatedAt).localeCompare(t.lastMessageAt??t.updatedAt)}function dn(t,e,n){var C,x;if(!e)return null;const s=t.find(w=>w.workspace.id===e);if(!s)return null;const i=new Map(s.sessions.map(w=>[w.sessionId,w])),c=i.get(n)??null;if(!c)return null;const l=new Map;for(const w of s.sessions){const _=((C=w.parentSessionId)==null?void 0:C.trim())||null;if(!_)continue;const E=l.get(_)??[];l.set(_,[...E,w.sessionId])}const u=new Set,h=new Set;let b=c,R=c.sessionId;for(;b&&!h.has(b.sessionId);){u.add(b.sessionId),h.add(b.sessionId),R=b.sessionId;const w=((x=b.parentSessionId)==null?void 0:x.trim())||null;b=w?i.get(w)??null:null}const S=hn(R,0,i,l,new Set),N=ri(S);return{root:S,current:c,currentPathIds:u,relatedSessionIds:N,sessionsById:i}}function ni(t){return((t==null?void 0:t.relatedSessionIds.size)??0)>1}function hn(t,e,n,s,i){const c=n.get(t);if(!c)throw new Error(`Session ${t} not found`);const l=new Set(i);l.add(t);const u=[...s.get(t)??[]].filter(h=>!l.has(h)).sort((h,b)=>{const R=n.get(h),S=n.get(b);return!R||!S?0:si(R,S)});return{session:c,depth:e,children:u.map(h=>hn(h,e+1,n,s,l))}}function ri(t){const e=new Set;function n(s){e.add(s.session.sessionId),s.children.forEach(n)}return n(t),e}function mn(t){const e=Gs(t),n=t.lastMessageAt??t.updatedAt,s=n?new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(n)):null;return[qt(t.provider),s,e].filter(Boolean).join(" · ")}function fn(t){return t.isArchived===!0}function ii(t){return[...t].sort((e,n)=>e.sequence-n.sequence).filter(e=>e.content.trim().length>0||e.kind==="tool_call"||e.kind==="tool_result")}function pn(t,e){return t<=0||e<=0?1:Math.min(1,t/e)}function oi(t,e,n,s){const i=pn(t,n),c=n*i,l=s*i,u=c<t?(t-c)/2:0;return{scale:i,offsetX:u,offsetY:0,shellWidth:Math.max(t,c),shellHeight:l}}function Bt(t,e,n){return Math.min(n,Math.max(e,t))}function ai(t,e,n,s){if(t<=0||e<=0||n<=0||s<=0)return 1;const i=Math.max(1,t-Ss*2),c=Math.max(1,e-Ss*2);return Math.min(1,i/n,c/s)}function ot(t,e,n,s,i){const c=s*t.scale,l=i*t.scale,u=(e-c)/2,h=(n-l)/2,b=c<=e?u:Bt(t.offsetX,e-c,0),R=l<=n?h:Bt(t.offsetY,n-l,0);return{scale:t.scale,offsetX:b,offsetY:R}}function tt(t,e,n,s){const i=ai(t,e,n,s);return ot({scale:i,offsetX:(t-n*i)/2,offsetY:(e-s*i)/2},t,e,n,s)}function li(t,e,n,s,i,c,l,u){const h=(n-t.offsetX)/t.scale,b=(s-t.offsetY)/t.scale;return ot({scale:e,offsetX:n-h*e,offsetY:s-b*e},i,c,l,u)}function ci(t){var n;const e=t.content.trim();if(e.length>0){const s=e.replace(/\s+/g," ").trim();return s.length<=160?s:`${s.slice(0,157)}...`}return(n=t.toolCall)!=null&&n.name?`${t.toolCall.name} ${o("conversation.branchTreeToolMessageFallback")}`:o("conversation.branchTreeMessageEmpty")}function ui(t){switch(t.role){case"assistant":return o("conversation.roleAssistant");case"system":return o("conversation.roleSystem");case"tool":return o("conversation.roleTool");case"user":default:return o("conversation.roleUser")}}function Ft(t,e){const n=e.get(t.session.sessionId);if(n!==void 0)return n;if(t.children.length===0)return e.set(t.session.sessionId,Fe),Fe;const s=t.children.reduce((c,l,u)=>{const h=c+Ft(l,e);return u===0?h:h+Dt},0),i=Math.max(Fe,s);return e.set(t.session.sessionId,i),i}function di(t){const e=new Map,n=[],s=new Map;function i(u,h,b){const R=Ft(u,e),S=h+R/2,N=ws+b*(Le+un),C=S-Fe/2,x=u.children.reduce((M,g,D)=>{const O=M+Ft(g,e);return D===0?O:O+Dt},0);let w=h+Math.max(0,(R-x)/2);const _=u.children.map(M=>{const g=i(M,w,b+1);return w+=g.subtreeWidth+Dt,g}),E={node:u,children:_,x:C,y:N,centerX:S,centerY:N+Le/2,subtreeWidth:R};return n.push(E),s.set(u.session.sessionId,E),E}const c=i(t,bs,0),l=n.reduce((u,h)=>Math.max(u,h.y+Le),0);return{root:c,nodes:n,bySessionId:s,width:c.subtreeWidth+bs*2,height:l+ws}}function hi(t){return Math.max(0,Math.min(255,Number.parseFloat(t)))}function mi(t){const e=t.trim();if(e.startsWith("#")){const s=e.slice(1);if(s.length===3){const[i,c,l]=s.split("").map(u=>Number.parseInt(u.repeat(2),16));return{r:i,g:c,b:l}}if(s.length>=6)return{r:Number.parseInt(s.slice(0,2),16),g:Number.parseInt(s.slice(2,4),16),b:Number.parseInt(s.slice(4,6),16)}}const n=e.match(/rgba?\(([^)]+)\)/i);if(n){const[s,i,c]=n[1].split(",").map(l=>hi(l));return{r:s,g:i,b:c}}return null}function Ce(t,e,n){const s=mi(t);return s?`rgba(${s.r}, ${s.g}, ${s.b}, ${e})`:n}function fi(t,e,n,s,i,c){const l=t.getContext("2d");if(!l)return;const u=l,h=window.devicePixelRatio||1;t.width=Math.max(1,Math.floor(e.width*h)),t.height=Math.max(1,Math.floor(e.height*h)),t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,u.setTransform(h,0,0,h,0,0),u.clearRect(0,0,e.width,e.height);const b=window.getComputedStyle(t),R=b.getPropertyValue("--accent").trim()||"#3b82f6",S=b.getPropertyValue("--border-primary").trim()||"#d4d8df",N=b.getPropertyValue("--bg-surface").trim()||"#ffffff";if(!c){const x=u.createLinearGradient(0,0,e.width,e.height);x.addColorStop(0,Ce(N,.38,"rgba(255, 255, 255, 0.38)")),x.addColorStop(1,Ce(R,.05,"rgba(59, 130, 246, 0.05)")),u.fillStyle=x,u.fillRect(0,0,e.width,e.height)}function C(x){for(const w of x.children){const _=s.has(x.node.session.sessionId)&&s.has(w.node.session.sessionId),E=x.node.session.sessionId===i||w.node.session.sessionId===i;u.beginPath(),u.moveTo(x.centerX,x.y+Le-10);const M=x.y+Le+un*.52;u.bezierCurveTo(x.centerX,M,w.centerX,M,w.centerX,w.y+10),u.lineWidth=E?3:_?2.5:1.5,u.strokeStyle=E?Ce(R,.52,"rgba(59, 130, 246, 0.52)"):_?Ce(R,.32,"rgba(59, 130, 246, 0.32)"):Ce(S,.72,"rgba(148, 163, 184, 0.72)"),u.stroke(),u.beginPath(),u.arc(w.centerX,w.y,E?4.5:3.5,0,Math.PI*2),u.fillStyle=E?Ce(R,.9,"rgba(59, 130, 246, 0.9)"):Ce(S,.78,"rgba(148, 163, 184, 0.78)"),u.fill(),C(w)}}C(e.root);for(const x of e.nodes){const w=x.node.session.sessionId===n,_=x.node.session.sessionId===i,E=s.has(x.node.session.sessionId);if(!w&&!_&&!E)continue;const M=u.createRadialGradient(x.centerX,x.centerY,10,x.centerX,x.centerY,_?90:64);M.addColorStop(0,Ce(R,_?.22:.14,"rgba(59, 130, 246, 0.22)")),M.addColorStop(1,"rgba(59, 130, 246, 0)"),u.fillStyle=M,u.beginPath(),u.ellipse(x.centerX,x.centerY,Fe*.72,Le*.9,0,0,Math.PI*2),u.fill(),(_||w)&&(u.beginPath(),u.arc(x.centerX,x.y+12,_?6:5,0,Math.PI*2),u.fillStyle=Ce(R,.94,"rgba(59, 130, 246, 0.94)"),u.fill())}}function pi(t,e,n){const s=Math.min(Jr,e-24),i=t.left+t.width/2-s/2,c=Math.max(12,Math.min(e-s-12,i)),h=n-t.bottom-12<220&&t.top>et?Math.max(12,t.top-et-12):Math.max(12,Math.min(n-et-12,t.bottom+12));return{width:s,left:c,top:h,maxHeight:Math.min(et,n-24)}}function gi({model:t,selectedSession:e,selectedTreeNode:n,previewEntry:s,onClose:i,onOpenSession:c}){const l=He(e.title,o("common.unknown")),u=e.sessionId===t.current.sessionId,h=fn(e),b=Xs(n.session),R=Vs(n.session),S=$s(n.session),N=Ys(n.session);return r.jsxs("div",{className:"conversation-branch-preview-popover",role:"dialog","aria-label":`${o("conversation.branchTreePreviewTitle")} ${l.fullTitle}`,children:[r.jsxs("div",{className:"conversation-branch-preview-popover-header",children:[r.jsxs("div",{className:"conversation-branch-preview-card-title-row",children:[r.jsx("strong",{title:l.fullTitle,children:l.displayTitle}),u?r.jsx("span",{className:"conversation-branch-current-badge",children:o("conversation.branchTreeCurrentBadge")}):null,h?r.jsx("span",{className:"conversation-branch-archived-badge",children:o("conversation.branchTreeArchivedBadge")}):null]}),r.jsx("button",{type:"button",className:"conversation-branch-preview-close","aria-label":o("common.close"),onClick:i,children:"x"})]}),r.jsx("p",{className:"conversation-branch-preview-popover-meta",children:mn(e)}),R&&b||N&&S?r.jsxs("div",{className:"conversation-branch-badge-row",children:[N&&S?r.jsx("span",{className:`session-fork-badge ${S}`,children:N}):null,R&&b?r.jsx("span",{className:`session-fork-badge ${b}`,children:R}):null]}):null,r.jsx("div",{className:"conversation-branch-preview-messages",children:s.status==="loading"?r.jsx("p",{className:"conversation-branch-empty",children:o("conversation.branchTreePreviewLoading")}):s.status==="error"?r.jsx("p",{className:"conversation-branch-empty",children:s.error||o("conversation.branchTreePreviewFailed")}):s.messages.length>0?s.messages.map(C=>r.jsxs("article",{className:"conversation-branch-preview-message",children:[r.jsxs("div",{className:"conversation-branch-preview-message-meta",children:[r.jsx("span",{children:ui(C)}),r.jsx("span",{children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(C.timestamp))})]}),r.jsx("p",{children:ci(C)})]},`${e.sessionId}:${C.messageId}`)):r.jsx("p",{className:"conversation-branch-empty",children:o("conversation.branchTreePreviewEmpty")})}),r.jsx("div",{className:"conversation-branch-preview-actions",children:r.jsx("button",{type:"button",className:"secondary-button",disabled:u,onClick:()=>c(e),children:u?o("conversation.branchTreeCurrentAction"):o("conversation.branchTreeSwitchAction")})})]})}function vi({layout:t,model:e,selectedSessionId:n,onSelectSession:s,onBackgroundClick:i,stageScale:c,desktopStageLayout:l,transform:u,isMobileViewport:h,viewportRef:b,onRegisterNodeElement:R,onViewportTouchStart:S,onViewportTouchMove:N,onViewportTouchEnd:C}){const x=a.useRef(null);return a.useEffect(()=>{const w=x.current;w&&fi(w,t,e.current.sessionId,e.currentPathIds,n,h)},[h,t,e.current.sessionId,e.currentPathIds,n]),r.jsx("div",{ref:b,className:"conversation-branch-canvas-viewport","data-scaled":c<.999,"data-mobile":h,onClick:w=>{w.target===w.currentTarget&&(i==null||i())},onTouchStart:S,onTouchMove:N,onTouchEnd:C,onTouchCancel:C,children:r.jsx("div",{className:"conversation-branch-canvas-stage-shell",style:{width:h?"100%":l.shellWidth,height:h?"100%":l.shellHeight},onClick:w=>{w.target===w.currentTarget&&(i==null||i())},children:r.jsxs("div",{className:"conversation-branch-canvas-stage",style:{width:t.width,height:t.height,transform:u?`translate(${u.offsetX}px, ${u.offsetY}px) scale(${u.scale})`:`translate(${l.offsetX}px, ${l.offsetY}px) scale(${l.scale})`,transformOrigin:"top left"},onClick:()=>{if(i){i();return}s(null)},children:[r.jsx("canvas",{ref:x,className:"conversation-branch-canvas",width:t.width,height:t.height,"aria-hidden":"true"}),t.nodes.map(w=>{const _=He(w.node.session.title,o("common.unknown")),E=Xs(w.node.session),M=Vs(w.node.session),g=$s(w.node.session),D=Ys(w.node.session),O=w.node.session.sessionId===e.current.sessionId,T=w.node.session.sessionId===n,F=e.currentPathIds.has(w.node.session.sessionId),y=fn(w.node.session);return r.jsx("button",{ref:k=>R(w.node.session.sessionId,k),type:"button",className:"conversation-branch-smart-card conversation-branch-canvas-node","data-current":O,"data-selected":T,"data-current-path":F,"data-archived":y,style:{left:w.x,top:w.y,width:Fe,minHeight:Le},"aria-pressed":T,onClick:k=>{k.stopPropagation(),s(w.node.session.sessionId)},children:r.jsxs("div",{className:"conversation-branch-smart-card-main",children:[r.jsxs("div",{className:"conversation-branch-smart-card-title-row",children:[r.jsx("strong",{title:_.fullTitle,children:_.displayTitle}),O?r.jsx("span",{className:"conversation-branch-current-badge",children:o("conversation.branchTreeCurrentBadge")}):null,y?r.jsx("span",{className:"conversation-branch-archived-badge",children:o("conversation.branchTreeArchivedBadge")}):null]}),r.jsx("p",{children:mn(w.node.session)}),M&&E||D&&g?r.jsxs("div",{className:"conversation-branch-badge-row",children:[D&&g?r.jsx("span",{className:`session-fork-badge ${g}`,children:D}):null,M&&E?r.jsx("span",{className:`session-fork-badge ${E}`,children:M}):null]}):null]})},w.node.session.sessionId)})]})})})}function Ms({model:t,onOpenSession:e,onClose:n}){const s=a.useMemo(()=>di(t.root),[t.root]),i=a.useRef(null),c=a.useRef(new Map),[l,u]=a.useState(null),[h,b]=a.useState(0),[R,S]=a.useState(0),[N,C]=a.useState(null),[x,w]=a.useState({}),_=a.useRef(new Set),[E,M]=a.useState(typeof window<"u"?window.innerWidth<=it:!1),[g,D]=a.useState(null),O=a.useRef({mode:"idle",startDistance:0,startScale:1,startOffsetX:0,startOffsetY:0,startTouchX:0,startTouchY:0,anchorX:0,anchorY:0,moved:!1});a.useEffect(()=>{const p=i.current;if(!p)return;const v=p;function P(){b(v.clientWidth),S(v.clientHeight),M(window.innerWidth<=it)}if(P(),typeof ResizeObserver>"u")return window.addEventListener("resize",P),()=>window.removeEventListener("resize",P);const H=new ResizeObserver(P);return H.observe(p),()=>H.disconnect()},[]),a.useEffect(()=>{u(null)},[t.current.sessionId,t.root.session.sessionId]);const T=a.useMemo(()=>pn(h,s.width),[h,s.width]),F=a.useMemo(()=>oi(h,R,s.width,s.height),[R,h,s.height,s.width]);a.useEffect(()=>{if(!E||h<=0||R<=0){D(null);return}D(p=>p?ot(p,h,R,s.width,s.height):tt(h,R,s.width,s.height))},[R,h,E,s.height,s.width]);const y=l?t.sessionsById.get(l)??null:null,k=y?s.bySessionId.get(y.sessionId)??null:null,j=y?x[y.sessionId]??{status:"idle",messages:[],error:null}:null,X=E&&!!n,$=!!n&&!X;a.useEffect(()=>{if(!l){C(null);return}const p=l;function v(){const P=c.current.get(p);if(!P){C(null);return}C(P.getBoundingClientRect())}return v(),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0)}},[l,T]),a.useEffect(()=>{if(!E)return;const p=l;if(!p)return;const v=window.requestAnimationFrame(()=>{const P=c.current.get(p);P&&C(P.getBoundingClientRect())});return()=>window.cancelAnimationFrame(v)},[E,g,l]),a.useEffect(()=>{if(!(y!=null&&y.sessionId)||(j==null?void 0:j.status)==="ready"||_.current.has(y.sessionId))return;let p=!1;return _.current.add(y.sessionId),w(v=>{var P;return{...v,[y.sessionId]:{status:"loading",messages:((P=v[y.sessionId])==null?void 0:P.messages)??[],error:null}}}),Us(y.sessionId,null,6,"backward").then(v=>{_.current.delete(y.sessionId),!p&&w(P=>({...P,[y.sessionId]:{status:"ready",messages:ii(v.messages),error:null}}))}).catch(v=>{_.current.delete(y.sessionId),!p&&w(P=>{var H;return{...P,[y.sessionId]:{status:"error",messages:((H=P[y.sessionId])==null?void 0:H.messages)??[],error:v instanceof Error?v.message:o("conversation.branchTreePreviewFailed")}}})}),()=>{p=!0}},[y==null?void 0:y.sessionId]);function te(p){!E||h<=0||R<=0||D(v=>{const P=v??tt(h,R,s.width,s.height);return ot(p(P),h,R,s.width,s.height)})}function oe(p){if(!E)return;const v=p.currentTarget.getBoundingClientRect();if(p.touches.length>=2){const q=p.touches[0],se=p.touches[1],Y=Math.hypot(se.clientX-q.clientX,se.clientY-q.clientY),K=(q.clientX+se.clientX)/2-v.left,G=(q.clientY+se.clientY)/2-v.top,U=g??tt(h,R,s.width,s.height);O.current={mode:"pinch",startDistance:Y,startScale:U.scale,startOffsetX:U.offsetX,startOffsetY:U.offsetY,startTouchX:K,startTouchY:G,anchorX:K,anchorY:G,moved:!1};return}const P=p.touches[0],H=g??tt(h,R,s.width,s.height);O.current={mode:"pan",startDistance:0,startScale:H.scale,startOffsetX:H.offsetX,startOffsetY:H.offsetY,startTouchX:P.clientX,startTouchY:P.clientY,anchorX:0,anchorY:0,moved:!1}}function Z(p){if(!E)return;const v=O.current;if(p.touches.length>=2){const Y=p.currentTarget.getBoundingClientRect(),K=p.touches[0],G=p.touches[1],U=Math.hypot(G.clientX-K.clientX,G.clientY-K.clientY);if(U<=0||v.startDistance<=0)return;p.preventDefault();const ge=(K.clientX+G.clientX)/2-Y.left,A=(K.clientY+G.clientY)/2-Y.top,f=Bt(v.startScale*(U/v.startDistance),Zr,ei);O.current={...v,mode:"pinch",moved:!0,anchorX:ge,anchorY:A},te(J=>li({...J,scale:v.startScale,offsetX:v.startOffsetX,offsetY:v.startOffsetY},f,ge,A,h,R,s.width,s.height));return}if(v.mode!=="pan"||p.touches.length!==1)return;const P=p.touches[0],H=P.clientX-v.startTouchX,q=P.clientY-v.startTouchY;(v.moved||Math.hypot(H,q)>=ti)&&(p.preventDefault(),O.current={...v,moved:!0},te(Y=>({...Y,offsetX:v.startOffsetX+H,offsetY:v.startOffsetY+q})))}function le(){O.current={mode:"idle",startDistance:0,startScale:(g==null?void 0:g.scale)??1,startOffsetX:(g==null?void 0:g.offsetX)??0,startOffsetY:(g==null?void 0:g.offsetY)??0,startTouchX:0,startTouchY:0,anchorX:0,anchorY:0,moved:!1}}return r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:`conversation-branch-tree-pane${n?" conversation-branch-dialog":""}${X?" conversation-branch-dialog-mobile-bare":""}`,role:n?"dialog":void 0,"aria-modal":n?"true":void 0,"aria-label":n?o("conversation.branchTreeTitle"):void 0,children:[$?r.jsx("div",{className:"conversation-branch-tree-pane-header",children:r.jsxs("div",{className:"conversation-branch-tree-pane-topbar",children:[r.jsxs("div",{className:"conversation-branch-tree-pane-heading",children:[r.jsx("h3",{children:o("conversation.branchTreeMapTitle")}),r.jsx("p",{children:o("conversation.branchTreeMapDescription")})]}),n?r.jsx("button",{type:"button",className:"conversation-branch-pane-close","aria-label":o("common.close"),onClick:n,children:"x"}):null]})}):null,r.jsxs("div",{className:"conversation-branch-canvas-shell",children:[X?r.jsx("button",{type:"button",className:"conversation-branch-pane-close conversation-branch-mobile-floating-close","aria-label":o("common.close"),onClick:n,children:"x"}):null,X?null:r.jsx("div",{className:"conversation-branch-canvas-tip",children:o("conversation.branchTreePreviewDescription")}),r.jsx(vi,{layout:s,model:t,selectedSessionId:l,onSelectSession:u,onBackgroundClick:X?n:void 0,stageScale:T,desktopStageLayout:F,transform:E?g:null,isMobileViewport:E,viewportRef:i,onRegisterNodeElement:(p,v)=>{if(v){c.current.set(p,v);return}c.current.delete(p)},onViewportTouchStart:oe,onViewportTouchMove:Z,onViewportTouchEnd:le})]})]}),y&&k&&j&&N&&typeof document<"u"?lt.createPortal(r.jsx("div",{className:"conversation-branch-preview-floating",style:pi(N,window.innerWidth,window.innerHeight),children:r.jsx(gi,{model:t,selectedSession:y,selectedTreeNode:k.node,previewEntry:j,onClose:()=>u(null),onOpenSession:e})}),document.body):null]})}function bi({open:t,navigationGroups:e,workspaceId:n,sessionId:s,onClose:i,onOpenSession:c}){const l=a.useMemo(()=>dn(e,n,s),[e,s,n]),[u,h]=a.useState(typeof window<"u"?window.innerWidth>it:!0);return a.useEffect(()=>{if(typeof window>"u")return;function b(){h(window.innerWidth>it)}return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[]),!t||!l||typeof document>"u"?null:u?r.jsx(Ht,{open:t,title:o("conversation.branchTreeMapTitle"),description:o("conversation.branchTreeMapDescription"),size:"regular",layout:"viewer",bodyClassName:"conversation-branch-modal-body",onClose:i,children:r.jsx(Ms,{model:l,onOpenSession:c})}):lt.createPortal(r.jsxs("div",{className:"workbench-modal-layer conversation-branch-panel-layer",children:[r.jsx("button",{type:"button",className:"workbench-modal-backdrop","aria-label":o("common.close"),onClick:i}),r.jsx(Ms,{model:l,onOpenSession:c,onClose:i})]}),document.body)}function wi(t){const e=t.trim().length;return e<=16?"xl":e<=26?"lg":e<=38?"md":"sm"}function gn({session:t,actions:e,workspaceContext:n=null}){const s=Xt(),i=yr(s);if(!t)return r.jsxs("header",{className:"conversation-header conversation-header-skeleton","aria-hidden":"true","data-window-drag-handle":"conversation-header","data-tauri-drag-region":i,children:[r.jsxs("div",{className:"conversation-header-main","data-tauri-drag-region":i,children:[r.jsx("span",{className:"skeleton-line short"}),r.jsx("span",{className:"skeleton-line long"})]}),e?r.jsx("div",{className:"conversation-header-actions",children:e}):null]});const c=He(t.title,o("conversation.titleFallback")),l=wi(c.displayTitle);return r.jsxs("header",{className:"conversation-header","data-workspace-tone":(n==null?void 0:n.tone)??"root",style:$t(n),"data-window-drag-handle":"conversation-header","data-tauri-drag-region":i,children:[r.jsx("div",{className:"conversation-header-main","data-tauri-drag-region":i,children:r.jsx("h1",{className:`conversation-title is-${l}`,title:c.fullTitle,"data-tauri-drag-region":i,children:c.displayTitle})}),e?r.jsx("div",{className:"conversation-header-actions",children:e}):null]})}const Is=30,Ve=40,vn=600,xs=300*1e3,Si=600,Mi=5e3,Ii=1e4;class xi{constructor(e,n={}){de(this,"state");de(this,"listeners",new Set);de(this,"realtimeClient",null);de(this,"historyBootstrapFallbackTimer",null);de(this,"historyBootstrapEnvelopeReceived",!1);de(this,"markSeenTimer",null);de(this,"markSeenInFlight",!1);de(this,"lastMarkSeenRequestAt",0);de(this,"seenWatermark",null);de(this,"runtimeRefreshTimer",null);de(this,"runtimeRefreshMode",null);de(this,"replaceSnapshotSeedOnBackfill",!1);de(this,"pendingReplyDebugTraces",[]);de(this,"hasAuthoritativeBootstrapMessages");de(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}));de(this,"getState",()=>this.state);var l;this.sessionId=e,this.options=n;const s=us(jt(e),xs);this.hasAuthoritativeBootstrapMessages=(((l=n.bootstrapMessages)==null?void 0:l.length)??0)>0;const i=st(n.initialSession??null,(s==null?void 0:s.session)??null),c=Ue((s==null?void 0:s.messages)??[],this.sessionId,n.bootstrapMessages??[]);this.replaceSnapshotSeedOnBackfill=!this.hasAuthoritativeBootstrapMessages&&((s==null?void 0:s.messages.length)??0)>0&&((s==null?void 0:s.messages.length)??0)<=Ve&&((s==null?void 0:s.pagesLoaded)??0)<=1,this.state=ds({session:i,capabilities:(s==null?void 0:s.capabilities)??null,runtimeHasActiveRun:(s==null?void 0:s.runtimeHasActiveRun)??null,runtimeCanInterrupt:(s==null?void 0:s.runtimeCanInterrupt)??null,contextUsage:(s==null?void 0:s.contextUsage)??null,messages:c,permissionRequests:(s==null?void 0:s.permissionRequests)??[],queuedMessages:(s==null?void 0:s.queuedMessages)??[],olderCursor:(s==null?void 0:s.olderCursor)??null,hasOlderMessages:(s==null?void 0:s.hasOlderMessages)??!1,lastCursor:(s==null?void 0:s.lastCursor)??null,interruptSource:(s==null?void 0:s.interruptSource)??null,pagesLoaded:(s==null?void 0:s.pagesLoaded)??0}),this.seenWatermark=(i==null?void 0:i.lastSeenAt)??null}async initialize(){this.historyBootstrapEnvelopeReceived=!1,this.clearHistoryBootstrapFallbackTimer();const e=this.options.bootstrapMessages??[],n=Ue(this.state.messages,this.sessionId,e),s=this.hasAuthoritativeBootstrapMessages;this.patch({messages:n,historyState:ki(this.state.session,s?n.length:0),loadingOlderMessages:!1,olderCursor:s?null:this.state.olderCursor,hasOlderMessages:Be({session:this.state.session,loadedMessageCount:n.length,olderCursor:s?null:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),pagesLoaded:s?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(),s&&this.scheduleMarkSeen()}catch(i){this.handleError(i)}}async reload(){var n,s;this.clearHistoryBootstrapFallbackTimer(),this.historyBootstrapEnvelopeReceived=!1,(n=this.realtimeClient)==null||n.close(),this.realtimeClient=null;const e=us(jt(this.sessionId),xs);this.state=ds({session:st(this.options.initialSession??null,(e==null?void 0:e.session)??null),capabilities:(e==null?void 0:e.capabilities)??null,runtimeHasActiveRun:(e==null?void 0:e.runtimeHasActiveRun)??null,runtimeCanInterrupt:(e==null?void 0:e.runtimeCanInterrupt)??null,contextUsage:(e==null?void 0:e.contextUsage)??null,messages:Ue((e==null?void 0:e.messages)??[],this.sessionId,this.options.bootstrapMessages??[]),permissionRequests:(e==null?void 0:e.permissionRequests)??[],queuedMessages:(e==null?void 0:e.queuedMessages)??[],olderCursor:(e==null?void 0:e.olderCursor)??null,hasOlderMessages:(e==null?void 0:e.hasOlderMessages)??!1,lastCursor:(e==null?void 0:e.lastCursor)??null,pagesLoaded:(e==null?void 0:e.pagesLoaded)??0}),this.seenWatermark=((s=this.state.session)==null?void 0:s.lastSeenAt)??null,this.replaceSnapshotSeedOnBackfill=!this.hasAuthoritativeBootstrapMessages&&((e==null?void 0:e.messages.length)??0)>0&&((e==null?void 0:e.messages.length)??0)<=Ve&&((e==null?void 0:e.pagesLoaded)??0)<=1,this.emit(),await this.initialize()}applyNavigationSession(e){if(!e||e.sessionId!==this.sessionId)return;const n=st(this.state.session,e);n!==this.state.session&&this.patch({session:n,hasOlderMessages:Be({session:n,loadedMessageCount:this.state.messages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})})}async sendMessage(e,n){const s=ks();this.beginPendingReplyDebugTrace("send_live",s,e.length);const i=tn(this.sessionId,e,s,(n==null?void 0:n.attachmentMeta)??[],(n==null?void 0:n.attachments)??[],Pr(this.state.messages));this.patch({messages:[...this.state.messages,i],session:Re(this.state.session,"running"),runtimeHasActiveRun:Es(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:As(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt});try{const c=await this.sendMessageWithFallback(e,s,n);this.markPendingReplyDebugTraceResponseReady(s,{returnedMessageId:c.message.messageId,returnedProviderSessionId:c.message.providerSessionId}),this.patch({messages:hs(this.state.messages,this.sessionId,c.message,s)})}catch(c){throw this.failPendingReplyDebugTrace(s,c),this.patch({messages:Lt(this.state.messages,s),session:Re(this.state.session,"failed"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1}),c}}async retryMessage(e){const n=this.state.messages.find(s=>s.clientRequestId===e);if(n){this.patch({messages:this.state.messages.map(s=>s.clientRequestId===e?{...s,deliveryState:"sending"}:s),runtimeHasActiveRun:Es(this.state.session,this.state.capabilities)?!0:this.state.runtimeHasActiveRun,runtimeCanInterrupt:As(this.state.session,this.state.capabilities)?!0:this.state.runtimeCanInterrupt}),this.beginPendingReplyDebugTrace("retry_live",e,n.content.length);try{const s=await this.sendMessageWithFallback(n.content,e,{attachments:n.attachmentPayloads??[],attachmentMeta:n.attachments});this.markPendingReplyDebugTraceResponseReady(e,{returnedMessageId:s.message.messageId,returnedProviderSessionId:s.message.providerSessionId}),this.patch({messages:hs(this.state.messages,this.sessionId,s.message,e)})}catch(s){throw this.failPendingReplyDebugTrace(e,s),this.patch({messages:Lt(this.state.messages,e),session:Re(this.state.session,"failed")}),s}}}async enqueueMessage(e,n){const s=ks();try{const i=await tr(this.sessionId,{content:e,clientRequestId:s,model:(n==null?void 0:n.model)??null,reasoningLevel:(n==null?void 0:n.reasoningLevel)??null,permissionMode:_e(),attachments:(n==null?void 0:n.attachments)??[]});this.patch({queuedMessages:Ni(this.state.queuedMessages,i)}),await this.refreshQueue()}catch(i){throw i}}async deleteQueuedMessage(e){await sr(this.sessionId,e),await this.refreshQueue()}async steerQueuedMessage(e){await nr(this.sessionId,e),await this.refreshRuntimeSnapshot("queue_steer")}async interrupt(){await rr(this.sessionId),this.patch({session:Re(this.state.session,"interrupted"),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:"user",errorCode:null,errorDetail:null})}async replyPermissionRequest(e,n){if(!(this.state.permissionRequests.find(c=>c.id===e)??null))return;const i=await ir(this.sessionId,e,n);this.patch({permissionRequests:Nt(this.state.permissionRequests,i)})}reconnect(){var e;(e=this.realtimeClient)==null||e.reconnectNow()}async loadOlderMessages(){var e;if(!(this.state.historyState!=="ready"||this.state.loadingOlderMessages||!this.state.olderCursor)){this.patch({loadingOlderMessages:!0,errorCode:null,errorDetail:null});try{if(!((e=this.realtimeClient)==null?void 0:e.requestOlderMessages(this.state.olderCursor,Is)))throw new Error("REALTIME_NOT_CONNECTED")}catch(n){const s=n instanceof Error?n.message:"unknown";this.patch({loadingOlderMessages:!1,errorCode:"HISTORY_LOAD_MORE_FAILED",errorDetail:s})}}}destroy(){var e;this.clearHistoryBootstrapFallbackTimer(),(e=this.realtimeClient)==null||e.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 n;if(!((n=It.getState().session)==null?void 0:n.accessToken)){It.clear();return}this.realtimeClient=new jr({sessionId:this.sessionId,cursor:this.state.lastCursor,limit:Ve,onSubscribed:()=>{ie("session_send.realtime_subscribed",{sessionId:this.sessionId,lastCursor:this.state.lastCursor}),this.patch({connectionState:"connected",hasOlderMessages:Be({session:this.state.session,loadedMessageCount:this.state.messages.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages})}),this.scheduleHistoryBootstrapFallback()},onConnectionChange:s=>{var c;const i=this.state.connectionState;if(this.patch({connectionState:s,session:s==="reconnecting"&&Ie((c=this.state.session)==null?void 0:c.runningState)?Re(this.state.session,"reconnecting"):this.state.session}),s==="connected"){this.clearRuntimeRefreshTimer("poll"),i!=="closed"&&i!=="connected"&&this.patch({errorCode:null,errorDetail:null});return}this.scheduleRuntimeRefresh("poll","connection_state_change")},onEnvelope:s=>{var u,h;this.historyBootstrapEnvelopeReceived=!0,this.clearHistoryBootstrapFallbackTimer();const i=s.type==="session.backfill"&&this.replaceSnapshotSeedOnBackfill,{messages:c,replacedSnapshotSeed:l}=this.mergeHistoryMessages(s.messages,i);this.patch({messages:c,lastCursor:s.cursor,historyState:"ready",olderCursor:s.type==="session.backfill"&&!l&&this.state.pagesLoaded>1?this.state.olderCursor:s.olderCursor??this.state.olderCursor,hasOlderMessages:s.type==="session.backfill"?!l&&this.state.pagesLoaded>1?this.state.hasOlderMessages:!!s.olderCursor:Be({session:this.state.session,loadedMessageCount:c.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),pagesLoaded:s.type==="session.backfill"?!l&&this.state.pagesLoaded>1?this.state.pagesLoaded:Math.max(this.state.pagesLoaded,c.length>0?1:0):this.state.pagesLoaded,session:Re(this.state.session,Cs(s.type,(u=this.state.session)==null?void 0:u.runningState))}),(h=this.realtimeClient)==null||h.updateCursor(s.cursor),this.scheduleMarkSeen(),this.state.queuedMessages.length>0&&this.refreshQueue()},onOlderHistory:s=>{const{messages:i}=this.mergeHistoryMessages(s.messages,!1);this.patch({messages:i,historyState:"ready",loadingOlderMessages:!1,olderCursor:s.olderCursor,hasOlderMessages:!!s.olderCursor,pagesLoaded:this.state.pagesLoaded+1,errorCode:null,errorDetail:null})},onRuntimeMessage:s=>{this.handleRuntimeMessage(s)},onActivity:s=>{this.handleActivity(s)},onRuntimeStatus:s=>{this.handleRuntimeStatus(s)},onRuntimeError:s=>{this.handleRuntimeError(s)},onInterrupted:s=>{this.handleInterrupted(s)},onPermissionRequest:s=>{this.handlePermissionRequest(s)},onPermissionRequestResolved:s=>{this.handlePermissionRequestResolved(s)},onError:s=>{this.patch({loadingOlderMessages:!1,errorCode:s.error_code,errorDetail:s.detail})},onUnauthorized:()=>{It.clear()}}),this.realtimeClient.start()}patch(e){let n=e;Object.prototype.hasOwnProperty.call(e,"session")&&(this.syncSeenWatermark(e.session??null),n={...e,session:this.applySeenWatermark(e.session??null)}),this.state={...this.state,...n},(Object.prototype.hasOwnProperty.call(n,"session")||Object.prototype.hasOwnProperty.call(n,"capabilities")||Object.prototype.hasOwnProperty.call(n,"contextUsage")||Object.prototype.hasOwnProperty.call(n,"messages")||Object.prototype.hasOwnProperty.call(n,"permissionRequests")||Object.prototype.hasOwnProperty.call(n,"queuedMessages"))&&this.persistSnapshot(),this.emit()}mergeHistoryMessages(e,n){const s=n&&this.replaceSnapshotSeedOnBackfill&&Ri(this.state.messages,e),i=s?this.state.messages.filter(l=>l.deliveryState!=="sent"):this.state.messages,c=Ue(i,this.sessionId,e);return s&&(this.replaceSnapshotSeedOnBackfill=!1),{messages:c,replacedSnapshotSeed:s}}handleError(e){this.clearHistoryBootstrapFallbackTimer();const n=e instanceof Error?e.message:"unknown";this.patch({historyState:"error",errorCode:"RUNTIME_INIT_FAILED",errorDetail:n})}scheduleMarkSeen(){if(this.markSeenTimer!==null)return;const e=this.getTargetSeenAt();if(this.markSeenInFlight||e===null)return;const n=this.getMarkSeenThrottleDelayMs(),s=Math.max(Si,n);this.markSeenTimer=window.setTimeout(()=>{this.markSeenTimer=null;const i=this.getTargetSeenAt();i!==null&&(ie("session_seen.start",{sessionId:this.sessionId,targetSeenAt:i,seenWatermark:this.seenWatermark}),this.markSeenInFlight=!0,this.lastMarkSeenRequestAt=Date.now(),or(this.sessionId).then(()=>{var c,l;this.bumpSeenWatermark(i),this.patch({session:ys(this.state.session,i)}),(l=(c=this.options).onSeen)==null||l.call(c,this.sessionId,i),ie("session_seen.end",{sessionId:this.sessionId,seenWatermark:this.seenWatermark})}).catch(()=>{ie("session_seen.error",{sessionId:this.sessionId,targetSeenAt:i})}).finally(()=>{this.markSeenInFlight=!1,this.shouldMarkSeen()&&this.scheduleMarkSeen()}))},s)}clearRuntimeRefreshTimer(e){this.runtimeRefreshTimer!==null&&(e&&this.runtimeRefreshMode!==e||(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 e=Math.min(vn,Math.max(Ve,this.state.messages.length,Is)),n=await Us(this.sessionId,null,e,"backward");if(this.historyBootstrapEnvelopeReceived)return;this.historyBootstrapEnvelopeReceived=!0;const{messages:s,replacedSnapshotSeed:i}=this.mergeHistoryMessages(n.messages,this.replaceSnapshotSeedOnBackfill);this.patch({messages:s,historyState:"ready",olderCursor:!i&&this.state.pagesLoaded>1?this.state.olderCursor:n.nextCursor,hasOlderMessages:!i&&this.state.pagesLoaded>1?this.state.hasOlderMessages:Be({session:this.state.session,loadedMessageCount:s.length,olderCursor:n.nextCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),lastCursor:n.cursor??this.state.lastCursor,pagesLoaded:!i&&this.state.pagesLoaded>1?this.state.pagesLoaded:s.length>0?Math.max(this.state.pagesLoaded,1):this.state.pagesLoaded,errorCode:null,errorDetail:null}),this.scheduleMarkSeen()}catch{}}scheduleRuntimeRefresh(e,n){var s,i;if(!Ie((s=this.state.session)==null?void 0:s.runningState)){this.clearRuntimeRefreshTimer();return}e==="poll"&&this.state.connectionState==="connected"||(this.clearRuntimeRefreshTimer(),this.runtimeRefreshMode=e,ie("session_runtime.refresh.schedule",{sessionId:this.sessionId,mode:e,reason:n,connectionState:this.state.connectionState,runningState:((i=this.state.session)==null?void 0:i.runningState)??null}),this.runtimeRefreshTimer=window.setTimeout(()=>{const c=this.runtimeRefreshMode??e;this.runtimeRefreshTimer=null,this.runtimeRefreshMode=null,this.refreshRuntimeState(c,n)},e==="poll"?Ii:1200))}async refreshRuntimeState(e,n){var s,i,c,l,u;ie("session_runtime.refresh.start",{sessionId:this.sessionId,mode:e,reason:n,connectionState:this.state.connectionState,runningState:((s=this.state.session)==null?void 0:s.runningState)??null});try{const h=await ls(this.sessionId),b=At(this.state.runtimeHasActiveRun,h.runningState,h.hasActiveRun),R=Pt(this.state.runtimeCanInterrupt,h.runningState,b,h.canInterrupt);this.patch({session:Rs(this.state.session,h),runtimeHasActiveRun:b,runtimeCanInterrupt:R,contextUsage:h.contextUsage,...kt(h,this.state.interruptSource)}),await this.refreshQueue();const S=e==="poll"&&this.state.connectionState!=="connected"&&Ie((i=this.state.session)==null?void 0:i.runningState);ie("session_runtime.refresh.end",{sessionId:this.sessionId,mode:e,reason:n,connectionState:this.state.connectionState,runningState:((c=this.state.session)==null?void 0:c.runningState)??null,continuePolling:S}),S&&this.scheduleRuntimeRefresh("poll","connection_poll")}catch(h){ie("session_runtime.refresh.error",{sessionId:this.sessionId,mode:e,reason:n,connectionState:this.state.connectionState,runningState:((l=this.state.session)==null?void 0:l.runningState)??null,message:h instanceof Error?h.message:"unknown"}),e==="poll"&&this.state.connectionState!=="connected"&&Ie((u=this.state.session)==null?void 0:u.runningState)&&this.scheduleRuntimeRefresh("poll","connection_poll_retry")}}async refreshSessionMetadata(){const e=[];this.state.session===null&&e.push(Hs(this.sessionId).then(n=>{this.patch({session:st(n,this.state.session)})}).catch(()=>{})),Ts(this.state.capabilities)&&e.push(ar(this.sessionId).then(n=>{this.patch({capabilities:n})}).catch(()=>{})),e.length!==0&&await Promise.allSettled(e)}async refreshPermissionRequests(){try{const e=await lr(this.sessionId);this.patch({permissionRequests:e.items})}catch{return}}shouldRefreshSessionDetail(){return this.state.session===null||Ts(this.state.capabilities)||this.state.session.runningState===null}shouldRefreshRuntimeSnapshot(){return this.state.contextUsage===null}async refreshRuntimeSnapshot(e){ie("session_runtime.snapshot.start",{sessionId:this.sessionId,reason:e});try{const n=await ls(this.sessionId),s=At(this.state.runtimeHasActiveRun,n.runningState,n.hasActiveRun),i=Pt(this.state.runtimeCanInterrupt,n.runningState,s,n.canInterrupt);this.patch({session:Rs(this.state.session,n),runtimeHasActiveRun:s,runtimeCanInterrupt:i,contextUsage:n.contextUsage,...kt(n,this.state.interruptSource)}),await this.refreshQueue(),ie("session_runtime.snapshot.end",{sessionId:this.sessionId,reason:e,hasContextUsage:n.contextUsage!==null})}catch(n){ie("session_runtime.snapshot.error",{sessionId:this.sessionId,reason:e,message:n instanceof Error?n.message:"unknown"})}}async refreshQueue(){try{const e=await cr(this.sessionId);this.patch({queuedMessages:e.items})}catch{return}}async sendMessageWithFallback(e,n,s){var i;try{return await Ut(this.sessionId,{content:e,clientRequestId:n,model:(s==null?void 0:s.model)??null,reasoningLevel:(s==null?void 0:s.reasoningLevel)??null,permissionMode:_e(),attachments:(s==null?void 0:s.attachments)??[]})}catch(c){if(!(c instanceof zn)||c.status!==404&&c.status!==405||(((i=s==null?void 0:s.attachments)==null?void 0:i.length)??0)>0)throw c;return ie("session_send.live_fallback",{sessionId:this.sessionId,clientRequestId:n,reason:c.message}),ur(this.sessionId,{content:e,clientRequestId:n,permissionMode:_e()})}}handleRuntimeStatus(e){var s;const n=Ct((s=this.state.session)==null?void 0:s.runningState,e.status);this.patch({session:Re(this.state.session,n),runtimeHasActiveRun:Ie(n)?this.state.runtimeHasActiveRun??!0:!1,runtimeCanInterrupt:Ie(n)?this.state.runtimeCanInterrupt:!1,interruptSource:n==="interrupted"?e.interruptSource??this.state.interruptSource:n==="completed"||n==="failed"?null:this.state.interruptSource,errorCode:null,errorDetail:n===e.status?e.detail:this.state.errorDetail}),at(n)&&(this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_terminal_before_message",{status:e.status,detail:e.detail}),this.clearRuntimeRefreshTimer(),this.refreshQueue(),this.refreshRuntimeSnapshot("runtime_terminal"))}handleActivity(e){const n=At(this.state.runtimeHasActiveRun,e.runningState,e.hasActiveRun),s=Pt(this.state.runtimeCanInterrupt,e.runningState,n,e.canInterrupt);if(this.patch({session:Ai(this.state.session,e),runtimeHasActiveRun:n,runtimeCanInterrupt:s,...kt(e,this.state.interruptSource)}),at(e.runningState)){this.clearRuntimeRefreshTimer(),this.refreshQueue();return}(e.runningState==="stale"||e.runningState==="unknown")&&this.scheduleRuntimeRefresh("tail","activity_watchdog")}handleRuntimeMessage(e){var s;e.message.role==="assistant"&&this.completePendingReplyDebugTrace(e);const n=Ue(this.state.messages,this.sessionId,[e.message]);this.patch({messages:n,historyState:"ready",hasOlderMessages:Be({session:this.state.session,loadedMessageCount:n.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),session:Re(this.state.session,Cs("session.delta",(s=this.state.session)==null?void 0:s.runningState))}),this.scheduleMarkSeen(),this.state.queuedMessages.length>0&&this.refreshQueue()}handleRuntimeError(e){var s;const n=Ct((s=this.state.session)==null?void 0:s.runningState,"failed");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_runtime_error",{errorCode:e.error_code,detail:e.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:Re(this.state.session,n),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:null,errorCode:n==="failed"?e.error_code:this.state.errorCode,errorDetail:n==="failed"?e.detail:this.state.errorDetail}),this.refreshQueue()}handleInterrupted(e){var s;const n=Ct((s=this.state.session)==null?void 0:s.runningState,"interrupted");this.completePendingReplyDebugTraceWithoutAssistant("session_send.client_interrupted",{detail:e.detail}),this.clearRuntimeRefreshTimer(),this.patch({session:Re(this.state.session,n),runtimeHasActiveRun:!1,runtimeCanInterrupt:!1,interruptSource:n==="interrupted"?e.interruptSource??this.state.interruptSource:this.state.interruptSource,errorCode:n==="interrupted"?null:this.state.errorCode,errorDetail:n==="interrupted"?e.detail:this.state.errorDetail}),this.refreshQueue()}handlePermissionRequest(e){this.patch({permissionRequests:Nt(this.state.permissionRequests,e.request)})}handlePermissionRequestResolved(e){this.patch({permissionRequests:Nt(this.state.permissionRequests,e.request)})}shouldMarkSeen(){return this.getTargetSeenAt()!==null}getTargetSeenAt(){const e=[...this.state.messages].reverse().find(s=>s.role!=="user");if(!e)return null;const n=this.seenWatermark;return n?e.timestamp>n?e.timestamp:null:e.timestamp}syncSeenWatermark(e){e!=null&&e.lastSeenAt&&this.bumpSeenWatermark(e.lastSeenAt)}bumpSeenWatermark(e){this.seenWatermark&&this.seenWatermark>=e||(this.seenWatermark=e)}getMarkSeenThrottleDelayMs(){return this.lastMarkSeenRequestAt<=0?0:Math.max(0,Mi-(Date.now()-this.lastMarkSeenRequestAt))}applySeenWatermark(e){return!e||!this.seenWatermark?e:ys(e,this.seenWatermark)}emit(){for(const e of this.listeners)e()}persistSnapshot(){Rr(jt(this.sessionId),{session:this.state.session,capabilities:this.state.capabilities,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage,messages:ji(this.state.messages),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(e,n,s){const i={mode:e,clientRequestId:n,startedAtMs:performance.now(),responseReadyAtMs:null,contentLength:s};this.pendingReplyDebugTraces.push(i),ie(`session_send.${e}.client_start`,{sessionId:this.sessionId,clientRequestId:n,contentLength:s})}markPendingReplyDebugTraceResponseReady(e,n={}){const s=this.pendingReplyDebugTraces.find(i=>i.clientRequestId===e);!s||s.responseReadyAtMs!==null||(s.responseReadyAtMs=performance.now(),ie(`session_send.${s.mode}.client_response`,{sessionId:this.sessionId,clientRequestId:e,durationMs:Math.round(s.responseReadyAtMs-s.startedAtMs),...n}))}failPendingReplyDebugTrace(e,n){const s=this.pendingReplyDebugTraces.find(i=>i.clientRequestId===e);s&&(ie(`session_send.${s.mode}.client_error`,{sessionId:this.sessionId,clientRequestId:e,durationMs:Math.round(performance.now()-s.startedAtMs),error:n instanceof Error?n.message:String(n)}),this.removePendingReplyDebugTrace(s.clientRequestId))}completePendingReplyDebugTrace(e){const n=this.pendingReplyDebugTraces[0];if(!n)return;const s=performance.now();ie(`session_send.${n.mode}.first_assistant_message`,{sessionId:this.sessionId,clientRequestId:n.clientRequestId,durationMs:Math.round(s-n.startedAtMs),responseToAssistantMs:n.responseReadyAtMs===null?null:Math.round(s-n.responseReadyAtMs),messageId:e.message.messageId,kind:e.message.kind,contentLength:e.message.content.length}),this.removePendingReplyDebugTrace(n.clientRequestId)}completePendingReplyDebugTraceWithoutAssistant(e,n={}){const s=this.pendingReplyDebugTraces[0];s&&(ie(e,{sessionId:this.sessionId,clientRequestId:s.clientRequestId,durationMs:Math.round(performance.now()-s.startedAtMs),responseReady:s.responseReadyAtMs!==null,...n}),this.removePendingReplyDebugTrace(s.clientRequestId))}removePendingReplyDebugTrace(e){const n=this.pendingReplyDebugTraces.findIndex(s=>s.clientRequestId===e);n<0||this.pendingReplyDebugTraces.splice(n,1)}}function ve(t,e){const[n,s]=a.useState(()=>e(t.getState()));return a.useEffect(()=>(s(e(t.getState())),t.subscribe(()=>{s(e(t.getState()))})),[e,t]),n}function yi(t){const e=t==null?void 0:t.messageCount;return typeof e=="number"&&Number.isFinite(e)?e:null}function Ri(t,e){const n=Ti(e);if(!n)return!1;const s=Ci(t);return s?Yt(n.sequence,n.timestamp,s.sequence,s.timestamp)>=0:!0}function Ti(t){let e=null;for(const n of t)(!e||Yt(n.sequence,n.timestamp,e.sequence,e.timestamp)>0)&&(e=n);return e}function Ci(t){let e=null;for(const n of t)n.deliveryState==="sent"&&(!e||Yt(n.sequence,n.timestamp,e.sequence,e.timestamp)>0)&&(e=n);return e}function Yt(t,e,n,s){return t!==n?t-n:e.localeCompare(s)}function ki(t,e){return e>0?"ready":"loading"}function Ei(t,e){const n=yi(t);return n!==null?n>e:e>=Ve}function Be(t){return t.olderCursor?!0:t.pagesLoaded>1?t.currentHasOlderMessages:Ei(t.session,t.loadedMessageCount)}function Re(t,e){return t&&{...t,runningState:e,activityState:wn(t,e,t.completedAt??null,Ie(e))}}function ys(t,e){return!t||t.lastSeenAt&&t.lastSeenAt>=e?t:{...t,lastSeenAt:e,activityState:t.activityState==="completed_unread"?"idle":t.activityState}}function Rs(t,e){return bn(t,{runningState:e.runningState,activityResolutionSource:e.activityResolutionSource,activityConfidence:e.activityConfidence,runId:e.runId,detail:e.detail,interruptSource:e.interruptSource,errorCode:e.errorCode,errorDetail:e.errorDetail,hasActiveRun:e.hasActiveRun,updatedAt:e.updatedAt,watchdogTriggeredAt:e.watchdogTriggeredAt})}function Ai(t,e){return bn(t,e)}function bn(t,e){if(!t)return t;const n=Pi(e.activityResolutionSource),s=at(e.runningState)?Et(t.completedAt,e.updatedAt):null,i=e.runningState==="completed"||e.runningState==="interrupted"||e.runningState==="failed"?Et(t.lastEventAt,e.updatedAt):e.updatedAt;return{...t,runningState:e.runningState,activitySource:n,activityResolutionSource:e.activityResolutionSource,activityConfidence:e.activityConfidence,runId:e.runId,lastEventAt:i,completedAt:s,lastErrorCode:e.runningState==="failed"?e.errorCode??t.lastErrorCode:null,lastErrorDetail:e.runningState==="failed"?e.errorDetail??e.detail??t.lastErrorDetail:null,watchdogTriggeredAt:e.watchdogTriggeredAt,updatedAt:Et(t.updatedAt,e.updatedAt)??e.updatedAt,activityState:wn(t,e.runningState,s,e.hasActiveRun)}}function wn(t,e,n,s){return s||Ie(e)?"running":n&&(!t.lastSeenAt||n>t.lastSeenAt)?"completed_unread":t.activityState==="running"||t.activityState==="completed_unread"?"idle":t.activityState??"idle"}function Ie(t){return t==="starting"||t==="running"||t==="reconnecting"}function at(t){return t==="completed"||t==="interrupted"||t==="failed"}function Ts(t){if(t===null)return!0;const e=t.modelOptions??[];return e.length===0?!0:e.every(n=>n.usesProviderDefault===!0)}function Cs(t,e){return t==="session.backfill"?e??"idle":e==="completed"||e==="interrupted"||e==="failed"?e:"running"}function Ct(t,e){return at(t)?t:e}function kt(t,e){return t.runningState==="failed"?{interruptSource:null,errorCode:t.errorCode,errorDetail:t.errorDetail??t.detail}:t.runningState==="interrupted"?{interruptSource:t.interruptSource??null,errorCode:null,errorDetail:t.detail}:t.runningState==="completed"?{interruptSource:null,errorCode:null,errorDetail:t.detail}:{interruptSource:e,errorCode:null,errorDetail:null}}function Pi(t){return t==="authoritative_runtime"||t==="authoritative_provider_event"?"runtime":t==="inferred_log"?"inferred":"none"}function Et(t,e){return t?e?t>=e?t:e:t:e??null}function ks(){var t,e;if(typeof((t=globalThis.crypto)==null?void 0:t.randomUUID)=="function")return globalThis.crypto.randomUUID();if(typeof((e=globalThis.crypto)==null?void 0:e.getRandomValues)=="function"){const n=new Uint8Array(16);globalThis.crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const s=Array.from(n,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}return`fallback-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Sn(t,e){return e&&(!t||t.provider===e.provider)?e:null}function Es(t,e){const n=Sn(t,e);return n?!!n.canSendMessage:t?Ws(t.provider):!1}function As(t,e){const n=Sn(t,e);return n?!(!n.supportsInterrupt||(t==null?void 0:t.provider)==="claude-code"&&t.activitySource==="inferred"):t?t.provider==="codex"||t.provider==="opencode"?!0:t.provider==="claude-code"&&t.activitySource!=="inferred":!1}function At(t,e,n){return n?!0:t===!0&&Ie(e)}function Pt(t,e,n,s){return s?!0:t===!0&&(n||Ie(e))}function jt(t){return`session-runtime.snapshot.${t}`}function ji(t){return t.filter(e=>e.deliveryState==="sent").slice(-vn)}function Ni(t,e){const n=t.filter(s=>s.id!==e.id);return n.push(e),n.sort((s,i)=>s.orderIndex-i.orderIndex),n}function Nt(t,e){const n=t.filter(s=>s.id!==e.id);return n.push(e),n.sort((s,i)=>s.status!==i.status?s.status==="pending"?-1:1:i.createdAt.localeCompare(s.createdAt)),n}function st(t,e){if(!t)return e;if(!e||Ps(t,e))return t;if(Ps(e,t))return e;const n=Date.parse(t.updatedAt||t.lastMessageAt||t.createdAt),s=Date.parse(e.updatedAt||e.lastMessageAt||e.createdAt);return!Number.isFinite(n)||!Number.isFinite(s)?e:n>=s?t:e}function Ps(t,e){return js(t)&&!js(e)&&t.lastEventAt===e.lastEventAt&&t.lastMessageAt===e.lastMessageAt&&t.completedAt===e.completedAt}function js(t){return t.activityState==="running"||Ie(t.runningState)}function _i(t,e,n){if(!e)return null;const s=t.find(l=>l.workspace.id===e);if(!s)return null;const i=zs([s]).filter(l=>!l.session.isArchived&&!ut(l.session)),c=i.findIndex(l=>l.session.sessionId===n);return c<0?null:i[c+1]??null}const Li=15e3,Ns=.6,_t=.6,_s=8,Oi=36,Di=48,Bi=96,Fi=320,Hi="workbench:focus-composer";function _o(){const{sessionId:t="",workspaceId:e}=vr(),n=Vt(),s=Ge(),i=a.useMemo(()=>new URLSearchParams(n.search),[n.search]),c=Gi(i.get("toolPanel")),l=(e==null?void 0:e.trim())||null,u=a.useMemo(()=>Vi(t,l,i),[l,i,t]),h=a.useMemo(()=>co(t,n.state),[n.state,t]);return u?r.jsx(Xi,{draft:u,navigate:s,initialToolPanel:c}):r.jsx(qi,{sessionId:t,bootstrapMessages:h,initialToolPanel:c})}function qi({sessionId:t,bootstrapMessages:e,initialToolPanel:n}){var is,os;const{shellMode:s,navigationGroups:i,requestNavigationRefresh:c,selectWorkspace:l,setSessionWorkspace:u,markNavigationSessionSeen:h,favoriteSessions:b,archiveSession:R,unarchiveSession:S,startDraftSession:N,upsertNavigationSession:C}=ct(),x=Ge(),w=a.useRef(null),_=a.useRef(null),[E,M]=a.useState(!1),[g,D]=a.useState(null),[O,T]=a.useState(!1),[F,y]=a.useState(!1),[k,j]=a.useState(null),[X,$]=a.useState(!1),[te,oe]=a.useState(!1),[Z,le]=a.useState(null),p=a.useMemo(()=>i.flatMap(d=>d.sessions).find(d=>d.sessionId===t)??null,[i,t]);(!w.current||_.current!==t)&&((is=w.current)==null||is.destroy(),w.current=new xi(t,{initialSession:p,bootstrapMessages:e,onSeen:(d,I)=>{h(d,I)}}),_.current=t);const v=w.current,{showToast:P,dismissToast:H}=Ye(),q=dr(d=>d.notificationPreferences.notifyOnPermissionRequest),se=Xt(),Y=Wt(),K=a.useRef(null),G=a.useRef(null),U=a.useRef(null),ge=a.useRef((p==null?void 0:p.runningState)??null),A=a.useRef(new Set),f=ve(v,d=>d.session),J=ve(v,d=>d.capabilities),he=ve(v,d=>d.runtimeHasActiveRun),Se=ve(v,d=>d.runtimeCanInterrupt),Te=ve(v,d=>d.messages),Ee=ve(v,d=>d.permissionRequests),L=ve(v,d=>d.queuedMessages),V=ve(v,d=>d.contextUsage),me=ve(v,d=>d.historyState),ce=ve(v,d=>d.errorCode),fe=ve(v,d=>d.errorDetail),m=ve(v,d=>d.interruptSource),B=ve(v,d=>d.loadingOlderMessages),z=ve(v,d=>d.hasOlderMessages),W=ve(v,d=>d.connectionState),[ne,be]=a.useState(null),[ee,pe]=a.useState(null),re=so(f),Pe=hr(J)&&(f==null?void 0:f.provider)===(J==null?void 0:J.provider),qe=L.some(d=>d.status==="queued"||d.status==="dispatching"),Oe=E&&!Z,ht=he===!0||Oe?!0:he,mt=Se===!0||Oe?!0:Se,ze=re||Oe,_n=no({sessionId:t,provider:(f==null?void 0:f.provider)??null,runningState:(f==null?void 0:f.runningState)??null,activityState:(f==null?void 0:f.activityState)??null,runtimeHasActiveRun:he,messages:Te})?o("conversation.runtimeThinkingPlaceholder",{provider:o("conversation.providerCodex")}):null,ue=s!=="mobile",xe=An(!ue),ae=(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??null,ye=kn({enabled:!ue,initialPanel:n,workspaceId:ae,suspendMainGesture:!ue&&xe.isVisible}),Gt=a.useMemo(()=>new Set(b.map(d=>d.session.sessionId)),[b]),Qe=a.useMemo(()=>i.map(d=>d.workspace),[i]),ft=a.useMemo(()=>zs(i),[i]),zt=a.useMemo(()=>rn(i),[i]),Ln=a.useMemo(()=>Qs(i),[i]),pt=a.useMemo(()=>In(i,(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??null,Gt),[Gt,i,p==null?void 0:p.workspaceId,f==null?void 0:f.workspaceId]),gt=a.useMemo(()=>xn(b,i),[b,i]),[On,Qt]=a.useState([]),Kt=a.useMemo(()=>[...gt,...pt],[gt,pt]),Jt=a.useMemo(()=>ae?Qe.find(d=>d.id===ae)??null:null,[ae,Qe]),Ae=(ae?Ln[ae]??null:null)??(Jt?Ks(Jt):null),Me=a.useMemo(()=>dt(i,ae),[ae,i]),je=zt.find(d=>d.workspace.id===ae)??(Me?{workspace:Me.workspace,label:Me.workspace.name,subtitle:Me.workspace.path}:null),vt=a.useMemo(()=>_i(i,ae,t),[ae,i,t]),bt=(f==null?void 0:f.provider)??(p==null?void 0:p.provider)??null,wt=a.useMemo(()=>{var d;return He(((d=f??p)==null?void 0:d.title)??null,o("conversation.titleFallback"))},[p,f]),De=f??p??null,Zt=ue?null:Cn(xe.mainGestureHandlers,ye.mainGestureHandlers);a.useEffect(()=>{const d=Zs(Kt,t,I=>I.session.sessionId);d.length!==0&&Qt(I=>{const Q=new Set(I);let we=!1;for(const Ne of d)Q.has(Ne)||(Q.add(Ne),we=!0);return we?Array.from(Q):I})},[Kt,t]);const Dn=a.useMemo(()=>mo(De,Te),[De,Te]),Ke=(De==null?void 0:De.workspaceId)??(p==null?void 0:p.workspaceId)??null,Bn=a.useMemo(()=>dn(i,Ke,t),[Ke,i,t]),Fn=ni(Bn),es=!!(De&&Ke&&Fn),ts=()=>{oe(!0)},St=a.useMemo(()=>(Me==null?void 0:Me.sessions.filter(d=>d.isArchived===!0&&!ut(d)))??[],[Me]),Hn=a.useRef(null),ss=a.useRef(null),Mt=a.useRef(null),ns=a.useRef(null),[qn,Un]=a.useState(null),{composerPortalTarget:Wn}=Js();a.useEffect(()=>{v.applyNavigationSession(p)},[p,v]),a.useEffect(()=>(v.initialize(),()=>{v.destroy()}),[v]),a.useEffect(()=>(u(t,(f==null?void 0:f.workspaceId)??null),()=>{u(t,null)}),[f==null?void 0:f.workspaceId,t,u]),a.useEffect(()=>{oe(!1),le(null)},[t]),a.useEffect(()=>()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},[]),a.useEffect(()=>{var Q;if(ce!=="SESSION_NOT_FOUND"&&ce!=="WORKSPACE_NOT_FOUND")return;H("conversation-runtime-error");const d=(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??((Q=i[0])==null?void 0:Q.workspace.id)??null,I=(d?ft.find(we=>we.workspace.id===d)??null:null)??ft[0]??null;x(I?ke(I.workspace.id,I.session.sessionId):d?rt(d):s==="mobile"?Tr():"/landing",{replace:!0})},[H,ft,x,i,p==null?void 0:p.workspaceId,ce,f==null?void 0:f.workspaceId,s]),a.useEffect(()=>{if(ce==="SESSION_NOT_FOUND"||ce==="WORKSPACE_NOT_FOUND"){U.current!==null&&(window.clearTimeout(U.current),U.current=null),G.current=null,K.current=null,H("conversation-runtime-error");return}if(!ce||!fe){U.current!==null&&(window.clearTimeout(U.current),U.current=null),G.current=null,K.current=null,H("conversation-runtime-error");return}const d=`${ce}:${fe}`;if(!(K.current===d||G.current===d)){if(U.current!==null&&(window.clearTimeout(U.current),U.current=null),Ui((f==null?void 0:f.provider)??null,ce,fe)){G.current=d,U.current=window.setTimeout(()=>{G.current=null,U.current=null,K.current=d,P({id:"conversation-runtime-error",title:o("conversation.runtimeErrorTitle"),description:fe,tone:"error",durationMs:null})},Li);return}G.current=null,K.current=d,P({id:"conversation-runtime-error",title:o("conversation.runtimeErrorTitle"),description:fe,tone:"error",durationMs:null})}},[H,ce,fe,f==null?void 0:f.provider,P]),a.useEffect(()=>{const d=ge.current,I=(f==null?void 0:f.runningState)??null;(d==="starting"||d==="running"||d==="reconnecting")&&I==="completed"&&Y.trigger("success"),ge.current=I},[Y,f==null?void 0:f.runningState]),a.useEffect(()=>{const d=Ee.filter(Q=>Q.status==="pending"),I=(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??null;for(const Q of d)A.current.has(Q.id)||(A.current.add(Q.id),q&&(P({id:`permission-request-${Q.id}`,title:o("conversation.permissionRequestToastTitle"),description:Q.title,tone:"warning",durationMs:8e3,action:I?{label:o("shell.contextOpenSession"),onClick:()=>{x(ke(I,t))}}:void 0}),se.bridge.showNotification(o("conversation.permissionRequestToastTitle"),Q.title)))},[p==null?void 0:p.workspaceId,x,q,Ee,se.bridge,f==null?void 0:f.workspaceId,t,P]),Rn(Mt,qn,!ue,t),Tn(Mt,ns,!ue,t);async function rs(d,I){var Ne,as;const Q=Z;if(!Q){await v.sendMessage(d,{model:I==null?void 0:I.model,reasoningLevel:I==null?void 0:I.reasoningLevel,attachments:I==null?void 0:I.attachments,attachmentMeta:I==null?void 0:I.attachmentMeta}),c();return}let we=null;try{we=await Bs(t,{sourceType:"message",sourceMessageId:Q.sourceMessageId,sourceMessageSnapshot:Q.sourceMessageSnapshot,strategy:"auto",targetProvider:Q.targetProvider}),C(we),await Ut(we.sessionId,{content:d,clientRequestId:((as=(Ne=globalThis.crypto)==null?void 0:Ne.randomUUID)==null?void 0:as.call(Ne))??`fork-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:Q.targetModel,reasoningLevel:(I==null?void 0:I.reasoningLevel)??null,permissionMode:_e(),attachments:(I==null?void 0:I.attachments)??[]}),le(null),c(),l(we.workspaceId),$e("preview"),x(ke(we.workspaceId,we.sessionId)),P({title:o("conversation.forkMessageSucceeded"),tone:"success"})}catch(Vn){throw we&&(C(we),c()),Vn}}function Xn(d){l(d),x(rt(d))}return r.jsxs(r.Fragment,{children:[r.jsxs("main",{ref:Mt,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!ue,"data-preview-mode":ue?void 0:xe.displayMode,"data-preview-dragging":ue?void 0:xe.isDragging,"data-workspace-tone":(Ae==null?void 0:Ae.tone)??"root","data-worktree-depth":(Ae==null?void 0:Ae.depth)??0,"data-tool-panel-open":ue?void 0:ye.isOpen,style:{...ue?{}:xe.pageStyle,...$t(Ae)??{}},children:[ue?r.jsx(gn,{session:f??p,workspaceContext:Ae,actions:r.jsxs(r.Fragment,{children:[es?r.jsx(to,{onOpenBranchTree:ts}):null,r.jsx(cn,{session:f??p})]})}):null,ue?null:r.jsx(on,{containerRef:ns,className:"mobile-conversation-page-header",gestureHandlers:Zt??void 0,currentWorkspace:je?{id:je.workspace.id,name:je.label,path:je.subtitle}:Qe[0]??null,workspaces:Qe,workspaceOptions:zt,onSelectWorkspace:Xn,heading:wt.fullTitle,trailing:r.jsxs("div",{className:"mobile-conversation-toolbar-main",children:[r.jsx("span",{className:"mobile-conversation-toolbar-title",title:wt.fullTitle,children:wt.displayTitle}),r.jsx(Qr,{session:f??p,onOpenBranchTree:es?ts:void 0})]})}),ue?null:r.jsx(Pn,{visible:!ye.isOpen&&xe.isVisible,widthPx:xe.previewWidthPx,isDragging:xe.isDragging,gestureHandlers:xe.railGestureHandlers,activeSessionId:t,createSessionActionLabel:ae&&bt?o("shell.createSession"):void 0,favoriteItems:gt,items:pt,expandedRootIds:On,workspaceSectionLabel:(je==null?void 0:je.label)??o("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:ae&&bt?()=>{N(ae,bt)}:void 0,archiveCurrentActionLabel:o("shell.archiveCurrentSessionAction"),archiveFolderActionLabel:St.length>0?o("shell.archiveFolderLabel"):void 0,onArchiveActiveSession:()=>{T(!0)},onOpenArchiveFolder:St.length>0?()=>{y(!0)}:void 0,onToggleSubsessions:d=>{Qt(I=>I.includes(d)?I.filter(Q=>Q!==d):[...I,d])},onActivate:d=>{xe.closePreview(),l(d.workspace.id),x(ke(d.workspace.id,d.session.sessionId))}}),r.jsx("div",{className:"mobile-conversation-stage",...Zt??{},children:r.jsxs("div",{ref:Hn,className:"mobile-conversation-main",children:[r.jsx(an,{connectionState:W,onReconnect:()=>v.reconnect()}),r.jsx(Nr,{requests:Ee,replyingRequestId:g,onReply:async(d,I)=>{D(d);try{await v.replyPermissionRequest(d,I)}catch(Q){P({title:o("conversation.permissionRequestReplyFailed"),description:Q instanceof Error?Q.message:void 0,tone:"error"})}finally{D(null)}}}),r.jsx("div",{ref:ss,className:"conversation-timeline-shell",children:r.jsx(sn,{sessionId:t,messages:Dn,historyState:me,loadingOlderMessages:B,hasOlderMessages:z,provider:(f==null?void 0:f.provider)??null,interruptedSource:m,runtimeThinkingPlaceholder:_n,onLoadOlderMessages:()=>{v.loadOlderMessages()},onRetryMessage:d=>{v.retryMessage(d)},onForkMessage:d=>{f&&(le({sourceMessageId:d.id,sourceMessageSnapshot:{role:d.role,kind:d.kind??(d.role==="tool"?"tool_result":"text"),content:d.content},content:d.content,sourceProvider:f.provider,workspaceId:f.workspaceId,targetProvider:f.provider,targetModel:null}),Wi())}})}),r.jsx(Vr,{containerRef:ss,session:f??p??null,currentCapabilities:J}),r.jsx(Kr,{items:L,deletingQueueItemId:ne,steeringQueueItemId:ee,canSteer:Pe,onDelete:async d=>{be(d);try{await v.deleteQueuedMessage(d)}finally{be(null)}},onSteer:async d=>{pe(d);try{await v.steerQueuedMessage(d),c()}finally{pe(null)}}}),ye.isOpen?null:r.jsx(nn,{capabilities:J,draftStorageId:t,forkDraft:Z,onClearForkDraft:()=>le(null),onForkDraftChange:d=>le(d),panelRef:ue?void 0:Un,portalContainer:ue?null:Wn,hasActiveRun:ht,contextUsage:V,taskProvider:((os=f??p)==null?void 0:os.provider)??null,taskMessages:Te,hasPendingQueuedMessages:qe,canInterrupt:mt,isSubmitting:E,isRunning:ze,onInterrupt:async()=>{await v.interrupt(),c()},onSend:async(d,I)=>{M(!0);try{await rs(d,{model:I==null?void 0:I.model,reasoningLevel:I==null?void 0:I.reasoningLevel,attachments:I==null?void 0:I.attachments,attachmentMeta:I==null?void 0:I.attachmentMeta})}finally{M(!1)}},onQueueSend:async(d,I)=>{M(!0);try{Z?await rs(d,{model:I==null?void 0:I.model,reasoningLevel:I==null?void 0:I.reasoningLevel,attachments:I==null?void 0:I.attachments,attachmentMeta:I==null?void 0:I.attachmentMeta}):await v.enqueueMessage(d,{model:I==null?void 0:I.model,reasoningLevel:I==null?void 0:I.reasoningLevel,attachments:I==null?void 0:I.attachments,attachmentMeta:I==null?void 0:I.attachmentMeta})}finally{M(!1)}}})]})}),!ue&&ae?r.jsx(En,{activePanel:ye.activePanel,open:ye.isOpen,sessionId:t,workspaceId:ae,navigationGroups:i,onClose:()=>{ye.closePanel()},onSelectPanel:d=>{ye.selectPanel(d)},onSelectPanelBySwipe:d=>{if(d===null){ye.closePanel();return}ye.selectPanel(d)}}):null]}),r.jsx(bi,{open:te,navigationGroups:i,workspaceId:Ke,sessionId:t,onClose:()=>oe(!1),onOpenSession:d=>{oe(!1),l(d.workspaceId),$e("preview"),x(ke(d.workspaceId,d.sessionId))}}),r.jsx(eo,{open:O,busy:X,onClose:()=>{X||T(!1)},onConfirm:async()=>{if(!X){$(!0);try{if(await R(t),T(!1),P({title:o("shell.archiveAdded"),tone:"success"}),ae){if(l(ae),$e("preview"),vt){x(ke(vt.workspace.id,vt.session.sessionId));return}x(rt(ae));return}x("/workspaces")}catch(d){P({title:d instanceof Error?d.message:o("shell.navigationLoadFailed"),tone:"error"})}finally{$(!1)}}}}),r.jsx(Nn,{open:F,workspaceName:(Me==null?void 0:Me.workspace.name)??null,sessions:St,restoringSessionId:k,onClose:()=>{k||y(!1)},onRestore:async d=>{j(d);try{await S(d),P({title:o("shell.archiveRestored"),tone:"success"})}catch(I){P({title:I instanceof Error?I.message:o("shell.navigationLoadFailed"),tone:"error"})}finally{j(null)}}})]})}function Ui(t,e,n){return t!=="opencode"?!1:e==="OPENCODE_REQUEST_TIMEOUT"||e==="PROVIDER_RUNTIME_TIMEOUT"||/\bSERVER_TIMEOUT\b/i.test(n)||/timeout/i.test(n)||/超时/.test(n)}function Wi(){typeof window>"u"||window.dispatchEvent(new CustomEvent(Hi))}function Xi({draft:t,navigate:e,initialToolPanel:n}){const{shellMode:s,navigationGroups:i,requestNavigationRefresh:c,selectWorkspace:l,setSessionWorkspace:u,upsertNavigationSession:h,favoriteSessions:b,unarchiveSession:R,startDraftSession:S}=ct(),[N,C]=a.useState(!1),[x,w]=a.useState([]),_=a.useMemo(()=>Xe(t.provider),[t.provider]),[E,M]=a.useState(_),g=s!=="mobile",{showToast:D}=Ye(),O=a.useMemo(()=>$i(t),[t]),T=An(!g),F=kn({enabled:!g,initialPanel:n,sessionId:t.sessionId,workspaceId:t.workspaceId,suspendMainGesture:!g&&T.isVisible}),y=a.useMemo(()=>new Set(b.map(L=>L.session.sessionId)),[b]),k=a.useMemo(()=>i.map(L=>L.workspace),[i]),j=a.useMemo(()=>rn(i),[i]),X=a.useMemo(()=>Qs(i),[i]),$=a.useMemo(()=>k.find(L=>L.id===t.workspaceId)??null,[t.workspaceId,k]),te=X[t.workspaceId]??($?Ks($):null),oe=a.useMemo(()=>He(O.title??null,o("conversation.titleFallback")),[O]),Z=a.useMemo(()=>In(i,t.workspaceId,y),[t.workspaceId,y,i]),le=a.useMemo(()=>xn(b,i),[b,i]),[p,v]=a.useState([]),P=a.useMemo(()=>[...le,...Z],[le,Z]),H=a.useMemo(()=>dt(i,t.workspaceId),[t.workspaceId,i]),q=a.useMemo(()=>(H==null?void 0:H.sessions.filter(L=>L.isArchived===!0&&!ut(L)))??[],[H]),se=j.find(L=>L.workspace.id===t.workspaceId)??(H?{workspace:H.workspace,label:H.workspace.name,subtitle:H.workspace.path}:null),Y=g?null:Cn(T.mainGestureHandlers,F.mainGestureHandlers),[K,G]=a.useState(!1),[U,ge]=a.useState(null),A=a.useRef(null),f=a.useRef(null),J=a.useRef(null),[he,Se]=a.useState(null),{composerPortalTarget:Te}=Js();a.useEffect(()=>{const L=Zs(P,t.sessionId,V=>V.session.sessionId);L.length!==0&&v(V=>{const me=new Set(V);let ce=!1;for(const fe of L)me.has(fe)||(me.add(fe),ce=!0);return ce?Array.from(me):V})},[t.sessionId,P]),a.useEffect(()=>(u(t.sessionId,t.workspaceId),()=>{u(t.sessionId,null)}),[t.sessionId,t.workspaceId,u]),a.useEffect(()=>{let L=!1;return M(_),Ds(t.provider,t.workspaceId).then(V=>{L||M(V)}).catch(()=>{}),()=>{L=!0}},[t.provider,t.workspaceId,_]),Rn(f,he,!g,t.sessionId),Tn(f,J,!g,t.sessionId);function Ee(L){l(L),e(rt(L))}return r.jsx(r.Fragment,{children:r.jsxs("main",{ref:f,className:"workbench-page conversation-page-shell mobile-page-fixed-root mobile-conversation-page","data-mobile-shell":!g,"data-preview-mode":g?void 0:T.displayMode,"data-preview-dragging":g?void 0:T.isDragging,"data-workspace-tone":(te==null?void 0:te.tone)??"root","data-worktree-depth":(te==null?void 0:te.depth)??0,"data-tool-panel-open":g?void 0:F.isOpen,style:{...g?{}:T.pageStyle,...$t(te)??{}},children:[g?r.jsx(gn,{session:O,workspaceContext:te}):null,g?null:r.jsx(on,{containerRef:J,className:"mobile-conversation-page-header",gestureHandlers:Y??void 0,currentWorkspace:se?{id:se.workspace.id,name:se.label,path:se.subtitle}:k[0]??null,workspaces:k,workspaceOptions:j,onSelectWorkspace:Ee,heading:oe.fullTitle,trailing:r.jsx("span",{className:"mobile-conversation-toolbar-title",title:oe.fullTitle,children:oe.displayTitle})}),g?null:r.jsx(Pn,{visible:!F.isOpen&&T.isVisible,widthPx:T.previewWidthPx,isDragging:T.isDragging,gestureHandlers:T.railGestureHandlers,activeSessionId:t.sessionId,createSessionActionLabel:o("shell.createSession"),favoriteItems:le,items:Z,expandedRootIds:p,workspaceSectionLabel:(se==null?void 0:se.label)??o("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:()=>{S(t.workspaceId,t.provider)},archiveFolderActionLabel:q.length>0?o("shell.archiveFolderLabel"):void 0,onOpenArchiveFolder:q.length>0?()=>{G(!0)}:void 0,onToggleSubsessions:L=>{v(V=>V.includes(L)?V.filter(me=>me!==L):[...V,L])},onActivate:L=>{T.closePreview(),l(L.workspace.id),e(ke(L.workspace.id,L.session.sessionId))}}),r.jsx("div",{className:"mobile-conversation-stage",...Y??{},children:r.jsxs("div",{ref:A,className:"mobile-conversation-main",children:[r.jsx(an,{connectionState:"closed",onReconnect:()=>{}}),r.jsx("div",{className:"conversation-timeline-shell",children:r.jsx(sn,{sessionId:t.sessionId,messages:x,historyState:"ready",loadingOlderMessages:!1,hasOlderMessages:!1,provider:t.provider,runtimeThinkingPlaceholder:null,onLoadOlderMessages:()=>{},onRetryMessage:()=>{}})}),F.isOpen?null:r.jsx(nn,{capabilities:E,draftStorageId:t.sessionId,panelRef:g?void 0:Se,portalContainer:g?null:Te,contextUsage:null,taskProvider:t.provider,taskMessages:x,isSubmitting:N,isRunning:!1,onSend:async(L,V)=>{var fe,m,B,z;const me=ho();w(W=>[...W,tn(t.sessionId,L,me,(V==null?void 0:V.attachmentMeta)??[],(V==null?void 0:V.attachments)??[])]),C(!0);const ce=performance.now();ie("session_send.start_live.client_start",{draftSessionId:t.sessionId,workspaceId:t.workspaceId,provider:t.provider,clientRequestId:me,contentLength:L.length});try{const W=await Fs({workspaceId:t.workspaceId,provider:t.provider,content:L,clientRequestId:me,model:(V==null?void 0:V.model)??null,reasoningLevel:(V==null?void 0:V.reasoningLevel)??null,permissionMode:_e(),attachments:(V==null?void 0:V.attachments)??[]});ie("session_send.start_live.client_response",{draftSessionId:t.sessionId,sessionId:W.sessionId,workspaceId:((fe=W.session)==null?void 0:fe.workspaceId)??t.workspaceId,provider:W.provider,clientRequestId:me,durationMs:Math.round(performance.now()-ce),returnedMessageId:((m=W.message)==null?void 0:m.messageId)??null}),W.session&&h(W.session);const ne=((z=(B=W.session)==null?void 0:B.workspaceId)==null?void 0:z.trim())||t.workspaceId;u(W.sessionId,ne),$e("preview"),e(ke(ne,W.sessionId),{replace:!0,state:W.message?{bootstrap:{sessionId:W.sessionId,messages:[W.message]}}:null}),c()}catch(W){throw ie("session_send.start_live.client_error",{draftSessionId:t.sessionId,workspaceId:t.workspaceId,provider:t.provider,clientRequestId:me,durationMs:Math.round(performance.now()-ce),error:W instanceof Error?W.message:String(W)}),w(ne=>Lt(ne,me)),W}finally{C(!1)}}})]})}),g?null:r.jsx(En,{activePanel:F.activePanel,open:F.isOpen,sessionId:t.sessionId,workspaceId:t.workspaceId,navigationGroups:i,onClose:()=>{F.closePanel()},onSelectPanel:L=>{F.selectPanel(L)},onSelectPanelBySwipe:L=>{if(L===null){F.closePanel();return}F.selectPanel(L)}}),r.jsx(Nn,{open:K,workspaceName:(H==null?void 0:H.workspace.name)??null,sessions:q,restoringSessionId:U,onClose:()=>{U||G(!1)},onRestore:async L=>{ge(L);try{await R(L),D({title:o("shell.archiveRestored"),tone:"success"})}catch(V){D({title:V instanceof Error?V.message:o("shell.navigationLoadFailed"),tone:"error"})}finally{ge(null)}}})]})})}function Vi(t,e,n,s=null){var l,u;if(!lo(t))return null;const i=e??((l=n.get("workspaceId"))==null?void 0:l.trim())??null,c=((u=n.get("provider"))==null?void 0:u.trim())??s??null;return!i||!Ws(c)?null:{sessionId:t,workspaceId:i,provider:c}}function $i(t){const e=new Date().toISOString();return{sessionId:t.sessionId,workspaceId:t.workspaceId,provider:t.provider,providerSessionId:`draft://${t.sessionId}`,rawStoreRef:`draft://${t.sessionId}`,parentSessionId:null,isSubagent:!1,subagentLabel:null,isArchived:!1,title:mr(t.provider),messageCount:0,lastMessageAt:null,createdAt:e,updatedAt:e,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 Yi(t){var e;return((e=t.parentSessionId)==null?void 0:e.trim())||null}function Mn(t){const e=new Map(t.map(i=>[i.sessionId,i])),n=new Map,s=i=>{const c=n.get(i.sessionId);if(typeof c=="boolean")return c;if(i.isArchived)return n.set(i.sessionId,!1),!1;const l=Yi(i);if(!l)return n.set(i.sessionId,!0),!0;const u=e.get(l);if(!u)return n.set(i.sessionId,!0),!0;const h=s(u);return n.set(i.sessionId,h),h};return t.filter(i=>s(i))}function In(t,e,n){if(!e)return[];const s=dt(t,e);if(!s)return[];const i=Mn(s.sessions).map(l=>({session:l,workspace:s.workspace}));return en(i).filter(l=>!n.has(l.item.session.sessionId)&&!Cr(l.children,u=>n.has(u.session.sessionId)))}function xn(t,e){return t.filter(n=>!ut(n.session)).flatMap(n=>{const s=dt(e,n.workspace.id);if(!s)return[];const i=en(Mn(s.sessions).map(l=>({session:l,workspace:s.workspace}))),c=yn(i,n.session.sessionId);return c?[c]:[]})}function yn(t,e){for(const n of t){if(n.item.session.sessionId===e)return n;const s=yn(n.children,e);if(s)return s}return null}function Rn(t,e,n,s){a.useEffect(()=>{const i=t.current;if(!n||!i){i&&i.style.removeProperty("--mobile-conversation-composer-height");return}if(!e){i.style.removeProperty("--mobile-conversation-composer-height");return}const c=i,l=e;function u(){!t.current||!l.isConnected||c.style.setProperty("--mobile-conversation-composer-height",`${l.offsetHeight}px`)}u();const h=typeof ResizeObserver<"u"?new ResizeObserver(u):null;return h==null||h.observe(l),window.addEventListener("resize",u),()=>{h==null||h.disconnect(),window.removeEventListener("resize",u),i.style.removeProperty("--mobile-conversation-composer-height")}},[e,n,s,t])}function Tn(t,e,n,s){a.useEffect(()=>{const i=t.current,c=e.current;if(!n||!i){i&&i.style.removeProperty("--mobile-conversation-page-header-height");return}if(!c){i.style.removeProperty("--mobile-conversation-page-header-height");return}const l=i,u=c;function h(){!t.current||!u.isConnected||l.style.setProperty("--mobile-conversation-page-header-height",`${u.offsetHeight}px`)}h();const b=typeof ResizeObserver<"u"?new ResizeObserver(h):null;return b==null||b.observe(u),window.addEventListener("resize",h),()=>{b==null||b.disconnect(),window.removeEventListener("resize",h),i.style.removeProperty("--mobile-conversation-page-header-height")}},[n,e,s,t])}function Gi(t){return t==="files"||t==="git"||t==="processes"?t:null}function Cn(...t){const e=t.filter(Boolean);return{onTouchStart(n){e.forEach(s=>s.onTouchStart(n))},onTouchMove(n){e.forEach(s=>s.onTouchMove(n))},onTouchEnd(n){e.forEach(s=>s.onTouchEnd(n))},onTouchCancel(n){e.forEach(s=>s.onTouchCancel(n))}}}function kn(t){const e=Vt(),n=Ge(),s=Wt(),i=a.useRef(null),[c,l]=a.useState(()=>t.initialPanel??ms()),u=t.initialPanel??c,h=t.enabled&&t.workspaceId!==null&&t.initialPanel!==null;a.useEffect(()=>{if(!t.enabled){i.current=null;return}const M=t.initialPanel??ms();l(M),fs(M)},[t.enabled,t.initialPanel]);function b(M,g){const D=new URLSearchParams(e.search);M?(D.set("toolPanel",M),l(M),fs(M)):D.delete("toolPanel");const O=D.toString();n({pathname:e.pathname,search:O?`?${O}`:""},{replace:(g==null?void 0:g.replace)??!1})}function R(M){s.trigger("selection"),b(M,{replace:h})}function S(){h&&(s.trigger("gesture"),b(null,{replace:!0}))}function N(M){if(!t.enabled||!t.workspaceId)return;const g=M??u;s.trigger("gesture"),b(g)}function C(M){if(!t.enabled||M.changedTouches.length!==1){i.current=null;return}if(zi(M.target)){i.current=null;return}const g=M.changedTouches[0];i.current={x:g.clientX,y:g.clientY}}function x(M){const g=i.current;if(i.current=null,!g||M.changedTouches.length!==1||h||t.suspendMainGesture)return;const D=M.changedTouches[0],O=D.clientX-g.x,T=D.clientY-g.y;O>-56||Math.abs(O)<=Math.abs(T)*1.15||N()}function w(M){const g=i.current;if(i.current=null,!g||M.changedTouches.length!==1||!h)return;const D=M.changedTouches[0],O=D.clientX-g.x,T=D.clientY-g.y;O<56||Math.abs(O)<=Math.abs(T)*1.15||S()}return{activePanel:u,closePanel:S,isOpen:h,mainGestureHandlers:{onTouchStart:C,onTouchMove:()=>{},onTouchEnd:x,onTouchCancel:()=>{i.current=null}},openPanel:N,panelGestureHandlers:{onTouchStart:C,onTouchMove:()=>{},onTouchEnd:w,onTouchCancel:()=>{i.current=null}},selectPanel:R}}function En(t){const e=a.useRef(null);if(!t.open)return null;function n(i){if(i.changedTouches.length!==1){e.current=null;return}if(Qi(i.target)){e.current=null;return}const c=i.changedTouches[0];e.current={x:c.clientX,y:c.clientY}}function s(i){const c=e.current;if(e.current=null,!c||i.changedTouches.length!==1)return;const l=i.changedTouches[0],u=l.clientX-c.x,h=l.clientY-c.y;if(Math.abs(u)<56||Math.abs(u)<=Math.abs(h)*1.15)return;const b=["files","git","processes"],R=b.indexOf(t.activePanel);if(u<0){t.onSelectPanelBySwipe(b[Math.min(b.length-1,R+1)]??t.activePanel);return}if(R===0){t.onSelectPanelBySwipe(null);return}t.onSelectPanelBySwipe(b[Math.max(0,R-1)]??t.activePanel)}return r.jsxs("section",{className:"mobile-conversation-tool-panel","data-panel":t.activePanel,onTouchStart:n,onTouchEnd:s,onTouchCancel:()=>{e.current=null},children:[r.jsxs("header",{className:"mobile-conversation-tool-panel-header","data-preview-gesture":"ignore",children:[r.jsx("button",{type:"button",className:"mobile-conversation-tool-panel-back","aria-label":o("shell.mobileConversationToolCloseAction"),title:o("shell.mobileConversationToolCloseAction"),onClick:t.onClose,children:r.jsx("span",{"aria-hidden":"true",children:"‹"})}),r.jsx("div",{className:"mobile-conversation-tool-panel-tabs",role:"tablist","aria-label":o("shell.mobileConversationToolTabsLabel"),children:["files","git","processes"].map(i=>r.jsx("button",{type:"button",role:"tab","aria-selected":t.activePanel===i,className:"mobile-conversation-tool-panel-tab",onClick:()=>{t.onSelectPanel(i)},children:i==="files"?o("shell.filesEntry"):i==="git"?o("shell.gitEntry"):o("shell.mobileConversationToolProcessesTab")},i))})]}),r.jsx("div",{className:"mobile-conversation-tool-panel-body",children:t.activePanel==="files"?r.jsx(Lr,{className:"mobile-conversation-tool-surface",hideHeading:!0,sessionId:t.sessionId,workspaceId:t.workspaceId}):t.activePanel==="git"?r.jsx(Or,{className:"mobile-conversation-tool-surface",panelActive:!0,workspaceId:t.workspaceId}):r.jsx(Dr,{className:"mobile-conversation-tool-surface mobile-tool-native-panel mobile-tool-process-panel",currentWorkspaceId:t.workspaceId,navigationGroups:t.navigationGroups})})]})}function zi(t){return t instanceof Element?!!t.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function Qi(t){return t instanceof Element?!!t.closest("input, textarea, select, option, [contenteditable='true']"):!1}function An(t){const e=Wt(),[n,s]=a.useState(()=>t?xt():"immersive"),[i,c]=a.useState(()=>Ls()),[l,u]=a.useState(()=>t&&xt()==="preview"?"default":"closed"),h=a.useRef(l),b=a.useRef(null);a.useEffect(()=>{h.current=l},[l]),a.useEffect(()=>{if(!t){b.current=null,h.current="closed",u("closed"),s("immersive");return}const y=xt();s(y),u(y==="preview"?"default":"closed")},[t]),a.useEffect(()=>{t&&$e(n)},[t,n]),a.useEffect(()=>{if(typeof window>"u")return;function y(){c(Ls())}return y(),window.addEventListener("resize",y),()=>{window.removeEventListener("resize",y)}},[]);function R(y){h.current=y,u(y)}function S(y="default"){R(y),s("preview")}function N(){R("closed"),s("immersive")}function C(){R("expanded"),s("preview")}function x(){if(h.current!=="closed"){e.trigger("gesture"),N();return}e.trigger("gesture"),S()}function w(y,k){const j=k.touches[0]??k.changedTouches[0];if(!t||!j){b.current=null;return}if(Ji(k.target)){b.current=null;return}if(y==="main"){if(h.current==="closed"&&j.clientX>Bi){b.current=null;return}}else if(h.current==="closed"){b.current=null;return}b.current={source:y,intent:y==="rail"?"rail":h.current==="closed"?"open":"close",startX:j.clientX,startY:j.clientY,lastX:j.clientX,lastY:j.clientY,horizontalLocked:!1}}function _(y){const k=b.current,j=y.touches[0];if(!t||!k||!j)return;const X=j.clientX-k.startX,$=j.clientY-k.startY;if(k.lastX=j.clientX,k.lastY=j.clientY,!k.horizontalLocked){if(Math.abs(X)<_s&&Math.abs($)<_s)return;if(Math.abs(X)<=Math.abs($)){b.current=null;return}if(k.intent==="open"&&X<=0){b.current=null;return}if(k.intent==="close"&&X>=0){b.current=null;return}k.horizontalLocked=!0}}function E(y){var $;const k=b.current;if(b.current=null,!(k!=null&&k.horizontalLocked))return;const j=($=y==null?void 0:y.changedTouches)==null?void 0:$[0];j&&(k.lastX=j.clientX,k.lastY=j.clientY);const X=k.lastX-k.startX;if(k.intent==="open"){X>=Oi&&(e.trigger("gesture"),S("default"));return}if(k.intent==="close"){X<=-34&&(e.trigger("gesture"),N());return}if(X<=-34){e.trigger("gesture"),N();return}X>=Di&&h.current==="default"&&(e.trigger("gesture"),C())}const M=l==="expanded"?_t:l==="default"?Ns:0,g=Math.round(i*M*100)/100,D=M===0?0:M/_t,O={"--mobile-conversation-preview-default-width":`${Math.round(i*Ns*100)/100}px`,"--mobile-conversation-preview-max-width":`${Math.round(i*_t*100)/100}px`,"--mobile-conversation-preview-width":`${g}px`,"--mobile-conversation-preview-progress":D.toFixed(4)};return{closePreview:N,displayMode:l==="closed"?"immersive":"preview",isDragging:!1,isVisible:l!=="closed",mainGestureHandlers:{onTouchStart:y=>w("main",y),onTouchMove:_,onTouchEnd:E,onTouchCancel:E},pageStyle:O,previewWidthPx:g,railGestureHandlers:{onTouchStart:y=>w("rail",y),onTouchMove:_,onTouchEnd:E,onTouchCancel:E},togglePreview:x}}function Pn({visible:t,widthPx:e,isDragging:n,gestureHandlers:s,activeSessionId:i,createSessionActionLabel:c,favoriteItems:l,items:u,expandedRootIds:h,workspaceSectionLabel:b,onCreateSession:R,archiveCurrentActionLabel:S,archiveFolderActionLabel:N,onArchiveActiveSession:C,onOpenArchiveFolder:x,onToggleSubsessions:w,onActivate:_}){if(!t)return null;function E(M,g){const{workspaceName:D,ancestorExpanded:O=!1,ancestorHasNextSiblings:T=[],hasNextSibling:F=!1,isFirstSibling:y=!1}=g??{},k=M.item.session.sessionId,j=M.children,X=M.depth===0&&j.length>0,$=O||X&&h.includes(k),te=M.depth>0?[...T,F]:[...T];return r.jsxs("div",{className:"mobile-conversation-preview-tree-node",children:[r.jsxs("div",{className:"mobile-conversation-preview-tree-row",style:{"--mobile-preview-tree-depth":M.depth},children:[M.depth>0?r.jsxs("div",{className:"mobile-conversation-preview-guides","aria-hidden":"true",children:[T.map((oe,Z)=>oe?r.jsx("span",{className:"mobile-conversation-preview-guide-column",style:{"--mobile-preview-tree-level":Z+1}},`${k}:ancestor:${Z}`):null),r.jsx("span",{className:"mobile-conversation-preview-guide-branch","data-continue":F,"data-first":y,style:{"--mobile-preview-tree-level":M.depth},children:r.jsx("span",{className:"mobile-conversation-preview-guide-branch-horizontal"})})]}):null,r.jsx(Ki,{entry:M.item,activeSessionId:i,hasSubsessions:X,subsessionsExpanded:$,workspaceName:D,onToggleSubsessions:X?()=>{w(k)}:void 0,onActivate:_})]}),j.length>0&&$?r.jsx("div",{className:"mobile-conversation-preview-children",children:j.map((oe,Z)=>E(oe,{workspaceName:D,ancestorExpanded:!0,ancestorHasNextSiblings:te,hasNextSibling:Z<j.length-1,isFirstSibling:Z===0}))}):null]},`${M.item.workspace.id}:${k}`)}return r.jsxs("aside",{className:"mobile-conversation-preview-rail terminal-mobile-list-rail surface-card","data-dragging":n,style:{width:`${e}px`,maxWidth:`${e}px`},...s,children:[c&&R?r.jsx("div",{className:"mobile-conversation-preview-topbar terminal-mobile-list-footer",children:r.jsxs("button",{type:"button",className:"mobile-conversation-preview-create-button workbench-import-toggle terminal-mobile-list-create",onClick:R,children:[r.jsx("span",{className:"workbench-import-toggle-symbol","aria-hidden":"true",children:"+"}),r.jsx("span",{className:"workbench-import-toggle-label",children:c})]})}):null,r.jsxs("div",{className:"mobile-conversation-preview-body terminal-mobile-list-body",children:[l.length>0?r.jsxs("section",{className:"mobile-conversation-preview-group mobile-conversation-preview-list-favorites terminal-mobile-list-group terminal-mobile-list-group-pinned",children:[r.jsxs("div",{className:"mobile-conversation-preview-group-heading terminal-mobile-list-group-heading",children:[r.jsx("span",{children:o("shell.favoriteSectionTitle")}),r.jsx("span",{className:"workbench-section-counter",children:l.length})]}),r.jsx("div",{className:"mobile-conversation-preview-list mobile-conversation-preview-list-static terminal-mobile-session-list",children:l.map(M=>r.jsx("div",{children:E(M,{workspaceName:M.item.workspace.name})},`favorite:${M.item.workspace.id}:${M.item.session.sessionId}`))})]}):null,r.jsxs("section",{className:"mobile-conversation-preview-group mobile-conversation-preview-group-workspace terminal-mobile-list-group terminal-mobile-list-group-workspace",children:[r.jsxs("div",{className:"mobile-conversation-preview-group-heading terminal-mobile-list-group-heading",children:[r.jsx("span",{children:b}),r.jsx("span",{className:"workbench-section-counter",children:u.length})]}),u.length===0?r.jsx("div",{className:"workbench-session-empty",children:o("shell.emptyWorkspaceSessions")}):r.jsx("div",{className:"mobile-conversation-preview-list terminal-mobile-session-list","data-preview-gesture":"ignore",children:u.map(M=>E(M))})]})]}),S&&C||N&&x?r.jsxs("div",{className:"mobile-conversation-preview-actions terminal-mobile-list-footer",children:[S&&C?r.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:()=>{C()},children:S}):null,N&&x?r.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:x,children:N}):null]}):null]})}function Ki({entry:t,activeSessionId:e,hasSubsessions:n=!1,subsessionsExpanded:s=!1,onActivate:i,onToggleSubsessions:c,workspaceName:l}){const u=t.session.sessionId===e;return r.jsxs("article",{className:"mobile-conversation-preview-entry terminal-mobile-session-card","data-active":u,children:[n?r.jsx("button",{type:"button",className:"mobile-conversation-preview-toggle","aria-label":s?o("shell.subagentCollapse"):o("shell.subagentExpand"),title:s?o("shell.subagentCollapse"):o("shell.subagentExpand"),"aria-expanded":s,onClick:h=>{h.stopPropagation(),c==null||c()},children:r.jsx("span",{className:Os(t.session,{isActive:u,hasSubsessions:n}),"aria-hidden":"true"})}):r.jsx("span",{className:Os(t.session,{isActive:u,hasSubsessions:n}),"aria-hidden":"true"}),r.jsx("button",{type:"button",className:"mobile-conversation-preview-item terminal-mobile-session-primary","data-active":u,onClick:()=>i(t),children:r.jsxs("div",{className:"mobile-conversation-preview-item-body",children:[r.jsx("span",{className:"mobile-conversation-preview-item-title",children:t.session.title||o("common.unknown")}),r.jsx("span",{className:"mobile-conversation-preview-item-meta",children:jn(t.session,l)})]})})]})}function Ls(){return typeof window>"u"?390:Math.max(window.innerWidth||390,320)}function Ji(t){return t instanceof Element?!!t.closest("input, textarea, select, option, label, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function Os(t,e){const n=kr("mobile-conversation-preview-indicator",t,{hasSubagents:e.hasSubsessions});return n.endsWith(" is-idle")&&e.isActive?"mobile-conversation-preview-indicator is-active":n}function jn(t,e){const n=Gs(t);return[e??null,qt(t.provider),Zi(t.lastMessageAt??t.updatedAt),n].filter(Boolean).join(" · ")}function Zi(t){return t?new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):o("common.unknown")}function eo({open:t,busy:e,onClose:n,onConfirm:s}){return r.jsx(Ht,{open:t,title:o("shell.archiveConfirmTitle"),description:o("shell.archiveConfirmDescription"),size:"narrow",layout:"confirm",dismissible:!e,showCloseButton:!1,footer:r.jsxs(qs,{children:[r.jsx("button",{type:"button",className:"secondary-button",disabled:e,onClick:n,children:o("common.cancel")}),r.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:e,onClick:()=>{s()},children:o("shell.archiveAction")})]}),onClose:n,children:r.jsx(r.Fragment,{})})}function Nn({open:t,workspaceName:e,sessions:n,restoringSessionId:s,onClose:i,onRestore:c}){return r.jsx(Ht,{open:t,title:o("shell.archiveModalTitle"),description:e?`${e} · ${o("shell.archiveModalDescription")}`:o("shell.archiveModalDescription"),size:"regular",layout:"list",dismissible:!s,showCloseButton:!1,onClose:i,children:n.length>0?r.jsx(fr,{className:"workbench-archive-list",children:n.map(l=>{const u=He(l.title,o("common.unknown"));return r.jsx(pr,{className:"workbench-archive-item",trailing:r.jsx("button",{type:"button",className:"secondary-button",disabled:s===l.sessionId,onClick:()=>{c(l.sessionId)},children:o("shell.unarchiveAction")}),children:r.jsxs("div",{className:"workbench-archive-item-main",children:[r.jsx("strong",{title:u.fullTitle,children:u.displayTitle}),r.jsx("p",{children:jn(l)})]})},l.sessionId)})}):r.jsx(gr,{title:o("shell.archiveEmpty"),compact:!0,className:"workbench-section-empty"})})}function to(t){return r.jsx("button",{type:"button",className:"conversation-header-ai-button","aria-label":o("conversation.branchTreeAction"),title:o("conversation.branchTreeAction"),onClick:t.onOpenBranchTree,children:r.jsx("span",{className:"conversation-header-ai-button-label","aria-hidden":"true",children:r.jsx(_r,{})})})}function so(t){return t?t.activityState==="running"?!0:t.runningState==="starting"||t.runningState==="running"||t.runningState==="reconnecting":!1}function no(t){const e=ro(t),[n,s]=a.useState(e==="show"),i=a.useRef(null);return a.useEffect(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null),s(e==="show")},[t.sessionId]),a.useEffect(()=>{if(e==="show"){i.current!==null&&(window.clearTimeout(i.current),i.current=null),s(!0);return}if(e==="hide_immediately"){i.current!==null&&(window.clearTimeout(i.current),i.current=null),s(!1);return}!n||i.current!==null||(i.current=window.setTimeout(()=>{i.current=null,s(!1)},Fi))},[e,n]),a.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),n}function ro(t){const{provider:e,runningState:n,activityState:s,runtimeHasActiveRun:i,messages:c}=t;if(e!=="codex")return"hide_immediately";const l=ao(c);return l<0||oo(c,l)?"hide_immediately":io(n,s,i)?"show":"hide_deferred"}function io(t,e,n){return n===!0||e==="running"||t==="starting"||t==="running"||t==="reconnecting"}function oo(t,e){return t.slice(e+1).some(n=>n.role==="assistant"&&(n.kind==="text"||n.kind==="thinking"))}function ao(t){let e=-1;for(let n=t.length-1;n>=0;n-=1){const s=t[n];if(s.role==="user"&&s.kind==="text"){e=n;break}}return e}function lo(t){return t.startsWith("draft-")}function co(t,e){if(!e||typeof e!="object")return[];const n=e.bootstrap;if(!n||typeof n!="object")return[];const s=n.sessionId,i=n.messages;return s!==t||!Array.isArray(i)?[]:i.filter(uo)}function uo(t){if(!t||typeof t!="object")return!1;const e=t;return typeof e.messageId=="string"&&typeof e.provider=="string"&&typeof e.providerSessionId=="string"&&typeof e.role=="string"&&typeof e.content=="string"&&typeof e.timestamp=="string"&&typeof e.sequence=="number"&&typeof e.rawRef=="string"}function ho(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function mo(t,e){var i;if(!t||t.forkSourceType!=="message"||typeof t.inheritedPrefixMessageCount!="number"||t.inheritedPrefixMessageCount<0)return e;const n=((i=t.createdAt)==null?void 0:i.trim())||"";if(n.length===0)return e;const s=Math.max(0,t.inheritedPrefixMessageCount);return e.filter(c=>c.sequence<=s?!0:c.timestamp>=n)}export{_o as ConversationPage};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/window-BWqRixxq.js","assets/event-DvH9tcej.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{b as a,l as R,_ as D,j as s,t as l}from"./index-C2G8Gmf1.js";import{u as L,g as N}from"./MobileSheet-Gzc14EpR.js";import{FileContextPanel as E}from"./FileContextPanel-C8T7oqRN.js";import{GitSidebar as j}from"./GitSidebar-Bze7DNnc.js";import{TerminalManagerPanel as q}from"./TerminalManagerPanel-PQ-EM64j.js";import{TerminalPage as y}from"./TerminalPage-CvnHXBhw.js";import{W as O,m as v}from"./WorkbenchLayout-rwQib5In.js";import{c as F,u as C,d as P,N as _}from"./App-WOLwMld_.js";import"./WorkbenchModal-B09hC9b5.js";import"./file-tree-icon-Dp_xhVfD.js";import"./default-session-permission-mode-D0wZ9Jek.js";import"./terminal-runtime-meta-BMT-rSEe.js";import"./TerminalRuntimeFallbackModal-D7Aq186N.js";import"./MobileWorkspaceSwitcherHeader-DOr4pTUq.js";import"./MobileTopHeaderFrame-BWorAJ1C.js";import"./window-BWqRixxq.js";import"./event-DvH9tcej.js";function $(n){return{navigationGroups:n,subscribeFileTree:()=>{},requestFileTreeRefresh:()=>{},addFileTreeSnapshotListener:()=>()=>{},subscribeGitSnapshot:()=>{},requestGitRefresh:()=>{},addGitSnapshotListener:()=>()=>{}}}function U(){return{subscribeGitSnapshot:()=>{},requestGitRefresh:()=>{},addGitSnapshotListener:()=>()=>{}}}function z(){return{subscribeTerminalManagerSnapshot:()=>{},requestTerminalManagerRefresh:()=>{},addTerminalManagerSnapshotListener:()=>()=>{}}}function A(n,p){return{navigationGroups:p,currentWorkspaceId:n,selectWorkspace:()=>{},subscribeTerminalManagerSnapshot:()=>{},requestTerminalManagerRefresh:()=>{},addTerminalManagerSnapshotListener:()=>()=>{}}}function T(n){return n.kind==="files"?l("shell.filesEntry"):n.kind==="git"?l("shell.gitEntry"):n.kind==="processes"?l("shell.terminalManagerEntry"):n.kind==="terminals"?l("shell.terminalsEntry"):n.kind}function K(n,p){var e;const i=n.workspaceId?((e=p.find(h=>h.workspace.id===n.workspaceId))==null?void 0:e.workspace.name)??null:null,u=T(n);return i?`CodingNS - ${u}(${i})`:`CodingNS - ${u}`}function le(){const{windowId:n}=F(),p=C(),i=P(),u=L(t=>t.sessionDisplaySortMode),[e,h]=a.useState(null),[W,f]=a.useState(!0),[S,k]=a.useState(null),[o,w]=a.useState([]),[r,g]=a.useState(null);a.useEffect(()=>{let t=!1;async function d(){if(!n){h(null),f(!1),k(l("desktopWindow.invalidWindowId"));return}f(!0),k(null);const c=await i.bridge.getWindowDescriptor(n),b=c.ok?c.value??null:i.windows.getDescriptor(n);if(!t){if(!b){h(null),f(!1),k(c.detail??l("desktopWindow.loadDescriptorFailed"));return}i.windows.registerDescriptor(b),i.windows.markWindowOpen(b.windowId),h(b),f(!1)}}return d(),()=>{t=!0}},[i,n]),a.useEffect(()=>{if(!(e!=null&&e.workspaceId)){w([]);return}let t=!1;async function d(){try{const c=await N();if(t)return;w(v(c,u))}catch{if(t)return;w([])}}return d(),()=>{t=!0}},[e==null?void 0:e.workspaceId,u]),a.useEffect(()=>{if(!e){g(null);return}const t=new O({onConnectionChange:()=>{},onSnapshot:d=>{w(v(d,u))},onUnauthorized:()=>{R.clear(),p(`/login?returnTo=${encodeURIComponent(`/desktop-window/${e.windowId}`)}`,{replace:!0})}});return g(t),t.start(),()=>{t.close(),g(null)}},[e,p,u]),a.useEffect(()=>{if(!i.isDesktop||!i.bridge.supported||!e||e.mode!=="external")return;const t=K(e,o);document.title=t,D(async()=>{const{getCurrentWindow:d}=await import("./window-BWqRixxq.js").then(c=>c.w);return{getCurrentWindow:d}},__vite__mapDeps([0,1])).then(({getCurrentWindow:d})=>d().setTitle(t)).catch(()=>{})},[e,o,i.bridge.supported,i.isDesktop]);const M=a.useMemo(()=>r?{navigationGroups:o,subscribeFileTree:r.subscribeFileTree.bind(r),requestFileTreeRefresh:r.requestFileTreeRefresh.bind(r),addFileTreeSnapshotListener:r.addFileTreeSnapshotListener.bind(r),subscribeGitSnapshot:r.subscribeGit.bind(r),requestGitRefresh:r.requestGitRefresh.bind(r),addGitSnapshotListener:r.addGitSnapshotListener.bind(r)}:$(o),[o,r]),x=a.useMemo(()=>r?{subscribeGitSnapshot:r.subscribeGit.bind(r),requestGitRefresh:r.requestGitRefresh.bind(r),addGitSnapshotListener:r.addGitSnapshotListener.bind(r)}:U(),[r]),I=a.useMemo(()=>r?{subscribeTerminalManagerSnapshot:r.subscribeTerminalManager.bind(r),requestTerminalManagerRefresh:r.requestTerminalManagerRefresh.bind(r),addTerminalManagerSnapshotListener:r.addTerminalManagerSnapshotListener.bind(r)}:z(),[r]),G=a.useMemo(()=>r?{navigationGroups:o,currentWorkspaceId:(e==null?void 0:e.workspaceId)??null,selectWorkspace:()=>{},subscribeTerminalManagerSnapshot:r.subscribeTerminalManager.bind(r),requestTerminalManagerRefresh:r.requestTerminalManagerRefresh.bind(r),addTerminalManagerSnapshotListener:r.addTerminalManagerSnapshotListener.bind(r)}:A((e==null?void 0:e.workspaceId)??null,o),[e==null?void 0:e.workspaceId,o,r]);if(!i.isDesktop)return s.jsx(_,{to:"/",replace:!0});if(W)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:l("common.loading")})});if(S)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:S})});if(!e)return s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:l("desktopWindow.loadDescriptorFailed")})});let m=null;return e.kind==="files"?m=s.jsx(E,{sessionId:e.sessionId,workspaceId:e.workspaceId,externalWindowMode:!0,workbenchShellOverrides:M}):e.kind==="git"?m=s.jsx(j,{workspaceId:e.workspaceId,externalWindowMode:!0,workbenchShellOverrides:x}):e.kind==="processes"?m=s.jsx(q,{currentWorkspaceId:e.workspaceId,navigationGroups:o,externalWindowMode:!0,workbenchShellOverrides:I}):e.kind==="terminals"&&(m=s.jsx(y,{externalWindowMode:!0,externalWindowWorkspaceId:e.workspaceId,workbenchShellOverrides:G})),m?s.jsx("main",{className:"desktop-window-page",children:s.jsx("div",{className:"desktop-window-body","data-window-kind":e.kind,"aria-label":T(e),children:m})}):s.jsx("main",{className:"desktop-window-page",children:s.jsx("p",{className:"status-text",children:l("desktopWindow.unsupportedKind",{kind:e.kind})})})}export{le as DesktopWindowPage};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as u,j as i,t as r,A as Ln}from"./index-C2G8Gmf1.js";import{e as Wn,d as fi,f as di}from"./App-WOLwMld_.js";import{ae as hi,u as pi}from"./MobileSheet-Gzc14EpR.js";import{av as mi,r as Kt,w as yt,aw as bi,u as vi,X as Ne,ax as yi,ay as $t,az as dt,aA as xi,aB as gi,aC as Ci}from"./WorkbenchLayout-rwQib5In.js";import{W as Pi}from"./WorkbenchModal-B09hC9b5.js";import{a as wt,b as St,F as ji}from"./file-tree-icon-Dp_xhVfD.js";import"./window-BWqRixxq.js";import"./event-DvH9tcej.js";const wi=new Set([".ds_store","thumbs.db","ehthumbs.db","desktop.ini",".spotlight-v100",".trashes",".fseventsd","__macosx","$recycle.bin","system volume information",".apdisk",".appledouble",".temporaryitems"]),Si=["._"];function Ot(t){return t.split(/[/\\]/).filter(Boolean).pop()??t}function Ni(t){const n=t.trim().toLowerCase();return n?wi.has(n)||Si.some(a=>n.startsWith(a)):!1}function Xt(t,n,a){return a?[...t]:t.filter(o=>!Ni(n(o)))}function xt(t,n){return Xt(t,a=>a.name,n)}function Di(t,n){return n?t:Object.entries(t).reduce((a,[o,h])=>(a[o]=xt(h,!1),a),{})}async function Ht(t,n){const[a,o]=await Promise.all([mi(n),hi(t)]);return Ei(a.changes,o.items)}function Ei(t,n){const a=new Set(n.map(o=>Ct(o.path)));return t.filter(o=>a.has(Ct(o.path))||o.oldPath!==null&&a.has(Ct(o.oldPath)))}function ki(t){const n=Sn("","");for(const a of t){const o=Ct(a.path),h=o.split("/").filter(Boolean);let d=n;h.forEach((m,x)=>{const C=h.slice(0,x+1).join("/");if(x===h.length-1){d.children.set(`file:${C}`,{kind:"file",name:m,path:o,change:a});return}const R=`directory:${C}`,k=d.children.get(R);if(k&&k.kind==="directory"){d=k;return}const V=Sn(m,C);d.children.set(R,V),d=V})}return Hn(On([...n.children.values()]))}function $n(t,n){const a=t.oldPath?`${t.oldPath} -> ${t.path}`:t.path;return qt(t)?`${a} ${n}`:a}function qt(t){return t.status==="D"||t.stagedStatus==="D"||t.worktreeStatus==="D"}function gt(t){return t.split("/").filter(Boolean).pop()??t}function Ct(t){return t.replace(/\\/g,"/").replace(/^\.\//,"").trim()}function Sn(t,n){return{kind:"directory",name:t,path:n,children:new Map}}function On(t){return[...t].sort((n,a)=>n.kind!==a.kind?n.kind==="directory"?-1:1:n.name.localeCompare(a.name,"zh-CN")).map(n=>n.kind==="directory"?{kind:"directory",name:n.name,path:n.path,children:On([...n.children.values()])}:n)}function Hn(t){return t.map(n=>{var m;if(n.kind!=="directory")return n;const a=Hn(n.children);let o=n.name,h=n.path,d=a;for(;d.length===1&&((m=d[0])==null?void 0:m.kind)==="directory";){const x=d[0];o=`${o}/${x.name}`,h=x.path,d=x.children}return{kind:"directory",name:o,path:h,children:d}})}const Mi=450,_i=60*1e3,Nn=20,Dn=16;function Ri({sessionId:t,workspaceId:n,showSystemFiles:a,selectedPath:o,refreshVersion:h,onCountChange:d,onSelectFile:m,onOpenFile:x}){const[C,R]=u.useState("tree"),[k,V]=u.useState([]),[oe,L]=u.useState(!0),[ce,ue]=u.useState(!1),[W,tt]=u.useState([]),D=u.useRef(null),{showToast:me}=Wn();u.useEffect(()=>{const b=Kt(ht(n,t),_i);R("tree"),V(b??[]),L(b===null),ue(!1),tt([]),D.current=null},[t,n]),u.useEffect(()=>{let b=!1;async function v(){L(!0);try{const j=await Ht(t,n);b||(V(j),yt(ht(n,t),j))}catch(j){b||me({title:zt(j,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{b||L(!1)}}return v(),()=>{b=!0}},[h,t,me,n]);async function Dt(){L(!0);try{const b=await Ht(t,n);V(b),yt(ht(n,t),b)}catch(b){me({title:zt(b,r("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{L(!1)}}async function be(){if(De.length!==0){ue(!0);try{await bi(n,De.map(v=>v.path));const b=await Ht(t,n);V(b),yt(ht(n,t),b),me({title:r("conversation.filePanelSessionStageSuccess"),tone:"success"})}catch(b){me({title:zt(b,r("git.stageFailed")),tone:"error"})}finally{ue(!1)}}}function S(b){tt(v=>v.includes(b)?v.filter(j=>j!==b):[...v,b])}function B(b){const v=Date.now(),j=D.current;return D.current={filePath:b,timestamp:v},(j==null?void 0:j.filePath)===b&&v-j.timestamp<=Mi}async function $(b,v){if(v&&B(b)){await x(b),D.current=null;return}v||(D.current=null),await m(b)}const N=u.useMemo(()=>Xt(k,b=>gt(b.path),a),[k,a]),De=N.filter(b=>!b.staged),O=ki(N),Ee=new Set(W);return u.useEffect(()=>{d==null||d(N.length)},[d,N.length]),i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"file-panel-session-toolbar",children:[i.jsxs("div",{className:"file-panel-view-modes",role:"tablist","aria-label":r("conversation.filePanelSessionViewLabel"),children:[i.jsx("button",{className:C==="tree"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":C==="tree",onClick:()=>R("tree"),children:r("conversation.filePanelSessionTreeView")}),i.jsx("button",{className:C==="list"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":C==="list",onClick:()=>R("list"),children:r("conversation.filePanelSessionListView")})]}),i.jsxs("div",{className:"file-panel-session-actions",children:[i.jsx("button",{className:"secondary-button",type:"button",onClick:()=>void Dt(),disabled:oe||ce,children:r("conversation.filePanelRefresh")}),i.jsx("button",{className:"primary-button",type:"button",onClick:()=>void be(),disabled:ce||De.length===0,children:r("conversation.filePanelSessionStageAll")})]})]}),i.jsxs("div",{className:"file-panel-session-summary",children:[i.jsx("span",{children:`${r("conversation.filePanelSessionSummary")} ${N.length}`}),i.jsx("span",{children:`${r("conversation.filePanelSessionUnstagedSummary")} ${De.length}`})]}),i.jsx("div",{className:"file-tree",children:oe?i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSessionLoading")}):N.length===0?i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSessionEmpty")}):C==="tree"?zn({nodes:O,depth:0,collapsedPathSet:Ee,selectedPath:o,onToggleTreePath:S,onFileClick:$}):Ti({items:N,selectedPath:o,onFileClick:$})})]})}function zn({nodes:t,depth:n,collapsedPathSet:a,selectedPath:o,onToggleTreePath:h,onFileClick:d}){return t.map(m=>{if(m.kind==="directory"){const x=!a.has(m.path);return i.jsxs("div",{className:"file-tree-node",children:[i.jsxs("button",{className:"file-tree-item",type:"button","data-kind":"directory","aria-expanded":x,style:{paddingInlineStart:`${Nn+n*Dn}px`},onClick:()=>h(m.path),children:[i.jsx("span",{className:"file-tree-chevron","aria-hidden":"true",children:x?"v":">"}),i.jsx("span",{className:"file-tree-label",children:m.name})]}),x?i.jsx("div",{className:"file-tree-children",children:zn({nodes:m.children,depth:n+1,collapsedPathSet:a,selectedPath:o,onToggleTreePath:h,onFileClick:d})}):null]},`session-directory:${m.path}`)}return i.jsx("div",{className:"file-tree-node",children:i.jsxs("button",{className:"file-tree-item is-session-change",type:"button","data-active":o===m.change.path,"data-kind":"file",style:{paddingInlineStart:`${Nn+n*Dn}px`},onClick:()=>void d(m.change.path,!qt(m.change)),children:[i.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),i.jsx("span",{className:"git-tree-file-icon","data-kind":St(m.name),"aria-hidden":"true",children:wt(m.name)}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:m.name}),i.jsx("span",{className:"file-tree-path",children:$n(m.change,r("conversation.filePanelSessionDeleted"))})]}),i.jsxs("span",{className:"file-session-item-meta",children:[i.jsx("span",{className:"file-session-badge","data-status":m.change.status,children:m.change.status}),i.jsx("span",{className:"file-session-badge subtle",children:m.change.staged?r("git.stagedLabel"):r("git.workingTreeLabel")})]})]})},`session-file:${m.path}`)})}function Ti({items:t,selectedPath:n,onFileClick:a}){return t.map(o=>i.jsx("div",{className:"file-session-list-item",children:i.jsxs("button",{className:"file-session-list-button",type:"button","data-active":n===o.path,onClick:()=>void a(o.path,!qt(o)),children:[i.jsx("span",{className:"git-tree-file-icon","data-kind":St(gt(o.path)),"aria-hidden":"true",children:wt(gt(o.path))}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:gt(o.path)}),i.jsx("span",{className:"file-tree-path",children:$n(o,r("conversation.filePanelSessionDeleted"))})]}),i.jsxs("span",{className:"file-session-item-meta",children:[i.jsx("span",{className:"file-session-badge","data-status":o.status,children:o.status}),i.jsx("span",{className:"file-session-badge subtle",children:o.staged?r("git.stagedLabel"):r("git.workingTreeLabel")})]})]})},`session-list:${o.path}`))}function ht(t,n){return`file-panel.session-changes.${t}.${n}`}function zt(t,n){return t instanceof Ln?t.message:typeof t=="object"&&t&&"message"in t?String(t.message??n):n}const g="",Fi=450,Z=8,pt=4,Ai=176,Bi=120,Li=300*1e3,Wi=60*1e3,En=1600,$i=20,Oi=16;function Da({className:t,sessionId:n,workspaceId:a,hideHeading:o=!1,hideTabs:h=!1,externalRevealRequest:d=null,externalWindowMode:m=!1,workbenchShellOverrides:x}){var Pn,jn;const C=vi(),{navigationGroups:R,subscribeFileTree:k,requestFileTreeRefresh:V,addFileTreeSnapshotListener:oe,subscribeGitSnapshot:L,requestGitRefresh:ce,addGitSnapshotListener:ue}={...C,...x},[W,tt]=u.useState({}),[D,me]=u.useState([]),[Dt,be]=u.useState([]),[S,B]=u.useState(g),[$,N]=u.useState([]),[De,O]=u.useState(null),[Ee,b]=u.useState(!1),[v,j]=u.useState(!1),[E,nt]=u.useState(!1),[We,$e]=u.useState(!1),[Q,Oe]=u.useState(""),[Et,I]=u.useState(null),[it,at]=u.useState(!1),[st,lt]=u.useState(null),[H,He]=u.useState("workspace"),[Zt,rt]=u.useState(0),[Jt,kt]=u.useState(0),[ze,fe]=u.useState(!1),[Ue,z]=u.useState(!1),[ee,K]=u.useState(null),[de,ke]=u.useState(null),[T,Me]=u.useState(null),[F,Qt]=u.useState(null),[It,en]=u.useState([]),[G,Mt]=u.useState(!1),[qn,ve]=u.useState(null),te=u.useRef({}),ne=u.useRef({}),M=u.useRef([]),X=u.useRef(g),Ve=u.useRef(!1),Ke=u.useRef(null),tn=u.useRef(null),nn=u.useRef(null),_t=u.useRef(null),an=u.useRef(null),sn=u.useRef(null),ye=u.useRef(0),ie=u.useRef(new Map),{showToast:P}=Wn(),Ge=fi(),q=pi(e=>e.showSystemFiles),Xe=!!(n!=null&&n.trim()),ln=o&&Ge.isMobile;u.useEffect(()=>{Ne("file_panel.props",{sessionId:n,workspaceId:a,externalWindowMode:m})},[m,n,a]),u.useEffect(()=>{X.current=S},[S]);function xe(e){tt(s=>{const l=typeof e=="function"?e(s):e;return te.current=l,l})}function _e(e){me(s=>{const l=typeof e=="function"?e(s):e;return M.current=l,l})}u.useEffect(()=>{var f,p;if(At(),!a){At(),Ve.current=!1,te.current={},ne.current={},M.current=[],X.current=g,xe({}),_e([]),be([]),B(g),$e(!1),Oe(""),I(null),at(!1),b(!1),Mt(!1),ve(null),N([]),O(null),K(null),ke(null),Me(null);return}Ve.current=!0;const e=Kt(Tn(a),Li);Ne("file_panel.workspace_snapshot",{workspaceId:a,cached:!!e,cachedRootItems:((p=(f=e==null?void 0:e.treeCache)==null?void 0:f[g])==null?void 0:p.length)??0,cachedDirectoryCount:Object.keys((e==null?void 0:e.treeCache)??{}).length});const s=na((e==null?void 0:e.activeDirectoryPath)??g,(e==null?void 0:e.treeCache)??{}),l=Rn((e==null?void 0:e.expandedDirectories)??[],s),c=vt((e==null?void 0:e.treeCache)??{},s,l);te.current=c,ne.current=Fn((e==null?void 0:e.treeRevisionByPath)??{},c),M.current=l,X.current=s,xe(c),_e(l),be([]),B(s),b(!1),j(!1),$e(!1),Oe(""),I(null),at(!1),queueMicrotask(()=>{Ve.current=!1})},[a]),u.useEffect(()=>{if(!d||d.workspaceId!==a)return;const e=()=>{if(sn.current===d.requestId)return;sn.current=d.requestId,He("workspace"),(d.openViewer?Ae(d.filePath):pe(d.filePath)).catch(l=>{P({title:J(l,r("conversation.filePanelOpenFailed")),tone:"error"})})};if(Ve.current){queueMicrotask(e);return}e()},[d,Ae,pe,P,a]),u.useEffect(()=>{if(a)return oe(e=>{e.workspaceId===a&&(ne.current={...ne.current,[e.path]:typeof e.revision=="string"?e.revision:null},xe(s=>({...s,[e.path]:e.items})),e.path===g&&b(!1),be(s=>s.filter(l=>l!==e.path)),Jn(e.path,e.items))})},[oe,a]),u.useEffect(()=>()=>{At()},[]),u.useEffect(()=>{a&&k(a,Vt(M.current,X.current),{knownRevisionByPath:ne.current})},[S,D,k,a]),u.useEffect(()=>{N([]),O(null),lt(null),ve(null),rt(0),fe(!1),z(!1),K(null),ke(null),Me(null),Ke.current=null,ye.current+=1},[n]),u.useEffect(()=>{!Xe&&H==="session"&&He("workspace")},[H,Xe]),u.useEffect(()=>{h&&H!=="workspace"&&He("workspace")},[H,h]),u.useEffect(()=>{if(!ze&&!Ue&&!ee)return;function e(l){var y,w,se;if(!(l.target instanceof Node))return;const c=((y=tn.current)==null?void 0:y.contains(l.target))??!1,f=((w=nn.current)==null?void 0:w.contains(l.target))??!1,p=((se=_t.current)==null?void 0:se.contains(l.target))??!1;!c&&!f&&!p&&(fe(!1),z(!1),K(null),ke(null))}function s(l){l.key==="Escape"&&(fe(!1),z(!1),K(null),ke(null))}return document.addEventListener("pointerdown",e),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",s)}},[ze,Ue,ee]),u.useLayoutEffect(()=>{if(!ee||typeof window>"u"){ke(null);return}const e=ee;function s(){const c=_t.current;if(!c)return;const f=c.getBoundingClientRect();ke(qi({x:e.positionX,y:e.positionY},{width:f.width||Ai,height:f.height||c.scrollHeight||0},{width:window.innerWidth,height:window.innerHeight}))}s();const l=window.requestAnimationFrame(s);return window.addEventListener("resize",s),window.addEventListener("scroll",s,!0),()=>{window.cancelAnimationFrame(l),window.removeEventListener("resize",s),window.removeEventListener("scroll",s,!0)}},[ee]),u.useEffect(()=>{if(!a)return;const e=Rn(D,S),s=vt(W,S,e);yt(Tn(a),{treeCache:s,treeRevisionByPath:Fn(ne.current,s),expandedDirectories:e,activeDirectoryPath:S})},[S,D,W,a]),u.useEffect(()=>{if(Ve.current)return;const e=vt(W,S,D);aa(W,e)||xe(e)},[S,D,W]),u.useEffect(()=>{let e=!1;const s=(a==null?void 0:a.trim())??null;async function l(f){if(!s)return;const p=xt(te.current[g]??[],q),y=(f==null?void 0:f.silent)!==!0&&p.length===0;y&&b(!0),Ne("file_panel.load_root_tree.start",{sessionId:n,workspaceId:s,silent:(f==null?void 0:f.silent)===!0,cachedRootItems:p.length});try{const w=await Ft(g,{force:!0});e||(Ne("file_panel.load_root_tree.end",{sessionId:n,workspaceId:s,itemCount:w.length}),xe(se=>({...vt(se,X.current,M.current),[g]:w})))}catch(w){!e&&!An(w)&&P({title:J(w,r("conversation.filePanelLoadFailed")),tone:"error"})}finally{!e&&y&&b(!1)}}if(xt(te.current[g]??[],q).length>0){const f=window.setTimeout(()=>{s&&(k(s,Vt(M.current,X.current),{knownRevisionByPath:ne.current}),l({silent:!0}))},1500);return()=>{e=!0,window.clearTimeout(f)}}return l(),()=>{e=!0}},[n,q,P,a]),u.useEffect(()=>{if(!a||!n){kt(0);return}const e=Kt(sa(a,n),Wi);Ne("file_panel.session_change_count.snapshot",{sessionId:n,workspaceId:a,cached:e!==null,cachedCount:e}),kt(e??0)},[n,Zt,a]),u.useEffect(()=>{if(!a){en([]);return}const e=a.trim();L(e),ce(e)},[a,L,ce]),u.useEffect(()=>{if(!a)return;const e=a.trim();return ue(s=>{var l;s.workspaceId===e&&en(((l=s.status)==null?void 0:l.changes)??[])})},[ue,a]);const ot=u.useMemo(()=>Xt(It,e=>Ot(e.path),q),[It,q]),A=u.useMemo(()=>{const e=new Map,s=new Set;for(const l of ot){const c=l.path.replace(/\\/g,"/"),f=l.worktreeStatus??l.stagedStatus??l.status;e.set(c,f);const p=c.split("/");for(let y=1;y<p.length;y++)s.add(p.slice(0,y).join("/"))}return{statusByPath:e,changedDirs:s}},[ot]),ge=u.useMemo(()=>Di(W,q),[q,W]),Ce=u.useMemo(()=>Et===null?null:xt(Et,q),[Et,q]),Re=ge[g]??[],Pe=We&&Ce!==null,ct=u.useMemo(()=>G?Gt(Re,ge,A.statusByPath,A.changedDirs):Re,[A.changedDirs,A.statusByPath,Re,G,ge]),Yn=u.useMemo(()=>Pe?(Ce??[]).map(e=>U(e.path,e.kind)):Un(ct,ge,D,G,A.statusByPath,A.changedDirs),[D,A.changedDirs,A.statusByPath,Pe,G,Ce,ge,ct]),Te=((Pn=R.find(e=>e.workspace.id===a))==null?void 0:Pn.workspace)??null,_=_n($),Rt=(_==null?void 0:_.path)??null,he=(_==null?void 0:_.kind)==="file"?_.path:null,ut=u.useMemo(()=>new Set($.map(e=>e.path)),[$]),qe=u.useMemo(()=>bt($),[$]),Tt=!!(Te!=null&&Te.path&&$.length===1&&Rt),rn=$.length===1&&(_==null?void 0:_.kind)==="file",on=qe.length>0,je=qe.length>0,Ye=!!(F!=null&&F.items.length&&a),cn=!!((he?re(he):S)&&D.length);async function un(e,s=!1){if(!a)return[];if(!s){const l=te.current[e];if(l)return l}e===g?b(!0):be(l=>jt(l,e));try{const l=await Ft(e,{force:s});return xe(c=>({...c,[e]:l})),l}catch(l){throw An(l)||P({title:J(l,r("conversation.filePanelLoadFailed")),tone:"error"}),l}finally{e===g?b(!1):be(l=>l.filter(c=>c!==e))}}async function we(e){if(!a)return;const s=(e==null?void 0:e.activeDirectoryPath)??X.current,l=(e==null?void 0:e.expandedDirectories)??M.current,c=ia(te.current,s,l);Ne("file_panel.refresh_tree_cache.start",{sessionId:n,workspaceId:a,targetDirectories:c});const p=(await Promise.all(c.map(async y=>{const w=await Ft(y,{force:!0});return[y,w]}))).reduce((y,[w,se])=>(y[w]=se,y),{});Ne("file_panel.refresh_tree_cache.end",{sessionId:n,workspaceId:a,targetDirectories:c,directoryCount:Object.keys(p).length}),xe(p)}async function Ft(e,s){if(!a)return[];if(!(s!=null&&s.force)){const c=te.current[e];if(c)return c}const l=Vt(jt(M.current,e),e||X.current);return k(a,l,{knownRevisionByPath:ne.current}),V(a,[e],{knownRevisionByPath:ne.current}),Zn(e,En,{allowCached:(s==null?void 0:s.force)!==!0})}function Zn(e,s=En,l){const c=te.current[e];return(l==null?void 0:l.allowCached)!==!1&&c?Promise.resolve(c):new Promise((f,p)=>{const y=window.setTimeout(()=>{Qn(e,y),p(new Error(`FILE_TREE_SNAPSHOT_TIMEOUT:${e}`))},s),w=ie.current.get(e)??[];ie.current.set(e,[...w,{resolve:f,reject:p,timerId:y}])})}function Jn(e,s){const l=ie.current.get(e)??[];l.length!==0&&(ie.current.delete(e),l.forEach(c=>{window.clearTimeout(c.timerId),c.resolve(s)}))}function Qn(e,s){const c=(ie.current.get(e)??[]).filter(f=>f.timerId!==s);if(c.length===0){ie.current.delete(e);return}ie.current.set(e,c)}function At(){for(const[e,s]of ie.current.entries())s.forEach(l=>{window.clearTimeout(l.timerId),l.reject(new Error(`FILE_TREE_ABORTED:${e}`))});ie.current.clear()}function Ze(e){N([e]),O(e.path)}function Je(e){B(e.kind==="directory"?e.path:re(e.path))}function In(e){const s=Ui(Yn,De,e);N(s),O(e.path),Je(e)}function ei(e){const s=zi($,e),l=_n(s);N(s),O(e.path),l&&Je(l)}function fn(e){Ze(e),Je(e)}function Fe(e,s){if(s!=null&&s.shiftKey){In(e);return}if(mt(s)){ei(e);return}fn(e)}async function ft(e,s=!1){const l=et(e,s);if(!l.length){B(g);return}_e(c=>Gn(c,l)),B(l[l.length-1]??g);for(const c of l)try{await un(c)}catch{return}}async function pe(e){const s=U(e,"file");Ze(s),Je(s),await ft(e)}async function Ae(e){lt(e),ve(null),Ke.current=null,ye.current+=1,pe(e);const s=ye.current,l=e.replace(/\\/g,"/"),c=A.statusByPath.get(l);if(a&&c&&c!=="?"&&c!=="D")try{const f=await yi(a,e,!1);ye.current===s&&ve(f.content||null)}catch{ye.current===s&&ve(null)}}function dn(e){const s=Date.now(),l=Ke.current;return Ke.current={filePath:e,timestamp:s},(l==null?void 0:l.filePath)===e&&s-l.timestamp<=Fi}function Se(){Ke.current=null}async function ti(e,s){const l=U(e,"file");if(s!=null&&s.shiftKey||mt(s)){Se(),Fe(l,s);return}if(dn(e)){await Ae(e);return}Fe(l,s),await ft(e)}function hn(){$e(!1),Oe(""),I(null),Se()}async function ni(e,s){const l=U(e.path,e.kind);if(s!=null&&s.shiftKey||mt(s)){Se(),Fe(l,s);return}if(e.kind==="directory"){hn(),Fe(l,s),await pn(e.path);return}if(dn(e.path)){hn(),await Ae(e.path);return}await pe(e.path)}async function pn(e){if(Ze(U(e,"directory")),B(e),!M.current.includes(e))try{await un(e),_e(s=>jt(s,e))}catch{}}async function mn(e){if(Ze(U(e,"directory")),B(e),M.current.includes(e)){bn(e);return}await pn(e)}function bn(e){_e(s=>s.filter(l=>l!==e&&!l.startsWith(`${e}/`))),B(re(e)),N([]),O(null)}async function vn(){if(!a)return;const e=a;try{if(ce(e),await we(),he&&await ft(he),Pe&&Q.trim()){const s=await dt(e,Q.trim());I(s.items)}}catch(s){P({title:J(s,r("conversation.filePanelLoadFailed")),tone:"error"})}}async function ii(e){if(e==null||e.preventDefault(),!a||!Q.trim()){I(null);return}at(!0);try{const s=await dt(a,Q.trim());I(s.items)}catch(s){P({title:J(s,r("conversation.filePanelSearchFailed")),tone:"error"})}finally{at(!1)}}function yn(){if(We){$e(!1),Oe(""),I(null);return}$e(!0)}function Y(e){z(!1),e()}function xn(){var e;(e=an.current)==null||e.click()}async function ai(e){var p;const s=((p=e.target.files)==null?void 0:p[0])??null;if(e.target.value="",!s||!a)return;const l=Hi(s.name);if(!l){P({title:r("conversation.filePanelUploadFailed"),tone:"error"});return}const c=kn(S,_),f=Mn(c,l);nt(!0);try{const y=await Ji(s);await xi({workspaceId:a,path:f,contentBase64:y}),await we(),await pe(f),P({title:r("conversation.filePanelUploadSuccess",{name:l}),tone:"success"})}catch(y){P({title:J(y,r("conversation.filePanelUploadFailed")),tone:"error"})}finally{nt(!1)}}async function Bt(e=he){if(!(!a||!e)){nt(!0);try{const s=await gi(a,e),l=Qi(s.contentBase64);Ii(s.fileName,new Blob([l],{type:"application/octet-stream"})),P({title:r("conversation.filePanelDownloadSuccess",{name:s.fileName}),tone:"success"})}catch(s){P({title:J(s,r("conversation.filePanelDownloadFailed")),tone:"error"})}finally{nt(!1)}}}function gn(){const e=he?re(he):S;!e||!M.current.includes(e)||bn(e)}async function Be(e,s=kn(S,_)){if(!a)return;const l=s,c=l?`${l}/`:"",f=window.prompt(e==="create_file"?r("conversation.filePanelCreateFilePrompt"):r("conversation.filePanelCreateDirectoryPrompt"),c);if(!(f!=null&&f.trim()))return;const p=f.trim();j(!0);try{await $t({workspaceId:a,opType:e,dstPath:p,content:e==="create_file"?"":void 0}),await we(),e==="create_directory"?(await ft(p,!0),Ze(U(p,"directory")),B(p)):await pe(p)}catch(y){P({title:J(y,r("conversation.filePanelMutateFailed")),tone:"error"})}finally{j(!1)}}function ae(e,s=qe){var c;if(s.length===0)return;const l=bt(s);Qt({mode:e,items:l}),N(l),O(((c=l[l.length-1])==null?void 0:c.path)??null),P({title:e==="copy"?r("conversation.filePanelCopySelectionSuccess",{count:l.length}):r("conversation.filePanelCutSelectionSuccess",{count:l.length}),tone:"success"}),K(null)}async function Qe(e=Gi(_,S)){if(!a||!F||!F.items.length)return;const s=e??g,l=F.items.map(c=>({source:c,destinationPath:Mn(s,Ot(c.path)||c.path)}));j(!0);try{for(const p of l)F.mode==="cut"&&Pt(p.source.path)===Pt(p.destinationPath)||await $t({workspaceId:a,opType:F.mode==="copy"?"copy":"move",srcPath:p.source.path,dstPath:p.destinationPath});const c=l.map(p=>U(p.destinationPath,p.source.kind)),f=c[c.length-1]??null;if(F.mode==="cut"&&Qt(null),N(c),O((f==null?void 0:f.path)??null),f&&Je(f),Se(),await we({activeDirectoryPath:(f==null?void 0:f.kind)==="directory"?f.path:f?re(f.path):X.current,expandedDirectories:M.current}),Pe&&Q.trim()){const p=await dt(a,Q.trim());I(p.items)}rt(p=>p+1),P({title:r("conversation.filePanelPasteSuccess",{count:c.length}),tone:"success"}),K(null)}catch(c){await we().catch(()=>{}),P({title:J(c,r("conversation.filePanelPasteFailed")),tone:"error"})}finally{j(!1)}}function Lt(e=qe){!e.length||v||(Me(bt(e)),K(null))}async function si(){var s,l;if(!a||!(T!=null&&T.length))return;const e=bt(T);j(!0);try{for(const p of e)await $t({workspaceId:a,opType:"delete",srcPath:p.path});const c=Xi(S,e),f=M.current.filter(p=>!e.some(y=>y.kind==="directory"&&Nt(y.path,p)));if(st&&e.some(p=>Nt(p.path,st))&&(ye.current+=1,lt(null),ve(null)),Me(null),N([]),O(null),X.current=c,M.current=f,B(c),_e(f),Se(),await we({activeDirectoryPath:c,expandedDirectories:f}),Pe&&Q.trim()){const p=await dt(a,Q.trim());I(p.items)}rt(p=>p+1),P({title:e.length===1?r("conversation.filePanelDeleteSuccess",{name:Ot(((s=e[0])==null?void 0:s.path)??"")||((l=e[0])==null?void 0:l.path)||""}):r("conversation.filePanelDeleteSelectionSuccess",{count:e.length}),tone:"success"})}catch(c){P({title:J(c,r("conversation.filePanelMutateFailed")),tone:"error"})}finally{j(!1)}}async function Le(e,s=_){const l=(Te==null?void 0:Te.path)??"",c=(s==null?void 0:s.path)??null;if(c===null||!l){fe(!1);return}try{const f=Zi(l),p=e==="absolute"?Yi(l,c,f):Pt(c,f);await ea(p,Ge),P({title:e==="absolute"?r("conversation.filePanelCopyAbsolutePathSuccess"):r("conversation.filePanelCopyRelativePathSuccess"),tone:"success"})}catch(f){P({title:f instanceof Error?f.message:r("conversation.filePanelCopyPathFailed"),tone:"error"})}finally{fe(!1),K(null)}}function li(e,s,l){return[{id:`open-${e.path}`,label:e.kind==="directory"?D.includes(e.path)?r("conversation.filePanelCollapseDirectory"):r("conversation.filePanelExpandDirectory"):r("conversation.filePanelOpenFile"),onSelect:()=>{if(e.kind==="directory"){mn(e.path);return}Ae(e.path)}},{id:`download-${e.path}`,label:r("conversation.filePanelDownload"),disabled:e.kind!=="file"||E,onSelect:()=>{Bt(e.kind==="file"?e.path:null)}},{id:`create-file-${e.path}`,label:r("conversation.filePanelNewFile"),disabled:!a||v||E,onSelect:()=>{Be("create_file",l)}},{id:`create-directory-${e.path}`,label:r("conversation.filePanelNewDirectory"),disabled:!a||v||E,onSelect:()=>{Be("create_directory",l)}},{id:`copy-${e.path}`,label:r("conversation.filePanelCopy"),disabled:s.length===0,onSelect:()=>ae("copy",s)},{id:`cut-${e.path}`,label:r("conversation.filePanelCut"),disabled:s.length===0,onSelect:()=>ae("cut",s)},{id:`paste-${e.path}`,label:r("conversation.filePanelPaste"),disabled:!Ye,onSelect:()=>{Qe(l)}},{id:`copy-relative-${e.path}`,label:r("conversation.filePanelCopyRelativePath"),onSelect:()=>{Le("relative",e)}},{id:`copy-absolute-${e.path}`,label:r("conversation.filePanelCopyAbsolutePath"),onSelect:()=>{Le("absolute",e)}},{id:`delete-${e.path}`,label:r("conversation.filePanelDelete"),disabled:s.length===0||v||E,onSelect:()=>Lt(s)}]}async function Cn(e,s){if(Ge.isMobile)return;e.preventDefault();const l=U(s.path,s.kind),c=ut.has(l.path)?qe:[l],f=l.kind==="directory"?l.path:re(l.path);ut.has(l.path)||fn(l);const p=li(l,c,f);if(Ge.isDesktop){await Ci(p);return}Ge.isWeb&&(fe(!1),z(!1),K({positionX:e.clientX,positionY:e.clientY,items:p}))}u.useEffect(()=>{if(H!=="workspace")return;function e(s){if(!Vi(s)||s.altKey||s.shiftKey||Ki(s.target))return;const l=s.key.toLowerCase();if(l==="c"&&je){s.preventDefault(),ae("copy");return}if(l==="x"&&je){s.preventDefault(),ae("cut");return}l==="v"&&Ye&&(s.preventDefault(),Qe())}return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[H,je,Ye,ae,Qe]);function Wt(e,s){return i.jsx(i.Fragment,{children:e.map(l=>{const c=U(l.path,l.kind),f=l.kind==="directory",p=f&&D.includes(l.path),y=f&&Dt.includes(l.path),w=ge[l.path]??[],se=G?Gt(w,ge,A.statusByPath,A.changedDirs):w,oi=ut.has(l.path),ci=Rt===l.path,Ie=A.statusByPath.get(l.path.replace(/\\/g,"/")),wn=f&&A.changedDirs.has(l.path.replace(/\\/g,"/")),ui=(F==null?void 0:F.mode)==="cut"&&F.items.some(le=>le.path===l.path);return i.jsxs("div",{className:"file-tree-node",children:[i.jsxs("button",{className:"file-tree-item",type:"button","data-active":ci,"data-selected":oi,"data-cut-pending":ui||void 0,"data-kind":l.kind,"aria-expanded":f?p:void 0,style:{paddingInlineStart:`${$i+s*Oi}px`},onClick:le=>{if(f){if(le.shiftKey||mt(le)){Se(),Fe(c,le);return}Se(),Fe(c,le),mn(l.path);return}ti(l.path,le)},onContextMenu:le=>{Cn(le,l)},children:[i.jsx("span",{className:`file-tree-chevron${f?"":" is-hidden"}`,"aria-hidden":"true",children:p?"v":">"}),f?null:i.jsx("span",{className:"git-tree-file-icon","data-kind":St(l.name),"aria-hidden":"true",children:wt(l.name)}),i.jsx("span",{className:"file-tree-label","data-status":Ie??void 0,"data-has-changes":wn||void 0,children:l.name}),!f&&Ie?i.jsx("span",{className:"git-status-badge","data-status":Ie,"aria-label":Ie,children:Ie}):null,f&&wn?i.jsx("span",{className:"file-tree-dir-badge","aria-hidden":"true"}):null,y?i.jsx("span",{className:"file-tree-meta",children:r("common.loading")}):null]}),f&&p?i.jsx("div",{className:"file-tree-children",children:y&&!w.length?i.jsx("p",{className:"file-tree-empty",children:r("common.loading")}):se.length?Wt(se,s+1):i.jsx("p",{className:"file-tree-empty",children:r("conversation.filePanelEmptyDirectory")})}):null]},`${l.kind}-${l.path}`)})})}function ri(e){return i.jsx(i.Fragment,{children:e.map(s=>{const l=s.kind==="directory",c=ut.has(s.path),f=Rt===s.path;return i.jsx("div",{className:"file-tree-node",children:i.jsxs("button",{className:"file-tree-item is-search-result",type:"button","data-active":f,"data-selected":c,"data-kind":s.kind,onClick:p=>{ni(s,p)},onContextMenu:p=>{Cn(p,s)},children:[i.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),l?null:i.jsx("span",{className:"git-tree-file-icon","data-kind":St(s.name),"aria-hidden":"true",children:wt(s.name)}),i.jsxs("span",{className:"file-tree-label",children:[i.jsx("span",{className:"file-tree-name",children:s.name}),i.jsx("span",{className:"file-tree-path",children:s.path})]})]})},`search-${s.kind}-${s.path}`)})})}return i.jsx("section",{className:["conversation-panel","surface-card","file-panel",t].filter(Boolean).join(" "),"data-testid":"file-context-panel",children:a?i.jsxs(i.Fragment,{children:[i.jsx(ji,{workspaceId:a,filePath:st,open:st!==null,onClose:()=>{ye.current+=1,lt(null),ve(null)},onSaved:async e=>{await we(),await pe(e),rt(s=>s+1)},diffContent:qn}),o?null:i.jsx("div",{className:"file-panel-heading-row",children:i.jsx("h2",{className:"file-panel-heading",children:r("conversation.filePanelTitle")})}),h?null:i.jsxs("div",{className:"file-panel-tabs",role:"tablist","aria-label":r("conversation.filePanelTitle"),children:[i.jsx("button",{className:H==="workspace"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":H==="workspace",onClick:()=>He("workspace"),children:r("conversation.filePanelWorkspaceTab")}),i.jsxs("button",{className:H==="session"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":H==="session",onClick:()=>{Xe&&He("session")},disabled:!Xe,children:[r("conversation.filePanelSessionTab"),i.jsx("span",{className:"file-panel-tab-badge","aria-label":`${r("conversation.filePanelSessionTab")} ${Jt}`,children:Jt})]})]}),H==="workspace"?i.jsxs(i.Fragment,{children:[i.jsx("input",{ref:an,"data-testid":"file-panel-upload-input",type:"file",hidden:!0,onChange:e=>void ai(e)}),ln?i.jsx("div",{className:"file-panel-toolbar file-panel-toolbar-mobile","aria-label":r("conversation.filePanelTitle"),children:i.jsxs("div",{className:"file-mobile-action-shell",ref:nn,children:[i.jsxs("button",{className:"secondary-button file-mobile-action-trigger",type:"button","aria-label":r("conversation.filePanelActionsMenu"),"aria-haspopup":"menu","aria-expanded":Ue,"data-active":Ue,onClick:()=>{fe(!1),z(e=>!e)},children:[i.jsx("span",{children:r("conversation.filePanelActionsMenu")}),i.jsx(va,{})]}),Ue?i.jsxs("div",{className:"file-mobile-action-menu",role:"menu","aria-label":r("conversation.filePanelActionsMenu"),children:[i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>ae("copy")),disabled:!je,children:r("conversation.filePanelCopy")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>ae("cut")),disabled:!je,children:r("conversation.filePanelCut")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Qe()),disabled:!Ye||v||E,children:r("conversation.filePanelPaste")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{z(!1),yn()},children:We?r("conversation.filePanelHideSearch"):r("conversation.filePanelShowSearch")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{z(!1),Mt(e=>!e)},disabled:ot.length===0,children:G?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(vn),disabled:Ee||v||it,children:r("conversation.filePanelRefresh")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{z(!1),gn()},disabled:!cn,children:r("conversation.filePanelCollapseCurrent")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{z(!1),xn()},disabled:v||E,children:r("conversation.filePanelUpload")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(Bt),disabled:!rn||E,children:r("conversation.filePanelDownload")}),i.jsx("button",{className:"file-mobile-action-menu-item danger",type:"button",role:"menuitem",onClick:()=>Y(Lt),disabled:!on||v||E,children:r("conversation.filePanelDelete")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Be("create_file")),disabled:v||E,children:r("conversation.filePanelNewFile")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Be("create_directory")),disabled:v||E,children:r("conversation.filePanelNewDirectory")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Le("absolute")),disabled:!Tt,children:r("conversation.filePanelCopyAbsolutePath")}),i.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Le("relative")),disabled:!Tt,children:r("conversation.filePanelCopyRelativePath")})]}):null]})}):i.jsxs("div",{className:"file-panel-toolbar","aria-label":r("conversation.filePanelTitle"),children:[i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCopy"),"aria-label":r("conversation.filePanelCopy"),onClick:()=>ae("copy"),disabled:!je,children:i.jsx(ca,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCut"),"aria-label":r("conversation.filePanelCut"),onClick:()=>ae("cut"),disabled:!je,children:i.jsx(ua,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelPaste"),"aria-label":r("conversation.filePanelPaste"),onClick:()=>void Qe(),disabled:!Ye||v||E,children:i.jsx(fa,{})}),i.jsxs("div",{className:"file-toolbar-menu-shell",ref:tn,children:[i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCopyPath"),"aria-label":r("conversation.filePanelCopyPath"),"aria-haspopup":"menu","aria-expanded":ze,"data-active":ze,onClick:()=>{z(!1),fe(e=>!e)},disabled:!Tt,children:i.jsx(oa,{})}),ze?i.jsxs("div",{className:"file-toolbar-menu",role:"menu",children:[i.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Le("absolute"),children:r("conversation.filePanelCopyAbsolutePath")}),i.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Le("relative"),children:r("conversation.filePanelCopyRelativePath")})]}):null]}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelCollapseCurrent"),"aria-label":r("conversation.filePanelCollapseCurrent"),onClick:gn,disabled:!cn,children:i.jsx(la,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelRefresh"),"aria-label":r("conversation.filePanelRefresh"),onClick:()=>void vn(),disabled:Ee||v||it,children:i.jsx(ra,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelSearchButton"),"aria-label":r("conversation.filePanelSearchButton"),"data-active":We,onClick:yn,disabled:Ee,children:i.jsx(Bn,{})}),ot.length>0?i.jsx("button",{className:"file-toolbar-button",type:"button",title:G?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges"),"aria-label":G?r("conversation.filePanelShowAll"):r("conversation.filePanelFilterChanges"),"data-active":G,onClick:()=>Mt(e=>!e),children:i.jsx(ya,{})}):null,i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelUpload"),"aria-label":r("conversation.filePanelUpload"),onClick:xn,disabled:v||E,children:i.jsx(ha,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelDownload"),"aria-label":r("conversation.filePanelDownload"),onClick:()=>void Bt(),disabled:!rn||E,children:i.jsx(pa,{})}),i.jsx("button",{className:"file-toolbar-button danger",type:"button",title:r("conversation.filePanelDelete"),"aria-label":r("conversation.filePanelDelete"),onClick:()=>Lt(),disabled:!on||v||E,children:i.jsx(ma,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelNewFile"),"aria-label":r("conversation.filePanelNewFile"),onClick:()=>void Be("create_file"),disabled:v||E,children:i.jsx(da,{})}),i.jsx("button",{className:"file-toolbar-button",type:"button",title:r("conversation.filePanelNewDirectory"),"aria-label":r("conversation.filePanelNewDirectory"),onClick:()=>void Be("create_directory"),disabled:v||E,children:i.jsx(ba,{})})]}),ee&&typeof document<"u"?di.createPortal(i.jsx("div",{className:"file-web-context-menu",ref:_t,role:"menu","aria-label":r("conversation.filePanelActionsMenu"),style:{left:`${(de==null?void 0:de.left)??Math.max(8,ee.positionX)}px`,top:`${(de==null?void 0:de.top)??Math.max(8,ee.positionY)}px`,maxHeight:de?`${de.maxHeight}px`:void 0},children:ee.items.map(e=>i.jsx("button",{className:["file-web-context-menu-item",e.label===r("conversation.filePanelDelete")?"danger":""].filter(Boolean).join(" "),type:"button",role:"menuitem",disabled:e.disabled,onClick:()=>{K(null),e.onSelect()},children:e.label},e.id))}),document.body):null,We?i.jsxs("form",{className:"file-toolbar-search",onSubmit:e=>void ii(e),children:[i.jsx("input",{value:Q,onChange:e=>Oe(e.target.value),placeholder:r("conversation.filePanelSearchPlaceholder")}),ln?i.jsx("button",{className:"secondary-button file-mobile-search-submit",type:"submit","aria-label":r("conversation.filePanelSearchButton"),disabled:it,children:r("conversation.filePanelSearchButton")}):i.jsx("button",{className:"file-toolbar-button",type:"submit",title:r("conversation.filePanelSearchButton"),"aria-label":r("conversation.filePanelSearchButton"),disabled:it,children:i.jsx(Bn,{})})]}):null,i.jsx("div",{className:"file-tree","data-search-mode":Pe,children:Ee&&Re.length===0?i.jsx("p",{className:"file-tree-status status-text",children:r("common.loading")}):Pe?Ce!=null&&Ce.length?ri(Ce):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelSearchEmpty")}):G?ct.length?Wt(ct,0):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelNoChanges")}):Re.length?Wt(Re,0):i.jsx("p",{className:"file-tree-status status-text",children:r("conversation.filePanelEmptyDirectory")})}),i.jsxs(Pi,{open:T!==null,title:r("conversation.filePanelDeleteConfirmTitle"),description:r("conversation.filePanelDeleteConfirmDescription"),onClose:()=>{v||Me(null)},children:[i.jsx("p",{className:"workbench-section-empty",children:T!=null&&T.length?T.length===1?((jn=T[0])==null?void 0:jn.kind)==="directory"?r("conversation.filePanelDeleteDirectoryConfirm",{path:T[0].path}):r("conversation.filePanelDeleteFileConfirm",{path:T[0].path}):r("conversation.filePanelDeleteSelectionConfirm",{count:T.length}):""}),i.jsxs("div",{className:"workbench-modal-actions",children:[i.jsx("button",{type:"button",className:"secondary-button",disabled:v,onClick:()=>Me(null),children:r("common.cancel")}),i.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:v,onClick:()=>{si()},children:v?r("conversation.filePanelDeleting"):r("conversation.filePanelDelete")})]})]})]}):Xe&&n?i.jsx(Ri,{sessionId:n,workspaceId:a,showSystemFiles:q,selectedPath:he,refreshVersion:Zt,onCountChange:kt,onSelectFile:pe,onOpenFile:Ae}):i.jsx("section",{className:"file-panel-section",children:i.jsx("p",{className:"status-text",children:r("conversation.filePanelSessionNoSession")})})]}):i.jsx("section",{className:"file-panel-section",children:i.jsx("p",{className:"status-text",children:r("conversation.filePanelNoWorkspace")})})})}function re(t){return t.includes("/")?t.split("/").slice(0,-1).join("/"):g}function et(t,n=!1){const a=t.split("/").filter(Boolean),o=n?a.length:a.length-1,h=[];for(let d=0;d<o;d+=1)h.push(a.slice(0,d+1).join("/"));return h}function kn(t,n){return t||((n==null?void 0:n.kind)==="directory"?n.path:n!=null&&n.path?re(n.path):g)}function Mn(t,n){return t?`${t}/${n}`:n}function Hi(t){var n;return((n=t.split(/[/\\]/).pop())==null?void 0:n.trim())??""}function U(t,n){return{path:t,kind:n}}function _n(t){return t[t.length-1]??null}function zi(t,n){return t.findIndex(o=>o.path===n.path)>=0?t.filter(o=>o.path!==n.path):[...t,n]}function Ui(t,n,a){const o=t.findIndex(x=>x.path===a.path);if(o<0)return[a];const h=n?t.findIndex(x=>x.path===n):o;if(h<0)return[a];const d=Math.min(h,o),m=Math.max(h,o);return t.slice(d,m+1)}function mt(t){return!!(t!=null&&t.ctrlKey||t!=null&&t.metaKey)}function Vi(t){return t.ctrlKey||t.metaKey}function Ki(t){if(!(t instanceof HTMLElement))return!1;const n=t.tagName.toLowerCase();return n==="input"||n==="textarea"||n==="select"||t.isContentEditable}function bt(t){const n=[...new Map(t.map(o=>[o.path,o])).values()].sort((o,h)=>o.path.localeCompare(h.path)),a=[];for(const o of n)a.some(h=>h.kind==="directory"&&Nt(h.path,o.path))||a.push(o);return a}function Gi(t,n){return(t==null?void 0:t.kind)==="directory"?t.path:t!=null&&t.path?re(t.path):n}function Xi(t,n){let a=t;for(;a&&n.some(o=>o.kind==="directory"&&Nt(o.path,a));)a=re(a);return a}function Un(t,n,a,o,h,d){const m=[];for(const x of t){if(m.push(U(x.path,x.kind)),x.kind!=="directory"||!a.includes(x.path))continue;const C=n[x.path]??[],R=o?Gt(C,n,h,d):C;m.push(...Un(R,n,a,o,h,d))}return m}function qi(t,n,a){const o=Math.max(0,a.width),h=Math.max(0,a.height),d=Math.max(0,h-Z*2),m=Math.max(0,o-Z*2),x=Math.min(Math.max(n.width,0),m),C=Math.max(0,h-t.y-pt-Z),R=Math.max(0,t.y-pt-Z),k=C<n.height&&R>C,oe=Ut(Math.max(k?R:C,Bi),0,d),L=Math.min(Math.max(n.height,0),oe),ce=k?t.y-pt-L:t.y+pt,ue=Math.max(Z,h-Z-L),W=Math.max(Z,o-Z-x);return{top:Ut(ce,Z,ue),left:Ut(t.x,Z,W),maxHeight:Math.max(0,oe)}}function Ut(t,n,a){return!Number.isFinite(t)||a<n?n:Math.min(Math.max(t,n),a)}function Pt(t,n="posix"){return t?Vn(t,n):"."}function Yi(t,n,a){const o=Vn(t,a),h=Pt(n,a).replace(/^\.[/\\]?/,"");if(!h)return o;const d=Kn(a),m=h.replace(/^[/\\]+/,"");return m?o.endsWith("/")||o.endsWith("\\")?`${o}${m}`:`${o}${d}${m}`:o}function Zi(t){return/^[a-zA-Z]:[\\/]/.test(t)||t.includes("\\")?"windows":"posix"}function Vn(t,n){return t&&(Kn(n)==="\\"?t.replace(/\//g,"\\"):t.replace(/\\/g,"/"))}function Kn(t){return t==="windows"?"\\":"/"}function Nt(t,n){return n===t||n.startsWith(`${t}/`)}async function Ji(t){const n=await t.arrayBuffer(),a=new Uint8Array(n),o=32768;let h="";for(let d=0;d<a.length;d+=o){const m=a.subarray(d,d+o);h+=String.fromCharCode(...m)}return btoa(h)}function Qi(t){const n=atob(t),a=new Uint8Array(n.length);for(let o=0;o<n.length;o+=1)a[o]=n.charCodeAt(o);return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}function Ii(t,n){if(typeof document>"u")throw new Error(r("conversation.filePanelDownloadFailed"));const a=window.URL.createObjectURL(n),o=document.createElement("a");o.href=a,o.download=t,document.body.append(o),o.click(),o.remove(),window.URL.revokeObjectURL(a)}async function ea(t,n){var a;if(!(n.isDesktop&&(await n.bridge.writeClipboardText(t)).ok)){if(typeof navigator<"u"&&((a=navigator.clipboard)!=null&&a.writeText))try{await navigator.clipboard.writeText(t);return}catch{}if(!ta(t))throw new Error(r("conversation.filePanelCopyPathFailed"))}}function ta(t){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.top="-9999px",n.style.left="-9999px",n.style.opacity="0",document.body.appendChild(n),n.focus(),n.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(n)}}function na(t,n){return t&&et(t,!0).every(h=>h in n)?t:g}function Rn(t,n){if(!n)return[];const a=et(n,!0);return t.filter(o=>a.includes(o))}function vt(t,n,a){const o=Yt(n,a);return Object.entries(t).reduce((h,[d,m])=>(o.has(d)&&(h[d]=m),h),{})}function ia(t,n,a){const h=[...Yt(n,a)].filter(d=>d===g||d in t);return h.length?h:[g]}function Yt(t,n){const a=new Set([g]),o=Gn(n,et(t,!0));for(const h of o){a.add(h);for(const d of et(h,!0))a.add(d)}return a}function aa(t,n){const a=Object.keys(t),o=Object.keys(n);return a.length!==o.length?!1:a.every(h=>t[h]===n[h])}function jt(t,n){return t.includes(n)?t:[...t,n]}function Gn(t,n){return n.reduce((a,o)=>jt(a,o),t)}function Tn(t){return`file-panel.workspace-tree.${t}`}function sa(t,n){return`file-panel.session-change-count.${t}.${n}`}function Fn(t,n){return Object.fromEntries(Object.keys(n).map(a=>[a,t[a]??null]))}function Vt(t,n){return[...Yt(n,t)]}function J(t,n){return t instanceof Ln?t.message:n}function An(t){return t instanceof Error&&(t.message.startsWith("FILE_TREE_SNAPSHOT_TIMEOUT:")||t.message.startsWith("FILE_TREE_ABORTED:"))}function la(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M2.5 4.5h11v2h-11zM2.5 7.5h7v2h-7zM2.5 10.5h4v2h-4z",fill:"currentColor"})})}function ra(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M12.8 5.2A5.5 5.5 0 1 0 13.5 8h-1.8A3.7 3.7 0 1 1 10.6 5l-1.4 1.4h4V2l-1.4 1.4z",fill:"currentColor"})})}function Bn(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M11.2 10.1l3 3-1.1 1.1-3-3a5 5 0 1 1 1.1-1.1zM6.8 10.3a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z",fill:"currentColor"})})}function oa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3.5 4.3h5.2v1.4H4.9v5.4H3.5zm3.8-2.1h5.2v9.5H7.3z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M5.7 10.8h4.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function ca(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M5 2.5h7.5v9H5z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M3.5 5H2.4V13.5H10V12.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function ua(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M4.2 4.2a1.4 1.4 0 1 1 0 2.8 1.4 1.4 0 0 1 0-2.8zm0 5.4a1.4 1.4 0 1 1 0 2.8 1.4 1.4 0 0 1 0-2.8zm1-3.2 6.6 5.6M5.2 9.6l6.6-5.6",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round"})})}function fa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 3.5h8v10H4zM6 2.2h4v2H6z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M6 7.2h4M6 9.6h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function da(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M4 1.5h5l3 3v10H4z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M9 1.5v3h3",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 6.5v5M5.5 9h5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function ha(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"m5.5 5 2.5-2.5L10.5 5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function pa(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"m5.5 8.5 2.5 2.5 2.5-2.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function ma(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M3.5 4.5h9M6.2 2.5h3.6l.6 1.4H13v1.2H3V3.9h2.6zM5.2 5.7v6.1m2.8-6.1v6.1m2.8-6.1v6.1M4.4 13.5h7.2",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function ba(){return i.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[i.jsx("path",{d:"M1.8 4.5h4l1.2 1.3h7.2v6.7H1.8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),i.jsx("path",{d:"M8.5 7.2v4M6.5 9.2h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function va(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"m4 6 4 4 4-4",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}function ya(){return i.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:i.jsx("path",{d:"M1.5 2h13l-5 6v5l-3 1.5V8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinejoin:"round"})})}function Gt(t,n,a,o){const h=[];for(const d of t){const m=d.path.replace(/\\/g,"/");d.kind==="file"?a.has(m)&&h.push(d):Xn(m,n,a,o)&&h.push(d)}return h}function Xn(t,n,a,o,h){const d=h??new Set;if(d.has(t))return!1;d.add(t);const m=n[t];if(!m)return o.has(t);for(const x of m){const C=x.path.replace(/\\/g,"/");if(x.kind==="file"){if(a.has(C))return!0}else if(Xn(C,n,a,o,d))return!0}return!1}export{Da as FileContextPanel};
|