@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
|
@@ -0,0 +1,2 @@
|
|
|
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 oe=(t,e,n)=>Yn(t,typeof e!="symbol"?e+"":e,n);import{t as o,b as a,u as Gn,j as r,m as yt,A as zn}from"./index-DEbFT-Aq.js";import{W as Qn,D as Ut}from"./WorkbenchModal-CbDxaCOR.js";import{l as Kn,m as Jn,n as Xe,o as Hs,p as Zn,q as nt,a as Wt,s as Bs,t as Xt,v as Fs,w as qs,S as er,x as Us,y as Lt,z as tr,A as sr,B as nr,C as rr,D as ir,E as or,F as us,G as ar,H as lr,I as cr,J as ur,K as Ws,u as dr,e as Vt,L as hr,N as mr,i as fr,j as pr,O as gr}from"./MobileSheet-D1lMrcvD.js";import{g as Oe}from"./default-session-permission-mode-Cu5SreTG.js";import{f as Ye,u as Ge,e as $t,g as lt,h as Yt,c as vr}from"./App-BFP7LCSC.js";import{u as ct,e as ds,b as ke,L as br,M as wr,N as Sr,O as Mr,P as yr,E as Ir,z as Fe,Q as Xs,R as Vs,S as $s,T as Ys,A as Gs,U as xr,V as Gt,r as hs,X as K,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-Brlj8K3i.js";import{B as Pr,M as Er,m as Ue,c as ms,a as tn,g as Ar,r as fs,b as Dt,R as jr,d as sn,C as nn,P as Nr,e as Or}from"./session-runtime-machine-Bfnxkk9B.js";import{FileContextPanel as _r}from"./FileContextPanel--FVTxDrq.js";import{GitSidebar as Lr}from"./GitSidebar-DAiSi9oc.js";import{TerminalManagerPanel as Dr}from"./TerminalManagerPanel-DhuTEdzV.js";import{f as rn,a as dt,M as on}from"./MobileWorkspaceSwitcherHeader-DJPV9ym2.js";import{w as $e,r as It,a as ps,b as gs}from"./styles-CSUx5LGe.js";import"./window-BWqRixxq.js";import"./event-DvH9tcej.js";import"./file-tree-icon-BMKuc5pw.js";import"./terminal-runtime-meta-B9xJGY__.js";import"./TerminalRuntimeFallbackModal-CNzOt5v5.js";import"./MobileTopHeaderFrame-COTc7cRr.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",Hr=420,Br=520,Fr=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 xt(t){return t&&nt.includes(t)?t:"codex"}function Ht(t){return t?t.nodeType===Node.ELEMENT_NODE?t:t.parentElement:null}function vs(t){var n,s;const e=Ht(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=Ht(n.startContainer),i=Ht(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=vs(n.startContainer),h=vs(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=$t(),{showToast:c}=Ye(),{shellMode:l,requestNavigationRefresh:u,selectWorkspace:h,upsertNavigationSession:b}=ct(),R=Gn(m=>m.profile.providers),[S,N]=a.useState(null),[C,I]=a.useState(!1),[w,O]=a.useState(""),[P,M]=a.useState(!1),[g,D]=a.useState(xt(e==null?void 0:e.provider)),[L,T]=a.useState(Je),[B,x]=a.useState(null),[k,j]=a.useState({}),[X,$]=a.useState(!1),[se,ae]=a.useState(!1),[ee,ce]=a.useState(!1),[p,v]=a.useState(0),[A,F]=a.useState(null),[q,ne]=a.useState(()=>({width:typeof window>"u"?0:window.innerWidth,height:typeof window>"u"?0:window.innerHeight})),Y=a.useRef(!1),J=a.useRef(!1),G=a.useRef(null),U=a.useRef(null),ge=l==="mobile"||i.isMobile,E=a.useMemo(()=>m=>{var H,z;return((z=(H=R[m])==null?void 0:H.defaultModel)==null?void 0:z.trim())||Je},[R]),f=a.useMemo(()=>g===(e==null?void 0:e.provider)&&n?n:B??Xe(g),[n,B,g,e==null?void 0:e.provider]),Z=a.useMemo(()=>{var H;const m=Xe(g).modelOptions??[];return(H=f.modelOptions)!=null&&H.length?f.modelOptions:m},[f.modelOptions,g]),he=a.useMemo(()=>Z.find(m=>m.id===L)??Z[0]??null,[Z,L]),Se=a.useMemo(()=>{const m=k[g]??(g===(e==null?void 0:e.provider)?n:B);return!m||m.canStartSession!==!1?null:m.limitations[0]??o("conversation.capabilityDenied")},[n,B,k,g,e==null?void 0:e.provider]),Te=a.useMemo(()=>{var te;if(!S||typeof window>"u")return null;const m=(te=t.current)==null?void 0:te.getBoundingClientRect(),H=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,re=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,H,Math.max(H,z)),top:Ze(S.rect.top-48,W,re)}},[t,S,q.height,q.width]),Pe=a.useMemo(()=>{var ze;if(!S||typeof window>"u")return null;const m=(ze=t.current)==null?void 0:ze.getBoundingClientRect(),H=(m==null?void 0:m.left)??0,z=(m==null?void 0:m.right)??q.width,W=(m==null?void 0:m.top)??0,re=(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-Fr),transform:"translate(-50%, -50%)"};const be=Math.max(280,Math.min(q.width-24,z-H-24)),te=Math.min(420,be),pe=S.rect.left+S.rect.width/2,ie=Math.max(12,H+12),Ae=Math.max(ie,Math.min(q.width-te-12,z-te-12)),qe=Math.min(Br,Math.max(280,re-W-24),Math.max(280,q.height-24)),Le=Math.max(12,W+12),ht=Math.max(Le,Math.min(q.height-qe-12,re-qe-12)),mt=S.rect.top-Hr-18;return{left:Ze(pe-te/2,ie,Ae),top:Ze(mt,Le,ht),width:te,maxHeight:qe}},[t,ge,S,q.height,q.width]);a.useEffect(()=>{if(typeof window>"u")return;const m=()=>{ne({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,J.current=!1,N(null),I(!1);return}const m=xt(e.provider);D(m),T(E(m))},[E,e]),a.useEffect(()=>{if(!e||!t.current||typeof window>"u"){U.current!==null&&(window.clearTimeout(U.current),U.current=null),G.current=null,J.current=!1,N(null);return}const m=t.current,H=ie=>{Y.current||(G.current=ie,N(ie),ie||I(!1))},z=()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},W=(ie,Ae)=>{if(G.current=ie,z(),Ae!=null&&Ae.immediate){H(ie);return}U.current=window.setTimeout(()=>{U.current=null,H(G.current)},qr)},re=()=>{const ie=Rt(m);if(J.current){G.current=ie;return}W(ie)},be=()=>{const ie=Rt(m);if(J.current){G.current=ie;return}W(ie,{immediate:!0})},te=ie=>{!(ie.target instanceof Node)||!m.contains(ie.target)||(J.current=!0,z())},pe=()=>{J.current&&(J.current=!1,W(Rt(m)))};return document.addEventListener("pointerdown",te),document.addEventListener("selectionchange",re),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",te),document.removeEventListener("selectionchange",re),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),x(n),()=>{m=!0}):($(!0),x(Xe(g)),Hs(g,e.workspaceId).then(H=>{m||x(H)}).catch(()=>{m||x(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(H=>{m||j(H)}),()=>{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 H=m[0];D(H),T(E(H))},[C,E,k,g,e]),a.useEffect(()=>{var H;const m=E(g);if(!Z.some(z=>z.id===L)){if(Z.some(z=>z.id===m)){T(m);return}T(((H=Z[0])==null?void 0:H.id)??Je)}},[Z,E,L,g]),a.useEffect(()=>{if(!C){Y.current=!1;return}Y.current=!0},[C]),a.useEffect(()=>{if(typeof window>"u")return;const m=H=>{H.key==="Escape"&&(I(!1),N(null),Y.current=!1)};return window.addEventListener("keydown",m),()=>{window.removeEventListener("keydown",m)}},[]);async function _(){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&&(F({title:"",content:S.text}),v(m=>m+1),ce(!0),I(!1),N(null),Y.current=!1)}function me(){if(!S||!e)return;const m=xt(e.provider);D(m),T(E(m)),O(""),M(!1),I(!0)}async function ue(){var m,H,z,W;if(!(!S||!e)){if(Se){c({title:Se,tone:"error"});return}ae(!0);try{const re=Xr(S.text,w),be=(he==null?void 0:he.id)===Je?null:(he==null?void 0:he.id)??null;let te=null;if(P&&S.sourceMessageId)te=await Bs(e.sessionId,{sourceType:"message",sourceMessageId:S.sourceMessageId,strategy:"auto",targetProvider:g,sessionKind:"annotation",annotationSourceMessageId:S.sourceMessageId,annotationSourceText:S.text}),b(te),await Xt(te.sessionId,{content:re,clientRequestId:((H=(m=globalThis.crypto)==null?void 0:m.randomUUID)==null?void 0:H.call(m))??`selection-action-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:be,permissionMode:Oe()});else{const pe=await Fs({workspaceId:e.workspaceId,provider:g,content:re,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:Oe(),parentSessionId:e.sessionId,sessionKind:"annotation",annotationSourceMessageId:S.sourceMessageId??null,annotationSourceText:S.text});te=pe.session??await qs(pe.sessionId)}b(te),u(),h(te.workspaceId),s(ke(te.workspaceId,te.sessionId)),I(!1),N(null),Y.current=!1}catch(re){c({title:re instanceof Error?re.message:o("conversation.selectionActionFailed"),tone:"error"})}finally{ae(!1)}}}function fe(m=!1){I(!1),Y.current=!1,m&&N(null)}return!e||!S||!Te||typeof document>"u"?r.jsx(ds,{open:ee,preferredWorkspaceId:(e==null?void 0:e.workspaceId)??null,preferredSessionId:(e==null?void 0:e.sessionId)??null,creationRequestId:p,initialDraft:A,onClose:()=>ce(!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 _(),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&&Pe?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:Pe,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=>O(m.target.value)})]}),r.jsxs("label",{className:"conversation-selection-checkbox",children:[r.jsx("input",{type:"checkbox",checked:P,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 H=m.target.value;D(H),T(E(H))},children:nt.map(m=>{var H;return r.jsx("option",{value:m,disabled:((H=k[m])==null?void 0:H.canStartSession)===!1,children:Wt(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:L,disabled:X||!!Se,onChange:m=>T(m.target.value),children:Z.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:se||!!Se,onClick:()=>void ue(),children:se?o("conversation.sendingState"):o("conversation.selectionActionSubmit")})]})]})]}):null]}),document.body),r.jsx(ds,{open:ee,preferredWorkspaceId:e.workspaceId,preferredSessionId:e.sessionId,creationRequestId:p,initialDraft:A,onClose:()=>ce(!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 bs(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,I]=a.useState(null),[w,O]=a.useState(null),[P,M]=a.useState(null),[g,D]=a.useState(bs(t==null?void 0:t.provider)),[L,T]=a.useState(""),[B,x]=a.useState(()=>Tt()),[k,j]=a.useState(We),[X,$]=a.useState(!1),[se,ae]=a.useState(0),ee=ln(),ce=a.useMemo(()=>{var E;return((E=t==null?void 0:t.title)==null?void 0:E.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,A=(C==null?void 0:C.latestVerificationRun)??null,F=v&&(v.status==="active"||v.status==="waiting_user")?v:null,q=A&&(A.status==="queued"||A.status==="running")?A:null;if(a.useEffect(()=>{R(!1),$(!1),O(null),I(null),T(""),D(bs(t==null?void 0:t.provider)),x(Tt()),j(We)},[t==null?void 0:t.sessionId]),a.useEffect(()=>{if(!(t!=null&&t.sessionId)){N(!1);return}let E=!1;return N(!0),O(null),br(t.sessionId).then(f=>{E||I(f.context)}).catch(f=>{E||(I(null),O(f instanceof Error?f.message:o("conversation.butlerActionLoadFailed")))}).finally(()=>{E||N(!1)}),()=>{E=!0}},[se,t==null?void 0:t.sessionId]),!(t!=null&&t.sessionId))return null;function ne(){S||ae(E=>E+1)}function Y(){!C&&!S&&ne()}a.useEffect(()=>{e||n<=0||(R(!0),Y())},[S,n,e,C]);async function J(){if(!p){Y();return}const E=L.trim(),f=B.trim();if(!E){s({title:o("conversation.butlerFollowUpObjectiveRequired"),tone:"warning"});return}if(!f){s({title:o("conversation.butlerFollowUpCompletionCriteriaRequired"),tone:"warning"});return}M("follow-up");try{const Z=await yr({projectId:p.project.id,butlerSessionId:p.session.id,providerId:g,objective:E,completionCriteria:f,maxAutoContinueCount:k});I(he=>he&&{...he,latestFollowUpTask:Z.task}),i(),s({title:o("conversation.butlerFollowUpStarted"),description:o("conversation.butlerFollowUpStartedDescription",{projectName:p.project.name}),tone:"success"}),T(""),x(Tt()),j(We),R(!1)}catch(Z){s({title:o("conversation.butlerFollowUpFailed"),description:Z instanceof Error?Z.message:void 0,tone:"error"})}finally{M(null)}}async function G(){if(v){M("follow-up");try{const E=await wr(v.id);I(f=>f&&{...f,latestFollowUpTask:E.task}),i(),s({title:o("conversation.butlerFollowUpStopped"),description:o("conversation.butlerFollowUpStoppedDescription"),tone:"success"}),R(!1)}catch(E){s({title:o("conversation.butlerFollowUpStopFailed"),description:E instanceof Error?E.message:void 0,tone:"error"})}finally{M(null)}}}async function U(){if(!p){Y();return}M("verification");try{const E=await Mr({projectId:p.project.id,butlerSessionId:p.session.id,verificationType:"browser",targetRef:ce||p.session.title||p.project.name});I(f=>f&&{...f,latestVerificationRun:E.result.run}),i(),s({title:o("conversation.butlerVerificationStarted"),description:o("conversation.butlerVerificationStartedDescription",{projectName:p.project.name}),tone:"success"}),R(!1)}catch(E){s({title:o("conversation.butlerVerificationFailed"),description:E instanceof Error?E.message:void 0,tone:"error"})}finally{M(null)}}async function ge(){if(A){M("verification");try{const E=await Sr(A.projectId,A.id);I(f=>f&&{...f,latestVerificationRun:E.run}),i(),s({title:o("conversation.butlerVerificationStopped"),description:o("conversation.butlerVerificationStoppedDescription"),tone:"success"}),R(!1)}catch(E){s({title:o("conversation.butlerVerificationStopFailed"),description:E instanceof Error?E.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(Pr,{})})}),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"),":",ws(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(Us,{children:[r.jsx("button",{type:"button",className:"secondary-button",disabled:P!==null,onClick:()=>{U()},children:o("conversation.butlerVerificationAction")}),r.jsx("button",{type:"button",className:"primary-button",disabled:P!==null,onClick:()=>{J()},children:o("conversation.butlerFollowUpAction")})]}):void 0,onClose:()=>{P||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||ce||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:P!==null,onSelect:E=>{Yr(E)&&D(E)}})]}),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:P!==null,onChange:E=>{const f=Number.parseInt(E.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:L,placeholder:o("conversation.butlerFollowUpObjectivePlaceholder"),disabled:P!==null,onChange:E=>{T(E.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:B,placeholder:o("conversation.butlerFollowUpCompletionCriteriaPlaceholder"),"aria-describedby":u,disabled:P!==null,onChange:E=>{x(E.target.value)}}),r.jsx("div",{className:"conversation-butler-preset-grid",role:"group","aria-label":o("conversation.butlerCompletionTemplateSectionLabel"),children:ee.map(E=>r.jsxs("button",{type:"button",className:"conversation-butler-preset-card","data-selected":B.trim()===E.value,"aria-pressed":B.trim()===E.value,disabled:P!==null,onClick:()=>{x(E.value)},children:[r.jsx("strong",{children:E.label}),r.jsx("span",{children:E.description})]},E.id))})]}),F||q?r.jsxs("div",{className:"conversation-butler-meta-grid",children:[F?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:ws(F.status)}),r.jsx("small",{children:o("conversation.butlerCurrentFollowUpProgress",{current:F.autoContinueCount,max:F.maxAutoContinueCount??We})}),r.jsx("button",{type:"button",className:"workbench-secondary-button",disabled:P!==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:P!==null,onClick:()=>{ge()},children:o("conversation.butlerStopVerificationAction")})]}):null]}):null]}):null]})})]})}function ws(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=Yt(),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=Ir(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})},B=k=>{var X,$;const j=k.target;j&&!((X=c.current)!=null&&X.contains(j))&&!(($=i.current)!=null&&$.contains(j))&&w()},x=k=>{k.key==="Escape"&&w()};return T(),window.addEventListener("pointerdown",B),window.addEventListener("keydown",x),window.addEventListener("resize",T),window.addEventListener("scroll",T,!0),()=>{window.removeEventListener("pointerdown",B),window.removeEventListener("keydown",x),window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0)}},[h,l]);function I(){var B;const T=(B=i.current)==null?void 0:B.getBoundingClientRect();T&&(b({x:T.right,y:T.bottom}),u(!0))}function w(){u(!1),b(null)}function O(T){n(T),w()}function P(T){const B=new URLSearchParams(s.search);B.set("toolPanel",T),O(`${s.pathname}?${B.toString()}`)}function M(){if(l){w();return}I()}function g(T){T.key!=="ContextMenu"&&!(T.shiftKey&&T.key==="F10")||(T.preventDefault(),T.stopPropagation(),I())}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:()=>{P("files")}},{key:"git",label:o("shell.gitEntry"),onSelect:()=>{P("git")}},{key:"processes",label:o("shell.mobileConversationToolProcessesTab"),onSelect:()=>{P("processes")}}],L=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(Er,{})})}),r.jsx(cn,{session:t,showTrigger:!1,openRequestKey:N})]}),L]})}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 Be=196,_e=82,Ss=28,Ms=24,un=34,Bt=18,Jr=332,et=360,it=840,ys=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,I;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 O=((C=w.parentSessionId)==null?void 0:C.trim())||null;if(!O)continue;const P=l.get(O)??[];l.set(O,[...P,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=((I=b.parentSessionId)==null?void 0:I.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[Wt(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 Ft(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-ys*2),c=Math.max(1,e-ys*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:Ft(t.offsetX,e-c,0),R=l<=n?h:Ft(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 qt(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,Be),Be;const s=t.children.reduce((c,l,u)=>{const h=c+qt(l,e);return u===0?h:h+Bt},0),i=Math.max(Be,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=qt(u,e),S=h+R/2,N=Ms+b*(_e+un),C=S-Be/2,I=u.children.reduce((M,g,D)=>{const L=M+qt(g,e);return D===0?L:L+Bt},0);let w=h+Math.max(0,(R-I)/2);const O=u.children.map(M=>{const g=i(M,w,b+1);return w+=g.subtreeWidth+Bt,g}),P={node:u,children:O,x:C,y:N,centerX:S,centerY:N+_e/2,subtreeWidth:R};return n.push(P),s.set(u.session.sessionId,P),P}const c=i(t,Ss,0),l=n.reduce((u,h)=>Math.max(u,h.y+_e),0);return{root:c,nodes:n,bySessionId:s,width:c.subtreeWidth+Ss*2,height:l+Ms}}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 I=u.createLinearGradient(0,0,e.width,e.height);I.addColorStop(0,Ce(N,.38,"rgba(255, 255, 255, 0.38)")),I.addColorStop(1,Ce(R,.05,"rgba(59, 130, 246, 0.05)")),u.fillStyle=I,u.fillRect(0,0,e.width,e.height)}function C(I){for(const w of I.children){const O=s.has(I.node.session.sessionId)&&s.has(w.node.session.sessionId),P=I.node.session.sessionId===i||w.node.session.sessionId===i;u.beginPath(),u.moveTo(I.centerX,I.y+_e-10);const M=I.y+_e+un*.52;u.bezierCurveTo(I.centerX,M,w.centerX,M,w.centerX,w.y+10),u.lineWidth=P?3:O?2.5:1.5,u.strokeStyle=P?Ce(R,.52,"rgba(59, 130, 246, 0.52)"):O?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,P?4.5:3.5,0,Math.PI*2),u.fillStyle=P?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 I of e.nodes){const w=I.node.session.sessionId===n,O=I.node.session.sessionId===i,P=s.has(I.node.session.sessionId);if(!w&&!O&&!P)continue;const M=u.createRadialGradient(I.centerX,I.centerY,10,I.centerX,I.centerY,O?90:64);M.addColorStop(0,Ce(R,O?.22:.14,"rgba(59, 130, 246, 0.22)")),M.addColorStop(1,"rgba(59, 130, 246, 0)"),u.fillStyle=M,u.beginPath(),u.ellipse(I.centerX,I.centerY,Be*.72,_e*.9,0,0,Math.PI*2),u.fill(),(O||w)&&(u.beginPath(),u.arc(I.centerX,I.y+12,O?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=Fe(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 I=a.useRef(null);return a.useEffect(()=>{const w=I.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:I,className:"conversation-branch-canvas",width:t.width,height:t.height,"aria-hidden":"true"}),t.nodes.map(w=>{const O=Fe(w.node.session.title,o("common.unknown")),P=Xs(w.node.session),M=Vs(w.node.session),g=$s(w.node.session),D=Ys(w.node.session),L=w.node.session.sessionId===e.current.sessionId,T=w.node.session.sessionId===n,B=e.currentPathIds.has(w.node.session.sessionId),x=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":L,"data-selected":T,"data-current-path":B,"data-archived":x,style:{left:w.x,top:w.y,width:Be,minHeight:_e},"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:O.fullTitle,children:O.displayTitle}),L?r.jsx("span",{className:"conversation-branch-current-badge",children:o("conversation.branchTreeCurrentBadge")}):null,x?r.jsx("span",{className:"conversation-branch-archived-badge",children:o("conversation.branchTreeArchivedBadge")}):null]}),r.jsx("p",{children:mn(w.node.session)}),M&&P||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&&P?r.jsx("span",{className:`session-fork-badge ${P}`,children:M}):null]}):null]})},w.node.session.sessionId)})]})})})}function Is({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),[I,w]=a.useState({}),O=a.useRef(new Set),[P,M]=a.useState(typeof window<"u"?window.innerWidth<=it:!1),[g,D]=a.useState(null),L=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 A(){b(v.clientWidth),S(v.clientHeight),M(window.innerWidth<=it)}if(A(),typeof ResizeObserver>"u")return window.addEventListener("resize",A),()=>window.removeEventListener("resize",A);const F=new ResizeObserver(A);return F.observe(p),()=>F.disconnect()},[]),a.useEffect(()=>{u(null)},[t.current.sessionId,t.root.session.sessionId]);const T=a.useMemo(()=>pn(h,s.width),[h,s.width]),B=a.useMemo(()=>oi(h,R,s.width,s.height),[R,h,s.height,s.width]);a.useEffect(()=>{if(!P||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,P,s.height,s.width]);const x=l?t.sessionsById.get(l)??null:null,k=x?s.bySessionId.get(x.sessionId)??null:null,j=x?I[x.sessionId]??{status:"idle",messages:[],error:null}:null,X=P&&!!n,$=!!n&&!X;a.useEffect(()=>{if(!l){C(null);return}const p=l;function v(){const A=c.current.get(p);if(!A){C(null);return}C(A.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(!P)return;const p=l;if(!p)return;const v=window.requestAnimationFrame(()=>{const A=c.current.get(p);A&&C(A.getBoundingClientRect())});return()=>window.cancelAnimationFrame(v)},[P,g,l]),a.useEffect(()=>{if(!(x!=null&&x.sessionId)||(j==null?void 0:j.status)==="ready"||O.current.has(x.sessionId))return;let p=!1;return O.current.add(x.sessionId),w(v=>{var A;return{...v,[x.sessionId]:{status:"loading",messages:((A=v[x.sessionId])==null?void 0:A.messages)??[],error:null}}}),Lt(x.sessionId,null,6,"backward").then(v=>{O.current.delete(x.sessionId),!p&&w(A=>({...A,[x.sessionId]:{status:"ready",messages:ii(v.messages),error:null}}))}).catch(v=>{O.current.delete(x.sessionId),!p&&w(A=>{var F;return{...A,[x.sessionId]:{status:"error",messages:((F=A[x.sessionId])==null?void 0:F.messages)??[],error:v instanceof Error?v.message:o("conversation.branchTreePreviewFailed")}}})}),()=>{p=!0}},[x==null?void 0:x.sessionId]);function se(p){!P||h<=0||R<=0||D(v=>{const A=v??tt(h,R,s.width,s.height);return ot(p(A),h,R,s.width,s.height)})}function ae(p){if(!P)return;const v=p.currentTarget.getBoundingClientRect();if(p.touches.length>=2){const q=p.touches[0],ne=p.touches[1],Y=Math.hypot(ne.clientX-q.clientX,ne.clientY-q.clientY),J=(q.clientX+ne.clientX)/2-v.left,G=(q.clientY+ne.clientY)/2-v.top,U=g??tt(h,R,s.width,s.height);L.current={mode:"pinch",startDistance:Y,startScale:U.scale,startOffsetX:U.offsetX,startOffsetY:U.offsetY,startTouchX:J,startTouchY:G,anchorX:J,anchorY:G,moved:!1};return}const A=p.touches[0],F=g??tt(h,R,s.width,s.height);L.current={mode:"pan",startDistance:0,startScale:F.scale,startOffsetX:F.offsetX,startOffsetY:F.offsetY,startTouchX:A.clientX,startTouchY:A.clientY,anchorX:0,anchorY:0,moved:!1}}function ee(p){if(!P)return;const v=L.current;if(p.touches.length>=2){const Y=p.currentTarget.getBoundingClientRect(),J=p.touches[0],G=p.touches[1],U=Math.hypot(G.clientX-J.clientX,G.clientY-J.clientY);if(U<=0||v.startDistance<=0)return;p.preventDefault();const ge=(J.clientX+G.clientX)/2-Y.left,E=(J.clientY+G.clientY)/2-Y.top,f=Ft(v.startScale*(U/v.startDistance),Zr,ei);L.current={...v,mode:"pinch",moved:!0,anchorX:ge,anchorY:E},se(Z=>li({...Z,scale:v.startScale,offsetX:v.startOffsetX,offsetY:v.startOffsetY},f,ge,E,h,R,s.width,s.height));return}if(v.mode!=="pan"||p.touches.length!==1)return;const A=p.touches[0],F=A.clientX-v.startTouchX,q=A.clientY-v.startTouchY;(v.moved||Math.hypot(F,q)>=ti)&&(p.preventDefault(),L.current={...v,moved:!0},se(Y=>({...Y,offsetX:v.startOffsetX+F,offsetY:v.startOffsetY+q})))}function ce(){L.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:B,transform:P?g:null,isMobileViewport:P,viewportRef:i,onRegisterNodeElement:(p,v)=>{if(v){c.current.set(p,v);return}c.current.delete(p)},onViewportTouchStart:ae,onViewportTouchMove:ee,onViewportTouchEnd:ce})]})]}),x&&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:x,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(Ut,{open:t,title:o("conversation.branchTreeMapTitle"),description:o("conversation.branchTreeMapDescription"),size:"regular",layout:"viewer",bodyClassName:"conversation-branch-modal-body",onClose:i,children:r.jsx(Is,{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(Is,{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=$t(),i=xr(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=Fe(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:Gt(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 Si=30,Ct=80,Ve=60,vn=600,xs=300*1e3,Mi=600,yi=5e3,Ii=1e4;class xi{constructor(e,n={}){oe(this,"state");oe(this,"listeners",new Set);oe(this,"realtimeClient",null);oe(this,"historyBootstrapFallbackTimer",null);oe(this,"historyBootstrapEnvelopeReceived",!1);oe(this,"markSeenTimer",null);oe(this,"markSeenInFlight",!1);oe(this,"lastMarkSeenRequestAt",0);oe(this,"seenWatermark",null);oe(this,"runtimeRefreshTimer",null);oe(this,"runtimeRefreshMode",null);oe(this,"replaceSnapshotSeedOnBackfill",!1);oe(this,"olderHistoryPrefetchCursor",null);oe(this,"olderHistoryPrefetchPromise",null);oe(this,"prefetchedOlderHistoryPage",null);oe(this,"pendingReplyDebugTraces",[]);oe(this,"hasAuthoritativeBootstrapMessages");oe(this,"subscribe",e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}));oe(this,"getState",()=>this.state);var l;this.sessionId=e,this.options=n;const s=hs(Nt(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=ms({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(),this.clearOlderHistoryPrefetch();const e=this.options.bootstrapMessages??[],n=Ue(this.state.messages,this.sessionId,e),s=this.hasAuthoritativeBootstrapMessages;this.patch({messages:n,historyState:Pi(this.state.session,s?n.length:0),loadingOlderMessages:!1,olderCursor:s?null:this.state.olderCursor,hasOlderMessages:He({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,this.clearOlderHistoryPrefetch(),(n=this.realtimeClient)==null||n.close(),this.realtimeClient=null;const e=hs(Nt(this.sessionId),xs);this.state=ms({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:He({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=Ps();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)??[],Ar(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:fs(this.state.messages,this.sessionId,c.message,s)})}catch(c){throw this.failPendingReplyDebugTrace(s,c),this.patch({messages:Dt(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:fs(this.state.messages,this.sessionId,s.message,e)})}catch(s){throw this.failPendingReplyDebugTrace(e,s),this.patch({messages:Dt(this.state.messages,e),session:Re(this.state.session,"failed")}),s}}}async enqueueMessage(e,n){const s=Ps();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:Oe(),attachments:(n==null?void 0:n.attachments)??[]});this.patch({queuedMessages:Oi(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:Ot(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{const n=this.state.olderCursor,s=await this.takePrefetchedOlderHistoryPage(n);if(s&&this.state.olderCursor===n){this.applyOlderHistoryPage(s,"prefetch_cache");return}if(!((e=this.realtimeClient)==null?void 0:e.requestOlderMessages(n,Ct)))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(),this.clearOlderHistoryPrefetch(),(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=yt.getState().session)==null?void 0:n.accessToken)){yt.clear();return}this.realtimeClient=new jr({sessionId:this.sessionId,cursor:this.state.lastCursor,limit:Ve,onSubscribed:()=>{K("session_send.realtime_subscribed",{sessionId:this.sessionId,lastCursor:this.state.lastCursor}),this.patch({connectionState:"connected",hasOlderMessages:He({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"&&ye((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:He({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,ks(s.type,(u=this.state.session)==null?void 0:u.runningState))}),(h=this.realtimeClient)==null||h.updateCursor(s.cursor),this.scheduleMarkSeen(),this.scheduleOlderHistoryPrefetch(s.type==="session.backfill"?"backfill":"delta"),this.state.queuedMessages.length>0&&this.refreshQueue()},onOlderHistory:s=>{this.applyOlderHistoryPage({messages:s.messages,nextCursor:s.olderCursor},"realtime")},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:()=>{yt.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&&Ti(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(Mi,n);this.markSeenTimer=window.setTimeout(()=>{this.markSeenTimer=null;const i=this.getTargetSeenAt();i!==null&&(K("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:Rs(this.state.session,i)}),(l=(c=this.options).onSeen)==null||l.call(c,this.sessionId,i),K("session_seen.end",{sessionId:this.sessionId,seenWatermark:this.seenWatermark})}).catch(()=>{K("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,Si)),n=await Lt(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:He({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(),this.scheduleOlderHistoryPrefetch("bootstrap_fallback")}catch{}}applyOlderHistoryPage(e,n){const{messages:s}=this.mergeHistoryMessages(e.messages,!1);this.patch({messages:s,historyState:"ready",loadingOlderMessages:!1,olderCursor:e.nextCursor,hasOlderMessages:!!e.nextCursor,pagesLoaded:this.state.pagesLoaded+1,errorCode:null,errorDetail:null}),K("session.history_older.applied",{sessionId:this.sessionId,source:n,messageCount:e.messages.length,nextCursor:e.nextCursor}),this.scheduleOlderHistoryPrefetch(n)}scheduleOlderHistoryPrefetch(e){var s;const n=this.state.olderCursor;this.state.historyState!=="ready"||this.state.loadingOlderMessages||!n||((s=this.prefetchedOlderHistoryPage)==null?void 0:s.requestedCursor)!==n&&(this.olderHistoryPrefetchPromise&&this.olderHistoryPrefetchCursor===n||this.prefetchOlderHistoryPage(n,e))}async prefetchOlderHistoryPage(e,n){var i;if(((i=this.prefetchedOlderHistoryPage)==null?void 0:i.requestedCursor)===e)return this.prefetchedOlderHistoryPage.page;if(this.olderHistoryPrefetchPromise&&this.olderHistoryPrefetchCursor===e)return this.olderHistoryPrefetchPromise;this.olderHistoryPrefetchCursor=e,K("session.history_older.prefetch.start",{sessionId:this.sessionId,requestedCursor:e,reason:n,limit:Ct});const s=Lt(this.sessionId,e,Ct,"backward").then(c=>(this.state.olderCursor===e&&(this.prefetchedOlderHistoryPage={requestedCursor:e,page:c}),K("session.history_older.prefetch.end",{sessionId:this.sessionId,requestedCursor:e,messageCount:c.messages.length,nextCursor:c.nextCursor}),c)).catch(c=>(K("session.history_older.prefetch.error",{sessionId:this.sessionId,requestedCursor:e,message:c instanceof Error?c.message:"unknown"}),null)).finally(()=>{this.olderHistoryPrefetchPromise===s&&(this.olderHistoryPrefetchPromise=null),this.olderHistoryPrefetchCursor===e&&(this.olderHistoryPrefetchCursor=null)});return this.olderHistoryPrefetchPromise=s,s}async takePrefetchedOlderHistoryPage(e){var n;if(((n=this.prefetchedOlderHistoryPage)==null?void 0:n.requestedCursor)===e){const s=this.prefetchedOlderHistoryPage.page;return this.prefetchedOlderHistoryPage=null,K("session.history_older.prefetch.hit",{sessionId:this.sessionId,requestedCursor:e,messageCount:s.messages.length,nextCursor:s.nextCursor}),s}if(this.olderHistoryPrefetchPromise&&this.olderHistoryPrefetchCursor===e){const s=await this.olderHistoryPrefetchPromise;return!s||this.state.olderCursor!==e?null:(this.prefetchedOlderHistoryPage=null,K("session.history_older.prefetch.await_hit",{sessionId:this.sessionId,requestedCursor:e,messageCount:s.messages.length,nextCursor:s.nextCursor}),s)}return null}clearOlderHistoryPrefetch(){this.olderHistoryPrefetchCursor=null,this.olderHistoryPrefetchPromise=null,this.prefetchedOlderHistoryPage=null}scheduleRuntimeRefresh(e,n){var s,i;if(!ye((s=this.state.session)==null?void 0:s.runningState)){this.clearRuntimeRefreshTimer();return}e==="poll"&&this.state.connectionState==="connected"||(this.clearRuntimeRefreshTimer(),this.runtimeRefreshMode=e,K("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;K("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 us(this.sessionId),b=At(this.state.runtimeHasActiveRun,h.runningState,h.hasActiveRun),R=jt(this.state.runtimeCanInterrupt,h.runningState,b,h.canInterrupt);this.patch({session:Ts(this.state.session,h),runtimeHasActiveRun:b,runtimeCanInterrupt:R,contextUsage:h.contextUsage,...Pt(h,this.state.interruptSource)}),await this.refreshQueue();const S=e==="poll"&&this.state.connectionState!=="connected"&&ye((i=this.state.session)==null?void 0:i.runningState);K("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){K("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"&&ye((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(qs(this.sessionId).then(n=>{this.patch({session:st(n,this.state.session)})}).catch(()=>{})),Cs(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||Cs(this.state.capabilities)||this.state.session.runningState===null}shouldRefreshRuntimeSnapshot(){return this.state.contextUsage===null}async refreshRuntimeSnapshot(e){K("session_runtime.snapshot.start",{sessionId:this.sessionId,reason:e});try{const n=await us(this.sessionId),s=At(this.state.runtimeHasActiveRun,n.runningState,n.hasActiveRun),i=jt(this.state.runtimeCanInterrupt,n.runningState,s,n.canInterrupt);this.patch({session:Ts(this.state.session,n),runtimeHasActiveRun:s,runtimeCanInterrupt:i,contextUsage:n.contextUsage,...Pt(n,this.state.interruptSource)}),await this.refreshQueue(),K("session_runtime.snapshot.end",{sessionId:this.sessionId,reason:e,hasContextUsage:n.contextUsage!==null})}catch(n){K("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 Xt(this.sessionId,{content:e,clientRequestId:n,model:(s==null?void 0:s.model)??null,reasoningLevel:(s==null?void 0:s.reasoningLevel)??null,permissionMode:Oe(),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 K("session_send.live_fallback",{sessionId:this.sessionId,clientRequestId:n,reason:c.message}),ur(this.sessionId,{content:e,clientRequestId:n,permissionMode:Oe()})}}handleRuntimeStatus(e){var s;const n=kt((s=this.state.session)==null?void 0:s.runningState,e.status);this.patch({session:Re(this.state.session,n),runtimeHasActiveRun:ye(n)?this.state.runtimeHasActiveRun??!0:!1,runtimeCanInterrupt:ye(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=jt(this.state.runtimeCanInterrupt,e.runningState,n,e.canInterrupt);if(this.patch({session:Ai(this.state.session,e),runtimeHasActiveRun:n,runtimeCanInterrupt:s,...Pt(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:He({session:this.state.session,loadedMessageCount:n.length,olderCursor:this.state.olderCursor,pagesLoaded:this.state.pagesLoaded,currentHasOlderMessages:this.state.hasOlderMessages}),session:Re(this.state.session,ks("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=kt((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=kt((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:Ot(this.state.permissionRequests,e.request)})}handlePermissionRequestResolved(e){this.patch({permissionRequests:Ot(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,yi-(Date.now()-this.lastMarkSeenRequestAt))}applySeenWatermark(e){return!e||!this.seenWatermark?e:Rs(e,this.seenWatermark)}emit(){for(const e of this.listeners)e()}persistSnapshot(){Rr(Nt(this.sessionId),{session:this.state.session,capabilities:this.state.capabilities,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage,messages:Ni(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),K(`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(),K(`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&&(K(`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();K(`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&&(K(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 Ri(t){const e=t==null?void 0:t.messageCount;return typeof e=="number"&&Number.isFinite(e)?e:null}function Ti(t,e){const n=Ci(e);if(!n)return!1;const s=ki(t);return s?zt(n.sequence,n.timestamp,s.sequence,s.timestamp)>=0:!0}function Ci(t){let e=null;for(const n of t)(!e||zt(n.sequence,n.timestamp,e.sequence,e.timestamp)>0)&&(e=n);return e}function ki(t){let e=null;for(const n of t)n.deliveryState==="sent"&&(!e||zt(n.sequence,n.timestamp,e.sequence,e.timestamp)>0)&&(e=n);return e}function zt(t,e,n,s){return t!==n?t-n:e.localeCompare(s)}function Pi(t,e){return e>0?"ready":"loading"}function Ei(t,e){const n=Ri(t);return n!==null?n>e:e>=Ve}function He(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,ye(e))}}function Rs(t,e){return!t||t.lastSeenAt&&t.lastSeenAt>=e?t:{...t,lastSeenAt:e,activityState:t.activityState==="completed_unread"?"idle":t.activityState}}function Ts(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=ji(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||ye(e)?"running":n&&(!t.lastSeenAt||n>t.lastSeenAt)?"completed_unread":t.activityState==="running"||t.activityState==="completed_unread"?"idle":t.activityState??"idle"}function ye(t){return t==="starting"||t==="running"||t==="reconnecting"}function at(t){return t==="completed"||t==="interrupted"||t==="failed"}function Cs(t){if(t===null)return!0;const e=t.modelOptions??[];return e.length===0?!0:e.every(n=>n.usesProviderDefault===!0)}function ks(t,e){return t==="session.backfill"?e??"idle":e==="completed"||e==="interrupted"||e==="failed"?e:"running"}function kt(t,e){return at(t)?t:e}function Pt(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 ji(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 Ps(){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&&ye(e)}function jt(t,e,n,s){return s?!0:t===!0&&(n||ye(e))}function Nt(t){return`session-runtime.snapshot.${t}`}function Ni(t){return t.filter(e=>e.deliveryState==="sent").slice(-vn)}function Oi(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 Ot(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||js(t,e))return t;if(js(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 js(t,e){return Ns(t)&&!Ns(e)&&t.lastEventAt===e.lastEventAt&&t.lastMessageAt===e.lastMessageAt&&t.completedAt===e.completedAt}function Ns(t){return t.activityState==="running"||ye(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,Os=.6,_t=.6,_s=8,Di=36,Hi=48,Bi=96,Fi=320,qi="workbench:focus-composer";function _o(){const{sessionId:t="",workspaceId:e}=vr(),n=Yt(),s=Ge(),i=a.useMemo(()=>new URLSearchParams(n.search),[n.search]),c=zi(i.get("toolPanel")),l=(e==null?void 0:e.trim())||null,u=a.useMemo(()=>$i(t,l,i),[l,i,t]),h=a.useMemo(()=>uo(t,n.state),[n.state,t]);return u?r.jsx(Vi,{draft:u,navigate:s,initialToolPanel:c}):r.jsx(Ui,{sessionId:t,bootstrapMessages:h,initialToolPanel:c})}function Ui({sessionId:t,bootstrapMessages:e,initialToolPanel:n}){var as,ls;const{shellMode:s,navigationGroups:i,requestNavigationRefresh:c,selectWorkspace:l,setSessionWorkspace:u,markNavigationSessionSeen:h,favoriteSessions:b,archiveSession:R,unarchiveSession:S,startDraftSession:N,upsertNavigationSession:C}=ct(),I=Ge(),w=a.useRef(null),O=a.useRef(null),[P,M]=a.useState(!1),[g,D]=a.useState(null),[L,T]=a.useState(!1),[B,x]=a.useState(!1),[k,j]=a.useState(null),[X,$]=a.useState(!1),[se,ae]=a.useState(!1),[ee,ce]=a.useState(null),p=a.useMemo(()=>i.flatMap(d=>d.sessions).find(d=>d.sessionId===t)??null,[i,t]);(!w.current||O.current!==t)&&((as=w.current)==null||as.destroy(),w.current=new xi(t,{initialSession:p,bootstrapMessages:e,onSeen:(d,y)=>{h(d,y)}}),O.current=t);const v=w.current,{showToast:A,dismissToast:F}=Ye(),q=dr(d=>d.notificationPreferences.notifyOnPermissionRequest),ne=$t(),Y=Vt(),J=a.useRef(null),G=a.useRef(null),U=a.useRef(null),ge=a.useRef((p==null?void 0:p.runningState)??null),E=a.useRef(new Set),f=ve(v,d=>d.session),Z=ve(v,d=>d.capabilities),he=ve(v,d=>d.runtimeHasActiveRun),Se=ve(v,d=>d.runtimeCanInterrupt),Te=ve(v,d=>d.messages),Pe=ve(v,d=>d.permissionRequests),_=ve(v,d=>d.queuedMessages),V=ve(v,d=>d.contextUsage),me=ve(v,d=>d.historyState),ue=ve(v,d=>d.errorCode),fe=ve(v,d=>d.errorDetail),m=ve(v,d=>d.interruptSource),H=ve(v,d=>d.loadingOlderMessages),z=ve(v,d=>d.hasOlderMessages),W=ve(v,d=>d.connectionState),[re,be]=a.useState(null),[te,pe]=a.useState(null),ie=no(f),Ae=hr(Z)&&(f==null?void 0:f.provider)===(Z==null?void 0:Z.provider),qe=_.some(d=>d.status==="queued"||d.status==="dispatching"),Le=P&&!ee,ht=he===!0||Le?!0:he,mt=Se===!0||Le?!0:Se,ze=ie||Le,On=ro({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,de=s!=="mobile",Ie=En(!de),le=(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??null,xe=kn({enabled:!de,initialPanel:n,workspaceId:le,suspendMainGesture:!de&&Ie.isVisible}),Qt=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]),Kt=a.useMemo(()=>rn(i),[i]),_n=a.useMemo(()=>Qs(i),[i]),pt=a.useMemo(()=>yn(i,(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??null,Qt),[Qt,i,p==null?void 0:p.workspaceId,f==null?void 0:f.workspaceId]),gt=a.useMemo(()=>In(b,i),[b,i]),[Ln,Jt]=a.useState([]),Zt=a.useMemo(()=>[...gt,...pt],[gt,pt]),es=a.useMemo(()=>le?Qe.find(d=>d.id===le)??null:null,[le,Qe]),Ee=(le?_n[le]??null:null)??(es?Ks(es):null),Me=a.useMemo(()=>dt(i,le),[le,i]),je=Kt.find(d=>d.workspace.id===le)??(Me?{workspace:Me.workspace,label:Me.workspace.name,subtitle:Me.workspace.path}:null),vt=a.useMemo(()=>_i(i,le,t),[le,i,t]),bt=(f==null?void 0:f.provider)??(p==null?void 0:p.provider)??null,wt=a.useMemo(()=>{var d;return Fe(((d=f??p)==null?void 0:d.title)??null,o("conversation.titleFallback"))},[p,f]),De=f??p??null,ts=de?null:Cn(Ie.mainGestureHandlers,xe.mainGestureHandlers);a.useEffect(()=>{const d=Zs(Zt,t,y=>y.session.sessionId);d.length!==0&&Jt(y=>{const Q=new Set(y);let we=!1;for(const Ne of d)Q.has(Ne)||(Q.add(Ne),we=!0);return we?Array.from(Q):y})},[Zt,t]);const Dn=a.useMemo(()=>fo(De,Te),[De,Te]),Ke=(De==null?void 0:De.workspaceId)??(p==null?void 0:p.workspaceId)??null,Hn=a.useMemo(()=>dn(i,Ke,t),[Ke,i,t]),Bn=ni(Hn),ss=!!(De&&Ke&&Bn),ns=()=>{ae(!0)},St=a.useMemo(()=>(Me==null?void 0:Me.sessions.filter(d=>d.isArchived===!0&&!ut(d)))??[],[Me]),Fn=a.useRef(null),rs=a.useRef(null),Mt=a.useRef(null),is=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(()=>{ae(!1),ce(null)},[t]),a.useEffect(()=>()=>{U.current!==null&&(window.clearTimeout(U.current),U.current=null)},[]),a.useEffect(()=>{var Q;if(ue!=="SESSION_NOT_FOUND"&&ue!=="WORKSPACE_NOT_FOUND")return;F("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,y=(d?ft.find(we=>we.workspace.id===d)??null:null)??ft[0]??null;I(y?ke(y.workspace.id,y.session.sessionId):d?rt(d):s==="mobile"?Tr():"/landing",{replace:!0})},[F,ft,I,i,p==null?void 0:p.workspaceId,ue,f==null?void 0:f.workspaceId,s]),a.useEffect(()=>{if(ue==="SESSION_NOT_FOUND"||ue==="WORKSPACE_NOT_FOUND"){U.current!==null&&(window.clearTimeout(U.current),U.current=null),G.current=null,J.current=null,F("conversation-runtime-error");return}if(!ue||!fe){U.current!==null&&(window.clearTimeout(U.current),U.current=null),G.current=null,J.current=null,F("conversation-runtime-error");return}const d=`${ue}:${fe}`;if(!(J.current===d||G.current===d)){if(U.current!==null&&(window.clearTimeout(U.current),U.current=null),Wi((f==null?void 0:f.provider)??null,ue,fe)){G.current=d,U.current=window.setTimeout(()=>{G.current=null,U.current=null,J.current=d,A({id:"conversation-runtime-error",title:o("conversation.runtimeErrorTitle"),description:fe,tone:"error",durationMs:null})},Li);return}G.current=null,J.current=d,A({id:"conversation-runtime-error",title:o("conversation.runtimeErrorTitle"),description:fe,tone:"error",durationMs:null})}},[F,ue,fe,f==null?void 0:f.provider,A]),a.useEffect(()=>{const d=ge.current,y=(f==null?void 0:f.runningState)??null;(d==="starting"||d==="running"||d==="reconnecting")&&y==="completed"&&Y.trigger("success"),ge.current=y},[Y,f==null?void 0:f.runningState]),a.useEffect(()=>{const d=Pe.filter(Q=>Q.status==="pending"),y=(f==null?void 0:f.workspaceId)??(p==null?void 0:p.workspaceId)??null;for(const Q of d)E.current.has(Q.id)||(E.current.add(Q.id),q&&(A({id:`permission-request-${Q.id}`,title:o("conversation.permissionRequestToastTitle"),description:Q.title,tone:"warning",durationMs:8e3,action:y?{label:o("shell.contextOpenSession"),onClick:()=>{I(ke(y,t))}}:void 0}),ne.bridge.showNotification(o("conversation.permissionRequestToastTitle"),Q.title)))},[p==null?void 0:p.workspaceId,I,q,Pe,ne.bridge,f==null?void 0:f.workspaceId,t,A]),Rn(Mt,qn,!de,t),Tn(Mt,is,!de,t);async function os(d,y){var Ne,cs;const Q=ee;if(!Q){await v.sendMessage(d,{model:y==null?void 0:y.model,reasoningLevel:y==null?void 0:y.reasoningLevel,attachments:y==null?void 0:y.attachments,attachmentMeta:y==null?void 0:y.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 Xt(we.sessionId,{content:d,clientRequestId:((cs=(Ne=globalThis.crypto)==null?void 0:Ne.randomUUID)==null?void 0:cs.call(Ne))??`fork-${Date.now()}-${Math.random().toString(16).slice(2)}`,model:Q.targetModel,reasoningLevel:(y==null?void 0:y.reasoningLevel)??null,permissionMode:Oe(),attachments:(y==null?void 0:y.attachments)??[]}),ce(null),c(),l(we.workspaceId),$e("preview"),I(ke(we.workspaceId,we.sessionId)),A({title:o("conversation.forkMessageSucceeded"),tone:"success"})}catch(Vn){throw we&&(C(we),c()),Vn}}function Xn(d){l(d),I(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":!de,"data-preview-mode":de?void 0:Ie.displayMode,"data-preview-dragging":de?void 0:Ie.isDragging,"data-workspace-tone":(Ee==null?void 0:Ee.tone)??"root","data-worktree-depth":(Ee==null?void 0:Ee.depth)??0,"data-tool-panel-open":de?void 0:xe.isOpen,style:{...de?{}:Ie.pageStyle,...Gt(Ee)??{}},children:[de?r.jsx(gn,{session:f??p,workspaceContext:Ee,actions:r.jsxs(r.Fragment,{children:[ss?r.jsx(so,{onOpenBranchTree:ns}):null,r.jsx(cn,{session:f??p})]})}):null,de?null:r.jsx(on,{containerRef:is,className:"mobile-conversation-page-header",gestureHandlers:ts??void 0,currentWorkspace:je?{id:je.workspace.id,name:je.label,path:je.subtitle}:Qe[0]??null,workspaces:Qe,workspaceOptions:Kt,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:ss?ns:void 0})]})}),de?null:r.jsx(An,{visible:!xe.isOpen&&Ie.isVisible,widthPx:Ie.previewWidthPx,isDragging:Ie.isDragging,gestureHandlers:Ie.railGestureHandlers,activeSessionId:t,createSessionActionLabel:le&&bt?o("shell.createSession"):void 0,favoriteItems:gt,items:pt,expandedRootIds:Ln,workspaceSectionLabel:(je==null?void 0:je.label)??o("shell.mobileConversationCurrentWorkspaceSection"),onCreateSession:le&&bt?()=>{N(le,bt)}:void 0,archiveCurrentActionLabel:o("shell.archiveCurrentSessionAction"),archiveFolderActionLabel:St.length>0?o("shell.archiveFolderLabel"):void 0,onArchiveActiveSession:()=>{T(!0)},onOpenArchiveFolder:St.length>0?()=>{x(!0)}:void 0,onToggleSubsessions:d=>{Jt(y=>y.includes(d)?y.filter(Q=>Q!==d):[...y,d])},onActivate:d=>{Ie.closePreview(),l(d.workspace.id),I(ke(d.workspace.id,d.session.sessionId))}}),r.jsx("div",{className:"mobile-conversation-stage",...ts??{},children:r.jsxs("div",{ref:Fn,className:"mobile-conversation-main",children:[r.jsx(an,{connectionState:W,onReconnect:()=>v.reconnect()}),r.jsx(Nr,{requests:Pe,replyingRequestId:g,onReply:async(d,y)=>{D(d);try{await v.replyPermissionRequest(d,y)}catch(Q){A({title:o("conversation.permissionRequestReplyFailed"),description:Q instanceof Error?Q.message:void 0,tone:"error"})}finally{D(null)}}}),r.jsx("div",{ref:rs,className:"conversation-timeline-shell",children:r.jsx(sn,{sessionId:t,messages:Dn,historyState:me,loadingOlderMessages:H,hasOlderMessages:z,provider:(f==null?void 0:f.provider)??null,interruptedSource:m,runtimeThinkingPlaceholder:On,onLoadOlderMessages:()=>{v.loadOlderMessages()},onRetryMessage:d=>{v.retryMessage(d)},onForkMessage:d=>{f&&(ce({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}),Xi())}})}),r.jsx(Vr,{containerRef:rs,session:f??p??null,currentCapabilities:Z}),r.jsx(Kr,{items:_,deletingQueueItemId:re,steeringQueueItemId:te,canSteer:Ae,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)}}}),xe.isOpen?null:r.jsx(nn,{capabilities:Z,draftStorageId:t,forkDraft:ee,onClearForkDraft:()=>ce(null),onForkDraftChange:d=>ce(d),panelRef:de?void 0:Un,portalContainer:de?null:Wn,hasActiveRun:ht,contextUsage:V,taskProvider:((ls=f??p)==null?void 0:ls.provider)??null,taskMessages:Te,hasPendingQueuedMessages:qe,canInterrupt:mt,isSubmitting:P,isRunning:ze,onInterrupt:async()=>{await v.interrupt(),c()},onSend:async(d,y)=>{M(!0);try{await os(d,{model:y==null?void 0:y.model,reasoningLevel:y==null?void 0:y.reasoningLevel,attachments:y==null?void 0:y.attachments,attachmentMeta:y==null?void 0:y.attachmentMeta})}finally{M(!1)}},onQueueSend:async(d,y)=>{M(!0);try{ee?await os(d,{model:y==null?void 0:y.model,reasoningLevel:y==null?void 0:y.reasoningLevel,attachments:y==null?void 0:y.attachments,attachmentMeta:y==null?void 0:y.attachmentMeta}):await v.enqueueMessage(d,{model:y==null?void 0:y.model,reasoningLevel:y==null?void 0:y.reasoningLevel,attachments:y==null?void 0:y.attachments,attachmentMeta:y==null?void 0:y.attachmentMeta})}finally{M(!1)}}})]})}),!de&&le?r.jsx(Pn,{activePanel:xe.activePanel,open:xe.isOpen,sessionId:t,workspaceId:le,navigationGroups:i,onClose:()=>{xe.closePanel()},onSelectPanel:d=>{xe.selectPanel(d)},onSelectPanelBySwipe:d=>{if(d===null){xe.closePanel();return}xe.selectPanel(d)}}):null]}),r.jsx(bi,{open:se,navigationGroups:i,workspaceId:Ke,sessionId:t,onClose:()=>ae(!1),onOpenSession:d=>{ae(!1),l(d.workspaceId),$e("preview"),I(ke(d.workspaceId,d.sessionId))}}),r.jsx(to,{open:L,busy:X,onClose:()=>{X||T(!1)},onConfirm:async()=>{if(!X){$(!0);try{if(await R(t),T(!1),A({title:o("shell.archiveAdded"),tone:"success"}),le){if(l(le),$e("preview"),vt){I(ke(vt.workspace.id,vt.session.sessionId));return}I(rt(le));return}I("/workspaces")}catch(d){A({title:d instanceof Error?d.message:o("shell.navigationLoadFailed"),tone:"error"})}finally{$(!1)}}}}),r.jsx(Nn,{open:B,workspaceName:(Me==null?void 0:Me.workspace.name)??null,sessions:St,restoringSessionId:k,onClose:()=>{k||x(!1)},onRestore:async d=>{j(d);try{await S(d),A({title:o("shell.archiveRestored"),tone:"success"})}catch(y){A({title:y instanceof Error?y.message:o("shell.navigationLoadFailed"),tone:"error"})}finally{j(null)}}})]})}function Wi(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 Xi(){typeof window>"u"||window.dispatchEvent(new CustomEvent(qi))}function Vi({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),[I,w]=a.useState([]),O=a.useMemo(()=>Xe(t.provider),[t.provider]),[P,M]=a.useState(O),g=s!=="mobile",{showToast:D}=Ye(),L=a.useMemo(()=>Yi(t),[t]),T=En(!g),B=kn({enabled:!g,initialPanel:n,sessionId:t.sessionId,workspaceId:t.workspaceId,suspendMainGesture:!g&&T.isVisible}),x=a.useMemo(()=>new Set(b.map(_=>_.session.sessionId)),[b]),k=a.useMemo(()=>i.map(_=>_.workspace),[i]),j=a.useMemo(()=>rn(i),[i]),X=a.useMemo(()=>Qs(i),[i]),$=a.useMemo(()=>k.find(_=>_.id===t.workspaceId)??null,[t.workspaceId,k]),se=X[t.workspaceId]??($?Ks($):null),ae=a.useMemo(()=>Fe(L.title??null,o("conversation.titleFallback")),[L]),ee=a.useMemo(()=>yn(i,t.workspaceId,x),[t.workspaceId,x,i]),ce=a.useMemo(()=>In(b,i),[b,i]),[p,v]=a.useState([]),A=a.useMemo(()=>[...ce,...ee],[ce,ee]),F=a.useMemo(()=>dt(i,t.workspaceId),[t.workspaceId,i]),q=a.useMemo(()=>(F==null?void 0:F.sessions.filter(_=>_.isArchived===!0&&!ut(_)))??[],[F]),ne=j.find(_=>_.workspace.id===t.workspaceId)??(F?{workspace:F.workspace,label:F.workspace.name,subtitle:F.workspace.path}:null),Y=g?null:Cn(T.mainGestureHandlers,B.mainGestureHandlers),[J,G]=a.useState(!1),[U,ge]=a.useState(null),E=a.useRef(null),f=a.useRef(null),Z=a.useRef(null),[he,Se]=a.useState(null),{composerPortalTarget:Te}=Js();a.useEffect(()=>{const _=Zs(A,t.sessionId,V=>V.session.sessionId);_.length!==0&&v(V=>{const me=new Set(V);let ue=!1;for(const fe of _)me.has(fe)||(me.add(fe),ue=!0);return ue?Array.from(me):V})},[t.sessionId,A]),a.useEffect(()=>(u(t.sessionId,t.workspaceId),()=>{u(t.sessionId,null)}),[t.sessionId,t.workspaceId,u]),a.useEffect(()=>{let _=!1;return M(O),Hs(t.provider,t.workspaceId).then(V=>{_||M(V)}).catch(()=>{}),()=>{_=!0}},[t.provider,t.workspaceId,O]),Rn(f,he,!g,t.sessionId),Tn(f,Z,!g,t.sessionId);function Pe(_){l(_),e(rt(_))}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":(se==null?void 0:se.tone)??"root","data-worktree-depth":(se==null?void 0:se.depth)??0,"data-tool-panel-open":g?void 0:B.isOpen,style:{...g?{}:T.pageStyle,...Gt(se)??{}},children:[g?r.jsx(gn,{session:L,workspaceContext:se}):null,g?null:r.jsx(on,{containerRef:Z,className:"mobile-conversation-page-header",gestureHandlers:Y??void 0,currentWorkspace:ne?{id:ne.workspace.id,name:ne.label,path:ne.subtitle}:k[0]??null,workspaces:k,workspaceOptions:j,onSelectWorkspace:Pe,heading:ae.fullTitle,trailing:r.jsx("span",{className:"mobile-conversation-toolbar-title",title:ae.fullTitle,children:ae.displayTitle})}),g?null:r.jsx(An,{visible:!B.isOpen&&T.isVisible,widthPx:T.previewWidthPx,isDragging:T.isDragging,gestureHandlers:T.railGestureHandlers,activeSessionId:t.sessionId,createSessionActionLabel:o("shell.createSession"),favoriteItems:ce,items:ee,expandedRootIds:p,workspaceSectionLabel:(ne==null?void 0:ne.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:_=>{v(V=>V.includes(_)?V.filter(me=>me!==_):[...V,_])},onActivate:_=>{T.closePreview(),l(_.workspace.id),e(ke(_.workspace.id,_.session.sessionId))}}),r.jsx("div",{className:"mobile-conversation-stage",...Y??{},children:r.jsxs("div",{ref:E,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:I,historyState:"ready",loadingOlderMessages:!1,hasOlderMessages:!1,provider:t.provider,runtimeThinkingPlaceholder:null,onLoadOlderMessages:()=>{},onRetryMessage:()=>{}})}),B.isOpen?null:r.jsx(nn,{capabilities:P,draftStorageId:t.sessionId,panelRef:g?void 0:Se,portalContainer:g?null:Te,contextUsage:null,taskProvider:t.provider,taskMessages:I,isSubmitting:N,isRunning:!1,onSend:async(_,V)=>{var fe,m,H,z;const me=mo();w(W=>[...W,tn(t.sessionId,_,me,(V==null?void 0:V.attachmentMeta)??[],(V==null?void 0:V.attachments)??[])]),C(!0);const ue=performance.now();K("session_send.start_live.client_start",{draftSessionId:t.sessionId,workspaceId:t.workspaceId,provider:t.provider,clientRequestId:me,contentLength:_.length});try{const W=await Fs({workspaceId:t.workspaceId,provider:t.provider,content:_,clientRequestId:me,model:(V==null?void 0:V.model)??null,reasoningLevel:(V==null?void 0:V.reasoningLevel)??null,permissionMode:Oe(),attachments:(V==null?void 0:V.attachments)??[]});K("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()-ue),returnedMessageId:((m=W.message)==null?void 0:m.messageId)??null}),W.session&&h(W.session);const re=((z=(H=W.session)==null?void 0:H.workspaceId)==null?void 0:z.trim())||t.workspaceId;u(W.sessionId,re),$e("preview"),e(ke(re,W.sessionId),{replace:!0,state:W.message?{bootstrap:{sessionId:W.sessionId,messages:[W.message]}}:null}),c()}catch(W){throw K("session_send.start_live.client_error",{draftSessionId:t.sessionId,workspaceId:t.workspaceId,provider:t.provider,clientRequestId:me,durationMs:Math.round(performance.now()-ue),error:W instanceof Error?W.message:String(W)}),w(re=>Dt(re,me)),W}finally{C(!1)}}})]})}),g?null:r.jsx(Pn,{activePanel:B.activePanel,open:B.isOpen,sessionId:t.sessionId,workspaceId:t.workspaceId,navigationGroups:i,onClose:()=>{B.closePanel()},onSelectPanel:_=>{B.selectPanel(_)},onSelectPanelBySwipe:_=>{if(_===null){B.closePanel();return}B.selectPanel(_)}}),r.jsx(Nn,{open:J,workspaceName:(F==null?void 0:F.workspace.name)??null,sessions:q,restoringSessionId:U,onClose:()=>{U||G(!1)},onRestore:async _=>{ge(_);try{await R(_),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 $i(t,e,n,s=null){var l,u;if(!co(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 Yi(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 Gi(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=Gi(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 yn(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 In(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=xn(i,n.session.sessionId);return c?[c]:[]})}function xn(t,e){for(const n of t){if(n.item.session.sessionId===e)return n;const s=xn(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 zi(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=Yt(),n=Ge(),s=Vt(),i=a.useRef(null),[c,l]=a.useState(()=>t.initialPanel??ps()),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??ps();l(M),gs(M)},[t.enabled,t.initialPanel]);function b(M,g){const D=new URLSearchParams(e.search);M?(D.set("toolPanel",M),l(M),gs(M)):D.delete("toolPanel");const L=D.toString();n({pathname:e.pathname,search:L?`?${L}`:""},{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(Qi(M.target)){i.current=null;return}const g=M.changedTouches[0];i.current={x:g.clientX,y:g.clientY}}function I(M){const g=i.current;if(i.current=null,!g||M.changedTouches.length!==1||h||t.suspendMainGesture)return;const D=M.changedTouches[0],L=D.clientX-g.x,T=D.clientY-g.y;L>-56||Math.abs(L)<=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],L=D.clientX-g.x,T=D.clientY-g.y;L<56||Math.abs(L)<=Math.abs(T)*1.15||S()}return{activePanel:u,closePanel:S,isOpen:h,mainGestureHandlers:{onTouchStart:C,onTouchMove:()=>{},onTouchEnd:I,onTouchCancel:()=>{i.current=null}},openPanel:N,panelGestureHandlers:{onTouchStart:C,onTouchMove:()=>{},onTouchEnd:w,onTouchCancel:()=>{i.current=null}},selectPanel:R}}function Pn(t){const e=a.useRef(null);if(!t.open)return null;function n(i){if(i.changedTouches.length!==1){e.current=null;return}if(Ki(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(_r,{className:"mobile-conversation-tool-surface",hideHeading:!0,sessionId:t.sessionId,workspaceId:t.workspaceId}):t.activePanel==="git"?r.jsx(Lr,{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 Qi(t){return t instanceof Element?!!t.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function Ki(t){return t instanceof Element?!!t.closest("input, textarea, select, option, [contenteditable='true']"):!1}function En(t){const e=Vt(),[n,s]=a.useState(()=>t?It():"immersive"),[i,c]=a.useState(()=>Ls()),[l,u]=a.useState(()=>t&&It()==="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 x=It();s(x),u(x==="preview"?"default":"closed")},[t]),a.useEffect(()=>{t&&$e(n)},[t,n]),a.useEffect(()=>{if(typeof window>"u")return;function x(){c(Ls())}return x(),window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x)}},[]);function R(x){h.current=x,u(x)}function S(x="default"){R(x),s("preview")}function N(){R("closed"),s("immersive")}function C(){R("expanded"),s("preview")}function I(){if(h.current!=="closed"){e.trigger("gesture"),N();return}e.trigger("gesture"),S()}function w(x,k){const j=k.touches[0]??k.changedTouches[0];if(!t||!j){b.current=null;return}if(Zi(k.target)){b.current=null;return}if(x==="main"){if(h.current==="closed"&&j.clientX>Bi){b.current=null;return}}else if(h.current==="closed"){b.current=null;return}b.current={source:x,intent:x==="rail"?"rail":h.current==="closed"?"open":"close",startX:j.clientX,startY:j.clientY,lastX:j.clientX,lastY:j.clientY,horizontalLocked:!1}}function O(x){const k=b.current,j=x.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 P(x){var $;const k=b.current;if(b.current=null,!(k!=null&&k.horizontalLocked))return;const j=($=x==null?void 0:x.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>=Di&&(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>=Hi&&h.current==="default"&&(e.trigger("gesture"),C())}const M=l==="expanded"?_t:l==="default"?Os:0,g=Math.round(i*M*100)/100,D=M===0?0:M/_t,L={"--mobile-conversation-preview-default-width":`${Math.round(i*Os*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:x=>w("main",x),onTouchMove:O,onTouchEnd:P,onTouchCancel:P},pageStyle:L,previewWidthPx:g,railGestureHandlers:{onTouchStart:x=>w("rail",x),onTouchMove:O,onTouchEnd:P,onTouchCancel:P},togglePreview:I}}function An({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:I,onToggleSubsessions:w,onActivate:O}){if(!t)return null;function P(M,g){const{workspaceName:D,ancestorExpanded:L=!1,ancestorHasNextSiblings:T=[],hasNextSibling:B=!1,isFirstSibling:x=!1}=g??{},k=M.item.session.sessionId,j=M.children,X=M.depth===0&&j.length>0,$=L||X&&h.includes(k),se=M.depth>0?[...T,B]:[...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((ae,ee)=>ae?r.jsx("span",{className:"mobile-conversation-preview-guide-column",style:{"--mobile-preview-tree-level":ee+1}},`${k}:ancestor:${ee}`):null),r.jsx("span",{className:"mobile-conversation-preview-guide-branch","data-continue":B,"data-first":x,style:{"--mobile-preview-tree-level":M.depth},children:r.jsx("span",{className:"mobile-conversation-preview-guide-branch-horizontal"})})]}):null,r.jsx(Ji,{entry:M.item,activeSessionId:i,hasSubsessions:X,subsessionsExpanded:$,workspaceName:D,onToggleSubsessions:X?()=>{w(k)}:void 0,onActivate:O})]}),j.length>0&&$?r.jsx("div",{className:"mobile-conversation-preview-children",children:j.map((ae,ee)=>P(ae,{workspaceName:D,ancestorExpanded:!0,ancestorHasNextSiblings:se,hasNextSibling:ee<j.length-1,isFirstSibling:ee===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:P(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=>P(M))})]})]}),S&&C||N&&I?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&&I?r.jsx("button",{type:"button",className:"mobile-conversation-preview-archive-button workbench-import-toggle",onClick:I,children:N}):null]}):null]})}function Ji({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:Ds(t.session,{isActive:u,hasSubsessions:n}),"aria-hidden":"true"})}):r.jsx("span",{className:Ds(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 Zi(t){return t instanceof Element?!!t.closest("input, textarea, select, option, label, [contenteditable='true'], [data-preview-gesture='ignore']"):!1}function Ds(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,Wt(t.provider),eo(t.lastMessageAt??t.updatedAt),n].filter(Boolean).join(" · ")}function eo(t){return t?new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}):o("common.unknown")}function to({open:t,busy:e,onClose:n,onConfirm:s}){return r.jsx(Ut,{open:t,title:o("shell.archiveConfirmTitle"),description:o("shell.archiveConfirmDescription"),size:"narrow",layout:"confirm",dismissible:!e,showCloseButton:!1,footer:r.jsxs(Us,{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(Ut,{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=Fe(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 so(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(Or,{})})})}function no(t){return t?t.activityState==="running"?!0:t.runningState==="starting"||t.runningState==="running"||t.runningState==="reconnecting":!1}function ro(t){const e=io(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 io(t){const{provider:e,runningState:n,activityState:s,runtimeHasActiveRun:i,messages:c}=t;if(e!=="codex")return"hide_immediately";const l=lo(c);return l<0||ao(c,l)?"hide_immediately":oo(n,s,i)?"show":"hide_deferred"}function oo(t,e,n){return n===!0||e==="running"||t==="starting"||t==="running"||t==="reconnecting"}function ao(t,e){return t.slice(e+1).some(n=>n.role==="assistant"&&(n.kind==="text"||n.kind==="thinking"))}function lo(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 co(t){return t.startsWith("draft-")}function uo(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(ho)}function ho(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 mo(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`}function fo(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 +1 @@
|
|
|
1
|
-
import{b as d,j as e}from"./index-
|
|
1
|
+
import{b as d,j as e}from"./index-DEbFT-Aq.js";function c(){return d.useEffect(()=>{const t=document.documentElement.style.background,s=document.body.style.background;return document.documentElement.style.background="transparent",document.body.style.background="transparent",()=>{document.documentElement.style.background=t,document.body.style.background=s}},[]),e.jsx("main",{className:"desktop-detach-preview-page","aria-hidden":"true",children:e.jsxs("section",{className:"desktop-detach-preview-card",children:[e.jsx("header",{className:"desktop-detach-preview-bar",children:e.jsx("strong",{className:"desktop-detach-preview-title",children:"小窗口"})}),e.jsx("div",{className:"desktop-detach-preview-body",children:e.jsx("span",{className:"desktop-detach-preview-badge"})})]})})}export{c as DesktopDetachPreviewPage};
|
|
@@ -0,0 +1,2 @@
|
|
|
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,m as R,_ as N,j as s,t as l}from"./index-DEbFT-Aq.js";import{u as D,g as L}from"./MobileSheet-D1lMrcvD.js";import{FileContextPanel as E}from"./FileContextPanel--FVTxDrq.js";import{GitSidebar as j}from"./GitSidebar-DAiSi9oc.js";import{TerminalManagerPanel as q}from"./TerminalManagerPanel-DhuTEdzV.js";import{TerminalPage as y}from"./TerminalPage-DpsvQQVR.js";import{W as O,m as v}from"./WorkbenchLayout-Brlj8K3i.js";import{c as F,u as C,e as P,N as _}from"./App-BFP7LCSC.js";import"./WorkbenchModal-CbDxaCOR.js";import"./file-tree-icon-BMKuc5pw.js";import"./default-session-permission-mode-Cu5SreTG.js";import"./terminal-runtime-meta-B9xJGY__.js";import"./TerminalRuntimeFallbackModal-CNzOt5v5.js";import"./MobileWorkspaceSwitcherHeader-DJPV9ym2.js";import"./MobileTopHeaderFrame-COTc7cRr.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.workspaceName??(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=D(t=>t.sessionDisplaySortMode),[e,h]=a.useState(null),[W,f]=a.useState(!0),[S,b]=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),b(l("desktopWindow.invalidWindowId"));return}f(!0),b(null);const c=await i.bridge.getWindowDescriptor(n),k=c.ok?c.value??null:i.windows.getDescriptor(n);if(!t){if(!k){h(null),f(!1),b(c.detail??l("desktopWindow.loadDescriptorFailed"));return}i.windows.registerDescriptor(k),i.windows.markWindowOpen(k.windowId),h(k),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 L();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,N(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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as c,j as n,t as o,A as Yn}from"./index-DEbFT-Aq.js";import{f as Zn,e as wi,g as Ni}from"./App-BFP7LCSC.js";import{ae as Di,u as Ei,h as ki,x as Mi}from"./MobileSheet-D1lMrcvD.js";import{aw as Ri,r as en,w as wt,ax as _i,u as Ti,X as ke,ay as Fi,az as yt,aA as Ve,aB as Ai,aC as Bi,aD as Li}from"./WorkbenchLayout-Brlj8K3i.js";import{W as Bn}from"./WorkbenchModal-CbDxaCOR.js";import{a as Mt,b as Rt,F as Wi}from"./file-tree-icon-BMKuc5pw.js";import"./window-BWqRixxq.js";import"./event-DvH9tcej.js";const $i=new Set([".ds_store","thumbs.db","ehthumbs.db","desktop.ini",".spotlight-v100",".trashes",".fseventsd","__macosx","$recycle.bin","system volume information",".apdisk",".appledouble",".temporaryitems"]),Oi=["._"];function xt(t){return t.split(/[/\\]/).filter(Boolean).pop()??t}function Hi(t){const i=t.trim().toLowerCase();return i?$i.has(i)||Oi.some(l=>i.startsWith(l)):!1}function nn(t,i,l){return l?[...t]:t.filter(r=>!Hi(i(r)))}function Nt(t,i){return nn(t,l=>l.name,i)}function zi(t,i){return i?t:Object.entries(t).reduce((l,[r,h])=>(l[r]=Nt(h,!1),l),{})}async function Zt(t,i){const[l,r]=await Promise.all([Ri(i),Di(t)]);return Ui(l.changes,r.items)}function Ui(t,i){const l=new Set(i.map(r=>Et(r.path)));return t.filter(r=>l.has(Et(r.path))||r.oldPath!==null&&l.has(Et(r.oldPath)))}function Vi(t){const i=Ln("","");for(const l of t){const r=Et(l.path),h=r.split("/").filter(Boolean);let d=i;h.forEach((p,y)=>{const C=h.slice(0,y+1).join("/");if(y===h.length-1){d.children.set(`file:${C}`,{kind:"file",name:p,path:r,change:l});return}const F=`directory:${C}`,_=d.children.get(F);if(_&&_.kind==="directory"){d=_;return}const Z=Ln(p,C);d.children.set(F,Z),d=Z})}return In(Qn([...i.children.values()]))}function Jn(t,i){const l=t.oldPath?`${t.oldPath} -> ${t.path}`:t.path;return an(t)?`${l} ${i}`:l}function an(t){return t.status==="D"||t.stagedStatus==="D"||t.worktreeStatus==="D"}function Dt(t){return t.split("/").filter(Boolean).pop()??t}function Et(t){return t.replace(/\\/g,"/").replace(/^\.\//,"").trim()}function Ln(t,i){return{kind:"directory",name:t,path:i,children:new Map}}function Qn(t){return[...t].sort((i,l)=>i.kind!==l.kind?i.kind==="directory"?-1:1:i.name.localeCompare(l.name,"zh-CN")).map(i=>i.kind==="directory"?{kind:"directory",name:i.name,path:i.path,children:Qn([...i.children.values()])}:i)}function In(t){return t.map(i=>{var p;if(i.kind!=="directory")return i;const l=In(i.children);let r=i.name,h=i.path,d=l;for(;d.length===1&&((p=d[0])==null?void 0:p.kind)==="directory";){const y=d[0];r=`${r}/${y.name}`,h=y.path,d=y.children}return{kind:"directory",name:r,path:h,children:d}})}const Ki=450,Gi=60*1e3,Wn=20,$n=16;function Xi({sessionId:t,workspaceId:i,showSystemFiles:l,selectedPath:r,refreshVersion:h,onCountChange:d,onSelectFile:p,onOpenFile:y}){const[C,F]=c.useState("tree"),[_,Z]=c.useState([]),[he,V]=c.useState(!0),[me,pe]=c.useState(!1),[K,ft]=c.useState([]),M=c.useRef(null),{showToast:Ce}=Zn();c.useEffect(()=>{const v=en(gt(i,t),Gi);F("tree"),Z(v??[]),V(v===null),pe(!1),ft([]),M.current=null},[t,i]),c.useEffect(()=>{let v=!1;async function b(){V(!0);try{const w=await Zt(t,i);v||(Z(w),wt(gt(i,t),w))}catch(w){v||Ce({title:Jt(w,o("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{v||V(!1)}}return b(),()=>{v=!0}},[h,t,Ce,i]);async function Tt(){V(!0);try{const v=await Zt(t,i);Z(v),wt(gt(i,t),v)}catch(v){Ce({title:Jt(v,o("conversation.filePanelSessionLoadFailed")),tone:"error"})}finally{V(!1)}}async function je(){if(Me.length!==0){pe(!0);try{await _i(i,Me.map(b=>b.path));const v=await Zt(t,i);Z(v),wt(gt(i,t),v),Ce({title:o("conversation.filePanelSessionStageSuccess"),tone:"success"})}catch(v){Ce({title:Jt(v,o("git.stageFailed")),tone:"error"})}finally{pe(!1)}}}function E(v){ft(b=>b.includes(v)?b.filter(w=>w!==v):[...b,v])}function A(v){const b=Date.now(),w=M.current;return M.current={filePath:v,timestamp:b},(w==null?void 0:w.filePath)===v&&b-w.timestamp<=Ki}async function O(v,b){if(b&&A(v)){await y(v),M.current=null;return}b||(M.current=null),await p(v)}const k=c.useMemo(()=>nn(_,v=>Dt(v.path),l),[_,l]),Me=k.filter(v=>!v.staged),G=Vi(k),Re=new Set(K);return c.useEffect(()=>{d==null||d(k.length)},[d,k.length]),n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"file-panel-session-toolbar",children:[n.jsxs("div",{className:"file-panel-view-modes",role:"tablist","aria-label":o("conversation.filePanelSessionViewLabel"),children:[n.jsx("button",{className:C==="tree"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":C==="tree",onClick:()=>F("tree"),children:o("conversation.filePanelSessionTreeView")}),n.jsx("button",{className:C==="list"?"file-panel-view-button active":"file-panel-view-button",type:"button",role:"tab","aria-selected":C==="list",onClick:()=>F("list"),children:o("conversation.filePanelSessionListView")})]}),n.jsxs("div",{className:"file-panel-session-actions",children:[n.jsx("button",{className:"secondary-button",type:"button",onClick:()=>void Tt(),disabled:he||me,children:o("conversation.filePanelRefresh")}),n.jsx("button",{className:"primary-button",type:"button",onClick:()=>void je(),disabled:me||Me.length===0,children:o("conversation.filePanelSessionStageAll")})]})]}),n.jsxs("div",{className:"file-panel-session-summary",children:[n.jsx("span",{children:`${o("conversation.filePanelSessionSummary")} ${k.length}`}),n.jsx("span",{children:`${o("conversation.filePanelSessionUnstagedSummary")} ${Me.length}`})]}),n.jsx("div",{className:"file-tree",children:he?n.jsx("p",{className:"file-tree-status status-text",children:o("conversation.filePanelSessionLoading")}):k.length===0?n.jsx("p",{className:"file-tree-status status-text",children:o("conversation.filePanelSessionEmpty")}):C==="tree"?ei({nodes:G,depth:0,collapsedPathSet:Re,selectedPath:r,onToggleTreePath:E,onFileClick:O}):qi({items:k,selectedPath:r,onFileClick:O})})]})}function ei({nodes:t,depth:i,collapsedPathSet:l,selectedPath:r,onToggleTreePath:h,onFileClick:d}){return t.map(p=>{if(p.kind==="directory"){const y=!l.has(p.path);return n.jsxs("div",{className:"file-tree-node",children:[n.jsxs("button",{className:"file-tree-item",type:"button","data-kind":"directory","aria-expanded":y,style:{paddingInlineStart:`${Wn+i*$n}px`},onClick:()=>h(p.path),children:[n.jsx("span",{className:"file-tree-chevron","aria-hidden":"true",children:y?"v":">"}),n.jsx("span",{className:"file-tree-label",children:p.name})]}),y?n.jsx("div",{className:"file-tree-children",children:ei({nodes:p.children,depth:i+1,collapsedPathSet:l,selectedPath:r,onToggleTreePath:h,onFileClick:d})}):null]},`session-directory:${p.path}`)}return n.jsx("div",{className:"file-tree-node",children:n.jsxs("button",{className:"file-tree-item is-session-change",type:"button","data-active":r===p.change.path,"data-kind":"file",style:{paddingInlineStart:`${Wn+i*$n}px`},onClick:()=>void d(p.change.path,!an(p.change)),children:[n.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),n.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(p.name),"aria-hidden":"true",children:Mt(p.name)}),n.jsxs("span",{className:"file-tree-label",children:[n.jsx("span",{className:"file-tree-name",children:p.name}),n.jsx("span",{className:"file-tree-path",children:Jn(p.change,o("conversation.filePanelSessionDeleted"))})]}),n.jsxs("span",{className:"file-session-item-meta",children:[n.jsx("span",{className:"file-session-badge","data-status":p.change.status,children:p.change.status}),n.jsx("span",{className:"file-session-badge subtle",children:p.change.staged?o("git.stagedLabel"):o("git.workingTreeLabel")})]})]})},`session-file:${p.path}`)})}function qi({items:t,selectedPath:i,onFileClick:l}){return t.map(r=>n.jsx("div",{className:"file-session-list-item",children:n.jsxs("button",{className:"file-session-list-button",type:"button","data-active":i===r.path,onClick:()=>void l(r.path,!an(r)),children:[n.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(Dt(r.path)),"aria-hidden":"true",children:Mt(Dt(r.path))}),n.jsxs("span",{className:"file-tree-label",children:[n.jsx("span",{className:"file-tree-name",children:Dt(r.path)}),n.jsx("span",{className:"file-tree-path",children:Jn(r,o("conversation.filePanelSessionDeleted"))})]}),n.jsxs("span",{className:"file-session-item-meta",children:[n.jsx("span",{className:"file-session-badge","data-status":r.status,children:r.status}),n.jsx("span",{className:"file-session-badge subtle",children:r.staged?o("git.stagedLabel"):o("git.workingTreeLabel")})]})]})},`session-list:${r.path}`))}function gt(t,i){return`file-panel.session-changes.${t}.${i}`}function Jt(t,i){return t instanceof Yn?t.message:typeof t=="object"&&t&&"message"in t?String(t.message??i):i}const g="",Yi=450,te=8,Pt=4,Zi=176,Ji=120,Qi=300*1e3,Ii=60*1e3,On=1600,ea=20,ta=16;function Ka({className:t,sessionId:i,workspaceId:l,hideHeading:r=!1,hideTabs:h=!1,externalRevealRequest:d=null,externalWindowMode:p=!1,workbenchShellOverrides:y}){var Tn,Fn;const C=Ti(),{navigationGroups:F,subscribeFileTree:_,requestFileTreeRefresh:Z,addFileTreeSnapshotListener:he,subscribeGitSnapshot:V,requestGitRefresh:me,addGitSnapshotListener:pe}={...C,...y},[K,ft]=c.useState({}),[M,Ce]=c.useState([]),[Tt,je]=c.useState([]),[E,A]=c.useState(g),[O,k]=c.useState([]),[Me,G]=c.useState(null),[Re,v]=c.useState(!1),[b,w]=c.useState(!1),[N,dt]=c.useState(!1),[Ge,Xe]=c.useState(!1),[B,qe]=c.useState(""),[Ft,X]=c.useState(null),[ht,mt]=c.useState(!1),[Se,Ye]=c.useState(null),[q,Ze]=c.useState("workspace"),[sn,_e]=c.useState(0),[on,At]=c.useState(0),[Je,J]=c.useState(!1),[Qe,L]=c.useState(!1),[ie,H]=c.useState(null),[be,Te]=c.useState(null),[W,Fe]=c.useState(null),[P,Bt]=c.useState(null),[S,Ie]=c.useState(null),[Lt,Ae]=c.useState(""),[rn,cn]=c.useState([]),[Q,Wt]=c.useState(!1),[oi,ve]=c.useState(null),un=c.useId(),ae=c.useRef({}),le=c.useRef({}),T=c.useRef([]),I=c.useRef(g),et=c.useRef(!1),tt=c.useRef(null),fn=c.useRef(null),dn=c.useRef(null),$t=c.useRef(null),hn=c.useRef(null),mn=c.useRef(null),ye=c.useRef(0),se=c.useRef(new Map),{showToast:j}=Zn(),nt=wi(),ee=Ei(e=>e.showSystemFiles),it=!!(i!=null&&i.trim()),pn=r&&nt.isMobile;c.useEffect(()=>{ke("file_panel.props",{sessionId:i,workspaceId:l,externalWindowMode:p})},[p,i,l]),c.useEffect(()=>{I.current=E},[E]);function we(e){ft(a=>{const s=typeof e=="function"?e(a):e;return ae.current=s,s})}function Be(e){Ce(a=>{const s=typeof e=="function"?e(a):e;return T.current=s,s})}c.useEffect(()=>{var f,m;if(Ut(),!l){Ut(),et.current=!1,ae.current={},le.current={},T.current=[],I.current=g,we({}),Be([]),je([]),A(g),Xe(!1),qe(""),X(null),mt(!1),v(!1),Wt(!1),ve(null),k([]),G(null),H(null),Te(null),Fe(null),Ie(null),Ae("");return}et.current=!0;const e=en(Kn(l),Qi);ke("file_panel.workspace_snapshot",{workspaceId:l,cached:!!e,cachedRootItems:((m=(f=e==null?void 0:e.treeCache)==null?void 0:f[g])==null?void 0:m.length)??0,cachedDirectoryCount:Object.keys((e==null?void 0:e.treeCache)??{}).length});const a=xa((e==null?void 0:e.activeDirectoryPath)??g,(e==null?void 0:e.treeCache)??{}),s=Vn((e==null?void 0:e.expandedDirectories)??[],a),u=St((e==null?void 0:e.treeCache)??{},a,s);ae.current=u,le.current=Gn((e==null?void 0:e.treeRevisionByPath)??{},u),T.current=s,I.current=a,we(u),Be(s),je([]),A(a),v(!1),w(!1),Xe(!1),qe(""),X(null),mt(!1),queueMicrotask(()=>{et.current=!1})},[l]),c.useEffect(()=>{if(!d||d.workspaceId!==l)return;const e=()=>{if(mn.current===d.requestId)return;mn.current=d.requestId,Ze("workspace"),(d.openViewer?He(d.filePath):re(d.filePath)).catch(s=>{j({title:ne(s,o("conversation.filePanelOpenFailed")),tone:"error"})})};if(et.current){queueMicrotask(e);return}e()},[d,He,re,j,l]),c.useEffect(()=>{if(l)return he(e=>{e.workspaceId===l&&(le.current={...le.current,[e.path]:typeof e.revision=="string"?e.revision:null},we(a=>({...a,[e.path]:e.items})),e.path===g&&v(!1),je(a=>a.filter(s=>s!==e.path)),ui(e.path,e.items))})},[he,l]),c.useEffect(()=>()=>{Ut()},[]),c.useEffect(()=>{l&&_(l,It(T.current,I.current),{knownRevisionByPath:le.current})},[E,M,_,l]),c.useEffect(()=>{k([]),G(null),Ye(null),ve(null),_e(0),J(!1),L(!1),H(null),Te(null),Fe(null),Ie(null),Ae(""),tt.current=null,ye.current+=1},[i]),c.useEffect(()=>{!it&&q==="session"&&Ze("workspace")},[q,it]),c.useEffect(()=>{h&&q!=="workspace"&&Ze("workspace")},[q,h]),c.useEffect(()=>{if(!Je&&!Qe&&!ie)return;function e(s){var x,D,ue;if(!(s.target instanceof Node))return;const u=((x=fn.current)==null?void 0:x.contains(s.target))??!1,f=((D=dn.current)==null?void 0:D.contains(s.target))??!1,m=((ue=$t.current)==null?void 0:ue.contains(s.target))??!1;!u&&!f&&!m&&(J(!1),L(!1),H(null),Te(null))}function a(s){s.key==="Escape"&&(J(!1),L(!1),H(null),Te(null))}return document.addEventListener("pointerdown",e),document.addEventListener("keydown",a),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",a)}},[Je,Qe,ie]),c.useLayoutEffect(()=>{if(!ie||typeof window>"u"){Te(null);return}const e=ie;function a(){const u=$t.current;if(!u)return;const f=u.getBoundingClientRect();Te(ca({x:e.positionX,y:e.positionY},{width:f.width||Zi,height:f.height||u.scrollHeight||0},{width:window.innerWidth,height:window.innerHeight}))}a();const s=window.requestAnimationFrame(a);return window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),()=>{window.cancelAnimationFrame(s),window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0)}},[ie]),c.useEffect(()=>{if(!l)return;const e=Vn(M,E),a=St(K,E,e);wt(Kn(l),{treeCache:a,treeRevisionByPath:Gn(le.current,a),expandedDirectories:e,activeDirectoryPath:E})},[E,M,K,l]),c.useEffect(()=>{if(et.current)return;const e=St(K,E,M);Pa(K,e)||we(e)},[E,M,K]),c.useEffect(()=>{let e=!1;const a=(l==null?void 0:l.trim())??null;async function s(f){if(!a)return;const m=Nt(ae.current[g]??[],ee),x=(f==null?void 0:f.silent)!==!0&&m.length===0;x&&v(!0),ke("file_panel.load_root_tree.start",{sessionId:i,workspaceId:a,silent:(f==null?void 0:f.silent)===!0,cachedRootItems:m.length});try{const D=await zt(g,{force:!0});e||(ke("file_panel.load_root_tree.end",{sessionId:i,workspaceId:a,itemCount:D.length}),we(ue=>({...St(ue,I.current,T.current),[g]:D})))}catch(D){!e&&!Xn(D)&&j({title:ne(D,o("conversation.filePanelLoadFailed")),tone:"error"})}finally{!e&&x&&v(!1)}}if(Nt(ae.current[g]??[],ee).length>0){const f=window.setTimeout(()=>{a&&(_(a,It(T.current,I.current),{knownRevisionByPath:le.current}),s({silent:!0}))},1500);return()=>{e=!0,window.clearTimeout(f)}}return s(),()=>{e=!0}},[i,ee,j,l]),c.useEffect(()=>{if(!l||!i){At(0);return}const e=en(Ca(l,i),Ii);ke("file_panel.session_change_count.snapshot",{sessionId:i,workspaceId:l,cached:e!==null,cachedCount:e}),At(e??0)},[i,sn,l]),c.useEffect(()=>{if(!l){cn([]);return}const e=l.trim();V(e),me(e)},[l,V,me]),c.useEffect(()=>{if(!l)return;const e=l.trim();return pe(a=>{var s;a.workspaceId===e&&cn(((s=a.status)==null?void 0:s.changes)??[])})},[pe,l]);const pt=c.useMemo(()=>nn(rn,e=>xt(e.path),ee),[rn,ee]),$=c.useMemo(()=>{const e=new Map,a=new Set;for(const s of pt){const u=s.path.replace(/\\/g,"/"),f=s.worktreeStatus??s.stagedStatus??s.status;e.set(u,f);const m=u.split("/");for(let x=1;x<m.length;x++)a.add(m.slice(0,x).join("/"))}return{statusByPath:e,changedDirs:a}},[pt]),Ne=c.useMemo(()=>zi(K,ee),[ee,K]),De=c.useMemo(()=>Ft===null?null:Nt(Ft,ee),[Ft,ee]),Le=Ne[g]??[],oe=Ge&&De!==null,bt=c.useMemo(()=>Q?tn(Le,Ne,$.statusByPath,$.changedDirs):Le,[$.changedDirs,$.statusByPath,Le,Q,Ne]),ri=c.useMemo(()=>oe?(De??[]).map(e=>U(e.path,e.kind)):ti(bt,Ne,M,Q,$.statusByPath,$.changedDirs),[M,$.changedDirs,$.statusByPath,oe,Q,De,Ne,bt]),We=((Tn=F.find(e=>e.workspace.id===l))==null?void 0:Tn.workspace)??null,R=Un(O),Ot=(R==null?void 0:R.path)??null,xe=(R==null?void 0:R.kind)==="file"?R.path:null,vt=c.useMemo(()=>new Set(O.map(e=>e.path)),[O]),at=c.useMemo(()=>jt(O),[O]),Ht=!!(We!=null&&We.path&&O.length===1&&Ot),bn=O.length===1&&(R==null?void 0:R.kind)==="file",vn=at.length>0,Ee=at.length>0,lt=!!(P!=null&&P.items.length&&l),yn=!!l&&O.length===1&&R!==null,xn=!!((xe?de(xe):E)&&M.length),gn=P?P.mode==="copy"?o("conversation.filePanelClipboardCopyReady",{count:P.items.length}):o("conversation.filePanelClipboardCutReady",{count:P.items.length}):null,z=S?ha(S):null;async function Pn(e,a=!1){if(!l)return[];if(!a){const s=ae.current[e];if(s)return s}e===g?v(!0):je(s=>kt(s,e));try{const s=await zt(e,{force:a});return we(u=>({...u,[e]:s})),s}catch(s){throw Xn(s)||j({title:ne(s,o("conversation.filePanelLoadFailed")),tone:"error"}),s}finally{e===g?v(!1):je(s=>s.filter(u=>u!==e))}}async function ge(e){if(!l)return;const a=(e==null?void 0:e.activeDirectoryPath)??I.current,s=(e==null?void 0:e.expandedDirectories)??T.current,u=ga(ae.current,a,s);ke("file_panel.refresh_tree_cache.start",{sessionId:i,workspaceId:l,targetDirectories:u});const m=(await Promise.all(u.map(async x=>{const D=await zt(x,{force:!0});return[x,D]}))).reduce((x,[D,ue])=>(x[D]=ue,x),{});ke("file_panel.refresh_tree_cache.end",{sessionId:i,workspaceId:l,targetDirectories:u,directoryCount:Object.keys(m).length}),we(m)}async function zt(e,a){if(!l)return[];if(!(a!=null&&a.force)){const u=ae.current[e];if(u)return u}const s=It(kt(T.current,e),e||I.current);return _(l,s,{knownRevisionByPath:le.current}),Z(l,[e],{knownRevisionByPath:le.current}),ci(e,On,{allowCached:(a==null?void 0:a.force)!==!0})}function ci(e,a=On,s){const u=ae.current[e];return(s==null?void 0:s.allowCached)!==!1&&u?Promise.resolve(u):new Promise((f,m)=>{const x=window.setTimeout(()=>{fi(e,x),m(new Error(`FILE_TREE_SNAPSHOT_TIMEOUT:${e}`))},a),D=se.current.get(e)??[];se.current.set(e,[...D,{resolve:f,reject:m,timerId:x}])})}function ui(e,a){const s=se.current.get(e)??[];s.length!==0&&(se.current.delete(e),s.forEach(u=>{window.clearTimeout(u.timerId),u.resolve(a)}))}function fi(e,a){const u=(se.current.get(e)??[]).filter(f=>f.timerId!==a);if(u.length===0){se.current.delete(e);return}se.current.set(e,u)}function Ut(){for(const[e,a]of se.current.entries())a.forEach(s=>{window.clearTimeout(s.timerId),s.reject(new Error(`FILE_TREE_ABORTED:${e}`))});se.current.clear()}function $e(e){k([e]),G(e.path)}function st(e){A(e.kind==="directory"?e.path:de(e.path))}function di(e){const a=aa(ri,Me,e);k(a),G(e.path),st(e)}function hi(e){const a=ia(O,e),s=Un(a);k(a),G(e.path),s&&st(s)}function Cn(e){$e(e),st(e)}function Oe(e,a){if(a!=null&&a.shiftKey){di(e);return}if(Ct(a)){hi(e);return}Cn(e)}async function ot(e,a=!1){const s=ut(e,a);if(!s.length){A(g);return}Be(u=>li(u,s)),A(s[s.length-1]??g);for(const u of s)try{await Pn(u)}catch{return}}async function re(e){const a=U(e,"file");$e(a),st(a),await ot(e)}async function He(e){Ye(e),ve(null),tt.current=null,ye.current+=1,re(e);const a=ye.current,s=e.replace(/\\/g,"/"),u=$.statusByPath.get(s);if(l&&u&&u!=="?"&&u!=="D")try{const f=await Fi(l,e,!1);ye.current===a&&ve(f.content||null)}catch{ye.current===a&&ve(null)}}function jn(e){const a=Date.now(),s=tt.current;return tt.current={filePath:e,timestamp:a},(s==null?void 0:s.filePath)===e&&a-s.timestamp<=Yi}function Pe(){tt.current=null}async function mi(e,a){const s=U(e,"file");if(a!=null&&a.shiftKey||Ct(a)){Pe(),Oe(s,a);return}if(jn(e)){await He(e);return}Oe(s,a),await ot(e)}function Sn(){Xe(!1),qe(""),X(null),Pe()}async function pi(e,a){const s=U(e.path,e.kind);if(a!=null&&a.shiftKey||Ct(a)){Pe(),Oe(s,a);return}if(e.kind==="directory"){Sn(),Oe(s,a),await wn(e.path);return}if(jn(e.path)){Sn(),await He(e.path);return}await re(e.path)}async function wn(e){if($e(U(e,"directory")),A(e),!T.current.includes(e))try{await Pn(e),Be(a=>kt(a,e))}catch{}}async function Nn(e){if($e(U(e,"directory")),A(e),T.current.includes(e)){Dn(e);return}await wn(e)}function Dn(e){Be(a=>a.filter(s=>s!==e&&!s.startsWith(`${e}/`))),A(de(e)),k([]),G(null)}async function En(){if(!l)return;const e=l;try{if(me(e),await ge(),xe&&await ot(xe),oe&&B.trim()){const a=await Ve(e,B.trim());X(a.items)}}catch(a){j({title:ne(a,o("conversation.filePanelLoadFailed")),tone:"error"})}}async function bi(e){if(e==null||e.preventDefault(),!l||!B.trim()){X(null);return}mt(!0);try{const a=await Ve(l,B.trim());X(a.items)}catch(a){j({title:ne(a,o("conversation.filePanelSearchFailed")),tone:"error"})}finally{mt(!1)}}function kn(){if(Ge){Xe(!1),qe(""),X(null);return}Xe(!0)}function Y(e){L(!1),e()}function Mn(){var e;(e=hn.current)==null||e.click()}async function vi(e){var m;const a=((m=e.target.files)==null?void 0:m[0])??null;if(e.target.value="",!a||!l)return;const s=na(a.name);if(!s){j({title:o("conversation.filePanelUploadFailed"),tone:"error"});return}const u=Hn(E,R),f=zn(u,s);dt(!0);try{const x=await ma(a);await Ai({workspaceId:l,path:f,contentBase64:x}),await ge(),await re(f),j({title:o("conversation.filePanelUploadSuccess",{name:s}),tone:"success"})}catch(x){j({title:ne(x,o("conversation.filePanelUploadFailed")),tone:"error"})}finally{dt(!1)}}async function Vt(e=xe){if(!(!l||!e)){dt(!0);try{const a=await Bi(l,e),s=pa(a.contentBase64);ba(a.fileName,new Blob([s],{type:"application/octet-stream"})),j({title:o("conversation.filePanelDownloadSuccess",{name:a.fileName}),tone:"success"})}catch(a){j({title:ne(a,o("conversation.filePanelDownloadFailed")),tone:"error"})}finally{dt(!1)}}}function Rn(){const e=xe?de(xe):E;!e||!T.current.includes(e)||Dn(e)}function Kt(){Ie(null),Ae("")}function Gt(){b||Kt()}function ze(e,a=Hn(E,R)){if(!l)return;const s=a,u=s?`${s}/`:"";J(!1),L(!1),H(null),Ie({mode:e,baseDirectory:s}),Ae(u)}function Xt(e=R){!l||!e||(J(!1),L(!1),H(null),Ie({mode:"rename",target:e}),Ae(e.path))}async function yi(e){if(e==null||e.preventDefault(),!l||!S)return;const a=(Lt??"").trim();if(a){if(S.mode==="rename"&&Ke(S.target.path)===Ke(a)){Gt();return}w(!0);try{if(S.mode==="rename"){const s=S.target.path,u=U(a,S.target.kind),f=Se?ai(Se,s,a):null;if(await yt({workspaceId:l,opType:"rename",srcPath:s,dstPath:a}),P&&Bt({...P,items:da(P.items,s,a)}),Kt(),Pe(),await ge(),S.target.kind==="directory"?(await ot(a,!0),$e(u),A(a)):await re(a),f!==Se&&(ye.current+=1,Ye(f),ve(null)),oe&&B.trim()){const m=await Ve(l,B.trim());X(m.items)}_e(m=>m+1),j({title:o("conversation.filePanelRenameSuccess",{name:xt(a)||a}),tone:"success"});return}if(await yt({workspaceId:l,opType:S.mode,dstPath:a,content:S.mode==="create_file"?"":void 0}),Kt(),await ge(),S.mode==="create_directory"?(await ot(a,!0),$e(U(a,"directory")),A(a)):await re(a),oe&&B.trim()){const s=await Ve(l,B.trim());X(s.items)}_e(s=>s+1)}catch(s){j({title:ne(s,o("conversation.filePanelMutateFailed")),tone:"error"})}finally{w(!1)}}}function ce(e,a=at){var u;if(a.length===0)return;const s=jt(a);Bt({mode:e,items:s}),k(s),G(((u=s[s.length-1])==null?void 0:u.path)??null),j({title:e==="copy"?o("conversation.filePanelCopySelectionSuccess",{count:s.length}):o("conversation.filePanelCutSelectionSuccess",{count:s.length}),tone:"success"}),H(null)}async function rt(e=oa(R,E)){if(!l||!P||!P.items.length)return;const a=e??g,s=P.items.map(u=>({source:u,destinationPath:zn(a,xt(u.path)||u.path)}));w(!0);try{for(const m of s)P.mode==="cut"&&Ke(m.source.path)===Ke(m.destinationPath)||await yt({workspaceId:l,opType:P.mode==="copy"?"copy":"move",srcPath:m.source.path,dstPath:m.destinationPath});const u=s.map(m=>U(m.destinationPath,m.source.kind)),f=u[u.length-1]??null;if(P.mode==="cut"&&Bt(null),k(u),G((f==null?void 0:f.path)??null),f&&st(f),Pe(),await ge({activeDirectoryPath:(f==null?void 0:f.kind)==="directory"?f.path:f?de(f.path):I.current,expandedDirectories:T.current}),oe&&B.trim()){const m=await Ve(l,B.trim());X(m.items)}_e(m=>m+1),j({title:o("conversation.filePanelPasteSuccess",{count:u.length}),tone:"success"}),H(null)}catch(u){await ge().catch(()=>{}),j({title:ne(u,o("conversation.filePanelPasteFailed")),tone:"error"})}finally{w(!1)}}function qt(e=at){!e.length||b||(Fe(jt(e)),H(null))}async function xi(){var a,s;if(!l||!(W!=null&&W.length))return;const e=jt(W);w(!0);try{for(const m of e)await yt({workspaceId:l,opType:"delete",srcPath:m.path});const u=ra(E,e),f=T.current.filter(m=>!e.some(x=>x.kind==="directory"&&_t(x.path,m)));if(Se&&e.some(m=>_t(m.path,Se))&&(ye.current+=1,Ye(null),ve(null)),Fe(null),k([]),G(null),I.current=u,T.current=f,A(u),Be(f),Pe(),await ge({activeDirectoryPath:u,expandedDirectories:f}),oe&&B.trim()){const m=await Ve(l,B.trim());X(m.items)}_e(m=>m+1),j({title:e.length===1?o("conversation.filePanelDeleteSuccess",{name:xt(((a=e[0])==null?void 0:a.path)??"")||((s=e[0])==null?void 0:s.path)||""}):o("conversation.filePanelDeleteSelectionSuccess",{count:e.length}),tone:"success"})}catch(u){j({title:ne(u,o("conversation.filePanelMutateFailed")),tone:"error"})}finally{w(!1)}}async function Ue(e,a=R){const s=(We==null?void 0:We.path)??"",u=(a==null?void 0:a.path)??null;if(u===null||!s){J(!1);return}try{const f=fa(s),m=e==="absolute"?ua(s,u,f):Ke(u,f);await va(m,nt),j({title:e==="absolute"?o("conversation.filePanelCopyAbsolutePathSuccess"):o("conversation.filePanelCopyRelativePathSuccess"),tone:"success"})}catch(f){j({title:f instanceof Error?f.message:o("conversation.filePanelCopyPathFailed"),tone:"error"})}finally{J(!1),H(null)}}function gi(e,a,s){return[{id:`open-${e.path}`,label:e.kind==="directory"?M.includes(e.path)?o("conversation.filePanelCollapseDirectory"):o("conversation.filePanelExpandDirectory"):o("conversation.filePanelOpenFile"),onSelect:()=>{if(e.kind==="directory"){Nn(e.path);return}He(e.path)}},{id:`download-${e.path}`,label:o("conversation.filePanelDownload"),disabled:e.kind!=="file"||N,onSelect:()=>{Vt(e.kind==="file"?e.path:null)}},{id:`create-file-${e.path}`,label:o("conversation.filePanelNewFile"),disabled:!l||b||N,onSelect:()=>{ze("create_file",s)}},{id:`create-directory-${e.path}`,label:o("conversation.filePanelNewDirectory"),disabled:!l||b||N,onSelect:()=>{ze("create_directory",s)}},{id:`rename-${e.path}`,label:o("conversation.filePanelRenameMove"),disabled:a.length!==1||b||N,onSelect:()=>Xt(e)},{id:`copy-${e.path}`,label:o("conversation.filePanelCopy"),disabled:a.length===0,onSelect:()=>ce("copy",a)},{id:`cut-${e.path}`,label:o("conversation.filePanelCut"),disabled:a.length===0,onSelect:()=>ce("cut",a)},{id:`paste-${e.path}`,label:o("conversation.filePanelPaste"),disabled:!lt,onSelect:()=>{rt(s)}},{id:`copy-relative-${e.path}`,label:o("conversation.filePanelCopyRelativePath"),onSelect:()=>{Ue("relative",e)}},{id:`copy-absolute-${e.path}`,label:o("conversation.filePanelCopyAbsolutePath"),onSelect:()=>{Ue("absolute",e)}},{id:`delete-${e.path}`,label:o("conversation.filePanelDelete"),disabled:a.length===0||b||N,onSelect:()=>qt(a)}]}async function _n(e,a){if(nt.isMobile)return;e.preventDefault();const s=U(a.path,a.kind),u=vt.has(s.path)?at:[s],f=s.kind==="directory"?s.path:de(s.path);vt.has(s.path)||Cn(s);const m=gi(s,u,f);if(nt.isDesktop){await Li(m);return}nt.isWeb&&(J(!1),L(!1),H({positionX:e.clientX,positionY:e.clientY,items:m}))}c.useEffect(()=>{if(q!=="workspace")return;function e(a){if(!la(a)||a.altKey||a.shiftKey||sa(a.target))return;const s=a.key.toLowerCase();if(s==="c"&&Ee){a.preventDefault(),ce("copy");return}if(s==="x"&&Ee){a.preventDefault(),ce("cut");return}s==="v"&<&&(a.preventDefault(),rt())}return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[q,Ee,lt,ce,rt]);function Yt(e,a){return n.jsx(n.Fragment,{children:e.map(s=>{const u=U(s.path,s.kind),f=s.kind==="directory",m=f&&M.includes(s.path),x=f&&Tt.includes(s.path),D=Ne[s.path]??[],ue=Q?tn(D,Ne,$.statusByPath,$.changedDirs):D,Ci=vt.has(s.path),ji=Ot===s.path,ct=$.statusByPath.get(s.path.replace(/\\/g,"/")),An=f&&$.changedDirs.has(s.path.replace(/\\/g,"/")),Si=(P==null?void 0:P.mode)==="cut"&&P.items.some(fe=>fe.path===s.path);return n.jsxs("div",{className:"file-tree-node",children:[n.jsxs("button",{className:"file-tree-item",type:"button","data-active":ji,"data-selected":Ci,"data-cut-pending":Si||void 0,"data-kind":s.kind,"aria-expanded":f?m:void 0,style:{paddingInlineStart:`${ea+a*ta}px`},onClick:fe=>{if(f){if(fe.shiftKey||Ct(fe)){Pe(),Oe(u,fe);return}Pe(),Oe(u,fe),Nn(s.path);return}mi(s.path,fe)},onContextMenu:fe=>{_n(fe,s)},children:[n.jsx("span",{className:`file-tree-chevron${f?"":" is-hidden"}`,"aria-hidden":"true",children:m?"v":">"}),f?null:n.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(s.name),"aria-hidden":"true",children:Mt(s.name)}),n.jsx("span",{className:"file-tree-label","data-status":ct??void 0,"data-has-changes":An||void 0,children:s.name}),!f&&ct?n.jsx("span",{className:"git-status-badge","data-status":ct,"aria-label":ct,children:ct}):null,f&&An?n.jsx("span",{className:"file-tree-dir-badge","aria-hidden":"true"}):null,x?n.jsx("span",{className:"file-tree-meta",children:o("common.loading")}):null]}),f&&m?n.jsx("div",{className:"file-tree-children",children:x&&!D.length?n.jsx("p",{className:"file-tree-empty",children:o("common.loading")}):ue.length?Yt(ue,a+1):n.jsx("p",{className:"file-tree-empty",children:o("conversation.filePanelEmptyDirectory")})}):null]},`${s.kind}-${s.path}`)})})}function Pi(e){return n.jsx(n.Fragment,{children:e.map(a=>{const s=a.kind==="directory",u=vt.has(a.path),f=Ot===a.path;return n.jsx("div",{className:"file-tree-node",children:n.jsxs("button",{className:"file-tree-item is-search-result",type:"button","data-active":f,"data-selected":u,"data-kind":a.kind,onClick:m=>{pi(a,m)},onContextMenu:m=>{_n(m,a)},children:[n.jsx("span",{className:"file-tree-chevron is-hidden","aria-hidden":"true",children:">"}),s?null:n.jsx("span",{className:"git-tree-file-icon","data-kind":Rt(a.name),"aria-hidden":"true",children:Mt(a.name)}),n.jsxs("span",{className:"file-tree-label",children:[n.jsx("span",{className:"file-tree-name",children:a.name}),n.jsx("span",{className:"file-tree-path",children:a.path})]})]})},`search-${a.kind}-${a.path}`)})})}return n.jsx("section",{className:["conversation-panel","surface-card","file-panel",t].filter(Boolean).join(" "),"data-testid":"file-context-panel",children:l?n.jsxs(n.Fragment,{children:[n.jsx(Wi,{workspaceId:l,filePath:Se,open:Se!==null,onClose:()=>{ye.current+=1,Ye(null),ve(null)},onSaved:async e=>{await ge(),await re(e),_e(a=>a+1)},diffContent:oi}),r?null:n.jsx("div",{className:"file-panel-heading-row",children:n.jsx("h2",{className:"file-panel-heading",children:o("conversation.filePanelTitle")})}),h?null:n.jsxs("div",{className:"file-panel-tabs",role:"tablist","aria-label":o("conversation.filePanelTitle"),children:[n.jsx("button",{className:q==="workspace"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":q==="workspace",onClick:()=>Ze("workspace"),children:o("conversation.filePanelWorkspaceTab")}),n.jsxs("button",{className:q==="session"?"file-panel-tab active":"file-panel-tab",type:"button",role:"tab","aria-selected":q==="session",onClick:()=>{it&&Ze("session")},disabled:!it,children:[o("conversation.filePanelSessionTab"),n.jsx("span",{className:"file-panel-tab-badge","aria-label":`${o("conversation.filePanelSessionTab")} ${on}`,children:on})]})]}),q==="workspace"?n.jsxs(n.Fragment,{children:[n.jsx("input",{ref:hn,"data-testid":"file-panel-upload-input",type:"file",hidden:!0,onChange:e=>void vi(e)}),pn?n.jsx("div",{className:"file-panel-toolbar file-panel-toolbar-mobile","aria-label":o("conversation.filePanelTitle"),children:n.jsxs("div",{className:"file-mobile-action-shell",ref:dn,children:[n.jsxs("button",{className:"secondary-button file-mobile-action-trigger",type:"button","aria-label":o("conversation.filePanelActionsMenu"),"aria-haspopup":"menu","aria-expanded":Qe,"data-active":Qe,onClick:()=>{J(!1),L(e=>!e)},children:[n.jsx("span",{children:o("conversation.filePanelActionsMenu")}),n.jsx(Aa,{})]}),Qe?n.jsxs("div",{className:"file-mobile-action-menu",role:"menu","aria-label":o("conversation.filePanelActionsMenu"),children:[n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>ce("copy")),disabled:!Ee,children:o("conversation.filePanelCopy")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>ce("cut")),disabled:!Ee,children:o("conversation.filePanelCut")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>rt()),disabled:!lt||b||N,children:o("conversation.filePanelPaste")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),kn()},children:Ge?o("conversation.filePanelHideSearch"):o("conversation.filePanelShowSearch")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Wt(e=>!e)},disabled:pt.length===0,children:Q?o("conversation.filePanelShowAll"):o("conversation.filePanelFilterChanges")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(En),disabled:Re||b||ht,children:o("conversation.filePanelRefresh")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Rn()},disabled:!xn,children:o("conversation.filePanelCollapseCurrent")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>{L(!1),Mn()},disabled:b||N,children:o("conversation.filePanelUpload")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(Vt),disabled:!bn||N,children:o("conversation.filePanelDownload")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(Xt),disabled:!yn||b||N,children:o("conversation.filePanelRenameMove")}),n.jsx("button",{className:"file-mobile-action-menu-item danger",type:"button",role:"menuitem",onClick:()=>Y(qt),disabled:!vn||b||N,children:o("conversation.filePanelDelete")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>ze("create_file")),disabled:b||N,children:o("conversation.filePanelNewFile")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>ze("create_directory")),disabled:b||N,children:o("conversation.filePanelNewDirectory")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Ue("absolute")),disabled:!Ht,children:o("conversation.filePanelCopyAbsolutePath")}),n.jsx("button",{className:"file-mobile-action-menu-item",type:"button",role:"menuitem",onClick:()=>Y(()=>Ue("relative")),disabled:!Ht,children:o("conversation.filePanelCopyRelativePath")})]}):null]})}):n.jsxs("div",{className:"file-panel-toolbar","aria-label":o("conversation.filePanelTitle"),children:[n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelCopy"),"aria-label":o("conversation.filePanelCopy"),onClick:()=>ce("copy"),disabled:!Ee,children:n.jsx(Na,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelCut"),"aria-label":o("conversation.filePanelCut"),onClick:()=>ce("cut"),disabled:!Ee,children:n.jsx(Da,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelPaste"),"aria-label":o("conversation.filePanelPaste"),onClick:()=>void rt(),disabled:!lt||b||N,children:n.jsx(Ea,{})}),n.jsxs("div",{className:"file-toolbar-menu-shell",ref:fn,children:[n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelCopyPath"),"aria-label":o("conversation.filePanelCopyPath"),"aria-haspopup":"menu","aria-expanded":Je,"data-active":Je,onClick:()=>{L(!1),J(e=>!e)},disabled:!Ht,children:n.jsx(wa,{})}),Je?n.jsxs("div",{className:"file-toolbar-menu",role:"menu",children:[n.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Ue("absolute"),children:o("conversation.filePanelCopyAbsolutePath")}),n.jsx("button",{className:"file-toolbar-menu-item",type:"button",role:"menuitem",onClick:()=>void Ue("relative"),children:o("conversation.filePanelCopyRelativePath")})]}):null]}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelCollapseCurrent"),"aria-label":o("conversation.filePanelCollapseCurrent"),onClick:Rn,disabled:!xn,children:n.jsx(ja,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelRefresh"),"aria-label":o("conversation.filePanelRefresh"),onClick:()=>void En(),disabled:Re||b||ht,children:n.jsx(Sa,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelSearchButton"),"aria-label":o("conversation.filePanelSearchButton"),"data-active":Ge,onClick:kn,disabled:Re,children:n.jsx(qn,{})}),pt.length>0?n.jsx("button",{className:"file-toolbar-button",type:"button",title:Q?o("conversation.filePanelShowAll"):o("conversation.filePanelFilterChanges"),"aria-label":Q?o("conversation.filePanelShowAll"):o("conversation.filePanelFilterChanges"),"data-active":Q,onClick:()=>Wt(e=>!e),children:n.jsx(Ba,{})}):null,n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelUpload"),"aria-label":o("conversation.filePanelUpload"),onClick:Mn,disabled:b||N,children:n.jsx(Ma,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelDownload"),"aria-label":o("conversation.filePanelDownload"),onClick:()=>void Vt(),disabled:!bn||N,children:n.jsx(Ra,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelRenameMove"),"aria-label":o("conversation.filePanelRenameMove"),onClick:()=>Xt(),disabled:!yn||b||N,children:n.jsx(Fa,{})}),n.jsx("button",{className:"file-toolbar-button danger",type:"button",title:o("conversation.filePanelDelete"),"aria-label":o("conversation.filePanelDelete"),onClick:()=>qt(),disabled:!vn||b||N,children:n.jsx(_a,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelNewFile"),"aria-label":o("conversation.filePanelNewFile"),onClick:()=>void ze("create_file"),disabled:b||N,children:n.jsx(ka,{})}),n.jsx("button",{className:"file-toolbar-button",type:"button",title:o("conversation.filePanelNewDirectory"),"aria-label":o("conversation.filePanelNewDirectory"),onClick:()=>void ze("create_directory"),disabled:b||N,children:n.jsx(Ta,{})})]}),ie&&typeof document<"u"?Ni.createPortal(n.jsx("div",{className:"file-web-context-menu",ref:$t,role:"menu","aria-label":o("conversation.filePanelActionsMenu"),style:{left:`${(be==null?void 0:be.left)??Math.max(8,ie.positionX)}px`,top:`${(be==null?void 0:be.top)??Math.max(8,ie.positionY)}px`,maxHeight:be?`${be.maxHeight}px`:void 0},children:ie.items.map(e=>n.jsx("button",{className:["file-web-context-menu-item",e.label===o("conversation.filePanelDelete")?"danger":""].filter(Boolean).join(" "),type:"button",role:"menuitem",disabled:e.disabled,onClick:()=>{H(null),e.onSelect()},children:e.label},e.id))}),document.body):null,gn?n.jsx("p",{className:"file-panel-clipboard-status","data-mode":P==null?void 0:P.mode,children:gn}):null,Ge?n.jsxs("form",{className:"file-toolbar-search",onSubmit:e=>void bi(e),children:[n.jsx("input",{value:B,onChange:e=>qe(e.target.value),placeholder:o("conversation.filePanelSearchPlaceholder")}),pn?n.jsx("button",{className:"secondary-button file-mobile-search-submit",type:"submit","aria-label":o("conversation.filePanelSearchButton"),disabled:ht,children:o("conversation.filePanelSearchButton")}):n.jsx("button",{className:"file-toolbar-button",type:"submit",title:o("conversation.filePanelSearchButton"),"aria-label":o("conversation.filePanelSearchButton"),disabled:ht,children:n.jsx(qn,{})})]}):null,n.jsx("div",{className:"file-tree","data-search-mode":oe,children:Re&&Le.length===0?n.jsx("p",{className:"file-tree-status status-text",children:o("common.loading")}):oe?De!=null&&De.length?Pi(De):n.jsx("p",{className:"file-tree-status status-text",children:o("conversation.filePanelSearchEmpty")}):Q?bt.length?Yt(bt,0):n.jsx("p",{className:"file-tree-status status-text",children:o("conversation.filePanelNoChanges")}):Le.length?Yt(Le,0):n.jsx("p",{className:"file-tree-status status-text",children:o("conversation.filePanelEmptyDirectory")})}),n.jsx(Bn,{open:S!==null,title:(z==null?void 0:z.title)??"",description:z==null?void 0:z.description,onClose:Gt,children:n.jsxs("form",{className:"workbench-rename-form",onSubmit:e=>void yi(e),children:[n.jsx(ki,{label:o("conversation.filePanelPathFieldLabel"),htmlFor:un,description:(S==null?void 0:S.mode)==="rename"?S.target.path:(S==null?void 0:S.baseDirectory)||void 0,children:n.jsx("input",{id:un,type:"text",value:Lt??"",placeholder:o("conversation.filePanelPathFieldPlaceholder"),autoFocus:!0,onChange:e=>Ae(e.target.value)})}),n.jsxs(Mi,{children:[n.jsx("button",{type:"button",className:"secondary-button",disabled:b,onClick:Gt,children:o("common.cancel")}),n.jsx("button",{type:"submit",className:"primary-button",disabled:b||!(Lt??"").trim(),children:b?(z==null?void 0:z.pendingLabel)??o("common.loading"):(z==null?void 0:z.submitLabel)??o("common.save")})]})]})}),n.jsxs(Bn,{open:W!==null,title:o("conversation.filePanelDeleteConfirmTitle"),description:o("conversation.filePanelDeleteConfirmDescription"),onClose:()=>{b||Fe(null)},children:[n.jsx("p",{className:"workbench-section-empty",children:W!=null&&W.length?W.length===1?((Fn=W[0])==null?void 0:Fn.kind)==="directory"?o("conversation.filePanelDeleteDirectoryConfirm",{path:W[0].path}):o("conversation.filePanelDeleteFileConfirm",{path:W[0].path}):o("conversation.filePanelDeleteSelectionConfirm",{count:W.length}):""}),n.jsxs("div",{className:"workbench-modal-actions",children:[n.jsx("button",{type:"button",className:"secondary-button",disabled:b,onClick:()=>Fe(null),children:o("common.cancel")}),n.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:b,onClick:()=>{xi()},children:b?o("conversation.filePanelDeleting"):o("conversation.filePanelDelete")})]})]})]}):it&&i?n.jsx(Xi,{sessionId:i,workspaceId:l,showSystemFiles:ee,selectedPath:xe,refreshVersion:sn,onCountChange:At,onSelectFile:re,onOpenFile:He}):n.jsx("section",{className:"file-panel-section",children:n.jsx("p",{className:"status-text",children:o("conversation.filePanelSessionNoSession")})})]}):n.jsx("section",{className:"file-panel-section",children:n.jsx("p",{className:"status-text",children:o("conversation.filePanelNoWorkspace")})})})}function de(t){return t.includes("/")?t.split("/").slice(0,-1).join("/"):g}function ut(t,i=!1){const l=t.split("/").filter(Boolean),r=i?l.length:l.length-1,h=[];for(let d=0;d<r;d+=1)h.push(l.slice(0,d+1).join("/"));return h}function Hn(t,i){return t||((i==null?void 0:i.kind)==="directory"?i.path:i!=null&&i.path?de(i.path):g)}function zn(t,i){return t?`${t}/${i}`:i}function na(t){var i;return((i=t.split(/[/\\]/).pop())==null?void 0:i.trim())??""}function U(t,i){return{path:t,kind:i}}function Un(t){return t[t.length-1]??null}function ia(t,i){return t.findIndex(r=>r.path===i.path)>=0?t.filter(r=>r.path!==i.path):[...t,i]}function aa(t,i,l){const r=t.findIndex(y=>y.path===l.path);if(r<0)return[l];const h=i?t.findIndex(y=>y.path===i):r;if(h<0)return[l];const d=Math.min(h,r),p=Math.max(h,r);return t.slice(d,p+1)}function Ct(t){return!!(t!=null&&t.ctrlKey||t!=null&&t.metaKey)}function la(t){return t.ctrlKey||t.metaKey}function sa(t){if(!(t instanceof HTMLElement))return!1;const i=t.tagName.toLowerCase();return i==="input"||i==="textarea"||i==="select"||t.isContentEditable}function jt(t){const i=[...new Map(t.map(r=>[r.path,r])).values()].sort((r,h)=>r.path.localeCompare(h.path)),l=[];for(const r of i)l.some(h=>h.kind==="directory"&&_t(h.path,r.path))||l.push(r);return l}function oa(t,i){return(t==null?void 0:t.kind)==="directory"?t.path:t!=null&&t.path?de(t.path):i}function ra(t,i){let l=t;for(;l&&i.some(r=>r.kind==="directory"&&_t(r.path,l));)l=de(l);return l}function ti(t,i,l,r,h,d){const p=[];for(const y of t){if(p.push(U(y.path,y.kind)),y.kind!=="directory"||!l.includes(y.path))continue;const C=i[y.path]??[],F=r?tn(C,i,h,d):C;p.push(...ti(F,i,l,r,h,d))}return p}function ca(t,i,l){const r=Math.max(0,l.width),h=Math.max(0,l.height),d=Math.max(0,h-te*2),p=Math.max(0,r-te*2),y=Math.min(Math.max(i.width,0),p),C=Math.max(0,h-t.y-Pt-te),F=Math.max(0,t.y-Pt-te),_=C<i.height&&F>C,he=Qt(Math.max(_?F:C,Ji),0,d),V=Math.min(Math.max(i.height,0),he),me=_?t.y-Pt-V:t.y+Pt,pe=Math.max(te,h-te-V),K=Math.max(te,r-te-y);return{top:Qt(me,te,pe),left:Qt(t.x,te,K),maxHeight:Math.max(0,he)}}function Qt(t,i,l){return!Number.isFinite(t)||l<i?i:Math.min(Math.max(t,i),l)}function Ke(t,i="posix"){return t?ni(t,i):"."}function ua(t,i,l){const r=ni(t,l),h=Ke(i,l).replace(/^\.[/\\]?/,"");if(!h)return r;const d=ii(l),p=h.replace(/^[/\\]+/,"");return p?r.endsWith("/")||r.endsWith("\\")?`${r}${p}`:`${r}${d}${p}`:r}function fa(t){return/^[a-zA-Z]:[\\/]/.test(t)||t.includes("\\")?"windows":"posix"}function ni(t,i){return t&&(ii(i)==="\\"?t.replace(/\//g,"\\"):t.replace(/\\/g,"/"))}function ii(t){return t==="windows"?"\\":"/"}function _t(t,i){return i===t||i.startsWith(`${t}/`)}function ai(t,i,l){return t===i?l:t.startsWith(`${i}/`)?`${l}${t.slice(i.length)}`:t}function da(t,i,l){return t.map(r=>({...r,path:ai(r.path,i,l)}))}function ha(t){return t.mode==="create_file"?{title:o("conversation.filePanelNewFile"),description:o("conversation.filePanelCreateFileDescription"),submitLabel:o("conversation.filePanelCreateFileSubmit"),pendingLabel:o("conversation.filePanelCreatingFile")}:t.mode==="create_directory"?{title:o("conversation.filePanelNewDirectory"),description:o("conversation.filePanelCreateDirectoryDescription"),submitLabel:o("conversation.filePanelCreateDirectorySubmit"),pendingLabel:o("conversation.filePanelCreatingDirectory")}:{title:o("conversation.filePanelRenameMove"),description:o("conversation.filePanelRenameDescription"),submitLabel:o("conversation.filePanelRenameSubmit"),pendingLabel:o("conversation.filePanelRenaming")}}async function ma(t){const i=await t.arrayBuffer(),l=new Uint8Array(i),r=32768;let h="";for(let d=0;d<l.length;d+=r){const p=l.subarray(d,d+r);h+=String.fromCharCode(...p)}return btoa(h)}function pa(t){const i=atob(t),l=new Uint8Array(i.length);for(let r=0;r<i.length;r+=1)l[r]=i.charCodeAt(r);return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}function ba(t,i){if(typeof document>"u")throw new Error(o("conversation.filePanelDownloadFailed"));const l=window.URL.createObjectURL(i),r=document.createElement("a");r.href=l,r.download=t,document.body.append(r),r.click(),r.remove(),window.URL.revokeObjectURL(l)}async function va(t,i){var l;if(!(i.isDesktop&&(await i.bridge.writeClipboardText(t)).ok)){if(typeof navigator<"u"&&((l=navigator.clipboard)!=null&&l.writeText))try{await navigator.clipboard.writeText(t);return}catch{}if(!ya(t))throw new Error(o("conversation.filePanelCopyPathFailed"))}}function ya(t){if(typeof document>"u"||typeof document.execCommand!="function")return!1;const i=document.createElement("textarea");i.value=t,i.setAttribute("readonly","true"),i.style.position="fixed",i.style.top="-9999px",i.style.left="-9999px",i.style.opacity="0",document.body.appendChild(i),i.focus(),i.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(i)}}function xa(t,i){return t&&ut(t,!0).every(h=>h in i)?t:g}function Vn(t,i){if(!i)return[];const l=ut(i,!0);return t.filter(r=>l.includes(r))}function St(t,i,l){const r=ln(i,l);return Object.entries(t).reduce((h,[d,p])=>(r.has(d)&&(h[d]=p),h),{})}function ga(t,i,l){const h=[...ln(i,l)].filter(d=>d===g||d in t);return h.length?h:[g]}function ln(t,i){const l=new Set([g]),r=li(i,ut(t,!0));for(const h of r){l.add(h);for(const d of ut(h,!0))l.add(d)}return l}function Pa(t,i){const l=Object.keys(t),r=Object.keys(i);return l.length!==r.length?!1:l.every(h=>t[h]===i[h])}function kt(t,i){return t.includes(i)?t:[...t,i]}function li(t,i){return i.reduce((l,r)=>kt(l,r),t)}function Kn(t){return`file-panel.workspace-tree.${t}`}function Ca(t,i){return`file-panel.session-change-count.${t}.${i}`}function Gn(t,i){return Object.fromEntries(Object.keys(i).map(l=>[l,t[l]??null]))}function It(t,i){return[...ln(i,t)]}function ne(t,i){return t instanceof Yn?t.message:i}function Xn(t){return t instanceof Error&&(t.message.startsWith("FILE_TREE_SNAPSHOT_TIMEOUT:")||t.message.startsWith("FILE_TREE_ABORTED:"))}function ja(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.jsx("path",{d:"M2.5 4.5h11v2h-11zM2.5 7.5h7v2h-7zM2.5 10.5h4v2h-4z",fill:"currentColor"})})}function Sa(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.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 qn(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.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 wa(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.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"}),n.jsx("path",{d:"M5.7 10.8h4.5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Na(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.jsx("path",{d:"M5 2.5h7.5v9H5z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M3.5 5H2.4V13.5H10V12.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Da(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.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 Ea(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.jsx("path",{d:"M4 3.5h8v10H4zM6 2.2h4v2H6z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M6 7.2h4M6 9.6h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function ka(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.jsx("path",{d:"M4 1.5h5l3 3v10H4z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M9 1.5v3h3",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M8 6.5v5M5.5 9h5",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Ma(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"m5.5 5 2.5-2.5L10.5 5",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Ra(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.jsx("path",{d:"M3 11.5v2h10v-2",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M8 2.5v8",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.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 _a(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.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 Ta(){return n.jsxs("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:[n.jsx("path",{d:"M1.8 4.5h4l1.2 1.3h7.2v6.7H1.8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2"}),n.jsx("path",{d:"M8.5 7.2v4M6.5 9.2h4",fill:"none",stroke:"currentColor",strokeWidth:"1.2"})]})}function Fa(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.jsx("path",{d:"M3.2 11.9h2.2l5.9-5.9-2.2-2.2-5.9 5.9zM8.3 3.8l2.2 2.2M2.8 13.2h10.4",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Aa(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.jsx("path",{d:"m4 6 4 4 4-4",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})}function Ba(){return n.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:n.jsx("path",{d:"M1.5 2h13l-5 6v5l-3 1.5V8z",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinejoin:"round"})})}function tn(t,i,l,r){const h=[];for(const d of t){const p=d.path.replace(/\\/g,"/");d.kind==="file"?l.has(p)&&h.push(d):si(p,i,l,r)&&h.push(d)}return h}function si(t,i,l,r,h){const d=h??new Set;if(d.has(t))return!1;d.add(t);const p=i[t];if(!p)return r.has(t);for(const y of p){const C=y.path.replace(/\\/g,"/");if(y.kind==="file"){if(l.has(C))return!0}else if(si(C,i,l,r,d))return!0}return!1}export{Ka as FileContextPanel};
|