farming-code 2.2.7 → 2.2.8

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.
@@ -1,8 +1,8 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FileEditorPane-RWiFD2cq.js","assets/chunk-DECur_0Z.js","assets/preload-helper-mJowh_hw.js","assets/FileEditorMarkdownPreview-elKWc8Im.js","assets/core-ZlAPicox.js","assets/file-icons-EFUGSSwf.js","assets/jsx-runtime-BthL93pI.js","assets/FileEditorMarkdownPreview-DRDNQ8mX.css","assets/editor.api2-B9h6iFPK.js","assets/editor-CtbFZlk0.css","assets/workers-BSQRIkqa.js","assets/monaco.contribution-CyLosfZI.js","assets/IconGlyphs-DfL0EBnj.js","assets/useWorkspaceMenuKeyboard-CneKAZUJ.js","assets/ProjectFilesSection-Q4PDsWmM.js","assets/workspace-view-state-CTyDzk2D.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./chunk-DECur_0Z.js";import{i as t,n,r,t as i}from"./jsx-runtime-BthL93pI.js";import{t as a}from"./react-dom-gtU6X-Hj.js";import{t as o}from"./preload-helper-mJowh_hw.js";import{$ as s,C as c,D as l,E as u,F as d,I as f,O as p,P as m,Q as h,S as g,X as _,Z as v,_ as y,a as b,b as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as ee,o as te,p as A,s as j,u as M,x as N,y as P}from"./workspace-view-state-CTyDzk2D.js";import{A as F,f as ne,g as I,j as L,n as R,u as z}from"./file-icons-EFUGSSwf.js";import{C as re,E as B,S as ie,T as V,_ as ae,a as oe,b as se,c as ce,d as le,f as ue,i as de,l as fe,n as pe,o as me,p as H,r as he,s as ge,t as _e,u as ve,v as ye,w as be,x as xe,y as Se}from"./IconGlyphs-DfL0EBnj.js";import{B as Ce,F as we,I as Te,L as Ee,R as De,U as Oe,V as ke,W as Ae,n as U,z as je}from"./FileEditorMarkdownPreview-elKWc8Im.js";import{o as Me}from"./api-D1lyBYIQ.js";var W=e(t());function Ne(){return typeof document>`u`?!0:document.visibilityState!==`hidden`}function Pe(){let[e,t]=(0,W.useState)(Ne);return(0,W.useEffect)(()=>{let e=()=>t(Ne());return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,e),window.addEventListener(`pageshow`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,e),window.removeEventListener(`pageshow`,e)}},[]),e}var Fe=1e3;function G(e,t){return t?!1:/(^|[/\\])\.farming[/\\]?$/.test(e||``)}function Ie(){let e=(0,W.useRef)(null),t=Pe(),[n,i]=(0,W.useState)({agents:[],taskHistory:[],mainPageSessionKeys:[],mainAgentId:null,systemStats:null,uptime:0,connected:!1,everConnected:!1,lastMessageAt:Date.now(),error:null,errorId:0,lastStartedAgentId:null}),a=(0,W.useRef)(new Map),o=(0,W.useRef)(new Map),s=(0,W.useCallback)(t=>{let n=e.current;return n&&n.readyState===WebSocket.OPEN?(n.send(JSON.stringify(t)),!0):(i(e=>({...e,error:`Farming backend is not connected`,errorId:e.errorId+1})),!1)},[]),c=(0,W.useCallback)((e,t,n,r)=>{let i={type:`start-agent`,command:e,workspace:t,asMain:n};return r?.task!==void 0&&(i.task=r.task),r?.workflowTemplate!==void 0&&(i.workflowTemplate=r.workflowTemplate),r?.customTitle!==void 0&&(i.customTitle=r.customTitle),r?.projectWorkspace!==void 0&&(i.projectWorkspace=r.projectWorkspace),r?.codexApprovalMode!==void 0&&(i.codexApprovalMode=r.codexApprovalMode),r?.codexRuntimeMode!==void 0&&(i.codexRuntimeMode=r.codexRuntimeMode),r?.agentRuntimeMode!==void 0&&(i.agentRuntimeMode=r.agentRuntimeMode),r?.dangerouslySkipPermissions!==void 0&&(i.dangerouslySkipPermissions=r.dangerouslySkipPermissions),r?.providerHomeId!==void 0&&(i.providerHomeId=r.providerHomeId),s(i)},[s]),l=(0,W.useCallback)((e,t)=>s(Array.isArray(e)?{type:`input`,inputParts:e,agentId:t}:{type:`input`,input:e,agentId:t}),[s]),u=(0,W.useCallback)((e,t,n=[])=>s({type:`composer-input`,message:e,agentId:t,...n.length>0?{attachments:n}:{}}),[s]),d=(0,W.useCallback)((e,t,n,r)=>s({type:`app-server-request-response`,agentId:e,requestId:t,result:n,...r?.reject===!0?{reject:!0}:{},...r?.reason?{reason:r.reason}:{}}),[s]),f=(0,W.useCallback)(e=>s({type:`focus-agent`,agentId:e}),[s]),p=(0,W.useCallback)((e,t,n)=>s({type:`resize-agent`,agentId:e,cols:t,rows:n}),[s]),m=(0,W.useCallback)(e=>s({type:`kill-agent`,agentId:e}),[s]),h=(0,W.useCallback)(e=>s({type:`interrupt-agent`,agentId:e}),[s]),g=(0,W.useCallback)(e=>s({type:`restart-main-agent`,command:e}),[s]),_=(0,W.useCallback)((e,t)=>(a.current.set(e,t),()=>{a.current.delete(e)}),[]),v=(0,W.useCallback)((e,t)=>{let n=o.current.get(e);return n||(n=new Set,o.current.set(e,n),s({type:`watch-workspace-files`,agentId:e})),n.add(t),()=>{let n=o.current.get(e);n&&(n.delete(t),n.size===0&&(o.current.delete(e),s({type:`unwatch-workspace-files`,agentId:e})))}},[s]);return(0,W.useEffect)(()=>{let n,s=!1,c=null,l=0;if(!t){let t=e.current;return e.current=null,t?.close(),i(e=>e.connected?{...e,connected:!1,error:null}:e),()=>{}}function u(e=Date.now()){e-l<Fe||(l=e,i(t=>({...t,lastMessageAt:e})))}function d(){if(s||!Ne())return;let t=r(),f=new URLSearchParams(location.search).get(`token`),p=document.cookie.match(/(?:^|;\s*)farming_token=([^;]+)/),m=f||p?.[1]||``;m&&(t+=`?token=${m}`);let h=new WebSocket(t);c=h,e.current=h,h.onopen=()=>{s||e.current!==h||(l=Date.now(),i(e=>({...e,connected:!0,everConnected:!0,lastMessageAt:l,error:null})),window.dispatchEvent(new Event(`farming:backend-connected`)),o.current.forEach((e,t)=>{e.size>0&&h.send(JSON.stringify({type:`watch-workspace-files`,agentId:t}))}))},h.onmessage=t=>{if(!(s||e.current!==h)){u();try{let e=JSON.parse(t.data);switch(e.type){case`state`:i(t=>{let n=new Map(t.agents.map(e=>[e.id,e])),r=e.state.agents.map(t=>{let r=n.get(t.id),i={...t,isMain:t.isMain||t.id===e.state.mainAgentId||G(t.cwd,t.parentAgentId)};return r?.previewSnapshot?{...i,previewSnapshot:r.previewSnapshot}:i});return{...t,agents:r,taskHistory:e.state.taskHistory??t.taskHistory,mainPageSessionKeys:Array.isArray(e.state.mainPageSessionKeys)?e.state.mainPageSessionKeys:t.mainPageSessionKeys,mainAgentId:e.state.mainAgentId,systemStats:e.state.systemStats??t.systemStats}});break;case`error`:i(t=>({...t,error:e.message,errorId:t.errorId+1}));break;case`agent-started`:i(t=>({...t,lastStartedAgentId:e.agentId}));break;case`session-preview`:i(t=>({...t,agents:t.agents.map(t=>t.id===e.preview.agentId?{...t,previewText:e.preview.previewText,previewCols:e.preview.cols,previewRows:e.preview.rows,previewSnapshot:e.preview.previewSnapshot??null,terminalStatus:e.preview.terminalStatus??t.terminalStatus??null}:t)}));break;case`session-output`:{let t=a.current.get(e.stream.agentId);t&&t(e.stream.data,e.stream.replace,e.stream.outputSeq);break}case`workspace-file-watch`:break;case`workspace-file-event`:o.current.get(e.event.agentId)?.forEach(t=>t(e.event));break;case`system-stats`:i(t=>({...t,systemStats:e.stats??t.systemStats,uptime:e.uptime??t.uptime}));break}}catch{}}},h.onclose=t=>{s||e.current!==h||(e.current=null,i(e=>({...e,connected:!1,error:t.code===4001?`Farming token expired or is invalid`:e.error,errorId:t.code===4001?e.errorId+1:e.errorId})),n=setTimeout(d,1e3))},h.onerror=()=>{h.close()}}return d(),()=>{s=!0,clearTimeout(n),e.current===c&&(e.current=null),c?.close()}},[t]),{...n,startAgent:c,sendInput:l,sendComposerInput:u,respondToAppServerRequest:d,focusAgent:f,resizeAgent:p,killAgent:m,interruptAgent:h,restartMainAgent:g,onSessionOutput:_,watchWorkspaceFiles:v}}function Le(e,t){let n=(0,W.useMemo)(()=>e.find(e=>e.id===t)??null,[e,t]),r=(0,W.useMemo)(()=>e.filter(e=>e.id!==t&&!e.isMain&&!e.archived&&e.status!==`dead`&&e.status!==`stopped`),[e,t]);return{mainAgent:n,otherAgents:r,activeCount:(0,W.useMemo)(()=>e.filter(e=>e.status===`running`).length,[e]),keyMap:(0,W.useMemo)(()=>{let e=new Map;return r.forEach((t,n)=>{n<9&&e.set(String(n+1),t.id)}),e},[r])}}function Re(e){return e instanceof HTMLElement?!!e.closest(`.terminal-session-host, .code-terminal-container`):!1}function ze(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable||!!e.closest(`.code-file-editor, .monaco-editor`):!1}function Be(e){return e instanceof HTMLElement?!!e.closest(`[role="dialog"]`):!1}function Ve(e){return e instanceof HTMLElement?!!e.closest(`[role="menu"]`):!1}function He(e){return Be(e)||Ve(e)}function Ue(){return!!document.querySelector(`[role="dialog"], [role="menu"], .code-context-menu, .code-file-context-menu`)}function We(e,t=!0){(0,W.useEffect)(()=>{if(!t)return;function n(t){let n=t.target,r=ze(n),i=Re(n),a=He(n)||Ue();for(let n of e){if(a&&!n.allowInOverlay||r&&!n.allowInInput||i&&!n.allowInTerminal)continue;let e=t.key.toLowerCase()===n.key.toLowerCase(),o=n.meta?t.metaKey&&!t.ctrlKey:n.ctrl?t.ctrlKey||t.metaKey:!(t.ctrlKey||t.metaKey),s=n.shift?t.shiftKey:!t.shiftKey,c=!t.altKey;if(e&&o&&s&&c){t.preventDefault(),n.handler(t);return}}}return window.addEventListener(`keydown`,n,!0),()=>window.removeEventListener(`keydown`,n,!0)},[e,t])}var Ge=[`codex`,`claude`,`opencode`,`qoder`,`bash`,`zsh`],Ke=new Set(Ge);function qe(e){let t=Ge.indexOf(e);return t===-1?Ge.length:t}function Je(e){let t=new Set;return e.filter(e=>e&&Ke.has(e.name)&&e.supported!==!1&&e.interactive!==!1).filter(e=>t.has(e.name)?!1:(t.add(e.name),!0)).sort((e,t)=>{let n=qe(e.name),r=qe(t.name);return n===r?e.name.localeCompare(t.name):n-r})}var Ye=[{id:``,label:`(none)`,prefix:``},{id:`ralph`,label:`Ralph loop`,prefix:`[Workflow: ralph loop]
2
+ import{r as e}from"./chunk-DECur_0Z.js";import{i as t,n,r,t as i}from"./jsx-runtime-BthL93pI.js";import{t as a}from"./react-dom-gtU6X-Hj.js";import{t as o}from"./preload-helper-mJowh_hw.js";import{$ as s,C as c,D as l,E as u,F as d,I as f,O as p,P as m,Q as h,S as g,X as _,Z as v,_ as y,a as b,b as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as ee,p as j,s as M,u as N,x as te,y as P}from"./workspace-view-state-CTyDzk2D.js";import{A as F,f as ne,g as I,j as L,n as re,u as R}from"./file-icons-EFUGSSwf.js";import{C as z,E as B,S as ie,T as V,_ as ae,a as oe,b as se,c as ce,d as le,f as ue,i as de,l as fe,n as pe,o as me,p as H,r as he,s as ge,t as _e,u as ve,v as ye,w as be,x as xe,y as Se}from"./IconGlyphs-DfL0EBnj.js";import{B as Ce,F as we,I as Te,L as Ee,R as De,U as Oe,V as ke,W as Ae,n as U,z as je}from"./FileEditorMarkdownPreview-elKWc8Im.js";import{o as Me}from"./api-D1lyBYIQ.js";var W=e(t()),Ne=1e3;function Pe(e,t){return t?!1:/(^|[/\\])\.farming[/\\]?$/.test(e||``)}function G(){let e=(0,W.useRef)(null),[t,n]=(0,W.useState)({agents:[],taskHistory:[],mainPageSessionKeys:[],mainAgentId:null,systemStats:null,uptime:0,connected:!1,everConnected:!1,lastMessageAt:Date.now(),error:null,errorId:0,lastStartedAgentId:null}),i=(0,W.useRef)(new Map),a=(0,W.useRef)(new Map),o=(0,W.useCallback)(t=>{let r=e.current;return r&&r.readyState===WebSocket.OPEN?(r.send(JSON.stringify(t)),!0):(n(e=>({...e,error:`Farming backend is not connected`,errorId:e.errorId+1})),!1)},[]),s=(0,W.useCallback)((e,t,n,r)=>{let i={type:`start-agent`,command:e,workspace:t,asMain:n};return r?.task!==void 0&&(i.task=r.task),r?.workflowTemplate!==void 0&&(i.workflowTemplate=r.workflowTemplate),r?.customTitle!==void 0&&(i.customTitle=r.customTitle),r?.projectWorkspace!==void 0&&(i.projectWorkspace=r.projectWorkspace),r?.codexApprovalMode!==void 0&&(i.codexApprovalMode=r.codexApprovalMode),r?.codexRuntimeMode!==void 0&&(i.codexRuntimeMode=r.codexRuntimeMode),r?.agentRuntimeMode!==void 0&&(i.agentRuntimeMode=r.agentRuntimeMode),r?.dangerouslySkipPermissions!==void 0&&(i.dangerouslySkipPermissions=r.dangerouslySkipPermissions),r?.providerHomeId!==void 0&&(i.providerHomeId=r.providerHomeId),o(i)},[o]),c=(0,W.useCallback)((e,t)=>o(Array.isArray(e)?{type:`input`,inputParts:e,agentId:t}:{type:`input`,input:e,agentId:t}),[o]),l=(0,W.useCallback)((e,t,n=[])=>o({type:`composer-input`,message:e,agentId:t,...n.length>0?{attachments:n}:{}}),[o]),u=(0,W.useCallback)((e,t,n,r)=>o({type:`app-server-request-response`,agentId:e,requestId:t,result:n,...r?.reject===!0?{reject:!0}:{},...r?.reason?{reason:r.reason}:{}}),[o]),d=(0,W.useCallback)(e=>o({type:`focus-agent`,agentId:e}),[o]),f=(0,W.useCallback)((e,t,n)=>o({type:`resize-agent`,agentId:e,cols:t,rows:n}),[o]),p=(0,W.useCallback)(e=>o({type:`kill-agent`,agentId:e}),[o]),m=(0,W.useCallback)(e=>o({type:`interrupt-agent`,agentId:e}),[o]),h=(0,W.useCallback)(e=>o({type:`restart-main-agent`,command:e}),[o]),g=(0,W.useCallback)((e,t)=>(i.current.set(e,t),()=>{i.current.delete(e)}),[]),_=(0,W.useCallback)((e,t)=>{let n=a.current.get(e);return n||(n=new Set,a.current.set(e,n),o({type:`watch-workspace-files`,agentId:e})),n.add(t),()=>{let n=a.current.get(e);n&&(n.delete(t),n.size===0&&(a.current.delete(e),o({type:`unwatch-workspace-files`,agentId:e})))}},[o]);return(0,W.useEffect)(()=>{let t,o=!1,s=null,c=0;function l(e=Date.now()){e-c<Ne||(c=e,n(t=>({...t,lastMessageAt:e})))}function u(){if(o)return;let d=r(),f=new URLSearchParams(location.search).get(`token`),p=document.cookie.match(/(?:^|;\s*)farming_token=([^;]+)/),m=f||p?.[1]||``;m&&(d+=`?token=${m}`);let h=new WebSocket(d);s=h,e.current=h,h.onopen=()=>{o||e.current!==h||(c=Date.now(),n(e=>({...e,connected:!0,everConnected:!0,lastMessageAt:c,error:null})),window.dispatchEvent(new Event(`farming:backend-connected`)),a.current.forEach((e,t)=>{e.size>0&&h.send(JSON.stringify({type:`watch-workspace-files`,agentId:t}))}))},h.onmessage=t=>{if(!(o||e.current!==h)){l();try{let e=JSON.parse(t.data);switch(e.type){case`state`:n(t=>{let n=new Map(t.agents.map(e=>[e.id,e])),r=e.state.agents.map(t=>{let r=n.get(t.id),i={...t,isMain:t.isMain||t.id===e.state.mainAgentId||Pe(t.cwd,t.parentAgentId)};return r?.previewSnapshot?{...i,previewSnapshot:r.previewSnapshot}:i});return{...t,agents:r,taskHistory:e.state.taskHistory??t.taskHistory,mainPageSessionKeys:Array.isArray(e.state.mainPageSessionKeys)?e.state.mainPageSessionKeys:t.mainPageSessionKeys,mainAgentId:e.state.mainAgentId,systemStats:e.state.systemStats??t.systemStats}});break;case`error`:n(t=>({...t,error:e.message,errorId:t.errorId+1}));break;case`agent-started`:n(t=>({...t,lastStartedAgentId:e.agentId}));break;case`session-preview`:n(t=>({...t,agents:t.agents.map(t=>t.id===e.preview.agentId?{...t,previewText:e.preview.previewText,previewCols:e.preview.cols,previewRows:e.preview.rows,previewSnapshot:e.preview.previewSnapshot??null,terminalStatus:e.preview.terminalStatus??t.terminalStatus??null}:t)}));break;case`session-output`:{let t=i.current.get(e.stream.agentId);t&&t(e.stream.data,e.stream.replace,e.stream.outputSeq);break}case`workspace-file-watch`:break;case`workspace-file-event`:a.current.get(e.event.agentId)?.forEach(t=>t(e.event));break;case`system-stats`:n(t=>({...t,systemStats:e.stats??t.systemStats,uptime:e.uptime??t.uptime}));break}}catch{}}},h.onclose=r=>{o||e.current!==h||(e.current=null,n(e=>({...e,connected:!1,error:r.code===4001?`Farming token expired or is invalid`:e.error,errorId:r.code===4001?e.errorId+1:e.errorId})),t=setTimeout(u,1e3))},h.onerror=()=>{h.close()}}return u(),()=>{o=!0,clearTimeout(t),e.current===s&&(e.current=null),s?.close()}},[]),{...t,startAgent:s,sendInput:c,sendComposerInput:l,respondToAppServerRequest:u,focusAgent:d,resizeAgent:f,killAgent:p,interruptAgent:m,restartMainAgent:h,onSessionOutput:g,watchWorkspaceFiles:_}}function Fe(){return typeof document>`u`?!0:document.visibilityState!==`hidden`}function Ie(){let[e,t]=(0,W.useState)(Fe);return(0,W.useEffect)(()=>{let e=()=>t(Fe());return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,e),window.addEventListener(`pageshow`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,e),window.removeEventListener(`pageshow`,e)}},[]),e}function Le(e,t){let n=(0,W.useMemo)(()=>e.find(e=>e.id===t)??null,[e,t]),r=(0,W.useMemo)(()=>e.filter(e=>e.id!==t&&!e.isMain&&!e.archived&&e.status!==`dead`&&e.status!==`stopped`),[e,t]);return{mainAgent:n,otherAgents:r,activeCount:(0,W.useMemo)(()=>e.filter(e=>e.status===`running`).length,[e]),keyMap:(0,W.useMemo)(()=>{let e=new Map;return r.forEach((t,n)=>{n<9&&e.set(String(n+1),t.id)}),e},[r])}}function Re(e){return e instanceof HTMLElement?!!e.closest(`.terminal-session-host, .code-terminal-container`):!1}function ze(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable||!!e.closest(`.code-file-editor, .monaco-editor`):!1}function Be(e){return e instanceof HTMLElement?!!e.closest(`[role="dialog"]`):!1}function Ve(e){return e instanceof HTMLElement?!!e.closest(`[role="menu"]`):!1}function He(e){return Be(e)||Ve(e)}function Ue(){return!!document.querySelector(`[role="dialog"], [role="menu"], .code-context-menu, .code-file-context-menu`)}function We(e,t=!0){(0,W.useEffect)(()=>{if(!t)return;function n(t){let n=t.target,r=ze(n),i=Re(n),a=He(n)||Ue();for(let n of e){if(a&&!n.allowInOverlay||r&&!n.allowInInput||i&&!n.allowInTerminal)continue;let e=t.key.toLowerCase()===n.key.toLowerCase(),o=n.meta?t.metaKey&&!t.ctrlKey:n.ctrl?t.ctrlKey||t.metaKey:!(t.ctrlKey||t.metaKey),s=n.shift?t.shiftKey:!t.shiftKey,c=!t.altKey;if(e&&o&&s&&c){t.preventDefault(),n.handler(t);return}}}return window.addEventListener(`keydown`,n,!0),()=>window.removeEventListener(`keydown`,n,!0)},[e,t])}var Ge=[`codex`,`claude`,`opencode`,`qoder`,`bash`,`zsh`],Ke=new Set(Ge);function qe(e){let t=Ge.indexOf(e);return t===-1?Ge.length:t}function Je(e){let t=new Set;return e.filter(e=>e&&Ke.has(e.name)&&e.supported!==!1&&e.interactive!==!1).filter(e=>t.has(e.name)?!1:(t.add(e.name),!0)).sort((e,t)=>{let n=qe(e.name),r=qe(t.name);return n===r?e.name.localeCompare(t.name):n-r})}var Ye=[{id:``,label:`(none)`,prefix:``},{id:`ralph`,label:`Ralph loop`,prefix:`[Workflow: ralph loop]
3
3
  `},{id:`developer`,label:`Developer loop`,prefix:`[Workflow: developer loop]
4
4
  `},{id:`reviewer`,label:`Reviewer loop`,prefix:`[Workflow: reviewer loop]
5
- `}];function Xe(e,t){let n=Ye.find(e=>e.id===t)?.prefix??``,r=e.trim();return{task:n?r?`${n}${r}`:n.trimEnd():r,workflowTemplate:t||``}}function Ze(e){let t=typeof e==`string`?e.trim():``;return!t||t===`/`||t===`~`?t:t.replace(/[\\/]+$/,``)}function Qe(e){let t=Ze(e);return t===`~/.farming`||/(^|[/\\])\.farming$/.test(t)}function $e(e){let t=Ze(e);return t===`/tmp`||t.startsWith(`/tmp/`)||t===`/private/tmp`||t.startsWith(`/private/tmp/`)||t===`/var/tmp`||t.startsWith(`/var/tmp/`)||t===`/private/var/tmp`||t.startsWith(`/private/var/tmp/`)||t===`/var/folders`||t.startsWith(`/var/folders/`)||t===`/private/var/folders`||t.startsWith(`/private/var/folders/`)}function et(e){let t=Ze(e);return!!t&&!$e(t)&&!Qe(t)}function tt(e,t=[]){let n=[e,...t].map(Ze).filter(e=>et(e)),r=[],i=new Set;return n.forEach(e=>{i.has(e)||(i.add(e),r.push(e))}),r.slice(0,5)}function nt(e=[],t=[]){let n=[],r=new Set;return[...e,...t].map(Ze).filter(e=>et(e)).forEach(e=>{r.has(e)||(r.add(e),n.push(e))}),n.slice(0,5)}function rt(e){let t=Ze(e);return t?Qe(t)?`~/.farming`:t:``}function it(e){let t=Ze(e?.lastMainWorkspace);if(t)return rt(t);let n=Ze(e?.workspace);return n?rt(n):`~/.farming`}function at(e,t,n=`~/.farming`){return Ze(e)||(t?Ze(n)||`~/.farming`:null)}function ot(e){let t=Ze(e);if(!t||Qe(t))return`~/.farming`;if(t.startsWith(`/Users/`)){let e=t.split(`/`);if(e.length>3)return`~/${e.slice(3).join(`/`)}`}return t}var K=i();function st(){return L()}function ct(e){return e===`opencode`?`opencode`:e===`qoder`?`qoder`:e===`bash`?`bash`:e===`zsh`?`zsh`:e===`claude`?`claude`:`codex`}function lt(e){return e===`codex`||e===`claude`||e===`qoder`}function ut(e){let t=Date.parse(e.updatedAt||``);return Number.isFinite(t)?t:0}function dt(e){return lt(e.provider)&&e.archived!==!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(`resume`)&&(Qe(e.cwd)||Qe(e.workspace))}function ft(e,t){let n=e.providerName||v(e.provider),r=s(ut(e));return[e.title||t.sessionFallbackTitle(n),n,r].filter(Boolean).join(` · `)}function pt({open:e,mustStartMain:t,initialWorkspace:r,initialCommand:i,initialCustomTitle:a,showWorkflowTaskFields:o=!0,copy:s,onStart:c,onClose:l}){let[u,d]=(0,W.useState)(`agent-list`),[f,p]=(0,W.useState)([]),[m,h]=(0,W.useState)(!1),[g,y]=(0,W.useState)(!1),[b,x]=(0,W.useState)(null),[S,C]=(0,W.useState)(``),[w,T]=(0,W.useState)(``),[E,D]=(0,W.useState)(``),[O,k]=(0,W.useState)([]),[ee,te]=(0,W.useState)({}),[A,j]=(0,W.useState)(`default`),[M,N]=(0,W.useState)(`cli`),[P,F]=(0,W.useState)(!1),[ne,I]=(0,W.useState)([]),[L,R]=(0,W.useState)([]),[z,re]=(0,W.useState)(-1),[B,ie]=(0,W.useState)(null),[V,ae]=(0,W.useState)(!0),[oe,se]=(0,W.useState)(`~/.farming`),[ce,ue]=(0,W.useState)(`codex`),[de,fe]=(0,W.useState)(!1),[pe,H]=(0,W.useState)(-1),[ve,ye]=(0,W.useState)(!1),be=(0,W.useRef)(null),xe=(0,W.useRef)(null),Se=(0,W.useRef)(null),Ce=(0,W.useRef)(null),we=(0,W.useRef)(null),Te=(0,W.useRef)(!1),Ee=(0,W.useRef)(!1),De=(0,W.useRef)(null),Oe=(0,W.useMemo)(()=>t?[]:nt(O,ne),[O,ne,t]),ke=(0,W.useMemo)(()=>B&&f.some(e=>e.name===B.provider)?B:null,[f,B]),Ae=V&&ke?ke.provider:ce;(0,W.useLayoutEffect)(()=>{if(!e)return;let a=!1;return d(`agent-list`),x(null),C(t?``:Ze(r||``)),T(``),D(``),Te.current=!1,Ee.current=!1,ye(!1),De.current!==null&&(window.clearTimeout(De.current),De.current=null),I([]),R([]),re(-1),ie(null),ae(!0),ue(`codex`),te({}),j(`default`),N(`cli`),F(!1),H(-1),h(!1),y(!1),fe(!1),fetch(n(`/api/executables`),{cache:`no-store`}).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(e=>{if(a)return;let n=Je(Array.isArray(e)?e:e.agents??[]).map(e=>({...e,description:e.description??``,category:e.category??`coding`})),r=!t&&i?n.find(e=>e.name===i):null;p(n),y(!1);let o=t?null:r;o&&(x(o),d(`workspace`),st()||setTimeout(()=>xe.current?.focus(),50))}).catch(()=>{a||(p([]),y(!0))}).finally(()=>{a||h(!0)}),fetch(n(`/api/settings`)).then(e=>e.json()).then(e=>{let n=e.settings??{},r=it(n),i=tt(null,n.workspaceHistory??[]);se(r),ue(ct(n.defaultLaunchAgent)),k(i),te(n.agentHomes??{}),N(n.codexRuntimeMode===`app-server`?`app-server`:`cli`),t&&!Te.current&&C(r),fe(!0)}).catch(()=>{k([]),se(`~/.farming`),t&&!Te.current&&C(`~/.farming`),fe(!0)}),()=>{a=!0}},[e,t,r,i]),(0,W.useEffect)(()=>{if(!e||!t)return;let r=!0;return ie(null),ae(!0),fetch(n(`/api/agent-sessions?limit=100&fresh=1`),{cache:`no-store`}).then(e=>e.json()).then(e=>{r&&ie((e.sessions??[]).filter(dt).sort((e,t)=>ut(t)-ut(e))[0]??null)}).catch(()=>{r&&ie(null)}),()=>{r=!1}},[e,t]),(0,W.useEffect)(()=>()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},[]),(0,W.useEffect)(()=>{if(!e||u!==`agent-list`||!m||g||t&&!de)return;let n=be.current;if(!n)return;let r=document.activeElement;if(r instanceof HTMLElement&&n.contains(r)&&(r.matches(`.agent-item`)||r.matches(`input, textarea, select`)))return;let i=()=>{let e=Array.from(n.querySelectorAll(`.agent-item:not(:disabled)`));(e.find(e=>e.dataset.testid===`agent-option-${Ae}`)??e[0])?.focus()};i();let a=requestAnimationFrame(i);return()=>cancelAnimationFrame(a)},[g,m,Ae,t,e,de,u]);let U=(0,W.useCallback)(()=>Ee.current?!1:(Ee.current=!0,ye(!0),De.current=window.setTimeout(()=>{Ee.current=!1,ye(!1),De.current=null},1200),!0),[]);(0,W.useEffect)(()=>{if(!e||t||!b)return;let r=!0;I([]);let i=new URLSearchParams({limit:`12`,agent:b.name});return fetch(n(`/api/workspaces/discovered?${i.toString()}`)).then(e=>e.json()).then(e=>{r&&I((e.workspaces??[]).map(e=>Ze(e.path)).filter(e=>et(e)))}).catch(()=>{r&&I([])}),()=>{r=!1}},[e,t,b]),(0,W.useEffect)(()=>{if(!e||u!==`workspace`){R([]),re(-1);return}let t=S.trim();if(!t||!t.includes(`/`)&&!t.startsWith(`~`)){R([]),re(-1);return}let r=new AbortController,i=window.setTimeout(()=>{let e=new URLSearchParams({path:t,limit:`50`});fetch(n(`/api/workspaces/complete?${e.toString()}`),{signal:r.signal}).then(e=>e.json()).then(e=>{let t=(e.suggestions??[]).filter(e=>typeof e.path==`string`&&e.path);R(t),re(e=>t.length===0?-1:Math.min(e,t.length-1))}).catch(e=>{e?.name!==`AbortError`&&(R([]),re(-1))})},120);return()=>{window.clearTimeout(i),r.abort()}},[e,u,S]),(0,W.useEffect)(()=>{if(z<0)return;let e=we.current;e&&e.querySelector(`[aria-selected="true"]`)?.scrollIntoView({block:`nearest`})},[z,L.length]);let je=(0,W.useCallback)(e=>{if(!(!t||!V||!ke)&&e.name===ke.provider)return{resumeSession:{provider:ke.provider,id:ke.id,providerHomeId:ke.providerHomeId},providerHomeId:ke.providerHomeId}},[t,ke,V]),Me=(0,W.useCallback)(e=>{if(t){if(!de||!U())return;let t=at(S,!0,oe);t&&c(e.command||e.name,t,{...je(e)||{},providerHomeId:A});return}x(e),j((Array.isArray(ee[e.name])?ee[e.name]:[])[0]?.id||`default`),F(!1),Te.current=!1,C(Ze(r||``)),I([]),H(-1),d(`workspace`),st()||setTimeout(()=>xe.current?.focus(),50)},[r,U,oe,t,c,je,de,S]),Ne=(0,W.useCallback)(async e=>{let t=tt(e,O),r=await fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspaceHistory:t})}).catch(()=>{});r?.ok&&k(tt(null,((await r.json().catch(()=>null))?.settings??{}).workspaceHistory??[]))},[O]),Pe=(0,W.useCallback)(async()=>{if(!b||!U())return;let e=at(Ze(xe.current?.value??S),t,oe);if(!e)return;!t&&et(e)&&await Ne(e);let n=je(b);if(n){c(b.command||b.name,e,{...n||{},providerHomeId:A});return}if(t){c(b.command||b.name,e,{providerHomeId:A});return}let r=o?Xe(w,E):{task:``,workflowTemplate:``};c(b.command||b.name,e,{task:r.task,workflowTemplate:r.workflowTemplate,...a?{customTitle:a}:{},providerHomeId:A,...[`codex`,`claude`,`opencode`,`qoder`].includes(b.name)?{codexRuntimeMode:M===`app-server`?`app-server`:`cli`,agentRuntimeMode:M===`acp`?`acp`:`terminal`}:{}})},[b,S,t,oe,U,Ne,c,je,o,w,E,M,a]),Fe=(0,W.useCallback)(e=>{let t=Ze(e);H(Oe.findIndex(e=>e===t))},[Oe]),G=(0,W.useCallback)(e=>{if(!Oe.length)return;let t=(e%Oe.length+Oe.length)%Oe.length,n=Oe[t]??``;Te.current=!0,C(n),H(t),requestAnimationFrame(()=>{if(xe.current){if(st()){xe.current.blur();return}xe.current.focus(),xe.current.setSelectionRange(n.length,n.length)}})},[Oe]),Ie=(0,W.useMemo)(()=>{if(!b)return[];let e=Array.isArray(ee[b.name])?ee[b.name]:[];return e.length>0?e:b.name===`codex`?[{id:`default`,path:`~/.codex`}]:b.name===`claude`?[{id:`default`,path:`~/.claude`}]:b.name===`opencode`?[{id:`default`,path:`~/.opencode`}]:b.name===`qoder`?[{id:`default`,path:`~/.qoder`}]:[{id:`default`,path:`~/.${b.name}`}]},[ee,b]),Le=(0,W.useMemo)(()=>Ie.find(e=>e.id===A)??Ie[0],[Ie,A]);(0,W.useEffect)(()=>{let e=Ie||[];if(e.length===0){j(`default`);return}e.some(e=>e.id===A)||j(e[0]?.id||`default`)},[Ie,A]),(0,W.useEffect)(()=>{if(!P)return;let e=e=>{Se.current?.contains(e.target)||F(!1)};return window.addEventListener(`mousedown`,e),()=>{window.removeEventListener(`mousedown`,e)}},[P]);let Re=(0,W.useCallback)(e=>{j(e),F(!1),requestAnimationFrame(()=>Ce.current?.focus())},[]),ze=(0,W.useCallback)(e=>{let t=L[e];return t?(Te.current=!0,C(t.path),H(-1),re(-1),requestAnimationFrame(()=>{if(xe.current){if(st()){xe.current.blur();return}xe.current.focus(),xe.current.setSelectionRange(t.path.length,t.path.length)}}),!0):!1},[L]),Be=(0,W.useCallback)(e=>L.length===0?!1:(re(((z===-1?e>0?0:L.length-1:z+e)%L.length+L.length)%L.length),H(-1),!0),[z,L]),Ve=(0,W.useCallback)(e=>Oe.length?(G(pe===-1?e>0?0:Oe.length-1:pe+e),!0):!1,[Oe,pe,G]),He=(0,W.useCallback)(e=>{let t=be.current;if(!t)return;let n=Array.from(t.querySelectorAll(`.agent-item:not(:disabled)`)).filter(e=>e.offsetParent!==null);if(n.length===0)return;let r=n.indexOf(document.activeElement),i=n.length-1,a=r;if(e.key===`ArrowDown`)a=r===-1?0:(r+1)%n.length;else if(e.key===`ArrowUp`)a=r===-1?i:(r-1+n.length)%n.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=i;else return;e.preventDefault(),n[a]?.focus()},[]),Ue=(0,W.useCallback)(e=>{if(u===`agent-list`&&(He(e),e.defaultPrevented)||e.key!==`Tab`)return;let t=be.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(n.length===0){e.preventDefault();return}let r=n[0],i=n[n.length-1],a=document.activeElement;if(e.shiftKey){(a===r||!t.contains(a))&&(e.preventDefault(),i?.focus());return}(a===i||!t.contains(a))&&(e.preventDefault(),r?.focus())},[He,u]);if(We([...f.slice(0,10).map((e,t)=>({key:String(t<9?t+1:0),allowInOverlay:!0,handler:()=>Me(e)})),{key:`Escape`,allowInOverlay:!0,handler:()=>!t&&l()}],e&&u===`agent-list`),We([{key:`Escape`,allowInOverlay:!0,handler:()=>{if(P){F(!1),requestAnimationFrame(()=>Ce.current?.focus());return}d(`agent-list`)}}],e&&u===`workspace`),!e)return null;let Ge=f.filter(e=>e.category===`coding`),Ke=f.filter(e=>e.category!==`coding`);return(0,K.jsx)(`div`,{className:`dialog-overlay`,"data-testid":`dialog-overlay`,children:(0,K.jsxs)(`div`,{className:`input-dialog fx-crt-panel`,"data-testid":`input-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`input-dialog-title`,ref:be,onKeyDown:Ue,children:[(0,K.jsxs)(`div`,{className:`dialog-header fx-crt-panel-compact`,children:[(0,K.jsx)(`div`,{className:`dialog-header-copy`,children:(0,K.jsx)(`h3`,{id:`input-dialog-title`,className:`dialog-header-title`,children:t?s.startMainAgent:s.startNewAgent})}),!t&&(0,K.jsx)(`button`,{type:`button`,className:`close-btn`,"data-testid":`input-dialog-close`,"aria-label":s.close,onClick:l,children:(0,K.jsx)(le,{})})]}),u===`agent-list`&&(0,K.jsxs)(`div`,{className:`agent-list`,children:[!m&&(0,K.jsxs)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:[(0,K.jsx)(`span`,{className:`agent-list-spinner`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:s.loadingAgents})]}),m&&g&&(0,K.jsx)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:s.agentListUnavailable}),m&&!g&&Ge.length===0&&Ke.length===0&&(0,K.jsx)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:s.noSupportedAgentsFound}),t&&ke&&(0,K.jsxs)(`label`,{className:`main-agent-resume-option fx-crt-panel`,"data-testid":`main-agent-resume-option`,children:[(0,K.jsx)(`input`,{type:`checkbox`,"data-testid":`main-agent-resume-toggle`,checked:V,onChange:e=>ae(e.target.checked)}),(0,K.jsxs)(`span`,{className:`main-agent-resume-copy`,children:[(0,K.jsx)(`span`,{className:`main-agent-resume-title`,children:s.resumePreviousMainAgent}),(0,K.jsx)(`span`,{className:`main-agent-resume-detail`,children:ft(ke,s)})]})]}),Ge.length>0&&(0,K.jsxs)(`div`,{className:`agent-group`,children:[(0,K.jsx)(`div`,{className:`group-label`,children:s.codingAgents}),Ge.map((e,n)=>(0,K.jsxs)(`button`,{className:`agent-item fx-crt-panel`,"data-testid":`agent-option-${e.name}`,disabled:t&&(ve||!de),onClick:()=>Me(e),children:[(0,K.jsx)(_,{name:e.name}),(0,K.jsx)(`span`,{className:`key-hint-badge`,children:n<9?n+1:0}),(0,K.jsxs)(`span`,{className:`agent-item-copy`,children:[(0,K.jsx)(`span`,{className:`agent-item-name`,children:v(e.name)}),(0,K.jsx)(`span`,{className:`agent-item-desc`,children:e.description})]})]},e.name))]}),Ke.length>0&&(0,K.jsxs)(`div`,{className:`agent-group`,children:[(0,K.jsx)(`div`,{className:`group-label`,children:s.otherAgents}),Ke.map((e,n)=>{let r=Ge.length+n;return(0,K.jsxs)(`button`,{className:`agent-item fx-crt-panel`,"data-testid":`agent-option-${e.name}`,disabled:t&&(ve||!de),onClick:()=>Me(e),children:[(0,K.jsx)(_,{name:e.name}),(0,K.jsx)(`span`,{className:`key-hint-badge`,children:r<9?r+1:0}),(0,K.jsxs)(`span`,{className:`agent-item-copy`,children:[(0,K.jsx)(`span`,{className:`agent-item-name`,children:v(e.name)}),(0,K.jsx)(`span`,{className:`agent-item-desc`,children:e.description})]})]},e.name)})]})]}),u===`workspace`&&b&&(0,K.jsxs)(`div`,{className:`workspace-input`,"data-testid":`workspace-step`,children:[(Ie?.length??0)>1&&(0,K.jsxs)(`div`,{className:`workspace-home-field`,ref:Se,children:[(0,K.jsxs)(`p`,{className:`workspace-field-copy`,children:[v(b.name),` Home`]}),(0,K.jsxs)(`button`,{ref:Ce,type:`button`,className:`workspace-home-trigger`,"data-testid":`agent-home-select`,"aria-label":`${v(b.name)} home`,"aria-expanded":P,"aria-controls":`agent-home-options`,onClick:()=>F(e=>!e),onKeyDown:e=>{if(e.key===`Escape`&&P){e.preventDefault(),e.stopPropagation(),F(!1);return}e.key!==`ArrowDown`&&e.key!==`ArrowUp`||(e.preventDefault(),F(!0),requestAnimationFrame(()=>{let t=e.key===`ArrowDown`?`[data-home-option]:first-child`:`[data-home-option]:last-child`;Se.current?.querySelector(t)?.focus()}))},children:[(0,K.jsxs)(`span`,{className:`workspace-home-trigger-copy`,children:[(0,K.jsx)(`strong`,{children:Le?.id||`default`}),(0,K.jsx)(`span`,{children:ot(Le?.path||``)})]}),(0,K.jsx)(ge,{})]}),P&&(0,K.jsx)(`div`,{className:`workspace-home-menu`,id:`agent-home-options`,"data-testid":`agent-home-menu`,role:`listbox`,"aria-label":`${v(b.name)} home`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),F(!1),requestAnimationFrame(()=>Ce.current?.focus()))},children:Ie.map(e=>{let t=e.id===A;return(0,K.jsxs)(`button`,{type:`button`,className:`workspace-home-option ${t?`selected`:``}`,"data-testid":`agent-home-option`,"data-home-option":!0,role:`option`,"aria-selected":t,onClick:()=>Re(e.id),children:[(0,K.jsx)(me,{className:`workspace-home-option-check`}),(0,K.jsxs)(`span`,{className:`workspace-home-option-copy`,children:[(0,K.jsx)(`strong`,{children:e.id}),(0,K.jsx)(`span`,{children:ot(e.path)})]})]},e.id)})})]}),[`codex`,`claude`,`opencode`,`qoder`].includes(b.name)&&(0,K.jsxs)(`div`,{className:`workspace-runtime-field`,"data-testid":`codex-runtime-mode`,children:[(0,K.jsxs)(`p`,{className:`workspace-field-copy`,children:[v(b.name),` runtime`]}),(0,K.jsxs)(`div`,{className:`workspace-runtime-options`,role:`group`,"aria-label":`${v(b.name)} runtime`,children:[(0,K.jsx)(`button`,{type:`button`,className:M===`cli`?`active`:``,"aria-pressed":M===`cli`,onClick:()=>N(`cli`),children:`Terminal`}),(0,K.jsxs)(`button`,{type:`button`,className:M===`acp`?`active`:``,"aria-pressed":M===`acp`,onClick:()=>N(`acp`),children:[`Chat `,(0,K.jsx)(`span`,{children:`ACP`})]}),b.name===`codex`&&(0,K.jsxs)(`button`,{type:`button`,className:M===`app-server`?`active`:``,"aria-pressed":M===`app-server`,onClick:()=>N(`app-server`),children:[`App Server `,(0,K.jsx)(`span`,{children:`unstable`})]})]})]}),(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:s.workspace}),(0,K.jsx)(`input`,{ref:xe,"data-testid":`workspace-input`,type:`text`,value:S,onFocus:()=>Fe(S),onChange:e=>{let t=e.target.value;Te.current=!0,C(t),Fe(t)},onKeyDown:e=>{if(e.key===`ArrowDown`){if(L.length>0&&Be(1)){e.preventDefault();return}Ve(1)&&e.preventDefault();return}if(e.key===`ArrowUp`){if(L.length>0&&Be(-1)){e.preventDefault();return}Ve(-1)&&e.preventDefault();return}if(e.key===`Tab`&&L.length>0){ze(z===-1?0:z)&&e.preventDefault();return}if(e.key===`Enter`){if(e.preventDefault(),z!==-1&&ze(z))return;Pe()}e.key===`Escape`&&(e.preventDefault(),d(`agent-list`))},placeholder:s.workspacePathPlaceholder,name:`workspace-path`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`go`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`}),L.length>0&&(0,K.jsx)(`div`,{ref:we,className:`workspace-path-suggestions fx-crt-panel`,"data-testid":`workspace-path-suggestions`,role:`listbox`,children:L.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`workspace-path-suggestion ${t===z?`active`:``}`,"data-testid":`workspace-path-suggestion`,role:`option`,"aria-selected":t===z,onMouseDown:e=>{e.preventDefault(),ze(t)},children:[(0,K.jsx)(`span`,{className:`workspace-path-suggestion-name`,children:e.name}),(0,K.jsx)(`span`,{className:`workspace-path-suggestion-path`,children:ot(e.path)})]},e.path))}),!t&&o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:`Workflow:`}),(0,K.jsx)(`select`,{className:`workflow-select fx-crt-panel`,"data-testid":`workflow-template-select`,value:E,onChange:e=>D(e.target.value),"aria-label":`Workflow template`,children:Ye.map(e=>(0,K.jsx)(`option`,{value:e.id,children:e.label},e.id||`none`))}),(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:`Task (optional):`}),(0,K.jsx)(`textarea`,{className:`task-input fx-crt-panel`,"data-testid":`task-input`,value:w,onChange:e=>T(e.target.value),placeholder:`Describe what this agent should focus on`,rows:4,name:`agent-task`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`})]}),Oe.length>0&&(0,K.jsxs)(`div`,{className:`workspace-history fx-crt-panel`,"data-testid":`workspace-history`,children:[(0,K.jsxs)(`div`,{className:`workspace-history-header`,children:[(0,K.jsx)(`span`,{children:s.recentWorkspacesLower}),(0,K.jsxs)(`span`,{className:`hint`,"aria-hidden":`true`,children:[(0,K.jsx)(he,{}),(0,K.jsx)(_e,{})]})]}),(0,K.jsx)(`div`,{className:`workspace-history-list`,children:Oe.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`workspace-history-item ${t===pe?`active`:``}`,"data-testid":`workspace-history-item`,onMouseDown:e=>{e.preventDefault(),G(t)},children:[(0,K.jsx)(`span`,{className:`workspace-history-index`,children:t+1}),(0,K.jsx)(`span`,{className:`workspace-history-path`,children:ot(e)}),t===0&&e===O[0]&&(0,K.jsx)(`span`,{className:`workspace-history-badge`,children:s.latest})]},e))})]}),(0,K.jsxs)(`div`,{className:`workspace-actions`,children:[(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-start`,"aria-label":s.start,disabled:ve,onClick:()=>void Pe(),children:s.start}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-back`,"aria-label":s.back,onClick:()=>d(`agent-list`),children:s.back})]})]})]})})}function mt(){return{entries:[],index:-1}}function ht(e,t=Date.now()){return{kind:`agent`,agentId:e,reason:`agent`,ts:t}}function gt(e,t=Date.now()){return{kind:`file`,agentId:e.agentId,filePath:e.filePath,view:e.view??`editor`,lineNumber:Math.max(1,e.lineNumber??1),column:Math.max(1,e.column??1),endColumn:e.endColumn,reason:e.reason??`file`,ts:t}}function _t(e,t){return e.kind===t.kind?e.kind===`agent`&&t.kind===`agent`?e.agentId===t.agentId:e.kind===`file`&&t.kind===`file`?e.agentId===t.agentId&&e.filePath===t.filePath&&e.view===t.view:!1:!1}function vt(e,t){if(!e||!_t(e,t))return!1;if(e.kind===`agent`&&t.kind===`agent`)return!0;if(e.kind!==`file`||t.kind!==`file`)return!1;let n=Math.abs(e.lineNumber-t.lineNumber);return e.lineNumber===t.lineNumber&&e.column===t.column&&e.endColumn===t.endColumn||t.reason===`cursor`&&(n<30||t.ts-e.ts<1e3)||n<=15}function yt(e,t,n=50){let r=e.entries[e.index],i=vt(r,t),a=e.entries,o=e.index;return i&&o>=0?(a=a.slice(),a[o]=t):(a=a.slice(0,o+1),a.push(t),a.length>n&&(a=a.slice(a.length-n)),o=a.length-1),{entries:a,index:o}}function bt(e,t=typeof navigator<`u`?navigator.platform:``){return!(e.key===`-`||e.key===`_`||e.code===`Minus`)||!e.ctrlKey||e.metaKey||e.altKey?null:e.shiftKey?1:-1}var xt={background:`#ffffff`,foreground:`#24292f`,cursor:`#24292f`,cursorAccent:`#ffffff`,selectionBackground:`rgba(31, 35, 40, 0.18)`,black:`#24292f`,red:`#cf222e`,green:`#1a7f37`,yellow:`#9a6700`,blue:`#0969da`,magenta:`#8250df`,cyan:`#1b7c83`,white:`#57606a`,brightBlack:`#6e7781`,brightRed:`#a40e26`,brightGreen:`#2da44e`,brightYellow:`#bf8700`,brightBlue:`#218bff`,brightMagenta:`#a475f9`,brightCyan:`#3192aa`,brightWhite:`#24292f`},St=[`"JetBrains Mono"`,`"SF Mono"`,`Menlo`,`Monaco`,`"Cascadia Mono"`,`"Segoe UI Mono"`,`"Sarasa Mono SC"`,`"PingFang SC"`,`"Hiragino Sans GB"`,`"Noto Sans Mono CJK SC"`,`"Microsoft YaHei UI"`,`monospace`].join(`, `),Ct=null,wt=null;async function Tt(){return Ct||wt||(wt=(async()=>{try{let e=n(`/vendor/ghostty-web`),t=`${e}/ghostty-web.js`,r=`${e}/ghostty-vt.wasm`,i=await o(()=>import(t),[]);return await i.init(r),Ct={Terminal:i.Terminal,FitAddon:i.FitAddon},Ct}catch(e){return console.error(`Failed to initialize Ghostty terminal:`,e),null}})(),wt)}async function Et(e){let t=await Tt();if(!t)return null;let n=e?.fontSize??12;return{terminal:new t.Terminal({theme:xt,fontSize:n,fontFamily:St,cursorBlink:!1,smoothScrollDuration:120,scrollback:5e3}),fitAddon:new t.FitAddon}}var Dt=Object.defineProperty,Ot=Object.getOwnPropertyDescriptor,kt=(e,t)=>{for(var n in t)Dt(e,n,{get:t[n],enumerable:!0})},At=(e,t,n,r)=>{for(var i=r>1?void 0:r?Ot(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&Dt(t,n,i),i},q=(e,t)=>(n,r)=>t(n,r,e),jt=`Terminal input`,Mt={get:()=>jt,set:e=>jt=e},Nt=`Too much output to announce, navigate to rows manually to read`,Pt={get:()=>Nt,set:e=>Nt=e};function Ft(e){return e.replace(/\r?\n/g,`\r`)}function It(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function Lt(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Rt(e,t,n,r){e.stopPropagation(),e.clipboardData&&zt(e.clipboardData.getData(`text/plain`),t,n,r)}function zt(e,t,n,r){e=Ft(e),e=It(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function Bt(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Vt(e,t,n,r,i){Bt(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Ht(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ut(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Wt=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},Gt=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}else this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Kt=``,qt=` `,Jt=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Yt}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return(this.fg&50331648)==0}isBgDefault(){return(this.bg&50331648)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Yt=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Xt=class e extends Jt{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Yt,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ht(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Zt=`di$target`,Qt=`di$dependencies`,$t=new Map;function en(e){return e[Qt]||[]}function tn(e){if($t.has(e))return $t.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);nn(t,e,r)};return t._id=e,$t.set(e,t),t}function nn(e,t,n){t[Zt]===t?t[Qt].push({id:e,index:n}):(t[Qt]=[{id:e,index:n}],t[Zt]=t)}var rn=tn(`BufferService`),an=tn(`CoreMouseService`),on=tn(`CoreService`),sn=tn(`CharsetService`),cn=tn(`InstantiationService`),ln=tn(`LogService`),un=tn(`OptionsService`),dn=tn(`OscLinkService`),fn=tn(`UnicodeService`),pn=tn(`DecorationService`),mn=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Xt,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(!(c===-1&&!n.hasContent(t))){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId)if(c===-1){c=t,s=a.extended.urlId;continue}else l=a.extended.urlId!==s;else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):hn(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};mn=At([q(0,rn),q(1,un),q(2,dn)],mn);function hn(e,t){if(confirm(`Do you want to navigate to ${t}?
5
+ `}];function Xe(e,t){let n=Ye.find(e=>e.id===t)?.prefix??``,r=e.trim();return{task:n?r?`${n}${r}`:n.trimEnd():r,workflowTemplate:t||``}}function Ze(e){let t=typeof e==`string`?e.trim():``;return!t||t===`/`||t===`~`?t:t.replace(/[\\/]+$/,``)}function Qe(e){let t=Ze(e);return t===`~/.farming`||/(^|[/\\])\.farming$/.test(t)}function $e(e){let t=Ze(e);return t===`/tmp`||t.startsWith(`/tmp/`)||t===`/private/tmp`||t.startsWith(`/private/tmp/`)||t===`/var/tmp`||t.startsWith(`/var/tmp/`)||t===`/private/var/tmp`||t.startsWith(`/private/var/tmp/`)||t===`/var/folders`||t.startsWith(`/var/folders/`)||t===`/private/var/folders`||t.startsWith(`/private/var/folders/`)}function et(e){let t=Ze(e);return!!t&&!$e(t)&&!Qe(t)}function tt(e,t=[]){let n=[e,...t].map(Ze).filter(e=>et(e)),r=[],i=new Set;return n.forEach(e=>{i.has(e)||(i.add(e),r.push(e))}),r.slice(0,5)}function nt(e=[],t=[]){let n=[],r=new Set;return[...e,...t].map(Ze).filter(e=>et(e)).forEach(e=>{r.has(e)||(r.add(e),n.push(e))}),n.slice(0,5)}function rt(e){let t=Ze(e);return t?Qe(t)?`~/.farming`:t:``}function it(e){let t=Ze(e?.lastMainWorkspace);if(t)return rt(t);let n=Ze(e?.workspace);return n?rt(n):`~/.farming`}function at(e,t,n=`~/.farming`){return Ze(e)||(t?Ze(n)||`~/.farming`:null)}function ot(e){let t=Ze(e);if(!t||Qe(t))return`~/.farming`;if(t.startsWith(`/Users/`)){let e=t.split(`/`);if(e.length>3)return`~/${e.slice(3).join(`/`)}`}return t}var K=i();function st(){return L()}function ct(e){return e===`opencode`?`opencode`:e===`qoder`?`qoder`:e===`bash`?`bash`:e===`zsh`?`zsh`:e===`claude`?`claude`:`codex`}function lt(e){return e===`codex`||e===`claude`||e===`qoder`}function ut(e){let t=Date.parse(e.updatedAt||``);return Number.isFinite(t)?t:0}function dt(e){return lt(e.provider)&&e.archived!==!0&&Array.isArray(e.capabilities)&&e.capabilities.includes(`resume`)&&(Qe(e.cwd)||Qe(e.workspace))}function ft(e,t){let n=e.providerName||v(e.provider),r=s(ut(e));return[e.title||t.sessionFallbackTitle(n),n,r].filter(Boolean).join(` · `)}function pt({open:e,mustStartMain:t,initialWorkspace:r,initialCommand:i,initialCustomTitle:a,showWorkflowTaskFields:o=!0,copy:s,onStart:c,onClose:l}){let[u,d]=(0,W.useState)(`agent-list`),[f,p]=(0,W.useState)([]),[m,h]=(0,W.useState)(!1),[g,y]=(0,W.useState)(!1),[b,x]=(0,W.useState)(null),[S,C]=(0,W.useState)(``),[w,T]=(0,W.useState)(``),[E,D]=(0,W.useState)(``),[O,k]=(0,W.useState)([]),[A,ee]=(0,W.useState)({}),[j,M]=(0,W.useState)(`default`),[N,te]=(0,W.useState)(`cli`),[P,F]=(0,W.useState)(!1),[ne,I]=(0,W.useState)([]),[L,re]=(0,W.useState)([]),[R,z]=(0,W.useState)(-1),[B,ie]=(0,W.useState)(null),[V,ae]=(0,W.useState)(!0),[oe,se]=(0,W.useState)(`~/.farming`),[ce,ue]=(0,W.useState)(`codex`),[de,fe]=(0,W.useState)(!1),[pe,H]=(0,W.useState)(-1),[ve,ye]=(0,W.useState)(!1),be=(0,W.useRef)(null),xe=(0,W.useRef)(null),Se=(0,W.useRef)(null),Ce=(0,W.useRef)(null),we=(0,W.useRef)(null),Te=(0,W.useRef)(!1),Ee=(0,W.useRef)(!1),De=(0,W.useRef)(null),Oe=(0,W.useMemo)(()=>t?[]:nt(O,ne),[O,ne,t]),ke=(0,W.useMemo)(()=>B&&f.some(e=>e.name===B.provider)?B:null,[f,B]),Ae=V&&ke?ke.provider:ce;(0,W.useLayoutEffect)(()=>{if(!e)return;let a=!1;return d(`agent-list`),x(null),C(t?``:Ze(r||``)),T(``),D(``),Te.current=!1,Ee.current=!1,ye(!1),De.current!==null&&(window.clearTimeout(De.current),De.current=null),I([]),re([]),z(-1),ie(null),ae(!0),ue(`codex`),ee({}),M(`default`),te(`cli`),F(!1),H(-1),h(!1),y(!1),fe(!1),fetch(n(`/api/executables`),{cache:`no-store`}).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(e=>{if(a)return;let n=Je(Array.isArray(e)?e:e.agents??[]).map(e=>({...e,description:e.description??``,category:e.category??`coding`})),r=!t&&i?n.find(e=>e.name===i):null;p(n),y(!1);let o=t?null:r;o&&(x(o),d(`workspace`),st()||setTimeout(()=>xe.current?.focus(),50))}).catch(()=>{a||(p([]),y(!0))}).finally(()=>{a||h(!0)}),fetch(n(`/api/settings`)).then(e=>e.json()).then(e=>{let n=e.settings??{},r=it(n),i=tt(null,n.workspaceHistory??[]);se(r),ue(ct(n.defaultLaunchAgent)),k(i),ee(n.agentHomes??{}),te(n.codexRuntimeMode===`app-server`?`app-server`:`cli`),t&&!Te.current&&C(r),fe(!0)}).catch(()=>{k([]),se(`~/.farming`),t&&!Te.current&&C(`~/.farming`),fe(!0)}),()=>{a=!0}},[e,t,r,i]),(0,W.useEffect)(()=>{if(!e||!t)return;let r=!0;return ie(null),ae(!0),fetch(n(`/api/agent-sessions?limit=100&fresh=1`),{cache:`no-store`}).then(e=>e.json()).then(e=>{r&&ie((e.sessions??[]).filter(dt).sort((e,t)=>ut(t)-ut(e))[0]??null)}).catch(()=>{r&&ie(null)}),()=>{r=!1}},[e,t]),(0,W.useEffect)(()=>()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},[]),(0,W.useEffect)(()=>{if(!e||u!==`agent-list`||!m||g||t&&!de)return;let n=be.current;if(!n)return;let r=document.activeElement;if(r instanceof HTMLElement&&n.contains(r)&&(r.matches(`.agent-item`)||r.matches(`input, textarea, select`)))return;let i=()=>{let e=Array.from(n.querySelectorAll(`.agent-item:not(:disabled)`));(e.find(e=>e.dataset.testid===`agent-option-${Ae}`)??e[0])?.focus()};i();let a=requestAnimationFrame(i);return()=>cancelAnimationFrame(a)},[g,m,Ae,t,e,de,u]);let U=(0,W.useCallback)(()=>Ee.current?!1:(Ee.current=!0,ye(!0),De.current=window.setTimeout(()=>{Ee.current=!1,ye(!1),De.current=null},1200),!0),[]);(0,W.useEffect)(()=>{if(!e||t||!b)return;let r=!0;I([]);let i=new URLSearchParams({limit:`12`,agent:b.name});return fetch(n(`/api/workspaces/discovered?${i.toString()}`)).then(e=>e.json()).then(e=>{r&&I((e.workspaces??[]).map(e=>Ze(e.path)).filter(e=>et(e)))}).catch(()=>{r&&I([])}),()=>{r=!1}},[e,t,b]),(0,W.useEffect)(()=>{if(!e||u!==`workspace`){re([]),z(-1);return}let t=S.trim();if(!t||!t.includes(`/`)&&!t.startsWith(`~`)){re([]),z(-1);return}let r=new AbortController,i=window.setTimeout(()=>{let e=new URLSearchParams({path:t,limit:`50`});fetch(n(`/api/workspaces/complete?${e.toString()}`),{signal:r.signal}).then(e=>e.json()).then(e=>{let t=(e.suggestions??[]).filter(e=>typeof e.path==`string`&&e.path);re(t),z(e=>t.length===0?-1:Math.min(e,t.length-1))}).catch(e=>{e?.name!==`AbortError`&&(re([]),z(-1))})},120);return()=>{window.clearTimeout(i),r.abort()}},[e,u,S]),(0,W.useEffect)(()=>{if(R<0)return;let e=we.current;e&&e.querySelector(`[aria-selected="true"]`)?.scrollIntoView({block:`nearest`})},[R,L.length]);let je=(0,W.useCallback)(e=>{if(!(!t||!V||!ke)&&e.name===ke.provider)return{resumeSession:{provider:ke.provider,id:ke.id,providerHomeId:ke.providerHomeId},providerHomeId:ke.providerHomeId}},[t,ke,V]),Me=(0,W.useCallback)(e=>{if(t){if(!de||!U())return;let t=at(S,!0,oe);t&&c(e.command||e.name,t,{...je(e)||{},providerHomeId:j});return}x(e),M((Array.isArray(A[e.name])?A[e.name]:[])[0]?.id||`default`),F(!1),Te.current=!1,C(Ze(r||``)),I([]),H(-1),d(`workspace`),st()||setTimeout(()=>xe.current?.focus(),50)},[r,U,oe,t,c,je,de,S]),Ne=(0,W.useCallback)(async e=>{let t=tt(e,O),r=await fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspaceHistory:t})}).catch(()=>{});r?.ok&&k(tt(null,((await r.json().catch(()=>null))?.settings??{}).workspaceHistory??[]))},[O]),Pe=(0,W.useCallback)(async()=>{if(!b||!U())return;let e=at(Ze(xe.current?.value??S),t,oe);if(!e)return;!t&&et(e)&&await Ne(e);let n=je(b);if(n){c(b.command||b.name,e,{...n||{},providerHomeId:j});return}if(t){c(b.command||b.name,e,{providerHomeId:j});return}let r=o?Xe(w,E):{task:``,workflowTemplate:``};c(b.command||b.name,e,{task:r.task,workflowTemplate:r.workflowTemplate,...a?{customTitle:a}:{},providerHomeId:j,...[`codex`,`claude`,`opencode`,`qoder`].includes(b.name)?{codexRuntimeMode:N===`app-server`?`app-server`:`cli`,agentRuntimeMode:N===`acp`?`acp`:`terminal`}:{}})},[b,S,t,oe,U,Ne,c,je,o,w,E,N,a]),G=(0,W.useCallback)(e=>{let t=Ze(e);H(Oe.findIndex(e=>e===t))},[Oe]),Fe=(0,W.useCallback)(e=>{if(!Oe.length)return;let t=(e%Oe.length+Oe.length)%Oe.length,n=Oe[t]??``;Te.current=!0,C(n),H(t),requestAnimationFrame(()=>{if(xe.current){if(st()){xe.current.blur();return}xe.current.focus(),xe.current.setSelectionRange(n.length,n.length)}})},[Oe]),Ie=(0,W.useMemo)(()=>{if(!b)return[];let e=Array.isArray(A[b.name])?A[b.name]:[];return e.length>0?e:b.name===`codex`?[{id:`default`,path:`~/.codex`}]:b.name===`claude`?[{id:`default`,path:`~/.claude`}]:b.name===`opencode`?[{id:`default`,path:`~/.opencode`}]:b.name===`qoder`?[{id:`default`,path:`~/.qoder`}]:[{id:`default`,path:`~/.${b.name}`}]},[A,b]),Le=(0,W.useMemo)(()=>Ie.find(e=>e.id===j)??Ie[0],[Ie,j]);(0,W.useEffect)(()=>{let e=Ie||[];if(e.length===0){M(`default`);return}e.some(e=>e.id===j)||M(e[0]?.id||`default`)},[Ie,j]),(0,W.useEffect)(()=>{if(!P)return;let e=e=>{Se.current?.contains(e.target)||F(!1)};return window.addEventListener(`mousedown`,e),()=>{window.removeEventListener(`mousedown`,e)}},[P]);let Re=(0,W.useCallback)(e=>{M(e),F(!1),requestAnimationFrame(()=>Ce.current?.focus())},[]),ze=(0,W.useCallback)(e=>{let t=L[e];return t?(Te.current=!0,C(t.path),H(-1),z(-1),requestAnimationFrame(()=>{if(xe.current){if(st()){xe.current.blur();return}xe.current.focus(),xe.current.setSelectionRange(t.path.length,t.path.length)}}),!0):!1},[L]),Be=(0,W.useCallback)(e=>L.length===0?!1:(z(((R===-1?e>0?0:L.length-1:R+e)%L.length+L.length)%L.length),H(-1),!0),[R,L]),Ve=(0,W.useCallback)(e=>Oe.length?(Fe(pe===-1?e>0?0:Oe.length-1:pe+e),!0):!1,[Oe,pe,Fe]),He=(0,W.useCallback)(e=>{let t=be.current;if(!t)return;let n=Array.from(t.querySelectorAll(`.agent-item:not(:disabled)`)).filter(e=>e.offsetParent!==null);if(n.length===0)return;let r=n.indexOf(document.activeElement),i=n.length-1,a=r;if(e.key===`ArrowDown`)a=r===-1?0:(r+1)%n.length;else if(e.key===`ArrowUp`)a=r===-1?i:(r-1+n.length)%n.length;else if(e.key===`Home`)a=0;else if(e.key===`End`)a=i;else return;e.preventDefault(),n[a]?.focus()},[]),Ue=(0,W.useCallback)(e=>{if(u===`agent-list`&&(He(e),e.defaultPrevented)||e.key!==`Tab`)return;let t=be.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(n.length===0){e.preventDefault();return}let r=n[0],i=n[n.length-1],a=document.activeElement;if(e.shiftKey){(a===r||!t.contains(a))&&(e.preventDefault(),i?.focus());return}(a===i||!t.contains(a))&&(e.preventDefault(),r?.focus())},[He,u]);if(We([...f.slice(0,10).map((e,t)=>({key:String(t<9?t+1:0),allowInOverlay:!0,handler:()=>Me(e)})),{key:`Escape`,allowInOverlay:!0,handler:()=>!t&&l()}],e&&u===`agent-list`),We([{key:`Escape`,allowInOverlay:!0,handler:()=>{if(P){F(!1),requestAnimationFrame(()=>Ce.current?.focus());return}d(`agent-list`)}}],e&&u===`workspace`),!e)return null;let Ge=f.filter(e=>e.category===`coding`),Ke=f.filter(e=>e.category!==`coding`);return(0,K.jsx)(`div`,{className:`dialog-overlay`,"data-testid":`dialog-overlay`,children:(0,K.jsxs)(`div`,{className:`input-dialog fx-crt-panel`,"data-testid":`input-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`input-dialog-title`,ref:be,onKeyDown:Ue,children:[(0,K.jsxs)(`div`,{className:`dialog-header fx-crt-panel-compact`,children:[(0,K.jsx)(`div`,{className:`dialog-header-copy`,children:(0,K.jsx)(`h3`,{id:`input-dialog-title`,className:`dialog-header-title`,children:t?s.startMainAgent:s.startNewAgent})}),!t&&(0,K.jsx)(`button`,{type:`button`,className:`close-btn`,"data-testid":`input-dialog-close`,"aria-label":s.close,onClick:l,children:(0,K.jsx)(le,{})})]}),u===`agent-list`&&(0,K.jsxs)(`div`,{className:`agent-list`,children:[!m&&(0,K.jsxs)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:[(0,K.jsx)(`span`,{className:`agent-list-spinner`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:s.loadingAgents})]}),m&&g&&(0,K.jsx)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:s.agentListUnavailable}),m&&!g&&Ge.length===0&&Ke.length===0&&(0,K.jsx)(`div`,{className:`agent-list-status fx-crt-panel`,"data-testid":`agent-list-status`,children:s.noSupportedAgentsFound}),t&&ke&&(0,K.jsxs)(`label`,{className:`main-agent-resume-option fx-crt-panel`,"data-testid":`main-agent-resume-option`,children:[(0,K.jsx)(`input`,{type:`checkbox`,"data-testid":`main-agent-resume-toggle`,checked:V,onChange:e=>ae(e.target.checked)}),(0,K.jsxs)(`span`,{className:`main-agent-resume-copy`,children:[(0,K.jsx)(`span`,{className:`main-agent-resume-title`,children:s.resumePreviousMainAgent}),(0,K.jsx)(`span`,{className:`main-agent-resume-detail`,children:ft(ke,s)})]})]}),Ge.length>0&&(0,K.jsxs)(`div`,{className:`agent-group`,children:[(0,K.jsx)(`div`,{className:`group-label`,children:s.codingAgents}),Ge.map((e,n)=>(0,K.jsxs)(`button`,{className:`agent-item fx-crt-panel`,"data-testid":`agent-option-${e.name}`,disabled:t&&(ve||!de),onClick:()=>Me(e),children:[(0,K.jsx)(_,{name:e.name}),(0,K.jsx)(`span`,{className:`key-hint-badge`,children:n<9?n+1:0}),(0,K.jsxs)(`span`,{className:`agent-item-copy`,children:[(0,K.jsx)(`span`,{className:`agent-item-name`,children:v(e.name)}),(0,K.jsx)(`span`,{className:`agent-item-desc`,children:e.description})]})]},e.name))]}),Ke.length>0&&(0,K.jsxs)(`div`,{className:`agent-group`,children:[(0,K.jsx)(`div`,{className:`group-label`,children:s.otherAgents}),Ke.map((e,n)=>{let r=Ge.length+n;return(0,K.jsxs)(`button`,{className:`agent-item fx-crt-panel`,"data-testid":`agent-option-${e.name}`,disabled:t&&(ve||!de),onClick:()=>Me(e),children:[(0,K.jsx)(_,{name:e.name}),(0,K.jsx)(`span`,{className:`key-hint-badge`,children:r<9?r+1:0}),(0,K.jsxs)(`span`,{className:`agent-item-copy`,children:[(0,K.jsx)(`span`,{className:`agent-item-name`,children:v(e.name)}),(0,K.jsx)(`span`,{className:`agent-item-desc`,children:e.description})]})]},e.name)})]})]}),u===`workspace`&&b&&(0,K.jsxs)(`div`,{className:`workspace-input`,"data-testid":`workspace-step`,children:[(Ie?.length??0)>1&&(0,K.jsxs)(`div`,{className:`workspace-home-field`,ref:Se,children:[(0,K.jsxs)(`p`,{className:`workspace-field-copy`,children:[v(b.name),` Home`]}),(0,K.jsxs)(`button`,{ref:Ce,type:`button`,className:`workspace-home-trigger`,"data-testid":`agent-home-select`,"aria-label":`${v(b.name)} home`,"aria-expanded":P,"aria-controls":`agent-home-options`,onClick:()=>F(e=>!e),onKeyDown:e=>{if(e.key===`Escape`&&P){e.preventDefault(),e.stopPropagation(),F(!1);return}e.key!==`ArrowDown`&&e.key!==`ArrowUp`||(e.preventDefault(),F(!0),requestAnimationFrame(()=>{let t=e.key===`ArrowDown`?`[data-home-option]:first-child`:`[data-home-option]:last-child`;Se.current?.querySelector(t)?.focus()}))},children:[(0,K.jsxs)(`span`,{className:`workspace-home-trigger-copy`,children:[(0,K.jsx)(`strong`,{children:Le?.id||`default`}),(0,K.jsx)(`span`,{children:ot(Le?.path||``)})]}),(0,K.jsx)(ge,{})]}),P&&(0,K.jsx)(`div`,{className:`workspace-home-menu`,id:`agent-home-options`,"data-testid":`agent-home-menu`,role:`listbox`,"aria-label":`${v(b.name)} home`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),F(!1),requestAnimationFrame(()=>Ce.current?.focus()))},children:Ie.map(e=>{let t=e.id===j;return(0,K.jsxs)(`button`,{type:`button`,className:`workspace-home-option ${t?`selected`:``}`,"data-testid":`agent-home-option`,"data-home-option":!0,role:`option`,"aria-selected":t,onClick:()=>Re(e.id),children:[(0,K.jsx)(me,{className:`workspace-home-option-check`}),(0,K.jsxs)(`span`,{className:`workspace-home-option-copy`,children:[(0,K.jsx)(`strong`,{children:e.id}),(0,K.jsx)(`span`,{children:ot(e.path)})]})]},e.id)})})]}),[`codex`,`claude`,`opencode`,`qoder`].includes(b.name)&&(0,K.jsxs)(`div`,{className:`workspace-runtime-field`,"data-testid":`codex-runtime-mode`,children:[(0,K.jsxs)(`p`,{className:`workspace-field-copy`,children:[v(b.name),` runtime`]}),(0,K.jsxs)(`div`,{className:`workspace-runtime-options`,role:`group`,"aria-label":`${v(b.name)} runtime`,children:[(0,K.jsx)(`button`,{type:`button`,className:N===`cli`?`active`:``,"aria-pressed":N===`cli`,onClick:()=>te(`cli`),children:`Terminal`}),(0,K.jsxs)(`button`,{type:`button`,className:N===`acp`?`active`:``,"aria-pressed":N===`acp`,onClick:()=>te(`acp`),children:[`Chat `,(0,K.jsx)(`span`,{children:`ACP`})]}),b.name===`codex`&&(0,K.jsxs)(`button`,{type:`button`,className:N===`app-server`?`active`:``,"aria-pressed":N===`app-server`,onClick:()=>te(`app-server`),children:[`App Server `,(0,K.jsx)(`span`,{children:`unstable`})]})]})]}),(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:s.workspace}),(0,K.jsx)(`input`,{ref:xe,"data-testid":`workspace-input`,type:`text`,value:S,onFocus:()=>G(S),onChange:e=>{let t=e.target.value;Te.current=!0,C(t),G(t)},onKeyDown:e=>{if(e.key===`ArrowDown`){if(L.length>0&&Be(1)){e.preventDefault();return}Ve(1)&&e.preventDefault();return}if(e.key===`ArrowUp`){if(L.length>0&&Be(-1)){e.preventDefault();return}Ve(-1)&&e.preventDefault();return}if(e.key===`Tab`&&L.length>0){ze(R===-1?0:R)&&e.preventDefault();return}if(e.key===`Enter`){if(e.preventDefault(),R!==-1&&ze(R))return;Pe()}e.key===`Escape`&&(e.preventDefault(),d(`agent-list`))},placeholder:s.workspacePathPlaceholder,name:`workspace-path`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`go`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`}),L.length>0&&(0,K.jsx)(`div`,{ref:we,className:`workspace-path-suggestions fx-crt-panel`,"data-testid":`workspace-path-suggestions`,role:`listbox`,children:L.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`workspace-path-suggestion ${t===R?`active`:``}`,"data-testid":`workspace-path-suggestion`,role:`option`,"aria-selected":t===R,onMouseDown:e=>{e.preventDefault(),ze(t)},children:[(0,K.jsx)(`span`,{className:`workspace-path-suggestion-name`,children:e.name}),(0,K.jsx)(`span`,{className:`workspace-path-suggestion-path`,children:ot(e.path)})]},e.path))}),!t&&o&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:`Workflow:`}),(0,K.jsx)(`select`,{className:`workflow-select fx-crt-panel`,"data-testid":`workflow-template-select`,value:E,onChange:e=>D(e.target.value),"aria-label":`Workflow template`,children:Ye.map(e=>(0,K.jsx)(`option`,{value:e.id,children:e.label},e.id||`none`))}),(0,K.jsx)(`p`,{className:`workspace-field-copy`,children:`Task (optional):`}),(0,K.jsx)(`textarea`,{className:`task-input fx-crt-panel`,"data-testid":`task-input`,value:w,onChange:e=>T(e.target.value),placeholder:`Describe what this agent should focus on`,rows:4,name:`agent-task`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`})]}),Oe.length>0&&(0,K.jsxs)(`div`,{className:`workspace-history fx-crt-panel`,"data-testid":`workspace-history`,children:[(0,K.jsxs)(`div`,{className:`workspace-history-header`,children:[(0,K.jsx)(`span`,{children:s.recentWorkspacesLower}),(0,K.jsxs)(`span`,{className:`hint`,"aria-hidden":`true`,children:[(0,K.jsx)(he,{}),(0,K.jsx)(_e,{})]})]}),(0,K.jsx)(`div`,{className:`workspace-history-list`,children:Oe.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`workspace-history-item ${t===pe?`active`:``}`,"data-testid":`workspace-history-item`,onMouseDown:e=>{e.preventDefault(),Fe(t)},children:[(0,K.jsx)(`span`,{className:`workspace-history-index`,children:t+1}),(0,K.jsx)(`span`,{className:`workspace-history-path`,children:ot(e)}),t===0&&e===O[0]&&(0,K.jsx)(`span`,{className:`workspace-history-badge`,children:s.latest})]},e))})]}),(0,K.jsxs)(`div`,{className:`workspace-actions`,children:[(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-start`,"aria-label":s.start,disabled:ve,onClick:()=>void Pe(),children:s.start}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`workspace-back`,"aria-label":s.back,onClick:()=>d(`agent-list`),children:s.back})]})]})]})})}function mt(){return{entries:[],index:-1}}function ht(e,t=Date.now()){return{kind:`agent`,agentId:e,reason:`agent`,ts:t}}function gt(e,t=Date.now()){return{kind:`file`,agentId:e.agentId,filePath:e.filePath,view:e.view??`editor`,lineNumber:Math.max(1,e.lineNumber??1),column:Math.max(1,e.column??1),endColumn:e.endColumn,reason:e.reason??`file`,ts:t}}function _t(e,t){return e.kind===t.kind?e.kind===`agent`&&t.kind===`agent`?e.agentId===t.agentId:e.kind===`file`&&t.kind===`file`?e.agentId===t.agentId&&e.filePath===t.filePath&&e.view===t.view:!1:!1}function vt(e,t){if(!e||!_t(e,t))return!1;if(e.kind===`agent`&&t.kind===`agent`)return!0;if(e.kind!==`file`||t.kind!==`file`)return!1;let n=Math.abs(e.lineNumber-t.lineNumber);return e.lineNumber===t.lineNumber&&e.column===t.column&&e.endColumn===t.endColumn||t.reason===`cursor`&&(n<30||t.ts-e.ts<1e3)||n<=15}function yt(e,t,n=50){let r=e.entries[e.index],i=vt(r,t),a=e.entries,o=e.index;return i&&o>=0?(a=a.slice(),a[o]=t):(a=a.slice(0,o+1),a.push(t),a.length>n&&(a=a.slice(a.length-n)),o=a.length-1),{entries:a,index:o}}function bt(e,t=typeof navigator<`u`?navigator.platform:``){return!(e.key===`-`||e.key===`_`||e.code===`Minus`)||!e.ctrlKey||e.metaKey||e.altKey?null:e.shiftKey?1:-1}var xt={background:`#ffffff`,foreground:`#24292f`,cursor:`#24292f`,cursorAccent:`#ffffff`,selectionBackground:`rgba(31, 35, 40, 0.18)`,black:`#24292f`,red:`#cf222e`,green:`#1a7f37`,yellow:`#9a6700`,blue:`#0969da`,magenta:`#8250df`,cyan:`#1b7c83`,white:`#57606a`,brightBlack:`#6e7781`,brightRed:`#a40e26`,brightGreen:`#2da44e`,brightYellow:`#bf8700`,brightBlue:`#218bff`,brightMagenta:`#a475f9`,brightCyan:`#3192aa`,brightWhite:`#24292f`},St=[`"JetBrains Mono"`,`"SF Mono"`,`Menlo`,`Monaco`,`"Cascadia Mono"`,`"Segoe UI Mono"`,`"Sarasa Mono SC"`,`"PingFang SC"`,`"Hiragino Sans GB"`,`"Noto Sans Mono CJK SC"`,`"Microsoft YaHei UI"`,`monospace`].join(`, `),Ct=null,wt=null;async function Tt(){return Ct||wt||(wt=(async()=>{try{let e=n(`/vendor/ghostty-web`),t=`${e}/ghostty-web.js`,r=`${e}/ghostty-vt.wasm`,i=await o(()=>import(t),[]);return await i.init(r),Ct={Terminal:i.Terminal,FitAddon:i.FitAddon},Ct}catch(e){return console.error(`Failed to initialize Ghostty terminal:`,e),null}})(),wt)}async function Et(e){let t=await Tt();if(!t)return null;let n=e?.fontSize??12;return{terminal:new t.Terminal({theme:xt,fontSize:n,fontFamily:St,cursorBlink:!1,smoothScrollDuration:120,scrollback:5e3}),fitAddon:new t.FitAddon}}var Dt=Object.defineProperty,Ot=Object.getOwnPropertyDescriptor,kt=(e,t)=>{for(var n in t)Dt(e,n,{get:t[n],enumerable:!0})},At=(e,t,n,r)=>{for(var i=r>1?void 0:r?Ot(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&Dt(t,n,i),i},q=(e,t)=>(n,r)=>t(n,r,e),jt=`Terminal input`,Mt={get:()=>jt,set:e=>jt=e},Nt=`Too much output to announce, navigate to rows manually to read`,Pt={get:()=>Nt,set:e=>Nt=e};function Ft(e){return e.replace(/\r?\n/g,`\r`)}function It(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function Lt(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function Rt(e,t,n,r){e.stopPropagation(),e.clipboardData&&zt(e.clipboardData.getData(`text/plain`),t,n,r)}function zt(e,t,n,r){e=Ft(e),e=It(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function Bt(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Vt(e,t,n,r,i){Bt(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Ht(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Ut(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Wt=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o);continue}i!==65279&&(t[r++]=i)}return r}},Gt=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}else this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(c=(i&31)<<6|a&63,c<128){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Kt=``,qt=` `,Jt=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Yt}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return(this.fg&50331648)==0}isBgDefault(){return(this.bg&50331648)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Yt=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Xt=class e extends Jt{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Yt,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Ht(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Zt=`di$target`,Qt=`di$dependencies`,$t=new Map;function en(e){return e[Qt]||[]}function tn(e){if($t.has(e))return $t.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);nn(t,e,r)};return t._id=e,$t.set(e,t),t}function nn(e,t,n){t[Zt]===t?t[Qt].push({id:e,index:n}):(t[Qt]=[{id:e,index:n}],t[Zt]=t)}var rn=tn(`BufferService`),an=tn(`CoreMouseService`),on=tn(`CoreService`),sn=tn(`CharsetService`),cn=tn(`InstantiationService`),ln=tn(`LogService`),un=tn(`OptionsService`),dn=tn(`OscLinkService`),fn=tn(`UnicodeService`),pn=tn(`DecorationService`),mn=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Xt,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(!(c===-1&&!n.hasContent(t))){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId)if(c===-1){c=t,s=a.extended.urlId;continue}else l=a.extended.urlId!==s;else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):hn(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};mn=At([q(0,rn),q(1,un),q(2,dn)],mn);function hn(e,t){if(confirm(`Do you want to navigate to ${t}?
6
6
 
7
7
  WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var gn=tn(`CharSizeService`),_n=tn(`CoreBrowserService`),vn=tn(`MouseService`),yn=tn(`RenderService`),bn=tn(`SelectionService`),xn=tn(`CharacterJoinerService`),Sn=tn(`ThemeService`),Cn=tn(`LinkProviderService`),wn=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?An.isErrorNoTelemetry(e)?new An(e.message+`
8
8
 
@@ -32,7 +32,7 @@ ${s.join(`
32
32
  `).slice(2,3).join(`
33
33
  `).trim(),t=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(e);Tr.register(a,t?.[2]??e,a)}return a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Cr<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||Tn;if(!n){e.value(t);return}try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners)if(this._listeners instanceof Sr)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}this._perfMon?.stop()}hasListeners(){return this._size>0}},Er=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Dr=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new X,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new X,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};Dr.INSTANCE=new Dr;var Or=Dr;function kr(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}Or.INSTANCE.onDidChangeZoomLevel;function Ar(e){return Or.INSTANCE.getZoomFactor(e)}Or.INSTANCE.onDidChangeFullscreen;var jr=typeof navigator==`object`?navigator.userAgent:``,Mr=jr.indexOf(`Firefox`)>=0,Nr=jr.indexOf(`AppleWebKit`)>=0,Pr=jr.indexOf(`Chrome`)>=0,Fr=!Pr&&jr.indexOf(`Safari`)>=0;jr.indexOf(`Electron/`),jr.indexOf(`Android`);var Ir=!1;if(typeof ar.matchMedia==`function`){let e=ar.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=ar.matchMedia(`(display-mode: fullscreen)`);Ir=e.matches,kr(ar,e,({matches:e})=>{Ir&&t.matches||(Ir=e)})}function Lr(){return Ir}var Rr=`en`,zr=!1,Br=!1,Vr=!1,Hr=!1,Ur=!1,Wr=Rr,Gr,Kr=globalThis,Z;typeof Kr.vscode<`u`&&typeof Kr.vscode.process<`u`?Z=Kr.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(Z=process);var qr=typeof Z?.versions?.electron==`string`&&Z?.type===`renderer`;if(typeof Z==`object`){zr=Z.platform===`win32`,Br=Z.platform===`darwin`,Vr=Z.platform===`linux`,Vr&&Z.env.SNAP&&Z.env.SNAP_REVISION,Z.env.CI||Z.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Wr=Rr;let e=Z.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,Wr=t.resolvedLanguage||Rr,t.languagePack?.translationsConfigFile}catch{}Hr=!0}else typeof navigator==`object`&&!qr?(Gr=navigator.userAgent,zr=Gr.indexOf(`Windows`)>=0,Br=Gr.indexOf(`Macintosh`)>=0,(Gr.indexOf(`Macintosh`)>=0||Gr.indexOf(`iPad`)>=0||Gr.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,Vr=Gr.indexOf(`Linux`)>=0,Gr?.indexOf(`Mobi`),Ur=!0,Wr=globalThis._VSCODE_NLS_LANGUAGE||Rr,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var Jr=zr,Yr=Br,Xr=Vr,Zr=Hr;Ur&&typeof Kr.importScripts==`function`&&Kr.origin;var Qr=Gr,$r=Wr,ei;(e=>{function t(){return $r}e.value=t;function n(){return $r.length===2?$r===`en`:$r.length>=3?$r[0]===`e`&&$r[1]===`n`&&$r[2]===`-`:!1}e.isDefaultVariant=n;function r(){return $r===`en`}e.isDefault=r})(ei||={});var ti=typeof Kr.postMessage==`function`&&!Kr.importScripts;(()=>{if(ti){let e=[];Kr.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),Kr.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var ni=!!(Qr&&Qr.indexOf(`Chrome`)>=0);Qr&&Qr.indexOf(`Firefox`),!ni&&Qr&&Qr.indexOf(`Safari`),Qr&&Qr.indexOf(`Edg/`),Qr&&Qr.indexOf(`Android`);var ri=typeof navigator==`object`?navigator:{};Zr||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||ri&&ri.clipboard&&ri.clipboard.writeText,Zr||ri&&ri.clipboard&&ri.clipboard.readText,Zr||Lr()||ri.keyboard,`ontouchstart`in ar||ri.maxTouchPoints,ar.PointerEvent&&(`ontouchstart`in ar||navigator.maxTouchPoints);var ii=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},ai=new ii,oi=new ii,si=new ii,ci=Array(230),li;(e=>{function t(e){return ai.keyCodeToStr(e)}e.toString=t;function n(e){return ai.strToKeyCode(e)}e.fromString=n;function r(e){return oi.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return si.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return oi.strToKeyCode(e)||si.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return ai.keyCodeToStr(e)}e.toElectronAccelerator=o})(li||={});var ui=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new di([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},di=class{constructor(e){if(e.length===0)throw kn(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function fi(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return li.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(Mr)switch(t){case 59:return 85;case 60:if(Xr)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Yr)return 57;break}else if(Nr&&(Yr&&t===93||!Yr&&t===92))return 57;return ci[t]||0}var pi=Yr?256:2048,mi=512,hi=1024,gi=Yr?2048:256,_i=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=fi(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=pi),this.altKey&&(t|=mi),this.shiftKey&&(t|=hi),this.metaKey&&(t|=gi),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new ui(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},vi=new WeakMap;function yi(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var bi=class{static getSameOriginWindowChain(e){let t=vi.get(e);if(!t){t=[],vi.set(e,t);let n=e,r;do r=yi(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},xi=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=bi.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Si=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(Pr){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)r?this.deltaY=t.wheelDeltaY/(120*i):this.deltaY=t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;t.deltaMode===t.DOM_DELTA_LINE?Mr&&!Yr?this.deltaY=-e.deltaY/3:this.deltaY=-e.deltaY:this.deltaY=-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)Fr&&Jr?this.deltaX=-(t.wheelDeltaX/120):r?this.deltaX=t.wheelDeltaX/(120*i):this.deltaX=t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;t.deltaMode===t.DOM_DELTA_LINE?Mr&&!Yr?this.deltaX=-e.deltaX/3:this.deltaX=-e.deltaX:this.deltaX=-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(r?this.deltaY=e.wheelDelta/(120*i):this.deltaY=e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},Ci=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),wi;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Ti?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:mr.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Ci})})(wi||={});var Ti=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Ci:(this._emitter||=new X,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},Ei=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new jn(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new jn(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Di=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new jn(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=er(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var Oi;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(Oi||={});var ki=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new X,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await mr.toPromise(this._onStateChanged.event)}while(!0)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};ki.EMPTY=ki.fromArray([]);function Ai(e){return 55296<=e&&e<=56319}function ji(e){return 56320<=e&&e<=57343}function Mi(e,t){return(e-55296<<10)+(t-56320)+65536}function Ni(e){return Pi(e,0)}function Pi(e,t){switch(typeof e){case`object`:return e===null?Fi(349,t):Array.isArray(e)?Ri(e,t):zi(e,t);case`string`:return Li(e,t);case`boolean`:return Ii(e,t);case`number`:return Fi(e,t);case`undefined`:return Fi(937,t);default:return Fi(617,t)}}function Fi(e,t){return(t<<5)-t+e|0}function Ii(e,t){return Fi(e?433:863,t)}function Li(e,t){t=Fi(149417,t);for(let n=0,r=e.length;n<r;n++)t=Fi(e.charCodeAt(n),t);return t}function Ri(e,t){return t=Fi(104579,t),e.reduce((e,t)=>Pi(t,e),t)}function zi(e,t){return t=Fi(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=Li(n,t),Pi(e[n],t)),t)}function Bi(e,t,n=32){let r=n-t,i=~((1<<r)-1);return(e<<t|(i&e)>>>r)>>>0}function Vi(e,t=0,n=e.byteLength,r=0){for(let i=0;i<n;i++)e[t+i]=r}function Hi(e,t,n=`0`){for(;e.length<t;)e=n+e;return e}function Ui(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``):Hi((e>>>0).toString(16),t/4)}var Wi=class e{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){let t=e.length;if(t===0)return;let n=this._buff,r=this._buffLen,i=this._leftoverHighSurrogate,a,o;for(i===0?(a=e.charCodeAt(0),o=0):(a=i,o=-1,i=0);;){let s=a;if(Ai(a))if(o+1<t){let t=e.charCodeAt(o+1);ji(t)?(o++,s=Mi(a,t)):s=65533}else{i=a;break}else ji(a)&&(s=65533);if(r=this._push(n,r,s),o++,o<t)a=e.charCodeAt(o);else break}this._buffLen=r,this._leftoverHighSurrogate=i}_push(e,t,n){return n<128?e[t++]=n:n<2048?(e[t++]=192|(n&1984)>>>6,e[t++]=128|(n&63)>>>0):n<65536?(e[t++]=224|(n&61440)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0):(e[t++]=240|(n&1835008)>>>18,e[t++]=128|(n&258048)>>>12,e[t++]=128|(n&4032)>>>6,e[t++]=128|(n&63)>>>0),t>=64&&(this._step(),t-=64,this._totalLen+=64,e[0]=e[64],e[1]=e[65],e[2]=e[66]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),Ui(this._h0)+Ui(this._h1)+Ui(this._h2)+Ui(this._h3)+Ui(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,Vi(this._buff,this._buffLen),this._buffLen>56&&(this._step(),Vi(this._buff));let e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){let t=e._bigBlock32,n=this._buffDV;for(let e=0;e<64;e+=4)t.setUint32(e,n.getUint32(e,!1),!1);for(let e=64;e<320;e+=4)t.setUint32(e,Bi(t.getUint32(e-12,!1)^t.getUint32(e-32,!1)^t.getUint32(e-56,!1)^t.getUint32(e-64,!1),1),!1);let r=this._h0,i=this._h1,a=this._h2,o=this._h3,s=this._h4,c,l,u;for(let e=0;e<80;e++)e<20?(c=i&a|~i&o,l=1518500249):e<40?(c=i^a^o,l=1859775393):e<60?(c=i&a|i&o|a&o,l=2400959708):(c=i^a^o,l=3395469782),u=Bi(r,5)+c+s+l+t.getUint32(e*4,!1)&4294967295,s=o,o=a,a=Bi(i,30),i=r,r=u;this._h0=this._h0+r&4294967295,this._h1=this._h1+i&4294967295,this._h2=this._h2+a&4294967295,this._h3=this._h3+o&4294967295,this._h4=this._h4+s&4294967295}};Wi._bigBlock32=new DataView(new ArrayBuffer(320));var{registerWindow:Gi,getWindow:Ki,getDocument:qi,getWindows:Ji,getWindowsCount:Yi,getWindowId:Xi,getWindowById:Zi,hasWindow:Qi,onDidRegisterWindow:$i,onWillUnregisterWindow:ea,onDidUnregisterWindow:ta}=function(){let e=new Map,t={window:ar,disposables:new nr};e.set(ar.vscodeWindowId,t);let n=new X,r=new X,i=new X;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return rr.None;let a=new nr,o={window:t,disposables:a.add(new nr)};return e.set(t.vscodeWindowId,o),a.add(er(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(ra(t,fa.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:ar},getDocument(e){return Ki(e).document}}}(),na=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function ra(e,t,n,r){return new na(e,t,n,r)}function ia(e,t){return function(n){return t(new xi(e,n))}}function aa(e){return function(t){return e(new _i(t))}}var oa=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=ia(Ki(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=aa(n)),ra(e,t,i,r)},sa,ca=class extends Di{constructor(e){super(),this.defaultTarget=e&&Ki(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},la=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){Tn(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(la.sort),a.shift().execute();r.set(i,!1)};sa=(t,r,a=0)=>{let o=Xi(t),s=new la(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var ua=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};ua.None=new ua(0,0);function da(e){let t=e.getBoundingClientRect(),n=Ki(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=Ni(n),a=r.get(i);if(a)a.users+=1;else{let o=new X,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(er(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var fa={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:Nr?`webkitAnimationStart`:`animationstart`,ANIMATION_END:Nr?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:Nr?`webkitAnimationIteration`:`animationiteration`},pa=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;function ma(e,t,n,...r){let i=pa.exec(t);if(!i)throw Error(`Bad use of emmet`);let a=i[1]||`div`,o;return o=e===`http://www.w3.org/1999/xhtml`?document.createElement(a):document.createElementNS(e,a),i[3]&&(o.id=i[3]),i[4]&&(o.className=i[4].replace(/\./g,` `).trim()),n&&Object.entries(n).forEach(([e,t])=>{typeof t>`u`||(/^on\w+$/.test(e)?o[e]=t:e===`selected`?t&&o.setAttribute(e,`true`):o.setAttribute(e,t))}),o.append(...r),o}function ha(e,t,...n){return ma(`http://www.w3.org/1999/xhtml`,e,t,...n)}ha.SVG=function(e,t,...n){return ma(`http://www.w3.org/2000/svg`,e,t,...n)};var ga=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=_a(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=_a(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=_a(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=_a(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=_a(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=_a(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=_a(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=_a(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=_a(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=_a(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=_a(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=_a(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=_a(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=_a(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function _a(e){return typeof e==`number`?`${e}px`:e}function va(e){return new ga(e)}var ya=class{constructor(){this._hooks=new nr,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(er(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=Ki(e)}this._hooks.add(ra(a,fa.POINTER_MOVE,e=>{if(e.buttons!==n){this.stopMonitoring(!0);return}e.preventDefault(),this._pointerMoveCallback(e)})),this._hooks.add(ra(a,fa.POINTER_UP,e=>this.stopMonitoring(!0)))}};function ba(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var xa;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(xa||={});var Sa=class e extends rr{constructor(){super(),this.dispatched=!1,this.targets=new cr,this.ignoreTargets=new cr,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(mr.runAndSubscribe($i,({window:e,disposables:t})=>{t.add(ra(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(ra(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(ra(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:ar,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Zn(new e),er(e.INSTANCE.targets.push(t))):rr.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=Zn(new e),er(e.INSTANCE.ignoreTargets.push(t))):rr.None}static isTouchDevice(){return`ontouchstart`in ar||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(xa.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-Pn(s.rollingPageX))<30&&Math.abs(s.initialPageY-Pn(s.rollingPageY))<30){let e=this.newGestureEvent(xa.Tap,s.initialTarget);e.pageX=Pn(s.rollingPageX),e.pageY=Pn(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-Pn(s.rollingPageX))<30&&Math.abs(s.initialPageY-Pn(s.rollingPageY))<30){let e=this.newGestureEvent(xa.Contextmenu,s.initialTarget);e.pageX=Pn(s.rollingPageX),e.pageY=Pn(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=Pn(s.rollingPageX),n=Pn(s.rollingPageY),i=Pn(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(xa.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===xa.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else (t.type===xa.Change||t.type===xa.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=sa(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(xa.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(xa.Change,i.initialTarget);a.translationX=r.pageX-Pn(i.rollingPageX),a.translationY=r.pageY-Pn(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Sa.SCROLL_FRICTION=-.005,Sa.HOLD_DELAY=700,Sa.CLEAR_TAP_COUNT_TIME=400,At([ba],Sa,`isTouchDevice`,1);var Ca=Sa,wa=class extends rr{onclick(e,t){this._register(ra(e,fa.CLICK,n=>t(new xi(Ki(e),n))))}onmousedown(e,t){this._register(ra(e,fa.MOUSE_DOWN,n=>t(new xi(Ki(e),n))))}onmouseover(e,t){this._register(ra(e,fa.MOUSE_OVER,n=>t(new xi(Ki(e),n))))}onmouseleave(e,t){this._register(ra(e,fa.MOUSE_LEAVE,n=>t(new xi(Ki(e),n))))}onkeydown(e,t){this._register(ra(e,fa.KEY_DOWN,e=>t(new _i(e))))}onkeyup(e,t){this._register(ra(e,fa.KEY_UP,e=>t(new _i(e))))}oninput(e,t){this._register(ra(e,fa.INPUT,t))}onblur(e,t){this._register(ra(e,fa.BLUR,t))}onfocus(e,t){this._register(ra(e,fa.FOCUS,t))}onchange(e,t){this._register(ra(e,fa.CHANGE,t))}ignoreGesture(e){return Ca.ignoreTarget(e)}},Ta=11,Ea=class extends wa{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Ta+`px`,this.domNode.style.height=Ta+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new ya),this._register(oa(this.bgDomNode,fa.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(oa(this.domNode,fa.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new ca),this._pointerdownScheduleRepeatTimer=this._register(new Ei)}_arrowPointerDown(e){!e.target||!(e.target instanceof Element)||(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Ki(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Da=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Oa=class extends rr{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new X),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Da(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Ma(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Ma.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},ka=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Aa(e,t){let n=t-e;return function(t){return e+n*Pa(t)}}function ja(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Ma=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),ja(Aa(e,r),Aa(i,t),.33)}return Aa(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new ka(this.scrollLeft(t),this.scrollTop(t),!1):new ka(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){return r+=10,new e(t,n,Date.now()-10,r)}};function Na(e){return e**3}function Pa(e){return 1-Na(1-e)}var Fa=class extends rr{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Ei)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3?!0:this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){if(!this._isNeeded){this._hide(!1);return}this._shouldBeVisible?this._reveal():this._hide(!0)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},Ia=140,La=class extends wa{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Fa(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new ya),this._shouldRender=!0,this.domNode=va(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(ra(this.domNode.domNode,fa.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Ea(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=va(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(ra(this.slider.domNode,fa.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=da(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(Jr&&a>Ia){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Ra=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize===t?!1:(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize===t?!1:(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition===t?!1:(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},za=class extends La{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Ra(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Ba=class extends La{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Ra(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Va=500,Ha=50,Ua=!0,Wa=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},Ga=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(!0);return t<=.5}acceptStandardWheelEvent(e){if(Pr){let t=Ar(Ki(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new Wa(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};Ga.INSTANCE=new Ga;var Ka=Ga,qa=class extends wa{constructor(e,t,n){super(),this._onScroll=this._register(new X),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new X),this.onWillScroll=this._onWillScroll.event,this._options=Ya(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Ba(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new za(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=va(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=va(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=va(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new Ei),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Qn(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Yr&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Si(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Qn(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(ra(this._listenOnDomNode,fa.MOUSE_WHEEL,e=>{this._onMouseWheel(new Si(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Ka.INSTANCE;Ua&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!Yr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=Ha*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=Ha*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(Ua&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Va)}},Ja=class extends qa{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function Ya(e){let t={lazyRender:typeof e.lazyRender<`u`?e.lazyRender:!1,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`?e.flipAxes:!1,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`?e.consumeMouseWheelIfScrollbarIsNeeded:!1,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`?e.alwaysConsumeMouseWheel:!1,scrollYToX:typeof e.scrollYToX<`u`?e.scrollYToX:!1,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`?e.horizontalHasArrows:!1,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`?e.verticalHasArrows:!1,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`?e.scrollByPage:!1};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,Yr&&(t.className+=` mac`),t}var Xa=class extends rr{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new X),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Oa({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>sa(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Ja(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(mr.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(er(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(er(()=>this._styleElement.remove())),this._register(mr.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
34
34
  `)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};Xa=At([q(2,rn),q(3,_n),q(4,an),q(5,Sn),q(6,un),q(7,yn)],Xa);var Za=class extends rr{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(er(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};Za=At([q(1,rn),q(2,_n),q(3,pn),q(4,yn)],Za);var Qa=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},$a={full:0,left:0,center:0,right:0},eo={full:0,left:0,center:0,right:0},to={full:0,left:0,center:0,right:0},no=class extends rr{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new Qa,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(er(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);eo.full=this._canvas.width,eo.left=e,eo.center=t,eo.right=e,this._refreshDrawHeightConstants(),to.full=1,to.left=1,to.center=1+eo.left,to.right=1+eo.left+eo.center}_refreshDrawHeightConstants(){$a.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);$a.left=t,$a.center=t,$a.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*$a.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*$a.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*$a.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*$a.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(to[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-$a[e.position||`full`]/2),eo[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+$a[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};no=At([q(2,rn),q(3,pn),q(4,yn),q(5,un),q(6,Sn),q(7,_n)],no);var Q;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
35
- `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))(Q||={});var ro;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(ro||={});var io;(e=>e.ST=`${Q.ESC}\\`)(io||={});var ao=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${Q.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};ao=At([q(2,rn),q(3,un),q(4,on),q(5,yn)],ao);var oo=0,so=0,co=0,lo=0,uo={css:`#00000000`,rgba:0},fo;(e=>{function t(e,t,n,r){return r===void 0?`#${_o(e)}${_o(t)}${_o(n)}`:`#${_o(e)}${_o(t)}${_o(n)}${_o(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(fo||={});var po;(e=>{function t(e,t){if(lo=(t.rgba&255)/255,lo===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return oo=a+Math.round((n-a)*lo),so=o+Math.round((r-o)*lo),co=s+Math.round((i-s)*lo),{css:fo.toCss(oo,so,co),rgba:fo.toRgba(oo,so,co)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=go.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return fo.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[oo,so,co]=go.toChannels(t),{css:fo.toCss(oo,so,co),rgba:t}}e.opaque=i;function a(e,t){return lo=Math.round(t*255),[oo,so,co]=go.toChannels(e.rgba),{css:fo.toCss(oo,so,co,lo),rgba:fo.toRgba(oo,so,co,lo)}}e.opacity=a;function o(e,t){return lo=e.rgba&255,a(e,lo*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(po||={});var mo;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return oo=parseInt(e.slice(1,2).repeat(2),16),so=parseInt(e.slice(2,3).repeat(2),16),co=parseInt(e.slice(3,4).repeat(2),16),fo.toColor(oo,so,co);case 5:return oo=parseInt(e.slice(1,2).repeat(2),16),so=parseInt(e.slice(2,3).repeat(2),16),co=parseInt(e.slice(3,4).repeat(2),16),lo=parseInt(e.slice(4,5).repeat(2),16),fo.toColor(oo,so,co,lo);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return oo=parseInt(r[1]),so=parseInt(r[2]),co=parseInt(r[3]),lo=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),fo.toColor(oo,so,co,lo);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[oo,so,co,lo]=t.getImageData(0,0,1,1).data,lo!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:fo.toRgba(oo,so,co,lo),css:e}}e.toColor=r})(mo||={});var ho;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(ho||={});var go;(e=>{function t(e,t){if(lo=(t&255)/255,lo===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return oo=a+Math.round((n-a)*lo),so=o+Math.round((r-o)*lo),co=s+Math.round((i-s)*lo),fo.toRgba(oo,so,co)}e.blend=t;function n(e,t,n){let a=ho.relativeLuminance(e>>8),o=ho.relativeLuminance(t>>8);if(vo(a,o)<n){if(o<a){let o=r(e,t,n),s=vo(a,ho.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>vo(a,ho.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=vo(a,ho.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>vo(a,ho.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(go||={});function _o(e){let t=e.toString(16);return t.length<2?`0`+t:t}function vo(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var yo=class extends Jt{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},bo=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Xt}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||qt.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)bo._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||qt.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};bo=At([q(0,rn)],bo);function xo(e){return 57508<=e&&e<=57558}function So(e){return 9472<=e&&e<=9631}function Co(e){return xo(e)||So(e)}function wo(){return{css:{canvas:To(),cell:To()},device:{canvas:To(),cell:To(),char:{width:0,height:0,left:0,top:0}}}}function To(){return{width:0,height:0}}var Eo=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Xt,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let ee=!1,te=k>=E,A=k,j=this._workCell;if(f.length>0&&k===f[0][0]&&te){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)te&&=i===this._isCellInSelection(v,t);te&&=!n||a<r[0]||a>=r[1],te?(ee=!0,j=new yo(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),A=r[1]-1,m=j.getWidth()):E=r[1]}let M=this._isCellInSelection(k,t),N=n&&k===a,P=O&&k>=l&&k<=u,F=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{F=!0});let ne=j.getChars()||qt;if(ne===` `&&(j.isUnderline()||j.isOverline())&&(ne=`\xA0`),T=m*s-c.get(ne,j.isBold(),j.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(M&&w||!M&&!w&&j.bg===y)&&(M&&w&&p.selectionForeground||j.fg===b)&&j.extended.ext===x&&P===S&&T===C&&!N&&!ee&&!F&&te){j.isInvisible()?_+=qt:_+=ne,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=j.bg,b=j.fg,x=j.extended.ext,S=P,C=T,w=M,ee&&a>=k&&a<=A&&(a=k),!this._coreService.isCursorHidden&&N&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`);break;default:break}}if(j.isBold()&&D.push(`xterm-bold`),j.isItalic()&&D.push(`xterm-italic`),j.isDim()&&D.push(`xterm-dim`),_=j.isInvisible()?qt:j.getChars()||qt,j.isUnderline()&&(D.push(`xterm-underline-${j.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!j.isUnderlineColorDefault()))if(j.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Jt.toColorRGB(j.getUnderlineColor()).join(`,`)})`;else{let e=j.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&j.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}j.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),j.isStrikethrough()&&D.push(`xterm-strikethrough`),P&&(h.style.textDecoration=`underline`);let I=j.getFgColor(),L=j.getFgColorMode(),R=j.getBgColor(),z=j.getBgColorMode(),re=!!j.isInverse();if(re){let e=I;I=R,R=e;let t=L;L=z,z=t}let B,ie,V=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&V||(e.backgroundColorRGB&&(z=50331648,R=e.backgroundColorRGB.rgba>>8&16777215,B=e.backgroundColorRGB),e.foregroundColorRGB&&(L=50331648,I=e.foregroundColorRGB.rgba>>8&16777215,ie=e.foregroundColorRGB),V=e.options.layer===`top`)}),!V&&M&&(B=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,R=B.rgba>>8&16777215,z=50331648,V=!0,p.selectionForeground&&(L=50331648,I=p.selectionForeground.rgba>>8&16777215,ie=p.selectionForeground)),V&&D.push(`xterm-decoration-top`);let ae;switch(z){case 16777216:case 33554432:ae=p.ansi[R],D.push(`xterm-bg-${R}`);break;case 50331648:ae=fo.toColor(R>>16,R>>8&255,R&255),this._addStyle(h,`background-color:#${Do((R>>>0).toString(16),`0`,6)}`);break;default:re?(ae=p.foreground,D.push(`xterm-bg-257`)):ae=p.background}switch(B||j.isDim()&&(B=po.multiplyOpacity(ae,.5)),L){case 16777216:case 33554432:j.isBold()&&I<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(I+=8),this._applyMinimumContrast(h,ae,p.ansi[I],j,B,void 0)||D.push(`xterm-fg-${I}`);break;case 50331648:let e=fo.toColor(I>>16&255,I>>8&255,I&255);this._applyMinimumContrast(h,ae,e,j,B,ie)||this._addStyle(h,`color:#${Do(I.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,ae,p.foreground,j,B,ie)||re&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!N&&!ee&&!F&&te?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=A}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Co(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=po.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Eo=At([q(1,xn),q(2,un),q(3,_n),q(4,on),q(5,pn),q(6,Sn)],Eo);function Do(e,t,n){for(;e.length<n;)e=t+e;return e}var Oo=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},ko=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Ao(){return new ko}var jo=`xterm-dom-renderer-owner-`,Mo=`xterm-rows`,No=`xterm-fg-`,Po=`xterm-bg-`,Fo=`xterm-focus`,Io=`xterm-selection`,Lo=1,Ro=class extends rr{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Lo++,this._rowElements=[],this._selectionRenderModel=Ao(),this.onRequestRedraw=this._register(new X).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(Mo),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(Io),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=wo(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Eo,document),this._element.classList.add(jo+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(er(()=>{this._element.classList.remove(jo+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Oo(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Mo} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Mo} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Mo} .xterm-dim { color: ${po.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Mo}.${Fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Mo}.${Fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Mo}.${Fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Io} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Io} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Io} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${No}${n} { color: ${r.css}; }${this._terminalSelector} .${No}${n}.xterm-dim { color: ${po.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${Po}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${No}257 { color: ${po.opaque(e.background).css}; }${this._terminalSelector} .${No}257.xterm-dim { color: ${po.multiplyOpacity(po.opaque(e.background),.5).css}; }${this._terminalSelector} .${Po}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Fo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Fo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${jo}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};Ro=At([q(7,cn),q(8,gn),q(9,un),q(10,rn),q(11,on),q(12,_n),q(13,Sn)],Ro);var zo=class extends rr{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new X),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Ho(this._optionsService))}catch{this._measureStrategy=this._register(new Vo(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};zo=At([q(2,un)],zo);var Bo=class extends rr{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},Vo=class extends Bo{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Ho=class extends Bo{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Uo=class extends rr{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Wo(this._window)),this._onDprChange=this._register(new X),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new X),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(mr.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(ra(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(ra(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Wo=class extends rr{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ir),this._onDprChange=this._register(new X),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(er(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=ra(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Go=class extends rr{constructor(){super(),this.linkProviders=[],this._register(er(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Ko(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function qo(e,t,n,r,i,a,o,s,c){if(!a)return;let l=Ko(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var Jo=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return qo(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=Ko(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};Jo=At([q(0,yn),q(1,gn)],Jo);var Yo=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Xo={};kt(Xo,{getSafariVersion:()=>rs,isChromeOS:()=>ls,isFirefox:()=>es,isIpad:()=>as,isIphone:()=>os,isLegacyEdge:()=>ts,isLinux:()=>cs,isMac:()=>is,isNode:()=>Zo,isSafari:()=>ns,isWindows:()=>ss});var Zo=typeof process<`u`&&`title`in process,Qo=Zo?`node`:navigator.userAgent,$o=Zo?`node`:navigator.platform,es=Qo.includes(`Firefox`),ts=Qo.includes(`Edge`),ns=/^((?!chrome|android).)*safari/i.test(Qo);function rs(){if(!ns)return 0;let e=Qo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var is=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes($o),as=$o===`iPad`,os=$o===`iPhone`,ss=[`Windows`,`Win16`,`Win32`,`WinCE`].includes($o),cs=$o.indexOf(`Linux`)>=0,ls=/\bCrOS\b/.test(Qo),us=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},ds=class extends us{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},fs=class extends us{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},ps=!Zo&&`requestIdleCallback`in window?fs:ds,ms=class{constructor(){this._queue=new ps}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},hs=class extends rr{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new ir),this._pausedResizeTask=new ms,this._observerDisposable=this._register(new ir),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new X),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new X),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new X),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new X),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Yo((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new gs(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(er(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=er(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};hs=At([q(2,un),q(3,gn),q(4,on),q(5,pn),q(6,rn),q(7,_n),q(8,Sn)],hs);var gs=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function _s(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return bs(i,a,e,t,n,r)+xs(a,t,n,r)+Ss(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,ks(Math.abs(i-e),Os(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return ks(ys(a>t?e:i,n)+(s-1)*n.cols+1+vs(a>t?i:e,n),Os(o,r))}function vs(e,t){return e-1}function ys(e,t){return t.cols-e}function bs(e,t,n,r,i,a){return xs(t,r,i,a).length===0?``:ks(Ds(e,t,e,t-ws(t,i),!1,i).length,Os(`D`,a))}function xs(e,t,n,r){let i=e-ws(e,n),a=t-ws(t,n);return ks(Math.abs(i-a)-Cs(e,t,n),Os(Es(e,t),r))}function Ss(e,t,n,r,i,a){let o;o=xs(t,r,i,a).length>0?r-ws(r,i):t;let s=r,c=Ts(e,t,n,r,i,a);return ks(Ds(e,o,n,s,c===`C`,i).length,Os(c,a))}function Cs(e,t,n){let r=0,i=e-ws(e,n),a=t-ws(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Es(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function ws(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Ts(e,t,n,r,i,a){let o;return o=xs(n,r,i,a).length>0?r-ws(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Es(e,t){return e>t?`A`:`B`}function Ds(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Os(e,t){let n=t?`O`:`[`;return Q.ESC+n+e}function ks(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var As=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function js(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Ms=50,Ns=15,Ps=50,Fs=500,Is=RegExp(`\xA0`,`g`),Ls=class extends rr{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Xt,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new X),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new X),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new X),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new X),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new As(this._bufferService),this._activeSelectionMode=0,this._register(er(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(Is,` `)).join(ss?`\r
35
+ `,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))(Q||={});var ro;(e=>(e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`))(ro||={});var io;(e=>e.ST=`${Q.ESC}\\`)(io||={});var ao=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${Q.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};ao=At([q(2,rn),q(3,un),q(4,on),q(5,yn)],ao);var oo=0,so=0,co=0,lo=0,uo={css:`#00000000`,rgba:0},fo;(e=>{function t(e,t,n,r){return r===void 0?`#${_o(e)}${_o(t)}${_o(n)}`:`#${_o(e)}${_o(t)}${_o(n)}${_o(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(fo||={});var po;(e=>{function t(e,t){if(lo=(t.rgba&255)/255,lo===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return oo=a+Math.round((n-a)*lo),so=o+Math.round((r-o)*lo),co=s+Math.round((i-s)*lo),{css:fo.toCss(oo,so,co),rgba:fo.toRgba(oo,so,co)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=go.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return fo.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[oo,so,co]=go.toChannels(t),{css:fo.toCss(oo,so,co),rgba:t}}e.opaque=i;function a(e,t){return lo=Math.round(t*255),[oo,so,co]=go.toChannels(e.rgba),{css:fo.toCss(oo,so,co,lo),rgba:fo.toRgba(oo,so,co,lo)}}e.opacity=a;function o(e,t){return lo=e.rgba&255,a(e,lo*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(po||={});var mo;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return oo=parseInt(e.slice(1,2).repeat(2),16),so=parseInt(e.slice(2,3).repeat(2),16),co=parseInt(e.slice(3,4).repeat(2),16),fo.toColor(oo,so,co);case 5:return oo=parseInt(e.slice(1,2).repeat(2),16),so=parseInt(e.slice(2,3).repeat(2),16),co=parseInt(e.slice(3,4).repeat(2),16),lo=parseInt(e.slice(4,5).repeat(2),16),fo.toColor(oo,so,co,lo);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return oo=parseInt(r[1]),so=parseInt(r[2]),co=parseInt(r[3]),lo=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),fo.toColor(oo,so,co,lo);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[oo,so,co,lo]=t.getImageData(0,0,1,1).data,lo!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:fo.toRgba(oo,so,co,lo),css:e}}e.toColor=r})(mo||={});var ho;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(ho||={});var go;(e=>{function t(e,t){if(lo=(t&255)/255,lo===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return oo=a+Math.round((n-a)*lo),so=o+Math.round((r-o)*lo),co=s+Math.round((i-s)*lo),fo.toRgba(oo,so,co)}e.blend=t;function n(e,t,n){let a=ho.relativeLuminance(e>>8),o=ho.relativeLuminance(t>>8);if(vo(a,o)<n){if(o<a){let o=r(e,t,n),s=vo(a,ho.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>vo(a,ho.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=vo(a,ho.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>vo(a,ho.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=vo(ho.relativeLuminance2(o,s,c),ho.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(go||={});function _o(e){let t=e.toString(16);return t.length<2?`0`+t:t}function vo(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var yo=class extends Jt{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},bo=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Xt}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||qt.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)bo._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||qt.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};bo=At([q(0,rn)],bo);function xo(e){return 57508<=e&&e<=57558}function So(e){return 9472<=e&&e<=9631}function Co(e){return xo(e)||So(e)}function wo(){return{css:{canvas:To(),cell:To()},device:{canvas:To(),cell:To(),char:{width:0,height:0,left:0,top:0}}}}function To(){return{width:0,height:0}}var Eo=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Xt,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,ee=k>=E,j=k,M=this._workCell;if(f.length>0&&k===f[0][0]&&ee){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)ee&&=i===this._isCellInSelection(v,t);ee&&=!n||a<r[0]||a>=r[1],ee?(A=!0,M=new yo(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),j=r[1]-1,m=M.getWidth()):E=r[1]}let N=this._isCellInSelection(k,t),te=n&&k===a,P=O&&k>=l&&k<=u,F=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{F=!0});let ne=M.getChars()||qt;if(ne===` `&&(M.isUnderline()||M.isOverline())&&(ne=`\xA0`),T=m*s-c.get(ne,M.isBold(),M.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(N&&w||!N&&!w&&M.bg===y)&&(N&&w&&p.selectionForeground||M.fg===b)&&M.extended.ext===x&&P===S&&T===C&&!te&&!A&&!F&&ee){M.isInvisible()?_+=qt:_+=ne,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=M.bg,b=M.fg,x=M.extended.ext,S=P,C=T,w=N,A&&a>=k&&a<=j&&(a=k),!this._coreService.isCursorHidden&&te&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`);break;default:break}}if(M.isBold()&&D.push(`xterm-bold`),M.isItalic()&&D.push(`xterm-italic`),M.isDim()&&D.push(`xterm-dim`),_=M.isInvisible()?qt:M.getChars()||qt,M.isUnderline()&&(D.push(`xterm-underline-${M.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!M.isUnderlineColorDefault()))if(M.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Jt.toColorRGB(M.getUnderlineColor()).join(`,`)})`;else{let e=M.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&M.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}M.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),M.isStrikethrough()&&D.push(`xterm-strikethrough`),P&&(h.style.textDecoration=`underline`);let I=M.getFgColor(),L=M.getFgColorMode(),re=M.getBgColor(),R=M.getBgColorMode(),z=!!M.isInverse();if(z){let e=I;I=re,re=e;let t=L;L=R,R=t}let B,ie,V=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&V||(e.backgroundColorRGB&&(R=50331648,re=e.backgroundColorRGB.rgba>>8&16777215,B=e.backgroundColorRGB),e.foregroundColorRGB&&(L=50331648,I=e.foregroundColorRGB.rgba>>8&16777215,ie=e.foregroundColorRGB),V=e.options.layer===`top`)}),!V&&N&&(B=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,re=B.rgba>>8&16777215,R=50331648,V=!0,p.selectionForeground&&(L=50331648,I=p.selectionForeground.rgba>>8&16777215,ie=p.selectionForeground)),V&&D.push(`xterm-decoration-top`);let ae;switch(R){case 16777216:case 33554432:ae=p.ansi[re],D.push(`xterm-bg-${re}`);break;case 50331648:ae=fo.toColor(re>>16,re>>8&255,re&255),this._addStyle(h,`background-color:#${Do((re>>>0).toString(16),`0`,6)}`);break;default:z?(ae=p.foreground,D.push(`xterm-bg-257`)):ae=p.background}switch(B||M.isDim()&&(B=po.multiplyOpacity(ae,.5)),L){case 16777216:case 33554432:M.isBold()&&I<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(I+=8),this._applyMinimumContrast(h,ae,p.ansi[I],M,B,void 0)||D.push(`xterm-fg-${I}`);break;case 50331648:let e=fo.toColor(I>>16&255,I>>8&255,I&255);this._applyMinimumContrast(h,ae,e,M,B,ie)||this._addStyle(h,`color:#${Do(I.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,ae,p.foreground,M,B,ie)||z&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!te&&!A&&!F&&ee?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=j}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||Co(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=po.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};Eo=At([q(1,xn),q(2,un),q(3,_n),q(4,on),q(5,pn),q(6,Sn)],Eo);function Do(e,t,n){for(;e.length<n;)e=t+e;return e}var Oo=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},ko=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);if(s>=e.rows||c<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0]}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function Ao(){return new ko}var jo=`xterm-dom-renderer-owner-`,Mo=`xterm-rows`,No=`xterm-fg-`,Po=`xterm-bg-`,Fo=`xterm-focus`,Io=`xterm-selection`,Lo=1,Ro=class extends rr{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=Lo++,this._rowElements=[],this._selectionRenderModel=Ao(),this.onRequestRedraw=this._register(new X).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(Mo),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(Io),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=wo(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(Eo,document),this._element.classList.add(jo+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(er(()=>{this._element.classList.remove(jo+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new Oo(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Mo} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Mo} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Mo} .xterm-dim { color: ${po.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Mo}.${Fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Mo}.${Fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Mo}.${Fo} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Mo} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Io} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Io} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Io} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${No}${n} { color: ${r.css}; }${this._terminalSelector} .${No}${n}.xterm-dim { color: ${po.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${Po}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${No}257 { color: ${po.opaque(e.background).css}; }${this._terminalSelector} .${No}257.xterm-dim { color: ${po.multiplyOpacity(po.opaque(e.background),.5).css}; }${this._terminalSelector} .${Po}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Fo),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Fo),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${jo}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};Ro=At([q(7,cn),q(8,gn),q(9,un),q(10,rn),q(11,on),q(12,_n),q(13,Sn)],Ro);var zo=class extends rr{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new X),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new Ho(this._optionsService))}catch{this._measureStrategy=this._register(new Vo(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};zo=At([q(2,un)],zo);var Bo=class extends rr{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},Vo=class extends Bo{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},Ho=class extends Bo{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},Uo=class extends rr{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new Wo(this._window)),this._onDprChange=this._register(new X),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new X),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(mr.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(ra(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(ra(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},Wo=class extends rr{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new ir),this._onDprChange=this._register(new X),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(er(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=ra(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Go=class extends rr{constructor(){super(),this.linkProviders=[],this._register(er(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function Ko(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function qo(e,t,n,r,i,a,o,s,c){if(!a)return;let l=Ko(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var Jo=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return qo(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=Ko(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};Jo=At([q(0,yn),q(1,gn)],Jo);var Yo=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},Xo={};kt(Xo,{getSafariVersion:()=>rs,isChromeOS:()=>ls,isFirefox:()=>es,isIpad:()=>as,isIphone:()=>os,isLegacyEdge:()=>ts,isLinux:()=>cs,isMac:()=>is,isNode:()=>Zo,isSafari:()=>ns,isWindows:()=>ss});var Zo=typeof process<`u`&&`title`in process,Qo=Zo?`node`:navigator.userAgent,$o=Zo?`node`:navigator.platform,es=Qo.includes(`Firefox`),ts=Qo.includes(`Edge`),ns=/^((?!chrome|android).)*safari/i.test(Qo);function rs(){if(!ns)return 0;let e=Qo.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var is=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes($o),as=$o===`iPad`,os=$o===`iPhone`,ss=[`Windows`,`Win16`,`Win32`,`WinCE`].includes($o),cs=$o.indexOf(`Linux`)>=0,ls=/\bCrOS\b/.test(Qo),us=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},ds=class extends us{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},fs=class extends us{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},ps=!Zo&&`requestIdleCallback`in window?fs:ds,ms=class{constructor(){this._queue=new ps}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},hs=class extends rr{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new ir),this._pausedResizeTask=new ms,this._observerDisposable=this._register(new ir),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new X),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new X),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new X),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new X),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new Yo((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new gs(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(er(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=er(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};hs=At([q(2,un),q(3,gn),q(4,on),q(5,pn),q(6,rn),q(7,_n),q(8,Sn)],hs);var gs=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function _s(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return bs(i,a,e,t,n,r)+xs(a,t,n,r)+Ss(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,ks(Math.abs(i-e),Os(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return ks(ys(a>t?e:i,n)+(s-1)*n.cols+1+vs(a>t?i:e,n),Os(o,r))}function vs(e,t){return e-1}function ys(e,t){return t.cols-e}function bs(e,t,n,r,i,a){return xs(t,r,i,a).length===0?``:ks(Ds(e,t,e,t-ws(t,i),!1,i).length,Os(`D`,a))}function xs(e,t,n,r){let i=e-ws(e,n),a=t-ws(t,n);return ks(Math.abs(i-a)-Cs(e,t,n),Os(Es(e,t),r))}function Ss(e,t,n,r,i,a){let o;o=xs(t,r,i,a).length>0?r-ws(r,i):t;let s=r,c=Ts(e,t,n,r,i,a);return ks(Ds(e,o,n,s,c===`C`,i).length,Os(c,a))}function Cs(e,t,n){let r=0,i=e-ws(e,n),a=t-ws(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=Es(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function ws(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function Ts(e,t,n,r,i,a){let o;return o=xs(n,r,i,a).length>0?r-ws(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function Es(e,t){return e>t?`A`:`B`}function Ds(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function Os(e,t){let n=t?`O`:`[`;return Q.ESC+n+e}function ks(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var As=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function js(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var Ms=50,Ns=15,Ps=50,Fs=500,Is=RegExp(`\xA0`,`g`),Ls=class extends rr{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Xt,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new X),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new X),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new X),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new X),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new As(this._bufferService),this._activeSelectionMode=0,this._register(er(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(Is,` `)).join(ss?`\r
36
36
  `:`
37
37
  `)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),cs&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=js(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Ko(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-Ms),Ms),t/=Ms,t/Math.abs(t)+Math.round(t*(Ns-1)))}shouldForceSelection(e){return is?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),Ps)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(is&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(!(!this._model.selectionEnd||!this._model.selectionStart)&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<Fs&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=_s(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);if(!n){this._oldHasSelection&&this._fireOnSelectionChange(e,t,n);return}!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(!(!t&&o.slice(s,c).trim()===``)){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=js(n,this._bufferService.cols)}};Ls=At([q(3,rn),q(4,on),q(5,vn),q(6,un),q(7,yn),q(8,_n)],Ls);var Rs=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},zs=class{constructor(){this._color=new Rs,this._css=new Rs}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Bs=Object.freeze((()=>{let e=[mo.toColor(`#2e3436`),mo.toColor(`#cc0000`),mo.toColor(`#4e9a06`),mo.toColor(`#c4a000`),mo.toColor(`#3465a4`),mo.toColor(`#75507b`),mo.toColor(`#06989a`),mo.toColor(`#d3d7cf`),mo.toColor(`#555753`),mo.toColor(`#ef2929`),mo.toColor(`#8ae234`),mo.toColor(`#fce94f`),mo.toColor(`#729fcf`),mo.toColor(`#ad7fa8`),mo.toColor(`#34e2e2`),mo.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:fo.toCss(r,i,a),rgba:fo.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:fo.toCss(n,n,n),rgba:fo.toRgba(n,n,n)})}return e})()),Vs=mo.toColor(`#ffffff`),Hs=mo.toColor(`#000000`),Us=mo.toColor(`#ffffff`),Ws=Hs,Gs={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},Ks=Vs,qs=class extends rr{constructor(e){super(),this._optionsService=e,this._contrastCache=new zs,this._halfContrastCache=new zs,this._onChangeColors=this._register(new X),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Vs,background:Hs,cursor:Us,cursorAccent:Ws,selectionForeground:void 0,selectionBackgroundTransparent:Gs,selectionBackgroundOpaque:po.blend(Hs,Gs),selectionInactiveBackgroundTransparent:Gs,selectionInactiveBackgroundOpaque:po.blend(Hs,Gs),scrollbarSliderBackground:po.opacity(Vs,.2),scrollbarSliderHoverBackground:po.opacity(Vs,.4),scrollbarSliderActiveBackground:po.opacity(Vs,.5),overviewRulerBorder:Vs,ansi:Bs.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=Js(e.foreground,Vs),t.background=Js(e.background,Hs),t.cursor=po.blend(t.background,Js(e.cursor,Us)),t.cursorAccent=po.blend(t.background,Js(e.cursorAccent,Ws)),t.selectionBackgroundTransparent=Js(e.selectionBackground,Gs),t.selectionBackgroundOpaque=po.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=Js(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=po.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?Js(e.selectionForeground,uo):void 0,t.selectionForeground===uo&&(t.selectionForeground=void 0),po.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=po.opacity(t.selectionBackgroundTransparent,.3)),po.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=po.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=Js(e.scrollbarSliderBackground,po.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=Js(e.scrollbarSliderHoverBackground,po.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=Js(e.scrollbarSliderActiveBackground,po.opacity(t.foreground,.5)),t.overviewRulerBorder=Js(e.overviewRulerBorder,Ks),t.ansi=Bs.slice(),t.ansi[0]=Js(e.black,Bs[0]),t.ansi[1]=Js(e.red,Bs[1]),t.ansi[2]=Js(e.green,Bs[2]),t.ansi[3]=Js(e.yellow,Bs[3]),t.ansi[4]=Js(e.blue,Bs[4]),t.ansi[5]=Js(e.magenta,Bs[5]),t.ansi[6]=Js(e.cyan,Bs[6]),t.ansi[7]=Js(e.white,Bs[7]),t.ansi[8]=Js(e.brightBlack,Bs[8]),t.ansi[9]=Js(e.brightRed,Bs[9]),t.ansi[10]=Js(e.brightGreen,Bs[10]),t.ansi[11]=Js(e.brightYellow,Bs[11]),t.ansi[12]=Js(e.brightBlue,Bs[12]),t.ansi[13]=Js(e.brightMagenta,Bs[13]),t.ansi[14]=Js(e.brightCyan,Bs[14]),t.ansi[15]=Js(e.brightWhite,Bs[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=Js(e.extendedAnsi[r],Bs[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0){for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];return}switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};qs=At([q(0,un)],qs);function Js(e,t){if(e!==void 0)try{return mo.toColor(e)}catch{}return t}var Ys=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},Xs=class{constructor(){this._services=new Ys,this._services.set(cn,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=en(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},Zs={trace:0,debug:1,info:2,warn:3,error:4,off:5},Qs=`xterm.js: `,$s=class extends rr{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),ec=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=Zs[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:Qs)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};$s=At([q(0,un)],$s);var ec,tc=class extends rr{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new X),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new X),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new X),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},nc=3,rc=Object.freeze(new Jt),ic=0,ac=2,oc=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*nc);let r=t||Xt.fromCharData([0,Kt,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*nc+0],n=t&2097151;return[this._data[e*nc+1],t&2097152?this._combined[e]:n?Ht(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*nc+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*nc+0]=e|2097152|t[2]<<22):this._data[e*nc+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*nc+0]>>22}hasWidth(e){return this._data[e*nc+0]&12582912}getFg(e){return this._data[e*nc+1]}getBg(e){return this._data[e*nc+2]}hasContent(e){return this._data[e*nc+0]&4194303}getCodePoint(e){let t=this._data[e*nc+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*nc+0]&2097152}getString(e){let t=this._data[e*nc+0];return t&2097152?this._combined[e]:t&2097151?Ht(t&2097151):``}isProtected(e){return this._data[e*nc+2]&536870912}loadCell(e,t){return ic=e*nc,t.content=this._data[ic+0],t.fg=this._data[ic+1],t.bg=this._data[ic+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*nc+0]=t.content,this._data[e*nc+1]=t.fg,this._data[e*nc+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*nc+0]=t|n<<22,this._data[e*nc+1]=r.fg,this._data[e*nc+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*nc+0];r&2097152?this._combined[e]+=Ht(t):r&2097151?(this._combined[e]=Ht(r&2097151)+Ht(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*nc+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Xt;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Xt;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r){for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;return}for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*ac<this._data.buffer.byteLength;let n=e*nc;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*ac<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*ac<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t){for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);return}this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*nc+0]&4194303)return e+(this._data[e*nc+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*nc+0]&4194303||this._data[e*nc+2]&50331648)return e+(this._data[e*nc+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<nc;e++)this._data[(n+i)*nc+e]=a[(t+i)*nc+e];a[(t+i)*nc+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<nc;e++)this._data[(n+i)*nc+e]=a[(t+i)*nc+e];a[(t+i)*nc+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*nc+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Ht(n):qt;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function sc(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=dc(u,d,t),p=1,m=0;for(;p<u.length;){let e=dc(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function cc(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function lc(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function uc(e,t,n){let r=[],i=e.map((n,r)=>dc(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=dc(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function dc(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var fc=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new X),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Qn(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};fc._nextId=1;var pc=fc,mc={},hc=mc.B;mc[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},mc.A={"#":`£`},mc.B=void 0,mc[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},mc.C=mc[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},mc.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},mc.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},mc.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},mc.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},mc.E=mc[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},mc.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},mc.H=mc[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},mc[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var gc=4294967295,_c=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=rc.clone(),this.savedCharset=hc,this.markers=[],this._nullCell=Xt.fromCharData([0,Kt,1,0]),this._whitespaceCell=Xt.fromCharData([0,qt,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new ps,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new tc(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Yt),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Yt),this._whitespaceCell}getBlankLine(e,t){return new oc(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>gc?gc:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=rc);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new tc(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(rc),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new oc(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new oc(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=sc(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(rc),n);if(r.length>0){let n=cc(this.lines,r);lc(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(rc),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new oc(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(rc),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=uc(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(rc,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=dc(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new pc(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},vc=class extends rr{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new X),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new _c(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new _c(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},yc=2,bc=1,xc=class extends rr{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new X),this.onResize=this._onResize.event,this._onScroll=this._register(new X),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,yc),this.rows=Math.max(e.rawOptions.rows||0,bc),this.buffers=this._register(new vc(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};xc=At([q(0,un)],xc);var Sc={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:is,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Cc=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],wc=class extends rr{constructor(e){super(),this._onOptionChange=this._register(new X),this.onOptionChange=this._onOptionChange.event;let t={...Sc};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(er(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Sc))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Sc))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Sc[e],!Tc(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Sc[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Cc.includes(t)?t:Sc[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={};break}return t}};function Tc(e){return e===`block`||e===`underline`||e===`bar`}function Ec(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Ec(e[r],t-1);return n}var Dc=Object.freeze({insertMode:!1}),Oc=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),kc=class extends rr{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new X),this.onData=this._onData.event,this._onUserInput=this._register(new X),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new X),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new X),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Ec(Dc),this.decPrivateModes=Ec(Oc)}reset(){this.modes=Ec(Dc),this.decPrivateModes=Ec(Oc)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};kc=At([q(0,rn),q(1,ln),q(2,un)],kc);var Ac={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};function jc(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Mc=String.fromCharCode,Nc={DEFAULT:e=>{let t=[jc(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Mc(t[0])}${Mc(t[1])}${Mc(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${jc(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${jc(e,!0)};${e.x};${e.y}${t}`}},Pc=class extends rr{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new X),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Ac))this.addProtocol(e,Ac[e]);for(let e of Object.keys(Nc))this.addEncoding(e,Nc[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Pc=At([q(0,rn),q(1,on),q(2,un)],Pc);var Fc=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Ic=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Lc;function Rc(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var zc=class{constructor(){if(this.version=`6`,!Lc){Lc=new Uint8Array(65536),Lc.fill(1),Lc[0]=0,Lc.fill(0,1,32),Lc.fill(0,127,160),Lc.fill(2,4352,4448),Lc[9001]=2,Lc[9002]=2,Lc.fill(2,11904,42192),Lc[12351]=1,Lc.fill(2,44032,55204),Lc.fill(2,63744,64256),Lc.fill(2,65040,65050),Lc.fill(2,65072,65136),Lc.fill(2,65280,65377),Lc.fill(2,65504,65511);for(let e=0;e<Fc.length;++e)Lc.fill(0,Fc[e][0],Fc[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Lc[e]:Rc(e,Ic)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=Bc.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Bc.createPropertyValue(0,n,r)}},Bc=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new X,this.onChange=this._onChange.event;let e=new zc;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return(e&1)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},Vc=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Hc(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Uc=2147483647,Wc=256,Gc=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>Wc)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>Uc?Uc:e}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>Uc?Uc:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,Uc):e}},Kc=[],qc=class{constructor(){this._state=0,this._active=Kc,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Kc}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Kc,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Kc,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,Ut(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Kc,this._id=-1,this._state=0}}},Jc=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Ut(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},Yc=[],Xc=class{constructor(){this._handlers=Object.create(null),this._active=Yc,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Yc}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Yc,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Yc,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,Ut(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Yc,this._ident=0}},Zc=new Gc;Zc.addParam(0);var Qc=class{constructor(e){this._handler=e,this._data=``,this._params=Zc,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Zc,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=Ut(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=Zc,this._data=``,this._hitLimit=!1,e));return this._params=Zc,this._data=``,this._hitLimit=!1,t}},$c=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},el=160,tl=function(){let e=new $c(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(el,0,2,0),e.add(el,8,5,8),e.add(el,6,0,6),e.add(el,11,0,11),e.add(el,13,13,13),e}(),nl=class extends rr{constructor(e=tl){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Gc,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(er(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new qc),this._dcsParser=this._register(new Xc),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:el)],i>>4){case 2:for(let i=n+1;;++i){if(i>=t||(r=e[i])<32||r>126&&r<el){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<el){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<el){this._printHandler(e,n,i),n=i-1;break}if(++i>=t||(r=e[i])<32||r>126&&r<el){this._printHandler(e,n,i),n=i-1;break}}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<el){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<el){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break}this.currentState=i&15}}},rl=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,il=/^[\da-f]+$/;function al(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=rl.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),il.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function ol(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function sl(e,t=16){let[n,r,i]=e;return`rgb:${ol(n,t)}/${ol(r,t)}/${ol(i,t)}`}var cl={"(":0,")":1,"*":2,"+":3,"-":1,".":2},ll=131072,ul=10;function dl(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var fl=5e3,pl=0,ml=class extends rr{constructor(e,t,n,r,i,a,o,s,c=new nl){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Wt,this._utf8Decoder=new Gt,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=rc.clone(),this._eraseAttrDataInternal=rc.clone(),this._onRequestBell=this._register(new X),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new X),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new X),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new X),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new X),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new X),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new X),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new X),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new X),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new X),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new X),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new X),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new X),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new hl(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler(Q.BEL,()=>this.bell()),this._parser.setExecuteHandler(Q.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(Q.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(Q.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(Q.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(Q.BS,()=>this.backspace()),this._parser.setExecuteHandler(Q.HT,()=>this.tab()),this._parser.setExecuteHandler(Q.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(Q.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(ro.IND,()=>this.index()),this._parser.setExecuteHandler(ro.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(ro.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Jc(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new Jc(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new Jc(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new Jc(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new Jc(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new Jc(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new Jc(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new Jc(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new Jc(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new Jc(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new Jc(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new Jc(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in mc)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new Qc((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),fl))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${fl} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>ll&&(a=this._parseStack.position+ll)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<ll&&(this._parseBuffer=new Uint32Array(Math.min(e.length,ll))),o||this._dirtyRowTracker.clearRange(),e.length>ll)for(let t=a;t<e.length;t+=ll){let a=t+ll<e.length?t+ll:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=Bc.extractWidth(t);let n=Bc.extractShouldJoin(t),m=n?Bc.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Ht(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof oc&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>dl(e.params[0],this._optionsService.rawOptions.windowOptions)?t(e):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new Qc(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Jc(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(rc));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=Bc.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(Q.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(Q.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(Q.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(Q.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(Q.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0;break}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,hc),this._charsetService.setgCharset(1,hc),this._charsetService.setgCharset(2,hc),this._charsetService.setgCharset(3,hc);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0;break}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1;break}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0);break}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${Q.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Jt.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=rc.fg,e.bg=rc.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=rc.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=rc.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=rc.fg&16777215,r.bg&=-67108864,r.bg|=rc.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${Q.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Q.ESC}[${e};${t}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${Q.ESC}[?${e};${t}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=rc.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`;break}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!dl(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${Q.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>ul&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>ul&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(gl(n))if(r===`?`)t.push({type:0,index:n});else{let e=al(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):n.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=al(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);gl(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,hc),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(cl[e[0]],mc[e[1]]||hc),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=rc.clone(),this._eraseAttrDataInternal=rc.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Xt;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${Q.ESC}${e}${Q.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},hl=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(pl=e,e=t,t=pl),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};hl=At([q(0,rn)],hl);function gl(e){return 0<=e&&e<256}var _l=5e7,vl=12,yl=50,bl=class extends rr{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new X),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>_l)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=vl?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=vl)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>yl&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},xl=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};xl=At([q(0,rn)],xl);var Sl=!1,Cl=class extends rr{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new ir),this._onBinary=this._register(new X),this.onBinary=this._onBinary.event,this._onData=this._register(new X),this.onData=this._onData.event,this._onLineFeed=this._register(new X),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new X),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new X),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new X),this._instantiationService=new Xs,this.optionsService=this._register(new wc(e)),this._instantiationService.setService(un,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(xc)),this._instantiationService.setService(rn,this._bufferService),this._logService=this._register(this._instantiationService.createInstance($s)),this._instantiationService.setService(ln,this._logService),this.coreService=this._register(this._instantiationService.createInstance(kc)),this._instantiationService.setService(on,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Pc)),this._instantiationService.setService(an,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Bc)),this._instantiationService.setService(fn,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Vc),this._instantiationService.setService(sn,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(xl),this._instantiationService.setService(dn,this._oscLinkService),this._inputHandler=this._register(new ml(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(mr.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(mr.forward(this._bufferService.onResize,this._onResize)),this._register(mr.forward(this.coreService.onData,this._onData)),this._register(mr.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new bl((e,t)=>this._inputHandler.parse(e,t))),this._register(mr.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new X),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!Sl&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),Sl=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,yc),t=Math.max(t,bc),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Hc.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Hc(this._bufferService),!1))),this._windowsWrappingHeuristics.value=er(()=>{for(let t of e)t.dispose()})}}},wl={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function Tl(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?t?i.key=Q.ESC+`OA`:i.key=Q.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?t?i.key=Q.ESC+`OD`:i.key=Q.ESC+`[D`:e.key===`UIKeyInputRightArrow`?t?i.key=Q.ESC+`OC`:i.key=Q.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(t?i.key=Q.ESC+`OB`:i.key=Q.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:Q.DEL,e.altKey&&(i.key=Q.ESC+i.key);break;case 9:if(e.shiftKey){i.key=Q.ESC+`[Z`;break}i.key=Q.HT,i.cancel=!0;break;case 13:i.key=e.altKey?Q.ESC+Q.CR:Q.CR,i.cancel=!0;break;case 27:i.key=Q.ESC,e.altKey&&(i.key=Q.ESC+Q.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`D`:t?i.key=Q.ESC+`OD`:i.key=Q.ESC+`[D`;break;case 39:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`C`:t?i.key=Q.ESC+`OC`:i.key=Q.ESC+`[C`;break;case 38:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`A`:t?i.key=Q.ESC+`OA`:i.key=Q.ESC+`[A`;break;case 40:if(e.metaKey)break;a?i.key=Q.ESC+`[1;`+(a+1)+`B`:t?i.key=Q.ESC+`OB`:i.key=Q.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=Q.ESC+`[2~`);break;case 46:a?i.key=Q.ESC+`[3;`+(a+1)+`~`:i.key=Q.ESC+`[3~`;break;case 36:a?i.key=Q.ESC+`[1;`+(a+1)+`H`:t?i.key=Q.ESC+`OH`:i.key=Q.ESC+`[H`;break;case 35:a?i.key=Q.ESC+`[1;`+(a+1)+`F`:t?i.key=Q.ESC+`OF`:i.key=Q.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:e.ctrlKey?i.key=Q.ESC+`[5;`+(a+1)+`~`:i.key=Q.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:e.ctrlKey?i.key=Q.ESC+`[6;`+(a+1)+`~`:i.key=Q.ESC+`[6~`;break;case 112:a?i.key=Q.ESC+`[1;`+(a+1)+`P`:i.key=Q.ESC+`OP`;break;case 113:a?i.key=Q.ESC+`[1;`+(a+1)+`Q`:i.key=Q.ESC+`OQ`;break;case 114:a?i.key=Q.ESC+`[1;`+(a+1)+`R`:i.key=Q.ESC+`OR`;break;case 115:a?i.key=Q.ESC+`[1;`+(a+1)+`S`:i.key=Q.ESC+`OS`;break;case 116:a?i.key=Q.ESC+`[15;`+(a+1)+`~`:i.key=Q.ESC+`[15~`;break;case 117:a?i.key=Q.ESC+`[17;`+(a+1)+`~`:i.key=Q.ESC+`[17~`;break;case 118:a?i.key=Q.ESC+`[18;`+(a+1)+`~`:i.key=Q.ESC+`[18~`;break;case 119:a?i.key=Q.ESC+`[19;`+(a+1)+`~`:i.key=Q.ESC+`[19~`;break;case 120:a?i.key=Q.ESC+`[20;`+(a+1)+`~`:i.key=Q.ESC+`[20~`;break;case 121:a?i.key=Q.ESC+`[21;`+(a+1)+`~`:i.key=Q.ESC+`[21~`;break;case 122:a?i.key=Q.ESC+`[23;`+(a+1)+`~`:i.key=Q.ESC+`[23~`;break;case 123:a?i.key=Q.ESC+`[24;`+(a+1)+`~`:i.key=Q.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=Q.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=Q.DEL:e.keyCode===219?i.key=Q.ESC:e.keyCode===220?i.key=Q.FS:e.keyCode===221&&(i.key=Q.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=wl[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=Q.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=Q.ESC+n}else if(e.keyCode===32)i.key=Q.ESC+(e.ctrlKey?Q.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=Q.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=Q.US),e.key===`@`&&(i.key=Q.NUL));break}return i}var El=0,Dl=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new ps,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new ps,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(El=this._search(t),El===-1)||this._getKey(this._array[El])!==t)return!1;do if(this._array[El]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(El),!0;while(++El<this._array.length&&this._getKey(this._array[El])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(El=this._search(e),!(El<0||El>=this._array.length)&&this._getKey(this._array[El])===e))do yield this._array[El];while(++El<this._array.length&&this._getKey(this._array[El])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(El=this._search(e),!(El<0||El>=this._array.length)&&this._getKey(this._array[El])===e))do t(this._array[El]);while(++El<this._array.length&&this._getKey(this._array[El])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},Ol=0,kl=0,Al=class extends rr{constructor(){super(),this._decorations=new Dl(e=>e?.marker.line),this._onDecorationRegistered=this._register(new X),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new X),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(er(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new jl(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{Ol=t.options.x??0,kl=Ol+(t.options.width??1),e>=Ol&&e<kl&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},jl=class extends nr{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new X),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new X),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=mo.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=mo.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},Ml=1e3,Nl=class{constructor(e,t=Ml){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},Pl=20,Fl=!1,Il=class extends rr{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new Nl(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);Fl?(this._accessibilityContainer.classList.add(`debug`),this._rowContainer.classList.add(`debug`),this._debugRootContainer=i.createElement(`div`),this._debugRootContainer.classList.add(`xterm`),this._debugRootContainer.appendChild(i.createTextNode(`------start a11y------`)),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(i.createTextNode(`------end a11y------`)),this._terminal.element.insertAdjacentElement(`afterend`,this._debugRootContainer)):this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
38
38
  `))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(ra(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(er(()=>{Fl?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<Pl+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
@@ -69,8 +69,8 @@ ${s.join(`
69
69
  `);return i.length<=1?e:i.reduce((e,t,i)=>{if(i===0)return t;let a=r.y+i;return`${e}${n.getLine?.(a)?.isWrapped?``:`
70
70
  `}${t}`},``)}function ap(e){let t=e.getSelection?.()||``,n=e.getSelectionPosition?.(),r=e.buffer?.active;if(!n||!r||typeof r.getLine!=`function`)return t;let i=rp(n,r);return i===null?ip(t,n,r):i}function op(e){if(!e.includes(`
71
71
  `))return e;let t=Hf(e.split(/\r?\n/).map((e,t)=>t===0?e.trimEnd():e.trim()).join(``));return Nf(t)?t:e}function sp(e){return e.length>0&&!/\s/u.test(e)}function cp(e,t,n){return Math.max(1,(t.row-e.row)*n+(t.col-e.col)+1)}function lp(e){let t=e.getScrollbackLength?.();return Number.isFinite(t)?Math.max(0,Number(t)):0}function up(e){let t=Number(e.viewportY||0);return Number.isFinite(t)?Math.max(0,t):0}function dp(e){let t=e.getVisibleBufferBase?.();return Number.isFinite(t)?Math.max(0,Number(t)):up(e)}function fp(e){return up(e.terminal)<=0}function pp(e){e.followOutputHandler?.({following:e.followOutput,hasUnreadOutput:e.hasUnreadOutput})}function mp(e,t,n,r={}){e.preserveUnreadOutputUntilJump&&!n&&r.allowClearUnread!==!0&&(n=!0),!n&&r.allowClearUnread===!0&&(e.preserveUnreadOutputUntilJump=!1),!(e.followOutput===t&&e.hasUnreadOutput===n)&&(e.followOutput=t,e.hasUnreadOutput=n,pp(e))}function hp(e){e.preserveUnreadOutputUntilJump=!0,mp(e,!1,!0)}function gp(e,t,n){let r=lp(e),i=up(e),a=Math.max(1,Math.floor((e.rows||n)*.9));return t===`PageUp`?Math.min(r,i+a):Math.max(0,i-a)}function _p(e,t,n){let r=lp(e)-n;return Math.max(0,t+r)}function vp(e,t){let n=Math.floor(Number(e)),r=Math.floor(Number(t));return!Number.isFinite(n)||!Number.isFinite(r)||n<40||r<10?null:{cols:n,rows:r}}function yp(e,t){let n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;let r=t.proposeDimensions();return r?vp(r.cols,r.rows):null}function bp(e,t,n,r,i={}){let a=vp(t,n);return!a||!i.force&&e.lastNotifiedResize&&e.lastNotifiedResize.cols===a.cols&&e.lastNotifiedResize.rows===a.rows||r(a.cols,a.rows)===!1?!1:(e.lastNotifiedResize=a,e.resizeNotificationCount+=1,!0)}function xp(e){e.lastNotifiedResize=null}var Sp=512;function Cp(e){if(wf(e.terminal)){e.terminal.refresh?.(0,Math.max(0,(e.terminal.rows||1)-1));return}let{renderer:t,wasmTerm:n}=e.terminal;!t?.render||!n||(wp(e),t.render(n,!0,e.terminal.viewportY||0,e.terminal))}function wp(e){let t=e.terminal.renderer?.getCanvas?.()||e.hostEl.querySelector(`canvas`);if(!(t instanceof HTMLCanvasElement))return;let n=t.getContext(`2d`);n&&(n.save(),n.setTransform(1,0,0,1,0,0),n.fillStyle=xt.background,n.fillRect(0,0,t.width,t.height),n.restore())}function Tp(e){return e===void 0?e:+(e>0)}function Ep(e){Cp(e),requestAnimationFrame(()=>{e.disposed||Cp(e)})}function Dp(e,t){let n=lp(e.terminal),r=Math.max(0,Math.min(n,t));typeof e.terminal.scrollToLine==`function`?e.terminal.scrollToLine(r):e.terminal.viewportY=r,Cp(e)}function Op(e,t){let n=lp(e.terminal);Dp(e,n-Math.max(0,Math.min(n,t)))}function kp(e,t={}){if(!e.disposed){if(lp(e.terminal)<=0){Cp(e),mp(e,!0,!1,t);return}typeof e.terminal.scrollToBottom==`function`?(e.terminal.scrollToBottom(),Cp(e)):Dp(e,0),mp(e,!0,!1,t)}}function Ap(e,t,n,r){e.disposed||(Dp(e,_p(e.terminal,t,n)),mp(e,!1,r))}function jp(e,t,n){Ap(e,t,n,!0)}function Mp(e,t,n,r,i){if(!e.disposed){if(r){kp(e,{allowClearUnread:!0});return}Ap(e,t,n,i)}}function Np(e,t,n){e.terminal.write(t,n)}function Pp(e,t,n){return e.terminalWriteQueue=e.terminalWriteQueue.catch(()=>{}).then(()=>new Promise(r=>{let i=!1,a=(t=!1)=>i?!1:(i=!0,e.terminalWriteResolvers.delete(a),t&&n?.(),r(),!0);e.terminalWriteResolvers.add(a),t(a)})),e.terminalWriteQueue}function Fp(e){let t=Array.from(e.terminalWriteResolvers);e.terminalWriteResolvers.clear(),t.forEach(e=>e(!0))}function Ip(e,t){e()&&t?.()}function Lp(e,t,n){if(!t||e.disposed||!wf(e.terminal)){n();return}if(Math.abs((e.terminal.cols||0)-t.cols)>1||t.y>=(e.terminal.rows||0)){n();return}e.terminal.write(`\x1b[${t.y+1};${t.x+1}H`,n)}function Rp(e,t,n,r={}){if(!t){n?.();return}Pp(e,i=>{if(e.disposed){Ip(i,n);return}let a=up(e.terminal),o=lp(e.terminal),s=e.followOutput,c=r.quiet===!0||t.length>=Sp,l=r.isOutputObserved?.()??!0;c&&(e.suspendRendering=!0),Np(e,t,()=>{if(e.disposed){Ip(i,n);return}e.suspendRendering=!1,s?l?c?kp(e,{allowClearUnread:!0}):mp(e,!0,!1,{allowClearUnread:!0}):hp(e):l?(jp(e,a,o),requestAnimationFrame(()=>{e.disposed||(jp(e,a,o),Cp(e))})):hp(e),l&&Cp(e),Ip(i,n)})},n)}function zp(e,t,n,r={}){Pp(e,i=>{if(e.disposed){Ip(i,n);return}let a=up(e.terminal),o=lp(e.terminal),s=e.followOutput;if(e.suspendRendering=!0,e.terminal.reset(),!t){e.suspendRendering=!1,Cp(e),Ip(i,n);return}Np(e,t,()=>{if(e.disposed){Ip(i,n);return}e.suspendRendering=!1,s?kp(e,{allowClearUnread:!0}):jp(e,a,o),!s&&o===lp(e.terminal)&&Cp(e),Lp(e,r.cursor??null,()=>{if(e.disposed){Ip(i,n);return}Cp(e),Ip(i,n)})})},n)}function Bp(){let e=document.getElementById(`terminal-session-parking-lot`);return e||(e=document.createElement(`div`),e.id=`terminal-session-parking-lot`,e.setAttribute(`aria-hidden`,`true`),e.style.display=`none`,document.body.appendChild(e),e)}function Vp(e){return!e.disposed&&e.attachedMount!==null&&e.hostEl.parentElement===e.attachedMount}function Hp(e,t){return e.attachGeneration===t&&Vp(e)}function Up(e){return e.attachGeneration+=1,e.attachGeneration}function Wp(e,t,n){return e.disposed?!1:(n?.(),e.hostEl.parentElement===t?Array.from(t.children).forEach(t=>{t!==e.hostEl&&t.remove()}):t.replaceChildren(e.hostEl),e.attachedMount=t,!0)}function Gp(e,t){return!(e.disposed||t&&e.attachedMount!==t||t&&e.hostEl.parentElement!==t)}function Kp(e){return e.disposed?!1:(e.attachedMount=null,e.attachGeneration+=1,Bp().appendChild(e.hostEl),!0)}function qp(e,t){let n=t.target;return n instanceof Node&&e.contains(n)}function Jp(e,t,n){return!n&&qp(e,t)}function Yp(e,t,n){return n&&qp(e,t)}function Xp(e){return e instanceof HTMLTextAreaElement&&e.classList.contains(`xterm-helper-textarea`)}function Zp(e){return e.imeComposing||typeof e.terminal.input!=`function`?!1:e.isXterm?!!(e.text&&/[^\x00-\x7F]/.test(e.text)):!0}function Qp(e,t){return Math.abs(e-t)<120}function $p(e){return e.session&&typeof e.session==`object`?e.session.renderOutput??e.session.output??``:typeof e.session==`string`?e.session:typeof e.renderOutput==`string`?e.renderOutput:e.output??``}function em(e){let t=e.session&&typeof e.session==`object`?e.session.outputSeq:e.outputSeq,n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function tm(e){return e.replace(/^(?:[ \t]*\r?\n)+/,``)}function nm(e){let t=e.split(/\r?\n/),n=0;for(let e=0;e<t.length-1&&(t[e]??``).trim()===``;e+=1)n+=1;return n}function rm(e){let t=e.session&&typeof e.session==`object`?e.session.previewSnapshot:e.previewSnapshot;return!t||!Array.isArray(t.cells)?null:t}function im(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:null}function am(e){let t=e.session&&typeof e.session==`object`?e.session:null;return{cols:im(t?.previewCols??t?.cols??e.previewCols??e.cols),rows:im(t?.previewRows??t?.rows??e.previewRows??e.rows)}}function om(e){return e.map(e=>e.char||` `).join(``).replace(/[ \t]+$/g,``)}function sm(e){if(!e)return 0;let t=0;for(let n of e.cells){if(om(n).trim()!==``)break;t+=1}return t}function cm(e){if(!e)return``;let t=e.cells.map(om);for(;t.length>0&&(t[0]??``).trim()===``;)t.shift();for(;t.length>0&&(t[t.length-1]??``).trim()===``;)t.pop();return t.join(`\r
72
- `)}function lm(e){let t=e.split(/\r?\n/).map(e=>e.replace(/[ \t]+$/g,``));for(;t.length>0&&(t[0]??``).trim()===``;)t.shift();for(;t.length>0&&(t[t.length-1]??``).trim()===``;)t.pop();return t}function um(e,t){if(!e||!t)return!1;let n=lm(e),r=lm(t);return n.length===r.length?n.every((e,t)=>e===r[t]):!1}function dm(e){if(!e)return null;let t=Math.floor(Number(e.cursorX)),n=Math.floor(Number(e.cursorY)),r=Math.floor(Number(e.cols)),i=Math.floor(Number(e.rows));return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0?null:{x:Math.max(0,Math.min(r-1,t)),y:Math.max(0,Math.min(i-1,n)),cols:r,rows:i}}function fm(e,t){return!e||t<=0?e:{...e,y:Math.max(0,e.y-t)}}function pm(e){let t=rm(e),n=$p(e),r=e.session&&typeof e.session==`object`?e.session.output??``:e.output??``,i=tm(n),a=tm(r),o=cm(t),s=am(e),c=i?nm(n):sm(t),l=!i||um(i,o)?fm(dm(t),c):null;return{output:i||o,textOutput:a,cursor:l,outputSeq:em(e),cols:s.cols,rows:s.rows}}function mm(e,t){return typeof e==`number`&&Number.isFinite(e)&&t!==null&&e<=t}var hm=4,gm=80,_m=new Map,vm=6,ym=520,bm=.025,xm=3.2,Sm=.972,Cm=90,wm=.28,Tm=30,Em=240,Dm=3e4;function Om(){return L()}function km(e,t){Wp(e,t,()=>Pm(e.hostEl,t)),Mm(e)}function Am(e){for(let t of _m.values())if(!(t instanceof Promise)&&t.hostEl===e)return t;return null}function jm(e){e.disposed||(e.followOutputHandler=null,e.pathOpenHandler=null,e.pathResolveHandler=null,Nm(e),wg(e),Kp(e))}function Mm(e){e.disposed||!e.resizeObserver||e.resizeObserver.observe(e.hostEl)}function Nm(e){e.resizeObserver?.disconnect()}function Pm(e,t){let n=t.closest(`.code-terminal-grid.panes-1`);n&&n.querySelectorAll(`.terminal-session-host`).forEach(t=>{if(t===e||!(t instanceof HTMLDivElement))return;let n=Am(t);n?jm(n):Bp().appendChild(t)})}function Fm(e){let t=e.dataset.terminalFontSize,n=t?Number(t):NaN;return Number.isFinite(n)&&n>0?n:12}async function Im(e){let t=await fetch(n(`/api/agents/${e}/session-view`));if(!t.ok)throw Error(`Terminal session view failed: ${t.status}`);return pm(await t.json())}function Lm(e){return new Promise(t=>window.setTimeout(t,e))}function Rm(e){let t=Math.floor(Number(e.terminal.cols)),n=Math.floor(Number(e.terminal.rows));return!Number.isFinite(t)||!Number.isFinite(n)||t<40||n<10?null:{cols:t,rows:n}}function zm(e,t){let n=Rm(e);return!n||t.cols===null||t.rows===null?!0:t.cols===n.cols&&t.rows===n.rows}async function Bm(e){let t=await Im(e.agentId);for(let n=0;n<hm;n+=1){if(e.disposed||zm(e,t))return t;await Lm(gm),t=await Im(e.agentId)}return!zm(e,t)&&t.textOutput?{...t,output:t.textOutput,cursor:null,cols:null,rows:null}:t}async function Vm(e){if(e.disposed||e.fixtureOverrideActive||!e.bootstrappingSnapshot&&!e.pendingSnapshotReplay)return;let t=++e.bootstrapRefreshSeq;try{let n=await Bm(e);if(e.disposed||e.fixtureOverrideActive||e.bootstrapRefreshSeq!==t||mm(n.outputSeq,e.lastOutputSeq))return;n.output&&Date.now()>=e.suppressOutputUntil&&(e.snapshotOutput=n.output,e.snapshotCursor=n.cursor,e.snapshotOutputSeq=n.outputSeq)}catch{}}function Hm(e,t){if(wf(t))return t.focus(),!0;let n=e.querySelector(`textarea`);return n instanceof HTMLTextAreaElement?(nh(e,t),n.focus(),!0):(t.focus(),!1)}function Um(e){return e.disposed||e.attachedMount===null?!1:Hm(e.hostEl,e.terminal)}function Wm(e){let t=document.activeElement;return document.querySelector(`.code-composer.menu-open, .code-composer-menu`)?!1:!(t instanceof Element)||t===document.body||e.contains(t)?!0:!t.closest([`.code-composer`,`.code-composer-menu`,`.code-context-menu`,`.input-dialog-overlay`,`.code-overlay-dialog`,`.code-file-editor`,`.code-files-section`,`input`,`textarea`,`select`,`[contenteditable="true"]`,`[role="dialog"]`,`[role="menu"]`].join(`,`))}function Gm(e){return e instanceof Element?!!e.closest([`.code-composer`,`.code-terminal-search`,`.code-file-editor`,`.monaco-editor`,`input`,`textarea`,`select`,`[contenteditable="true"]`,`[role="dialog"]`,`[role="menu"]`].join(`,`)):!1}function Km(e,t){if(e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(Gm(n))return!1;let r=window.getSelection?.();if(!r||r.isCollapsed)return!0;let i=r.anchorNode,a=r.focusNode;return!!(i&&e.hostEl.contains(i)||a&&e.hostEl.contains(a))}function qm(e){return e.key.toLowerCase()!==`c`||e.altKey||e.shiftKey?!1:e.metaKey&&!e.ctrlKey?!0:!navigator.platform.toLowerCase().includes(`mac`)&&e.ctrlKey&&!e.metaKey}function Jm(e,t){if(!qm(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(Gm(n))return!1;let r=window.getSelection?.();if(!r||r.isCollapsed)return!0;let i=r.anchorNode,a=r.focusNode;return!!(i&&e.hostEl.contains(i)||a&&e.hostEl.contains(a))}function Ym(e){return e.key.toLowerCase()!==`k`||e.altKey||e.shiftKey||e.ctrlKey?!1:navigator.platform.toLowerCase().includes(`mac`)&&e.metaKey}function Xm(e,t){if(!Ym(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function Zm(e,t){return Xm(e,t)?(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),bg(e),!0):!1}function Qm(e){return Vp(e)}function $m(e){return Qm(e)}function eh(e,t){if(t.type!==`keydown`||![`PageUp`,`PageDown`].includes(t.key)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function th(e,t){if(!eh(e,t))return!1;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let n=gp(e.terminal,t.key===`PageUp`?`PageUp`:`PageDown`,10);return Dp(e,n),mp(e,n<=0,n<=0?!1:e.hasUnreadOutput,{allowClearUnread:n<=0}),pp(e),!0}function nh(e,t){let n=e.querySelector(`textarea`),r=t.renderer?.getMetrics?.(),i=t.wasmTerm?.getCursor?.();if(!(n instanceof HTMLTextAreaElement)||!r||!i)return;let a=Fm(e),o=Math.max(0,i.x*r.width),s=Math.max(0,i.y*r.height),c=Math.max(a+2,r.height),l=Math.max(r.width*8,120);n.classList.add(`terminal-ime-input`),n.style.position=`absolute`,n.style.left=`${o}px`,n.style.top=`${s}px`,n.style.width=`${l}px`,n.style.height=`${c}px`,n.style.lineHeight=`${c}px`,n.style.fontSize=`${a}px`,n.style.fontFamily=St,n.style.padding=`0`,n.style.margin=`0`,n.style.border=`0`,n.style.outline=`0`,n.style.background=`transparent`,n.style.clipPath=`none`,n.style.overflow=`hidden`,n.style.whiteSpace=`pre`,n.style.resize=`none`}function rh(e,t){return Hp(e,t)}function ih(e,t){if(e.fixtureOverrideActive||e.disposed||!e.pendingSnapshotReplay||!e.snapshotOutput||t!==void 0&&!rh(e,t))return;let n=e.snapshotOutput,r=e.snapshotCursor,i=e.snapshotOutputSeq;if(e.pendingSnapshotReplay=!1,e.snapshotCursor=null,mm(i,e.lastOutputSeq)){e.bootstrappingSnapshot=!1,dh(e),t!==void 0&&ah(e,t);return}zp(e,n,()=>{e.bootstrappingSnapshot=!1,i!==null&&(e.lastOutputSeq=Math.max(e.lastOutputSeq??0,i)),lh(e),dh(e),t!==void 0&&ah(e,t)},{cursor:r})}function ah(e,t){e.needsReconnectOutputSync&&requestAnimationFrame(()=>oh(e,t))}function oh(e,t){if(!e.needsReconnectOutputSync||e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.fixtureOverrideActive||!rh(e,t))return;let n=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=n,Bm(e).then(r=>{if(!(e.disposed||e.reconnectSnapshotSeq!==n||e.fixtureOverrideActive||!rh(e,t)||Date.now()<e.suppressOutputUntil)){if(!r.output||r.outputSeq===null||mm(r.outputSeq,e.lastOutputSeq)){e.needsReconnectOutputSync=!1;return}e.needsReconnectOutputSync=!1,zp(e,r.output,()=>{e.lastOutputSeq=Math.max(e.lastOutputSeq??0,r.outputSeq??0),_h(e)},{cursor:r.cursor})}}).catch(()=>{})}function sh(e,t){e.fixtureOverrideActive||Bm(e).then(n=>{e.disposed||e.fixtureOverrideActive||e.attachGeneration!==t||!n.output||n.outputSeq!==null&&mm(n.outputSeq,e.lastOutputSeq)||zp(e,n.output,()=>{typeof n.outputSeq==`number`&&Number.isFinite(n.outputSeq)&&(e.lastOutputSeq=Math.max(e.lastOutputSeq??0,n.outputSeq)),_h(e)},{cursor:n.cursor})}).catch(()=>{})}function ch(e){let t=e.attachGeneration;[120,400,1e3].forEach(n=>{window.setTimeout(()=>{e.disposed||e.attachGeneration!==t||sh(e,t)},n)})}function lh(e){let t=e.snapshotOutputSeq;t!==null&&(e.queuedOutput=e.queuedOutput.filter(e=>!mm(e.outputSeq,t)))}function uh(e,t,n,r){if(!mm(r,e.lastOutputSeq)){if(n){if(e.fixtureOverrideActive)return;zp(e,t,()=>_h(e)),typeof r==`number`&&Number.isFinite(r)&&(e.lastOutputSeq=r);return}t&&(Rp(e,t,void 0,{isOutputObserved:()=>Qm(e)}),typeof r==`number`&&Number.isFinite(r)&&(e.lastOutputSeq=r),_h(e))}}function dh(e){e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.queuedOutput.splice(0).forEach(t=>uh(e,t.data,t.replace,t.outputSeq))}function fh(e){return e.terminal.getCellMetrics?.()??e.terminal.renderer?.getMetrics?.()}function ph(e){let t=e.terminal.getScreenElement?.();if(t instanceof HTMLElement)return t.getBoundingClientRect();let n=e.terminal.renderer?.getCanvas?.()||e.hostEl.querySelector(`canvas`);return n instanceof HTMLCanvasElement?n.getBoundingClientRect():null}function mh(e){let t=fp(e);mp(e,t,t?!1:e.hasUnreadOutput,{allowClearUnread:t})}function hh(e){e.queuedOutput=[],e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1}function gh(e){e.followCheckFrame!==null&&cancelAnimationFrame(e.followCheckFrame),e.followCheckFrame=requestAnimationFrame(()=>{if(e.followCheckFrame=null,e.disposed||!Qm(e))return;let t=fp(e);mp(e,t,t?!1:e.hasUnreadOutput,{allowClearUnread:t})})}function _h(e){e.imeComposing&&requestAnimationFrame(()=>{!e.disposed&&e.imeComposing&&nh(e.hostEl,e.terminal)})}function vh(e){return wf(e.terminal)?!1:e.imeComposing||e.suppressRendererCursor}function yh(e,t=!0){let n=e.terminal.renderer;if(!e.disposed){if(e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,vh(e)),!n){t&&Cp(e);return}vh(e)?n.cursorVisible=!1:!e.imeComposing&&e.rendererCursorWasVisible!==void 0&&(n.cursorVisible=e.rendererCursorWasVisible,e.rendererCursorWasVisible=void 0),t&&Cp(e)}}function bh(e,t){if(e.suppressRendererCursor===t){e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,vh(e));return}e.suppressRendererCursor=t,yh(e)}function xh(e,t){let n=e.terminal.renderer;if(!(e.disposed||!n)){if(t){e.imeComposing||(e.rendererCursorWasVisible=n.cursorVisible===void 0?void 0:!!n.cursorVisible),e.imeComposing=!0,yh(e);return}if(e.imeComposing){if(e.imeComposing=!1,e.suppressRendererCursor){n.cursorVisible=!1,Cp(e);return}n.cursorVisible=e.rendererCursorWasVisible??!0,e.rendererCursorWasVisible=void 0,Cp(e)}}}function Sh(e){let t=e.terminal.renderer;if(!t?.render||e.originalRender)return;let n=t.render.bind(t);e.originalRender=n,t.render=(r,i,a,o,s)=>{let c=Tp(s);if(!e.suspendRendering){if(!vh(e)){n(r,i,a,o,c);return}t.cursorVisible=!1,n(r,!0,a,o,c),t.cursorVisible=!1}}}function Ch(e){if(wf(e.terminal))return;let t=e.hostEl.querySelector(`textarea`);if(!(t instanceof HTMLTextAreaElement))return;let n=()=>{e.disposed||nh(e.hostEl,e.terminal)},r=()=>requestAnimationFrame(n),i=()=>{e.imeComposing&&r()},a=()=>{n(),e.hostEl.classList.add(`terminal-ime-active`),t.classList.add(`terminal-ime-composing`),xh(e,!0)},o=()=>{xh(e,!1),requestAnimationFrame(()=>{e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`),t.value=``,n()})},s=()=>{xh(e,!1),e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`)},c=e=>{(e.isComposing||e.keyCode===229)&&a()};t.addEventListener(`focus`,n),e.hostEl.addEventListener(`keydown`,c,!0),e.hostEl.addEventListener(`compositionstart`,a,!0),e.hostEl.addEventListener(`compositionupdate`,n,!0),e.hostEl.addEventListener(`compositionend`,o,!0),t.addEventListener(`input`,i),t.addEventListener(`blur`,s),e.imeKeydownHandler=c;let l=e.terminal.onCursorMove?.(i),u=e.terminal.onKey?.(i);e.imeOverlayDisposables.push(()=>t.removeEventListener(`focus`,n),()=>e.hostEl.removeEventListener(`keydown`,c,!0),()=>e.hostEl.removeEventListener(`compositionstart`,a,!0),()=>e.hostEl.removeEventListener(`compositionupdate`,n,!0),()=>e.hostEl.removeEventListener(`compositionend`,o,!0),()=>t.removeEventListener(`input`,i),()=>t.removeEventListener(`blur`,s),s),l&&e.imeOverlayDisposables.push(()=>l.dispose()),u&&e.imeOverlayDisposables.push(()=>u.dispose()),n()}function wh(e,t,n=12){rh(e,t)&&Wm(e.hostEl)&&(Um(e)||n<=0||requestAnimationFrame(()=>{wh(e,t,n-1)}))}function Th(e,t,n={}){try{let r=yp(e.hostEl,e.fitAddon);if(!r)return;Eh(e,r.cols,r.rows,t,n)}catch{}}function Eh(e,t,n,r=e.resizeHandler,i={}){Qm(e)&&bp(e,t,n,r,i)}function Dh(e){xp(e),e.needsReconnectOutputSync=!0,!e.disposed&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(Th(e,e.resizeHandler,{force:!0}),oh(e,e.attachGeneration)))}function Oh(e,t){return Math.max(0,(typeof e?.length==`number`?e.length:t)-1)}function kh(e,t,n){return ep(e.getLine(t)?.getCell?.(n))}function Ah(e,t,n,r){if(n>0)return{row:t,col:n-1};let i=e.getLine(t);if(t<=0||!i?.isWrapped)return null;let a=e.getLine(t-1);return{row:t-1,col:Oh(a,r)}}function jh(e,t,n,r){if(n<Oh(e.getLine(t),r))return{row:t,col:n+1};let i=t+1;return e.getLine(i)?.isWrapped?{row:i,col:0}:null}function Mh(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof r.getLine!=`function`||typeof e.terminal.select!=`function`)return``;let a=dp(e.terminal)+n;if(!sp(kh(r,a,t)))return``;let o={row:a,col:t};for(;;){let e=Ah(r,o.row,o.col,i);if(!e||!sp(kh(r,e.row,e.col)))break;o=e}let s={row:a,col:t};for(;;){let e=jh(r,s.row,s.col,i);if(!e||!sp(kh(r,e.row,e.col)))break;s=e}return e.terminal.select(o.col,o.row,cp(o,s,i)),e.cachedSelection=ap(e.terminal),e.cachedSelection}function Nh(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof e.terminal.select!=`function`)return``;let a=dp(e.terminal),o={row:a+t.row,col:t.col},s={row:a+n.row,col:n.col},c=o.row<s.row||o.row===s.row&&o.col<=s.col?{start:o,end:s}:{start:s,end:o};return e.terminal.select(c.start.col,c.start.row,cp(c.start,c.end,i)),e.cachedSelection=ap(e.terminal),e.cachedSelection}function Ph(e){let t=e.terminal.buffer?.active,n=e.terminal.cols||80;if(!t||typeof t.getLine!=`function`||typeof e.terminal.select!=`function`)return``;let r=typeof t.length==`number`?t.length:dp(e.terminal)+(e.terminal.rows||1),i=Math.max(0,r-1),a=Oh(t.getLine(i),n);return e.terminal.select(0,0,cp({row:0,col:0},{row:i,col:a},n)),e.cachedSelection=ap(e.terminal),e.cachedSelection}function Fh(e,t){let n=fh(e),r=ph(e);return!n||!r||t.clientX<r.left||t.clientX>r.right||t.clientY<r.top||t.clientY>r.bottom?null:{col:Math.max(0,Math.min(Math.floor((t.clientX-r.left)/n.width),(e.terminal.cols||1)-1)),row:Math.max(0,Math.min(Math.floor((t.clientY-r.top)/n.height),(e.terminal.rows||1)-1))}}function Ih(e,t,n,r=!0){let i=e.getLine(t);if(!i||typeof i.getCell!=`function`)return``;let a=Math.max(0,typeof i.length==`number`?i.length:n),o=``;for(let e=0;e<a;e+=1)o+=ep(i.getCell(e))||` `;return r?o.trimEnd():o}function Lh(e){return e.button===0&&(e.ctrlKey||e.metaKey)}function Rh(e){return e.ctrlKey||e.metaKey}function zh(e,t){return Rh(t)||e.openModifierActive}function Bh(e,t){if(!e.decorations){e.decorations=t;return}e.decorations.pointerCursor=t.pointerCursor,e.decorations.underline=t.underline}function Vh(e){return[e.path,e.lineNumber??``,e.column??``,e.endColumn??``].join(`\0`)}async function Hh(e,t){if(!e.pathResolveHandler)return t;let n=Vh(t),r=e.pathResolveCache.get(n);if(r&&Date.now()-r.resolvedAt<=Dm)return r.promise?await r.promise:r.target;let i=Promise.resolve(e.pathResolveHandler(e.agentId,t)).catch(()=>null);e.pathResolveCache.set(n,{resolvedAt:Date.now(),target:null,promise:i});let a=await i;return e.pathResolveCache.set(n,{resolvedAt:Date.now(),target:a}),a}async function Uh(e,t){return e.pathResolveHandler?(await Promise.all(t.map(async t=>{if(t.kind!==`path`||!t.pathTarget)return t;let n=await Hh(e,t.pathTarget);return n?{...t,pathTarget:n}:null}))).filter(e=>!!e):t}function Wh(e,t){if(!e.pathResolveHandler||t.kind!==`path`||!t.pathTarget)return t;let n=e.pathResolveCache.get(Vh(t.pathTarget));return!n||n.promise||Date.now()-n.resolvedAt>Dm?null:n.target?{...t,pathTarget:n.target}:null}function Gh(e){if(!wf(e.terminal)||typeof e.terminal.registerLinkProvider!=`function`)return;let t=e.terminal.registerLinkProvider({provideLinks:(t,n)=>{if(e.disposed){n(void 0);return}let r=qh(e,t-1);if(!r?.text){n(void 0);return}let i=Zf(r.text,!!e.pathOpenHandler);if(i.length===0){n(void 0);return}(async()=>{let t=await Uh(e,i);if(e.disposed){n(void 0);return}if(t.length===0){n(void 0);return}n(t.map(t=>{let n=t.kind===`path`&&!!(t.pathTarget&&e.pathOpenHandler),i={range:Qf(t,r),text:t.text,decorations:{pointerCursor:n,underline:n},activate:r=>{if(r.button!==0)return;let i=zh(e,r);Qm(e)&&(t.kind===`url`&&!i||t.kind===`path`&&!n||(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),t.kind===`url`?sg(t.text):t.pathTarget&&e.pathOpenHandler&&e.pathOpenHandler(e.agentId,t.pathTarget),e.suppressClickUntil=Date.now()+250))},hover:r=>{if(!$m(e)||Om())return;e.linkProviderHoverTarget={kind:t.kind,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},e.lastLinkHoverEvent=r;let a=n||zh(e,r);Bh(i,{pointerCursor:a,underline:n||t.kind===`url`||a}),pg(e,a)},leave:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null),Bh(i,{pointerCursor:n,underline:n}),ug(e)},dispose:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null)}};return i}))})()}});e.linkProviderDisposable=()=>t.dispose()}function Kh(e,t){let n=e.terminal.buffer?.active;if(!t||!n||typeof n.getLine!=`function`)return null;let r=dp(e.terminal)+t.row,i=e.terminal.cols||80,a=r;for(;a>0&&n.getLine(a)?.isWrapped;)--a;let o=r;for(;n.getLine(o+1)?.isWrapped;)o+=1;let s=[];for(let e=a;e<=o;e+=1)s.push(Ih(n,e,i,e===o));let c=(r-a)*i+t.col;return{text:s.join(``).trimEnd(),col:c,startRow:a,endRow:o,bufferRow:r,cols:i,buffer:n}}function qh(e,t){let n=e.terminal.buffer?.active;if(!n||typeof n.getLine!=`function`||!Number.isFinite(t)||t<0)return null;let r=e.terminal.cols||80,i=t;for(;i>0&&n.getLine(i)?.isWrapped;)--i;let a=t;for(;n.getLine(a+1)?.isWrapped;)a+=1;let o=[];for(let e=i;e<=a;e+=1)o.push(Ih(n,e,r,e===a));return{text:o.join(``).trimEnd(),col:0,startRow:i,endRow:a,bufferRow:t,cols:r,buffer:n}}function Jh(e,t){let n=Kh(e,t);return n?{text:n.text,col:n.col}:null}function Yh(e,t){let n=document.elementFromPoint(t.clientX,t.clientY);if(!(n instanceof HTMLElement))return null;let r=n.closest(`.xterm-rows > div`);if(!r||!e.hostEl.contains(r))return null;let i=fh(e),a=r.getBoundingClientRect();if(!i||i.width<=0||a.width<=0)return null;let o=(r.textContent||``).trimEnd();if(!o)return null;let s=Bf(t.clientX-a.left,i.width,o.length);return s===null?null:{text:o,col:s}}function Xh(e,t,n){let r=t;for(;r>0&&e.getLine(r)?.isWrapped;)--r;let i=[];for(let a=r;a<=t;a+=1)i.push({row:a,text:Ih(e,a,n,a===t),startCol:0});return{startRow:r,endRow:t,text:i.map(e=>e.text).join(``).trimEnd(),lastPhysicalText:i[i.length-1]?.text??``,segments:i}}function Zh(e,t,n){let r=``,i=-1;for(let a of e){if(a.row===t){let e=n-a.startCol;e>=0&&e<a.text.length&&(i=r.length+e)}r+=a.text}return i>=0?{text:r,col:i}:null}function Qh(e,t){let n=Kh(e,t);if(!n)return null;let{buffer:r,bufferRow:i,cols:a}=n,o=[];for(let e=n.startRow;e<=n.endRow;e+=1)o.push({row:e,text:Ih(r,e,a,e===n.endRow),startCol:0});for(;;){let e=o[0];if(!e||e.row<=0)break;let t=Xh(r,e.row-1,a),n=Uf(t.text),i=n?Jf(e.text,n.rawUrl):null;if(!n||Wf(n)||!i||!qf(t.lastPhysicalText,n.rawUrl,a))break;e.text=i.text,e.startCol=i.startCol,o.unshift(...t.segments)}for(;;){let e=o[o.length-1];if(!e)break;let t=Uf(o.map(e=>e.text).join(``));if(!t||Wf(t)||!qf(e.text,t.rawUrl,a)||!r.getLine(e.row+1))break;let n=Jf(Ih(r,e.row+1,a),t.rawUrl);if(!n)break;o.push({row:e.row+1,text:n.text,startCol:n.startCol})}return Zh(o,i,t.col)}function $h(e,t){let n=Fh(e,t);if(n){let t=Jh(e,n),r=t?zf(t.text,t.col):null;if(r)return r}let r=Yh(e,t);return r?zf(r.text,r.col):null}function eg(e,t){let n=$h(e,t);return n?Wh(e,n):null}function tg(e,t){return eg(e,t)?.pathTarget??null}function ng(e,t){let n=Fh(e,t);if(n){let t=Qh(e,n),r=t?Yf(t.text,t.col):null;if(r)return r}let r=Yh(e,t);return r?Yf(r.text,r.col):null}function rg(e){return op(e.terminal.getSelection()||``)}function ig(e,t){return(wf(e.terminal)?rg(e):op(ap(e.terminal)))||(!wf(e.terminal)&&t?.includeNativeFallback?op(og(e.hostEl)):``)}function ag(e,t){let n=e.terminal.getSelectionPosition?.();if(!n||!e.terminal.getSelection?.())return!1;let r=Fh(e,t);if(!r)return!1;let{start:i,end:a}=$f(n),o={x:r.col,y:dp(e.terminal)+r.row};return!(o.y<i.y||o.y>a.y||o.y===i.y&&o.x<i.x||o.y===a.y&&o.x>a.x)}function og(e){let t=window.getSelection?.();if(!t||t.isCollapsed)return``;let n=t.anchorNode,r=t.focusNode;return n&&!e.contains(n)||r&&!e.contains(r)?``:t.toString()}function sg(e){window.open(e,`_blank`,`noopener,noreferrer`)}function cg(e){let t=navigator.platform.toLowerCase().includes(`mac`)?`Cmd`:`Ctrl`;return(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`)?e===`url`?`按住 ${t} 点击打开链接`:`点击打开文件或文件夹`:e===`url`?`${t}-click to open link`:`Click to open file or folder`}function lg(e,t){e.hostEl.classList.toggle(`terminal-open-target-hover`,t!==null),e.hostEl.classList.toggle(`terminal-open-target-url`,t===`url`),e.hostEl.classList.toggle(`terminal-open-target-path`,t===`path`),t?(e.hostEl.dataset.terminalOpenTarget=t,e.hostEl.title=cg(t)):(delete e.hostEl.dataset.terminalOpenTarget,e.hostEl.removeAttribute(`title`))}function ug(e){e.openModifierActive=!1,e.lastLinkHoverEvent=null,e.linkProviderHoverTarget=null,lg(e,null)}function dg(e,t,n=zh(e,t)){return e.pathOpenHandler&&tg(e,t)?`path`:n&&ng(e,t)?`url`:null}async function fg(e,t){if(!e.pathOpenHandler)return null;let n=$h(e,t);if(!n?.pathTarget)return null;let r=await Hh(e,n.pathTarget);return r?{...n,pathTarget:r}:null}function pg(e,t){if(!$m(e)||Om()){lg(e,null);return}let n=e.linkProviderHoverTarget,r=t??e.openModifierActive;if(n){lg(e,n.kind===`path`||r?n.kind:null);return}if(!e.lastLinkHoverEvent){lg(e,null);return}lg(e,dg(e,e.lastLinkHoverEvent,r))}function mg(e){e.contextMenuCleanup?.(),e.contextMenuCleanup=null,e.contextMenuEl?.remove(),e.contextMenuEl=null,e.contextMenuSelection=``}function hg(e){let t=(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`);return e===`copy`?t?`复制`:`Copy`:e===`paste`?t?`粘贴`:`Paste`:e===`clear`?t?`清除`:`Clear`:t?`全选`:`Select All`}function gg(e,t,n=160,r=148){return{x:Math.max(8,Math.min(e,window.innerWidth-n-8)),y:Math.max(8,Math.min(t,window.innerHeight-r-8))}}function _g(e){e.querySelector(`button:not(:disabled)`)?.focus()}function vg(e,t,n={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`terminal-context-menu-item`,r.setAttribute(`role`,`menuitem`),r.textContent=e,r.disabled=n.disabled===!0,r.addEventListener(`click`,()=>{r.disabled||t()}),r}function yg(e,t){return!t||e.disposed||e.attachedMount===null?!1:(e.fixtureOverrideActive=!1,kp(e,{allowClearUnread:!0}),e.lastTerminalDataAt=Date.now(),e.inputCount+=1,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.inputHandler(t),ch(e),!0)}function bg(e){e.disposed||e.attachedMount===null||(Cg(e),e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.terminal.clearSearch?.(),typeof e.terminal.clearBuffer==`function`?e.terminal.clearBuffer():e.terminal.reset(),mp(e,!0,!1,{allowClearUnread:!0}),fetch(n(`/api/control/agents/${encodeURIComponent(e.agentId)}/clear`),{method:`POST`}).catch(()=>{}))}function xg(e,t,n){mg(e);let r=gg(t.clientX,t.clientY),i=document.createElement(`div`);i.className=`terminal-context-menu terminal-context-menu-pooled`,i.setAttribute(`data-testid`,`code-terminal-context-menu`),i.setAttribute(`role`,`menu`),i.style.left=`${r.x}px`,i.style.top=`${r.y}px`;let a=vg(hg(`copy`),()=>{j(n).finally(()=>{mg(e),Om()||Um(e)})},{disabled:!n}),o=vg(hg(`paste`),()=>{te().then(t=>{yg(e,t)}).finally(()=>{mg(e),Om()||Um(e)})}),s=vg(hg(`selectAll`),()=>{mg(e),Cg(e),requestAnimationFrame(()=>{if(e.disposed)return;let t=Ph(e);e.contextMenuSelection=t,e.lastNonEmptySelection=t||e.lastNonEmptySelection,Om()||Um(e)})},{disabled:typeof e.terminal.select!=`function`||!e.terminal.buffer?.active}),c=vg(hg(`clear`),()=>{mg(e),bg(e),Om()||Um(e)});i.addEventListener(`mousedown`,e=>e.stopPropagation()),i.addEventListener(`pointerdown`,e=>e.stopPropagation()),i.addEventListener(`keydown`,e=>{if(!(e.target instanceof HTMLButtonElement)||e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(i.querySelectorAll(`button:not(:disabled)`)),n=t.indexOf(e.target);n<0||t.length===0||(e.preventDefault(),t[(n+(e.key===`ArrowDown`?1:-1)+t.length)%t.length]?.focus())}),i.appendChild(a),i.appendChild(o),i.appendChild(s),i.appendChild(c),document.body.appendChild(i),e.contextMenuEl=i;let l=t=>{let n=t.target;n instanceof Node&&i.contains(n)||mg(e)},u=t=>{t.key===`Escape`&&(t.preventDefault(),mg(e),Om()||Um(e))},d=()=>mg(e);document.addEventListener(`mousedown`,l,!0),document.addEventListener(`pointerdown`,l,!0),document.addEventListener(`keydown`,u,!0),window.addEventListener(`resize`,d),window.addEventListener(`scroll`,d,!0),e.contextMenuCleanup=()=>{document.removeEventListener(`mousedown`,l,!0),document.removeEventListener(`pointerdown`,l,!0),document.removeEventListener(`keydown`,u,!0),window.removeEventListener(`resize`,d),window.removeEventListener(`scroll`,d,!0)},requestAnimationFrame(()=>_g(i))}function Sg(e){let t=window.getSelection?.();if(!t||t.rangeCount===0)return;let n=t.anchorNode,r=t.focusNode;n&&!e.contains(n)||r&&!e.contains(r)||t.removeAllRanges()}function Cg(e){e.cachedSelection=``,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.dragSelection=null,e.terminal.clearTerminalSelection?.(),Sg(e.hostEl)}function wg(e){mg(e),ug(e),Cg(e)}function Tg(e){wg(e),wf(e.terminal)&&(e.terminal.reattach?.(),e.terminal.syncAppearanceTheme?.(),e.terminal.forceRedraw?.()),Ep(e),requestAnimationFrame(()=>{e.disposed||e.attachedMount===null||(wf(e.terminal)&&e.terminal.forceRedraw?.(),Cp(e))})}function Eg(e,t){let n=ig(e)||e.contextMenuSelection||e.lastNonEmptySelection,r=ng(e,t),i=e.pathOpenHandler?eg(e,t):null,a=!!n&&ag(e,t),o=n.replace(/\s+/g,``);if(r&&(!a||r.includes(o)))return r;if(i?.text&&(!a||i.text.includes(o)))return i.text;if(n)return n;let s=Fh(e,t);return s?Mh(e,s.col,s.row):``}function Dg(e,t){let n=n=>{if(!(n.target instanceof Node)||!e.hostEl.contains(n.target))return;let r=e.pathOpenHandler?$h(e,n):null;if(r?.pathTarget){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),Hh(e,r.pathTarget).then(t=>{if(!e.disposed){if(t){xg(e,n,r.text);return}xg(e,n,Eg(e,n))}});return}if(e.pathOpenHandler&&Lh(n)){let r=tg(e,n);if(r){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),e.pathOpenHandler(t,r);return}}let i=Eg(e,n);n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),xg(e,n,i)},r=t=>{if(!(!(t.target instanceof Node)||!e.hostEl.contains(t.target))){if(t.button===0){e.contextMenuSelection=``,e.lastNonEmptySelection=``;return}t.button===2&&(e.contextMenuSelection=ig(e)||op(e.cachedSelection)||e.lastNonEmptySelection)}};window.addEventListener(`mousedown`,r,!0),window.addEventListener(`contextmenu`,n,!0),e.hostEl.addEventListener(`mousedown`,r,!0),e.hostEl.addEventListener(`contextmenu`,n,!0),e.contextMenuMouseDownHandler=r,e.contextMenuHandler=n}function Og(e){let t=null,n=0,r=0,i=0,a=0,o=0,s=0,c=!1,l=null,u=0,d=[],f=0,p=null,m=null,h=null,g=e=>Math.max(-xm,Math.min(xm,e)),_=()=>{m!==null&&(window.clearTimeout(m),m=null),h=null},v=()=>e.hostEl.querySelector(`.xterm-screen`),y=()=>{p!==null&&(window.clearTimeout(p),p=null)},b=(e,t=!1)=>{let n=v();f=e,n&&(y(),n.style.transition=t?`transform ${Em}ms cubic-bezier(0.22, 0.75, 0.28, 1)`:`none`,n.style.transform=e===0?``:`translate3d(0, ${e}px, 0)`,t&&(p=window.setTimeout(()=>{n.style.transition=``,n.style.transform=``,p=null},Em)))},x=e=>{b(Math.max(-Tm,Math.min(Tm,f+e*wm)))},S=(e=!0)=>{f===0&&p===null||b(0,e)},C=(e,t)=>{d.push({y:e,at:t});let n=t-Cm;for(;d.length>2&&d[0].at<n;)d.shift()},w=()=>{let e=d[0],t=d[d.length-1];return!e||!t||t.at<=e.at?o:g((t.y-e.y)/(t.at-e.at))},T=()=>{let t=h;if(_(),!t||e.disposed||c)return;let n=Eg(e,t);n&&xg(e,t,n)},E=t=>{let n=Math.max(8,fh(e)?.height||16);s+=t;let r=Math.trunc(s/n);if(r===0)return!1;s-=r*n;let i=up(e.terminal);Dp(e,i+r);let a=up(e.terminal)!==i;return a&&(mh(e),mg(e)),a},D=()=>{l!==null&&(window.cancelAnimationFrame(l),l=null),u=0,o=0,s=0},O=t=>{if(e.disposed){l=null;return}let n=u===0?16:Math.min(48,Math.max(1,t-u));u=t;let r=o*n,i=E(r);if(o*=Sm**(n/16),!i||Math.abs(o)<bm){i||x(r),D(),S();return}l=window.requestAnimationFrame(O)},k=()=>{if(Math.abs(o)<bm){o=0;return}u=0,l=window.requestAnimationFrame(O)},ee=o=>{if(o.pointerType===`touch`){D(),S(!1),t=o.pointerId,n=o.clientX,r=o.clientY,i=o.clientY,a=o.timeStamp||performance.now(),d=[],C(o.clientY,a),s=0,c=!1,h=o,m=window.setTimeout(T,ym);try{e.hostEl.setPointerCapture(o.pointerId)}catch{}}},te=e=>{if(t===null||e.pointerId!==t)return;Math.hypot(e.clientX-n,e.clientY-r)>vm&&(c=!0,_());let s=e.clientY-i,l=e.timeStamp||performance.now(),u=Math.max(1,l-a);if(i=e.clientY,a=l,Math.abs(s)<.5)return;C(e.clientY,l);let d=s/u;o=g(w()*.72+d*.28);let p=E(s);!p&&c?x(s):p&&f!==0&&S(!1),(c||p)&&(e.preventDefault(),e.stopPropagation())},A=n=>{if(t===null||n.pointerId!==t)return;let r=c;t=null,_(),r?(n.preventDefault(),n.stopPropagation(),mh(e),o=w(),n.type===`pointerup`&&f===0?k():(D(),S())):(o=0,s=0,S()),d=[];try{e.hostEl.releasePointerCapture(n.pointerId)}catch{}};e.hostEl.addEventListener(`pointerdown`,ee,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointermove`,te,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointerup`,A,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointercancel`,A,{capture:!0,passive:!1}),e.hostEl.addEventListener(`lostpointercapture`,A,{capture:!0,passive:!1}),e.touchInteraction={pointerDownHandler:ee,pointerMoveHandler:te,pointerUpHandler:A,stopTouchMomentum:D}}function kg(){typeof window>`u`||!window.__FARMING_E2E__||window.__farmingTerminalTest||(window.__farmingTerminalTest={async writeFixture(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.bootstrapRefreshSeq+=1,r.reconnectSnapshotSeq+=1,r.snapshotOutput=``,r.snapshotOutputSeq=null,r.snapshotCursor=null,r.pendingSnapshotReplay=!1,r.bootstrappingSnapshot=!1,r.needsReconnectOutputSync=!1,r.fixtureOverrideActive=!0,r.queuedOutput=[],r.suppressOutputUntil=Date.now()+1500,r.terminal.reset(),r.terminal.viewportY=0,r.terminal.scrollToLine?.(0),await new Promise(e=>r.terminal.write(t,e)),r.terminal.viewportY=0,r.terminal.scrollToLine?.(0),mp(r,fp(r),!1,{allowClearUnread:!0}),Cp(r),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},getSelection(e){return Ig(e)},getCellCenter(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=fh(r),a=ph(r);return!i||!a?null:{x:a.left+(t+.5)*i.width,y:a.top+(n+.5)*i.height}},getRows(e,t=6){let n=_m.get(e);if(!n||n instanceof Promise||n.disposed)return[];let r=n.terminal.buffer?.active;if(!r||typeof r.getLine!=`function`)return[];let i=[],a=dp(n.terminal);for(let e=0;e<t;e+=1){let t=r.getLine(a+e),o=[],s=n.terminal.cols||t?.length||0;for(let e=0;e<s;e+=1){let n=t?.getCell?.(e);tp(n)||o.push(ep(n)||` `)}i.push(o.join(``).trimEnd())}return i},getHostDiagnostics(){return Array.from(document.querySelectorAll(`.terminal-session-host`)).map(e=>{let t=e,n=Am(t),r=t.getBoundingClientRect(),i=t.parentElement,a=i?.classList.contains(`terminal-container`)?i:null;return{agentId:t.dataset.agentId||``,paneAgentId:t.closest(`[data-testid="code-terminal-pane"]`)?.getAttribute(`data-agent-id`)||``,inParkingLot:t.closest(`#terminal-session-parking-lot`)!==null,recordAttached:n?Qm(n):!1,attachedMountMatchesParent:n?n.attachedMount!==null&&n.hostEl.parentElement===n.attachedMount:!1,visible:r.width>0&&r.height>0&&getComputedStyle(t).display!==`none`,hostCountInMount:a?a.querySelectorAll(`.terminal-session-host`).length:0}})},doubleClickCell(e,t,n){let r=_m.get(e);return!r||r instanceof Promise||r.disposed?``:Mh(r,t,n)},getUrlAtCell(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=Qh(r,{col:t,row:n});return i?Yf(i.text,i.col):null},isReady(e){let t=_m.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed&&!t.bootstrappingSnapshot&&!t.pendingSnapshotReplay)},getPathAtCell(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=Jh(r,{col:t,row:n});return i?If(i.text,i.col)??Lf(i.text,i.col):null},openPathAtCell(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed||!r.pathOpenHandler)return!1;let i=Jh(r,{col:t,row:n}),a=i?If(i.text,i.col)??Lf(i.text,i.col):null;return a?(r.pathOpenHandler(e,a),!0):!1},getCursor(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:t.terminal.wasmTerm?.getCursor?.()??null},getCursorVisible(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return;let n=t.terminal.wasmTerm?.getCursor?.().visible;return n===void 0?void 0:!!n},getRendererCursorVisible(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return;let n=t.terminal.renderer?.cursorVisible;return n===void 0?void 0:!!n},getCursorCellPixel(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`),r=fh(t),i=t.terminal.wasmTerm?.getCursor?.();if(!(n instanceof HTMLCanvasElement)||!r||!i){let e=t.hostEl.querySelector(`.xterm-cursor`);if(!(e instanceof HTMLElement))return null;let n=(getComputedStyle(e).backgroundColor||xt.cursor).match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);return n?{r:Number(n[1]??36),g:Number(n[2]??41),b:Number(n[3]??47),a:Math.round(Number(n[4]??1)*255)}:{r:36,g:41,b:47,a:255}}let a=n.width/Math.max(1,n.getBoundingClientRect().width),o=n.height/Math.max(1,n.getBoundingClientRect().height),s=Math.min(n.width-1,Math.max(0,Math.floor((i.x+.5)*r.width*a))),c=Math.min(n.height-1,Math.max(0,Math.floor((i.y+.5)*r.height*o))),l=n.getContext(`2d`)?.getImageData(s,c,1,1).data;return l?{r:l[0]??0,g:l[1]??0,b:l[2]??0,a:l[3]??0}:null},getCanvasInkPixelCount(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return 0;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`);if(!(n instanceof HTMLCanvasElement))return(t.hostEl.querySelector(`.xterm-rows`)?.textContent?.trim()??``).length*8;let r=n.getContext(`2d`);if(!r)return 0;let i=r.getImageData(0,0,n.width,n.height).data,a=0;for(let e=0;e<i.length;e+=4){let t=i[e]??255,n=i[e+1]??255,r=i[e+2]??255;(i[e+3]??0)>0&&!(t>248&&n>248&&r>245)&&(a+=1)}return a},async writeRaw(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);await new Promise(e=>Rp(r,t,e,{isOutputObserved:()=>Qm(r)})),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeSequenced(e,t,n){let r=_m.get(e),i=r instanceof Promise?await r:r;if(!i||i.disposed)throw Error(`Terminal session not found: ${e}`);uh(i,t,!1,n),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeRawAndSampleViewport(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);let i=up(r.terminal),a=lp(r.terminal),o=i;return await new Promise(e=>{Rp(r,t,e,{isOutputObserved:()=>Qm(r)}),o=up(r.terminal)}),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),{before:i,during:o,after:up(r.terminal),beforeScrollbackLength:a,afterScrollbackLength:lp(r.terminal),following:r.followOutput,hasUnreadOutput:r.hasUnreadOutput}},getViewport(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:{viewportY:up(t.terminal),scrollbackLength:lp(t.terminal),following:t.followOutput,hasUnreadOutput:t.hasUnreadOutput}},getInputCount(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?0:t.inputCount},getLastNotifiedResize(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastNotifiedResize},getResizeNotificationCount(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?0:t.resizeNotificationCount},notifyResizeForTest(e,t,n){let r=_m.get(e);return!r||r instanceof Promise||r.disposed?0:(Eh(r,t,n),r.resizeNotificationCount)},getLastOutputSeq(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastOutputSeq},getBufferDiagnostics(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.buffer?.active;return{engine:t.terminal.__farmingTerminalEngine,cols:t.terminal.cols||0,rows:t.terminal.rows||0,viewportY:up(t.terminal),scrollbackLength:lp(t.terminal),visibleBufferBase:dp(t.terminal),bufferViewportY:typeof n?.viewportY==`number`?n.viewportY:void 0,bufferBaseY:typeof n?.baseY==`number`?n.baseY:void 0,bufferLength:typeof n?.length==`number`?n.length:void 0}},async scrollToLine(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.touchInteraction?.stopTouchMomentum(),Op(r,t);let i=fp(r);mp(r,i,i?!1:r.hasUnreadOutput,{allowClearUnread:i}),await new Promise(e=>requestAnimationFrame(()=>e()))},async scrollToBottom(e){let t=_m.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.touchInteraction?.stopTouchMomentum(),kp(n,{allowClearUnread:!0}),await new Promise(e=>requestAnimationFrame(()=>e()))},async search(e,t,n=`next`,r={}){return Hg(e,t,n,r)},async clearSearch(e){await Ug(e)},dispatchPasteToTextarea(e,t){let n=_m.get(e);if(!n||n instanceof Promise||n.disposed)return{prevented:!1};let r=n.hostEl.querySelector(`textarea`);if(!(r instanceof HTMLTextAreaElement))return{prevented:!1};let i=new window.DataTransfer;i.setData(`text/plain`,t);let a=new window.ClipboardEvent(`paste`,{clipboardData:i,bubbles:!0,cancelable:!0});return r.dispatchEvent(a),{prevented:a.defaultPrevented}},dispatchCopyFromTextarea(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return{prevented:!1,text:``};let n=t.hostEl.querySelector(`textarea`);if(!(n instanceof HTMLTextAreaElement))return{prevented:!1,text:``};let r=new window.DataTransfer,i=new window.ClipboardEvent(`copy`,{clipboardData:r,bubbles:!0,cancelable:!0});return n.dispatchEvent(i),{prevented:i.defaultPrevented,text:r.getData(`text/plain`)}}})}async function Ag(e,t){let n=Om()?11:12,r=await Ef({fontSize:n});if(!r)throw Error(`Failed to create terminal for ${e}`);let i=document.createElement(`div`);i.className=`terminal-session-host`,i.dataset.agentId=e,i.dataset.terminalFontSize=String(n),i.style.width=`100%`,i.style.height=`100%`,i.style.position=`relative`,i.style.overflow=`hidden`;let{terminal:a,fitAddon:o}=r;a.loadAddon(o);let s={agentId:e,hostEl:i,attachedMount:null,attachGeneration:0,terminal:a,fitAddon:o,unsubscribeOutput:null,selectionChangeDisposable:null,imeOverlayDisposables:[],resizeObserver:null,scrollChangeDisposable:null,backendConnectedHandler:null,clickHandler:null,pointerDownSelectionHandler:null,pointerMoveSelectionHandler:null,pointerUpSelectionHandler:null,mouseDownOpenTargetHandler:null,mouseDownSelectionHandler:null,mouseMoveSelectionHandler:null,mouseUpSelectionHandler:null,mouseUpOpenTargetHandler:null,doubleClickHandler:null,copyHandler:null,copyKeyHandler:null,clearKeyHandler:null,pasteHandler:null,inputFallbackKeydownHandler:null,inputFallbackHandler:null,inputFallbackTimer:null,lastTerminalDataAt:0,lastLinkHoverEvent:null,openModifierActive:!1,linkHoverHandler:null,linkHoverLeaveHandler:null,linkHoverKeyHandler:null,linkHoverBlurHandler:null,linkProviderDisposable:null,linkProviderHoverTarget:null,contextMenuHandler:null,contextMenuMouseDownHandler:null,contextMenuEl:null,contextMenuCleanup:null,contextMenuSelection:``,imeKeydownHandler:null,scrollIntentHandler:null,scrollKeyHandler:null,touchInteraction:null,inputHandler:t.onInput,resizeHandler:t.onResize,lastNotifiedResize:null,resizeNotificationCount:0,followOutputHandler:t.onFollowOutputChange??null,pathOpenHandler:t.onPathOpen??null,pathResolveHandler:t.onPathResolve??null,pathResolveCache:new Map,originalRender:null,snapshotOutput:``,snapshotOutputSeq:null,lastOutputSeq:null,terminalWriteQueue:Promise.resolve(),terminalWriteResolvers:new Set,snapshotCursor:null,bootstrapRefreshSeq:0,reconnectSnapshotSeq:0,needsReconnectOutputSync:!1,pendingSnapshotReplay:!1,bootstrappingSnapshot:!0,fixtureOverrideActive:!1,queuedOutput:[],suspendRendering:!1,cachedSelection:``,lastNonEmptySelection:``,openTargetMouseDown:null,dragSelection:null,suppressClickUntil:0,suppressOutputUntil:0,imeComposing:!1,suppressRendererCursor:!!t.suppressRendererCursor,rendererCursorWasVisible:void 0,inputCount:0,followOutput:!0,hasUnreadOutput:!1,preserveUnreadOutputUntilJump:!1,followCheckFrame:null,disposed:!1,bootstrapped:!0};a.onData(e=>{s.disposed||s.attachedMount===null||(s.fixtureOverrideActive=!1,s.lastTerminalDataAt=Date.now(),s.inputCount+=1,s.contextMenuSelection=``,s.lastNonEmptySelection=``,s.inputHandler(e))}),a.onResize(({cols:e,rows:t})=>{Eh(s,e,t)}),Dg(s,e),a.open(i),Gh(s),a.syncAppearanceTheme?.(),requestAnimationFrame(()=>{s.disposed||a.syncAppearanceTheme?.()}),Sh(s),yh(s,!1);let c=a.onSelectionChange?.(()=>{s.cachedSelection=ap(a),s.cachedSelection&&(s.lastNonEmptySelection=op(s.cachedSelection))});s.selectionChangeDisposable=c?()=>c.dispose():null;let l=a.onScroll?.(()=>{gh(s)}),u=a.onRender?.(()=>{gh(s)});s.scrollChangeDisposable=l||u?()=>{l?.dispose(),u?.dispose()}:null;let d=()=>Dh(s);window.addEventListener(`farming:backend-connected`,d),s.backendConnectedHandler=d,Ch(s);let f=e=>{wf(a)||Xp(e.target)};i.addEventListener(`keydown`,f,!1),s.inputFallbackKeydownHandler=f;let p=e=>{if(s.imeComposing||typeof a.input!=`function`)return;let t=e.target;if(!Xp(t))return;let n=Date.now();s.inputFallbackTimer!==null&&window.clearTimeout(s.inputFallbackTimer),s.inputFallbackTimer=window.setTimeout(()=>{if(s.inputFallbackTimer=null,!Zp({isXterm:wf(a),imeComposing:s.imeComposing,text:t.value,terminal:a}))return;let e=a.input;if(typeof e!=`function`)return;let r=t.value;r&&(t.value=``,!Qp(s.lastTerminalDataAt,n)&&e(r,!0))},80)};i.addEventListener(`input`,p,!1),s.inputFallbackHandler=p;let m=t=>{let n=zh(s,t),r=t.button===0&&n?ng(s,t):null;if(r)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),sg(r),s.suppressClickUntil=Date.now()+250,!0;if(s.pathOpenHandler&&t.button===0){let n=tg(s,t);if(n)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),s.pathOpenHandler(e,n),s.suppressClickUntil=Date.now()+250,!0}return!1},h=(e,t)=>{if(Om()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;let n=Fh(s,e);return n?(s.dragSelection={start:n,active:!0,moved:!1,pointerId:t},!0):!1},g=e=>{let t=s.dragSelection;if(!t?.active||`pointerId`in e&&t.pointerId!==void 0&&e.pointerId!==t.pointerId)return!1;let n=Fh(s,e);return!n||n.col===t.start.col&&n.row===t.start.row&&!t.moved?!1:(t.moved=!0,Nh(s,t.start,n),e.preventDefault(),e.stopPropagation(),!0)},_=e=>{let t=s.dragSelection;return!t?.active||`pointerId`in e&&t.pointerId!==void 0&&e.pointerId!==t.pointerId||(s.dragSelection=null,!t.moved)?!1:(s.suppressClickUntil=Date.now()+250,s.cachedSelection=ap(a),e.preventDefault(),e.stopPropagation(),!0)},v=e=>{if(s.openTargetMouseDown=null,Om()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return;let t=s.pathOpenHandler?$h(s,e):null;t?.pathTarget&&(s.openTargetMouseDown={x:e.clientX,y:e.clientY,pathTarget:t.pathTarget})};i.addEventListener(`mousedown`,v,!0),s.mouseDownOpenTargetHandler=v;let y=t=>{if(Om()||t.button!==0)return;if(zh(s,t)){let e=ng(s,t);if(e){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),sg(e),s.suppressClickUntil=Date.now()+250;return}}let n=s.openTargetMouseDown;if(s.openTargetMouseDown=null,n){if(Math.hypot(t.clientX-n.x,t.clientY-n.y)>4){s.suppressClickUntil=Date.now()+250;return}ig(s)||m(t)||(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Hh(s,n.pathTarget).then(t=>{if(!s.disposed){if(!t){Um(s);return}s.pathOpenHandler?.(e,t),s.suppressClickUntil=Date.now()+250}}))}};i.addEventListener(`mouseup`,y,!0),s.mouseUpOpenTargetHandler=y;let b=e=>{if(e.pointerType!==`touch`&&h(e,e.pointerId))try{s.hostEl.setPointerCapture(e.pointerId)}catch{}};if(!wf(a)){i.addEventListener(`pointerdown`,b,!0),s.pointerDownSelectionHandler=b;let e=e=>{e.pointerType!==`touch`&&g(e)};window.addEventListener(`pointermove`,e,!0),s.pointerMoveSelectionHandler=e;let t=e=>{if(e.pointerType===`touch`)return;let t=_(e);if(t||m(e),t||Date.now()<s.suppressClickUntil)try{s.hostEl.releasePointerCapture(e.pointerId)}catch{}};window.addEventListener(`pointerup`,t,!0),window.addEventListener(`pointercancel`,t,!0),s.pointerUpSelectionHandler=t;let n=e=>{s.dragSelection||h(e)};i.addEventListener(`mousedown`,n,!0),s.mouseDownSelectionHandler=n;let r=e=>{g(e)};window.addEventListener(`mousemove`,r,!0),s.mouseMoveSelectionHandler=r;let a=e=>{_(e)};window.addEventListener(`mouseup`,a,!0),s.mouseUpSelectionHandler=a}let x=e=>{if(!Om()){if(Date.now()<s.suppressClickUntil){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}m(e)||Um(s)}};i.addEventListener(`click`,x,!0),s.clickHandler=x;let S=e=>{if(wf(a)||Om())return;let t=Fh(s,e);t&&Mh(s,t.col,t.row)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())};i.addEventListener(`dblclick`,S,!0),s.doubleClickHandler=S;let C=e=>{if(!Km(s,e))return;let t=ig(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.clipboardData?.setData(`text/plain`,t))};i.addEventListener(`copy`,C,!0),document.addEventListener(`copy`,C,!0),s.copyHandler=C;let w=e=>{if(!Jm(s,e))return;let t=ig(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),j(t))};document.addEventListener(`keydown`,w,!0),s.copyKeyHandler=w;let T=e=>{Zm(s,e)};a.attachCustomKeyEventHandler||(document.addEventListener(`keydown`,T,!0),s.clearKeyHandler=T);let E=e=>{let t=Qm(s);if(Jp(s.hostEl,e,t)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}Yp(s.hostEl,e,t)&&(wf(s.terminal)||yg(s,e.clipboardData?.getData(`text/plain`)||``)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()))};window.addEventListener(`paste`,E,!0),i.addEventListener(`paste`,E,!0),s.pasteHandler=E;let D=e=>{if(!$m(s)){ug(s);return}s.lastLinkHoverEvent=e,dg(s,e)||(s.linkProviderHoverTarget=null,lg(s,null)),pg(s),fg(s,e).then(t=>{!t||s.disposed||s.lastLinkHoverEvent!==e||(s.linkProviderHoverTarget={kind:`path`,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},lg(s,`path`))})};i.addEventListener(`mousemove`,D,!0),s.linkHoverHandler=D;let O=()=>{ug(s)};i.addEventListener(`mouseleave`,O,!0),s.linkHoverLeaveHandler=O;let k=e=>{if(!$m(s)){ug(s);return}e.type===`keydown`&&[`Control`,`Meta`].includes(e.key)?s.openModifierActive=!0:s.openModifierActive=Rh(e),s.lastLinkHoverEvent&&(![`Control`,`Meta`].includes(e.key)&&!s.openModifierActive||pg(s,s.openModifierActive))};window.addEventListener(`keydown`,k,!0),window.addEventListener(`keyup`,k,!0),s.linkHoverKeyHandler=k;let ee=()=>{ug(s)};window.addEventListener(`blur`,ee),s.linkHoverBlurHandler=ee;let te=e=>{e instanceof WheelEvent&&e.deltaY<0&&mp(s,!1,s.hasUnreadOutput),gh(s),window.setTimeout(()=>gh(s),80)};i.addEventListener(`wheel`,te,!0),i.addEventListener(`pointerup`,te,!0),s.scrollIntentHandler=te;let A=e=>{th(s,e)};return a.attachCustomKeyEventHandler?a.attachCustomKeyEventHandler(e=>!(Zm(s,e)||th(s,e))):(document.addEventListener(`keydown`,A,!0),i.addEventListener(`keydown`,A,!0),s.scrollKeyHandler=A),Og(s),s.resizeObserver=new ResizeObserver(()=>{requestAnimationFrame(()=>{if(!s.disposed)try{o.fit(),Th(s,t.onResize)}catch{}})}),s.unsubscribeOutput=t.onSessionOutput(e,(e,t,n)=>{if(!s.disposed&&!(Date.now()<s.suppressOutputUntil)){if(s.bootstrappingSnapshot||s.pendingSnapshotReplay){s.queuedOutput.push({data:e,replace:t,outputSeq:n});return}uh(s,e,t,n)}}),kg(),s}async function jg(e,t){let n=_m.get(e);if(n)return n instanceof Promise?n:Promise.resolve(n);let r=Ag(e,t).then(t=>(_m.set(e,t),t)).catch(n=>{throw _m.delete(e),t.onError?.(n instanceof Error?n:Error(String(n))),n});return _m.set(e,r),r}function Mg(e,t,n){let r=e.followOutput,i=up(e.terminal),a=lp(e.terminal),o=e.hasUnreadOutput;requestAnimationFrame(()=>{if(rh(e,n)){try{e.fitAddon.fit()}catch{}Th(e,t.onResize),Mp(e,i,a,r,o),Ep(e),t.autoFocus&&!Om()&&Wm(e.hostEl)&&wh(e,n),requestAnimationFrame(()=>{if(rh(e,n)){try{e.fitAddon.fit()}catch{}Th(e,t.onResize),Mp(e,i,a,r,o),Ep(e),window.setTimeout(()=>{rh(e,n)&&Vm(e).finally(()=>{rh(e,n)&&(e.snapshotOutput&&Date.now()>=e.suppressOutputUntil?(e.pendingSnapshotReplay=!0,ih(e,n)):(e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1,dh(e),ah(e,n)),t.onReady?.())})},120)}})}})}async function Ng(e,t){if(t.signal?.aborted)return;let n=await jg(e,t);if(n.disposed||t.signal?.aborted||_m.get(e)!==n)return;let r=Up(n);km(n,t.mountEl),Tg(n),n.inputHandler=t.onInput,n.resizeHandler=t.onResize,n.followOutputHandler=t.onFollowOutputChange??null,n.pathOpenHandler=t.onPathOpen??null,n.pathResolveHandler=t.onPathResolve??null,pp(n),bh(n,!!t.suppressRendererCursor),Mg(n,t,r),ah(n,r)}async function Pg(e,t){let n=_m.get(e);if(!n)return;let r=await n;r.disposed||_m.get(e)===r&&Gp(r,t)&&jm(r)}async function Fg(e){let t=_m.get(e);if(!t)return``;let n=await t;return n.disposed?``:(n.cachedSelection=ap(n.terminal),n.cachedSelection&&(n.lastNonEmptySelection=op(n.cachedSelection)),n.cachedSelection)}function Ig(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?``:(t.cachedSelection=ap(t.terminal),t.cachedSelection&&(t.lastNonEmptySelection=op(t.cachedSelection)),t.cachedSelection)}async function Lg(e){let t=_m.get(e);if(!t)return;_m.delete(e);let n=await t;n.disposed||(n.disposed=!0,hh(n),Fp(n),n.unsubscribeOutput?.(),n.selectionChangeDisposable?.(),n.scrollChangeDisposable?.(),n.backendConnectedHandler&&window.removeEventListener(`farming:backend-connected`,n.backendConnectedHandler),n.imeOverlayDisposables.forEach(e=>e()),n.resizeObserver?.disconnect(),n.followCheckFrame!==null&&cancelAnimationFrame(n.followCheckFrame),n.clickHandler&&n.hostEl.removeEventListener(`click`,n.clickHandler,!0),n.pointerDownSelectionHandler&&n.hostEl.removeEventListener(`pointerdown`,n.pointerDownSelectionHandler,!0),n.pointerMoveSelectionHandler&&window.removeEventListener(`pointermove`,n.pointerMoveSelectionHandler,!0),n.pointerUpSelectionHandler&&(window.removeEventListener(`pointerup`,n.pointerUpSelectionHandler,!0),window.removeEventListener(`pointercancel`,n.pointerUpSelectionHandler,!0)),n.mouseDownOpenTargetHandler&&n.hostEl.removeEventListener(`mousedown`,n.mouseDownOpenTargetHandler,!0),n.mouseDownSelectionHandler&&n.hostEl.removeEventListener(`mousedown`,n.mouseDownSelectionHandler,!0),n.mouseMoveSelectionHandler&&window.removeEventListener(`mousemove`,n.mouseMoveSelectionHandler,!0),n.mouseUpSelectionHandler&&window.removeEventListener(`mouseup`,n.mouseUpSelectionHandler,!0),n.mouseUpOpenTargetHandler&&n.hostEl.removeEventListener(`mouseup`,n.mouseUpOpenTargetHandler,!0),n.doubleClickHandler&&n.hostEl.removeEventListener(`dblclick`,n.doubleClickHandler,!0),n.copyHandler&&(n.hostEl.removeEventListener(`copy`,n.copyHandler,!0),document.removeEventListener(`copy`,n.copyHandler,!0)),n.copyKeyHandler&&document.removeEventListener(`keydown`,n.copyKeyHandler,!0),n.clearKeyHandler&&document.removeEventListener(`keydown`,n.clearKeyHandler,!0),n.pasteHandler&&(window.removeEventListener(`paste`,n.pasteHandler,!0),n.hostEl.removeEventListener(`paste`,n.pasteHandler,!0)),n.inputFallbackKeydownHandler&&n.hostEl.removeEventListener(`keydown`,n.inputFallbackKeydownHandler,!1),n.inputFallbackHandler&&n.hostEl.removeEventListener(`input`,n.inputFallbackHandler,!1),n.inputFallbackTimer!==null&&(window.clearTimeout(n.inputFallbackTimer),n.inputFallbackTimer=null),n.linkHoverHandler&&n.hostEl.removeEventListener(`mousemove`,n.linkHoverHandler,!0),n.linkHoverLeaveHandler&&n.hostEl.removeEventListener(`mouseleave`,n.linkHoverLeaveHandler,!0),n.linkHoverKeyHandler&&(window.removeEventListener(`keydown`,n.linkHoverKeyHandler,!0),window.removeEventListener(`keyup`,n.linkHoverKeyHandler,!0)),n.linkHoverBlurHandler&&window.removeEventListener(`blur`,n.linkHoverBlurHandler),n.linkProviderDisposable?.(),n.contextMenuHandler&&(n.hostEl.removeEventListener(`contextmenu`,n.contextMenuHandler,!0),window.removeEventListener(`contextmenu`,n.contextMenuHandler,!0)),n.contextMenuMouseDownHandler&&(n.hostEl.removeEventListener(`mousedown`,n.contextMenuMouseDownHandler,!0),window.removeEventListener(`mousedown`,n.contextMenuMouseDownHandler,!0)),mg(n),n.scrollIntentHandler&&(n.hostEl.removeEventListener(`wheel`,n.scrollIntentHandler,!0),n.hostEl.removeEventListener(`pointerup`,n.scrollIntentHandler,!0)),n.scrollKeyHandler&&(document.removeEventListener(`keydown`,n.scrollKeyHandler,!0),n.hostEl.removeEventListener(`keydown`,n.scrollKeyHandler,!0)),n.touchInteraction&&(n.touchInteraction.stopTouchMomentum(),n.hostEl.removeEventListener(`pointerdown`,n.touchInteraction.pointerDownHandler,!0),n.hostEl.removeEventListener(`pointermove`,n.touchInteraction.pointerMoveHandler,!0),n.hostEl.removeEventListener(`pointerup`,n.touchInteraction.pointerUpHandler,!0),n.hostEl.removeEventListener(`pointercancel`,n.touchInteraction.pointerUpHandler,!0),n.hostEl.removeEventListener(`lostpointercapture`,n.touchInteraction.pointerUpHandler,!0)),n.originalRender&&n.terminal.renderer&&(n.terminal.renderer.render=n.originalRender),n.terminal.dispose(),n.hostEl.remove())}async function Rg(e){let t=new Set(e),n=[..._m.keys()].filter(e=>!t.has(e));await Promise.all(n.map(e=>Lg(e)))}function zg(e){let t=_m.get(e);if(!t)return Promise.resolve(!1);if(typeof t.then!=`function`){let e=t;return Promise.resolve(Um(e))}return t.then(e=>Um(e))}async function Bg(e,t={}){let n=_m.get(e);if(!n)return!1;let r=await n;if(r.disposed||!Qm(r))return!1;let i=r.followOutput,a=up(r.terminal),o=lp(r.terminal),s=r.hasUnreadOutput,c=()=>{if(!(r.disposed||!Qm(r))){try{r.fitAddon.fit()}catch{}Th(r,r.resizeHandler,{force:!0}),Mp(r,a,o,i,s),Ep(r),t.autoFocus&&!Om()&&Wm(r.hostEl)&&wh(r,r.attachGeneration)}};return requestAnimationFrame(()=>{c(),requestAnimationFrame(c)}),!0}async function Vg(e){let t=_m.get(e);if(!t)return;let n=await t;n.disposed||(n.touchInteraction?.stopTouchMomentum(),kp(n,{allowClearUnread:!0}))}async function Hg(e,t,n=`next`,r={}){let i=_m.get(e);if(!i)return{found:!1,resultIndex:0,resultCount:0};let a=await i;return a.disposed||typeof a.terminal.search!=`function`?{found:!1,resultIndex:0,resultCount:0}:a.terminal.search(t,n,r)}async function Ug(e){let t=_m.get(e);if(!t)return;let n=await t;n.disposed||n.terminal.clearSearch?.()}function Wg({agentId:e,containerRef:t,onInput:n,onResize:r,onSessionOutput:i,suppressRendererCursor:a=!1,onFollowOutputChange:o,onPathOpen:s,onPathResolve:c,onReady:l,onError:u}){let d=(0,W.useRef)({onInput:n,onResize:r,onSessionOutput:i,onFollowOutputChange:o,onPathOpen:s,onPathResolve:c,onReady:l,onError:u});d.current={onInput:n,onResize:r,onSessionOutput:i,onFollowOutputChange:o,onPathOpen:s,onPathResolve:c,onReady:l,onError:u};let f=(0,W.useCallback)(e=>{d.current.onInput(e)},[]),p=(0,W.useCallback)((e,t)=>d.current.onResize(e,t),[]),m=(0,W.useCallback)((e,t)=>d.current.onSessionOutput(e,t),[]),h=(0,W.useCallback)(e=>{d.current.onFollowOutputChange?.(e)},[]),g=(0,W.useCallback)((e,t)=>{d.current.onPathOpen?.(e,t)},[]),_=(0,W.useCallback)((e,t)=>d.current.onPathResolve?.(e,t)??null,[]),v=(0,W.useCallback)(()=>{d.current.onReady?.()},[]),y=(0,W.useCallback)(e=>{d.current.onError?.(e)},[]);return(0,W.useEffect)(()=>{if(!e||!t.current)return;let n=t.current,r=new AbortController,i=!1;return n.replaceChildren(),Ng(e,{mountEl:n,onInput:f,onResize:p,onSessionOutput:m,suppressRendererCursor:a,onFollowOutputChange:h,onPathOpen:g,onPathResolve:_,onError:y,signal:r.signal,onReady:()=>{i||v()}}).catch(e=>{console.error(`Failed to attach terminal session:`,e),y(e instanceof Error?e:Error(String(e)))}),()=>{i=!0,r.abort(),Pg(e,n).catch(e=>{console.error(`Failed to detach terminal session:`,e)})}},[e,t,y,h,f,g,_,v,p,m,a]),{focus:(0,W.useCallback)(()=>{let n=t.current;!e||!n||zg(e).then(t=>{if(!t)return Ng(e,{mountEl:n,onInput:f,onResize:p,onSessionOutput:m,autoFocus:!0,suppressRendererCursor:a,onFollowOutputChange:h,onPathOpen:g,onPathResolve:_,onError:y,onReady:v})}).catch(e=>{console.error(`Failed to focus terminal session:`,e),y(e instanceof Error?e:Error(String(e)))})},[e,t,y,h,f,g,_,v,p,m,a]),refreshLayout:(0,W.useCallback)((t={})=>{e&&Bg(e,t).catch(e=>{console.error(`Failed to refresh terminal layout:`,e)})},[e]),getSelection:(0,W.useCallback)(async()=>e?Fg(e):``,[e]),getSelectionNow:(0,W.useCallback)(()=>e?Ig(e):``,[e]),scrollToBottom:(0,W.useCallback)(()=>{e&&Vg(e).catch(e=>{console.error(`Failed to scroll terminal session to bottom:`,e)})},[e]),search:(0,W.useCallback)((t,n=`next`,r)=>e?Hg(e,t,n,r):Promise.resolve({found:!1,resultIndex:0,resultCount:0}),[e]),clearSearch:(0,W.useCallback)(()=>e?Ug(e):Promise.resolve(),[e])}}function Gg(e){let t=String(e||``).trim().split(/\s+/)[0]||``;return[`claude`,`codex`,`qwen`,`opencode`,`qodercli`,`aider`,`github-copilot-cli`,`amazon-q`].includes(t)}function Kg(){return L()}function qg(e){return(e.metaKey&&!e.ctrlKey||e.ctrlKey&&!e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`}function Jg(e){return e.key===`F3`&&!e.metaKey&&!e.ctrlKey&&!e.altKey}function Yg(e){if(!e.altKey||e.metaKey||e.ctrlKey||e.shiftKey)return null;let t=e.code||`Key${e.key.toUpperCase()}`;return t===`KeyC`?`caseSensitive`:t===`KeyW`?`wholeWord`:t===`KeyR`?`regex`:null}function Xg(e,t){return!(e instanceof Node)||t?.contains(e)?!0:e===document.body||e===document.documentElement}function Zg(e,t,n){return!e.trim()||!t?``:t.found?typeof t.resultCount==`number`&&t.resultCount>0&&typeof t.resultIndex==`number`&&t.resultIndex>=0?n.terminalSearchResults(t.resultIndex+1,t.resultCount):``:n.terminalSearchNoResults}function Qg(e){let t=e.replace(/\r/g,``).trim();if(!t)return``;let n=t.split(`
73
- `).map(e=>e.trim()).filter(Boolean);if(n.length!==1)return``;let r=n[0];return r?r.slice(0,240):``}function $g(e){return`code-terminal-search-button option${e?` active`:``}`}function e_({agent:e,active:t,focusSignal:n,onActivate:r,sendInput:i,resizeAgent:a,onSessionOutput:o,onOpenPath:s,onResolvePath:c,onFollowOutputChange:l,copy:u}){let d=(0,W.useRef)(null),f=(0,W.useRef)(null),p=(0,W.useRef)(null),[m,h]=(0,W.useState)({following:!0,hasUnreadOutput:!1}),[g,_]=(0,W.useState)(!1),[v,y]=(0,W.useState)(``),[b,x]=(0,W.useState)({}),[S,C]=(0,W.useState)(null),[w,T]=(0,W.useState)(null),E=e.codexCliObserverDeferred===!0,D=(0,W.useCallback)(t=>{E||i(t,e.id)},[e.id,E,i]),O=(0,W.useCallback)((t,n)=>a(e.id,t,n),[e.id,a]),k=(0,W.useCallback)(t=>{h(t),l?.(e.id,t)},[e.id,l]),ee=(0,W.useCallback)(()=>{T(null)},[]),te=(0,W.useCallback)(e=>{T(e.message||u.terminalSessionUnavailable)},[u.terminalSessionUnavailable]),{focus:A,refreshLayout:j,getSelectionNow:M,scrollToBottom:N,search:P,clearSearch:F}=Wg({agentId:e.id,containerRef:f,onInput:D,onResize:O,onSessionOutput:o,suppressRendererCursor:Gg(e.command),onFollowOutputChange:k,onPathOpen:s,onPathResolve:c,onReady:ee,onError:te}),ne=(0,W.useCallback)((e=!1)=>{window.requestAnimationFrame(()=>{j({autoFocus:e}),window.requestAnimationFrame(()=>j({autoFocus:e}))})},[j]);(0,W.useEffect)(()=>{t&&ne(!1)},[t,ne]),(0,W.useEffect)(()=>{!t||n<=0||Kg()||(ne(!0),A())},[t,A,n,ne]),(0,W.useEffect)(()=>()=>{F()},[F]);let I=(0,W.useCallback)((e,t=`next`,n)=>{let r=e.trim();if(!r){C(null),F();return}P(r,t,{...b,...n}).then(C).catch(e=>{console.error(`Failed to search terminal:`,e),C({found:!1,resultIndex:0,resultCount:0})})},[F,P,b]),L=(0,W.useCallback)(e=>{x(t=>({...t,[e]:t[e]!==!0}))},[]),R=(0,W.useCallback)(()=>{let e=Qg(M());e&&(y(e),I(e,`next`,{incremental:!0})),_(!0),window.requestAnimationFrame(()=>{let e=p.current;e?.focus(),e?.select()})},[M,I]),z=(0,W.useCallback)(()=>{_(!1),C(null),F(),Kg()||A()},[F,A]),re=(0,W.useCallback)(e=>{let t=Yg(e.nativeEvent);if(t){e.preventDefault(),e.stopPropagation(),L(t);return}e.target===p.current&&e.key===`Enter`&&(e.preventDefault(),I(v,e.shiftKey?`previous`:`next`)),e.key===`Escape`&&(e.preventDefault(),z())},[z,I,v,L]);(0,W.useEffect)(()=>{g&&I(v,`next`,{incremental:!0})},[I,g,v]);let ie=(0,W.useCallback)(e=>{if(Xg(e.target,d.current)){if(qg(e)){e.preventDefault(),e.stopPropagation(),R();return}if(g&&Jg(e)){e.preventDefault(),e.stopPropagation(),I(v,e.shiftKey?`previous`:`next`);return}g&&e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),z())}},[z,R,I,g,v]);(0,W.useEffect)(()=>{if(!t)return;let e=e=>{ie(e)};return window.addEventListener(`keydown`,e,!0),()=>{window.removeEventListener(`keydown`,e,!0)}},[t,ie]);let V=(0,W.useCallback)(n=>{let i=n?.target,a=i instanceof Element&&i.closest(`.xterm`),o=n&&`pointerType`in n?n.pointerType:``;if(n&&n.button!==0){t||r(e.id,{focusTerminal:!1});return}if(a){t||r(e.id,{focusTerminal:!1}),(!Kg()||o&&o!==`touch`)&&A();return}r(e.id),!(Kg()&&(!o||o===`touch`))&&A()},[t,e.id,A,r]),ae=(0,W.useCallback)(()=>{N(),!Kg()&&A()},[A,N]),oe=(0,W.useCallback)(()=>{T(null),A()},[A]),ce=!m.following||m.hasUnreadOutput,ue=Zg(v,S,u);return(0,K.jsxs)(`section`,{className:`code-terminal-pane ${t?`active`:``}`,"data-testid":`code-terminal-pane`,"data-agent-id":e.id,ref:d,onKeyDownCapture:ie,onPointerDown:V,children:[(0,K.jsx)(`div`,{className:`code-terminal-container terminal-container`,"data-testid":`code-terminal-container`,ref:f}),E?(0,K.jsx)(`div`,{className:`code-terminal-status-card`,"data-testid":`code-terminal-app-server-ready`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:(0,K.jsx)(`span`,{children:u.appServerWaitingForFirstMessage})}):w?(0,K.jsxs)(`div`,{className:`code-terminal-status-card`,"data-testid":`code-terminal-status-card`,title:w,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`span`,{children:u.terminalSessionUnavailable}),(0,K.jsx)(`button`,{type:`button`,onClick:oe,children:u.retry})]}):null,g?(0,K.jsxs)(`form`,{className:`code-terminal-search`,"data-testid":`code-terminal-search`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onSubmit:e=>{e.preventDefault(),I(v,`next`)},onKeyDown:re,children:[(0,K.jsx)(`input`,{ref:p,type:`search`,name:`farming-terminal-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:v,placeholder:u.terminalSearchPlaceholder,"aria-label":u.terminalSearchPlaceholder,"data-testid":`code-terminal-search-input`,spellCheck:!1,enterKeyHint:`search`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,onChange:e=>y(e.target.value)}),(0,K.jsx)(`span`,{className:`code-terminal-search-status ${S&&!S.found?`empty`:``}`,children:ue}),(0,K.jsx)(`button`,{type:`button`,className:$g(b.caseSensitive),"aria-label":u.terminalSearchCaseSensitive,"aria-pressed":b.caseSensitive===!0,title:u.terminalSearchCaseSensitive,"data-testid":`code-terminal-search-case-sensitive`,onClick:()=>L(`caseSensitive`),children:(0,K.jsx)(de,{})}),(0,K.jsx)(`button`,{type:`button`,className:$g(b.wholeWord),"aria-label":u.terminalSearchWholeWord,"aria-pressed":b.wholeWord===!0,title:u.terminalSearchWholeWord,"data-testid":`code-terminal-search-whole-word`,onClick:()=>L(`wholeWord`),children:(0,K.jsx)(B,{})}),(0,K.jsx)(`button`,{type:`button`,className:$g(b.regex),"aria-label":u.terminalSearchRegex,"aria-pressed":b.regex===!0,title:u.terminalSearchRegex,"data-testid":`code-terminal-search-regex`,onClick:()=>L(`regex`),children:(0,K.jsx)(se,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":u.terminalSearchPrevious,title:u.terminalSearchPrevious,onClick:()=>I(v,`previous`),children:(0,K.jsx)(he,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":u.terminalSearchNext,title:u.terminalSearchNext,onClick:()=>I(v,`next`),children:(0,K.jsx)(_e,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button close`,"aria-label":u.terminalSearchClose,title:u.terminalSearchClose,onClick:z,children:(0,K.jsx)(le,{})})]}):null,ce?(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-jump-bottom`,"data-testid":`code-terminal-jump-bottom`,"aria-label":`Jump to latest output`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),ae()},children:(0,K.jsx)(_e,{})}):null]})}function t_(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function n_(e){let t=e[e.length-1];if(String(t?.type||``).toLowerCase()===`thought`)return`thinking`;let n=t&&t_(t)?t:void 0;if(!n)for(let t=e.length-1;t>=0;--t){let r=e[t];if(r&&String(r.type||``).toLowerCase()!==`plan`&&t_(r)){n=r;break}}if(!n)return`processing`;let r=String(n.type||``).toLowerCase(),i=String(n.kind||``).toLowerCase();return i===`think`?`thinking`:r===`plan`?`plan`:r===`patch`||[`edit`,`delete`,`move`].includes(i)?`editing`:i===`execute`?`running`:i===`read`?`reading`:i===`search`?`searching`:i===`fetch`?`fetching`:r===`tool`?`tool`:`processing`}function r_(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n||String(n.type||``).toLowerCase()!==`plan`||!t_(n))continue;let r=Number(n.completedSteps),i=Number(n.totalSteps);return!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<=0||r>i?null:{completed:r,total:i}}return null}function i_(e,t=10){let n=r_(e);if(!n)return``;let r=[...e].reverse().find(e=>String(e.type||``).toLowerCase()===`plan`&&t_(e)),i=String(r?.currentStep||``).trim().replace(/\s+/g,` `);if(!i)return``;let a=`${n.completed}/${n.total} `,o=Math.max(0,t-[...a].length);if(o<=0)return a.trim();let s=[...i];return`${a}${s.length<=o?i:`${s.slice(0,Math.max(1,o-1)).join(``)}…`}`}function a_({terminalId:e,output:t,interactive:n,onInput:r,onResize:i}){let a=(0,W.useRef)(null),o=(0,W.useRef)(null),s=(0,W.useRef)(``),c=(0,W.useRef)(t),l=(0,W.useRef)(n),u=(0,W.useRef)(r),d=(0,W.useRef)(i),f=(0,W.useRef)(``),[p,m]=(0,W.useState)(``);return c.current=t,l.current=n,u.current=r,d.current=i,(0,W.useEffect)(()=>{let e=a.current;if(!e)return;let t=!1,n=null,r;return Cf({fontSize:12}).then(({terminal:i,fitAddon:a})=>{if(t){i.dispose(),a.dispose();return}i.loadAddon(a),i.open(e),e.querySelector(`textarea`)?.setAttribute(`aria-label`,`Terminal input`),o.current=i;let p=c.current;p&&i.write(p),s.current=p;let h=i.onData(e=>{!l.current||!u.current||u.current(e).then(()=>m(``)).catch(e=>{m(e instanceof Error?e.message:`Failed to send terminal input`)})}),g=()=>{if(!e.isConnected||e.clientWidth<=0||e.clientHeight<=0)return;a.fit();let t=Number(i.cols||0),n=Number(i.rows||0),r=`${t}x${n}`;!d.current||t<40||n<10||r===f.current||(f.current=r,d.current(t,n).catch(()=>{}))};n=new ResizeObserver(g),n.observe(e),window.requestAnimationFrame(g),r=()=>{n?.disconnect(),h.dispose(),a.dispose(),i.dispose()}}).catch(e=>{t||m(e instanceof Error?e.message:`Failed to start terminal view`)}),()=>{t=!0,o.current=null,r?.()}},[e]),(0,W.useEffect)(()=>{let e=o.current;!e||t===s.current||(t.startsWith(s.current)?e.write(t.slice(s.current.length)):(e.clearBuffer?.(),e.write(t)),s.current=t)},[t]),(0,K.jsxs)(`div`,{className:`code-acp-embedded-terminal ${n?`interactive`:`readonly`}`,"data-testid":`code-acp-embedded-terminal`,children:[(0,K.jsx)(`div`,{ref:a,className:`code-acp-embedded-terminal-host`,onClick:()=>o.current?.focus()}),(0,K.jsx)(`pre`,{className:`code-visually-hidden`,"aria-label":`Terminal output`,children:t}),p?(0,K.jsx)(`small`,{className:`code-codex-transcript-terminal-error`,role:`alert`,children:p}):null]})}var o_=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends o_{};function s_(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function c_(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function l_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function u_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function d_(e,t){return l_(e,t,``)}function f_(e,t){return u_(e,t,``)}function p_(e,t){return t.slice(0,m_(e,t))}function m_(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function h_(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function g_(e,t){if(t)return v_(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function __(e,t){if(t)return v_(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function v_(e,t){if(!t)return[__(e),g_(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=h_(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var y_=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,b_=RegExp(`[${y_}]+|\\s+|[^${y_}]`,`ug`);new class extends o_{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=h_(e,r)}else n=e.match(b_)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&x_(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&x_(n,i,r,null,t.intlSegmenter),e}};function x_(e,t,n,r,i){if(t&&n){let[a,o]=v_(t.value,i),[s,c]=v_(n.value,i);if(e){let r=s_(a,s);e.value=u_(e.value,s,r),t.value=d_(t.value,r),n.value=d_(n.value,r)}if(r){let e=c_(o,c);r.value=l_(r.value,c,e),t.value=f_(t.value,e),n.value=f_(n.value,e)}}else if(n){if(e){let e=__(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=__(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=__(r.value,i),[a,o]=v_(t.value,i),s=s_(n,a);t.value=d_(t.value,s);let c=c_(d_(n,s),o);t.value=f_(t.value,c),r.value=l_(r.value,n,c),e.value=u_(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=__(r.value,i),n=p_(g_(t.value,i),e);t.value=f_(t.value,n)}else if(e){let n=p_(g_(e.value,i),__(t.value,i));t.value=d_(t.value,n)}}new class extends o_{tokenize(e){let t=RegExp(`(\\r?\\n)|[${y_}]+|[^\\S\\n\\r]+|[^${y_}]`,`ug`);return e.match(t)||[]}};var S_=new class extends o_{constructor(){super(...arguments),this.tokenize=w_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
72
+ `)}function lm(e){let t=e.split(/\r?\n/).map(e=>e.replace(/[ \t]+$/g,``));for(;t.length>0&&(t[0]??``).trim()===``;)t.shift();for(;t.length>0&&(t[t.length-1]??``).trim()===``;)t.pop();return t}function um(e,t){if(!e||!t)return!1;let n=lm(e),r=lm(t);return n.length===r.length?n.every((e,t)=>e===r[t]):!1}function dm(e){if(!e)return null;let t=Math.floor(Number(e.cursorX)),n=Math.floor(Number(e.cursorY)),r=Math.floor(Number(e.cols)),i=Math.floor(Number(e.rows));return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0?null:{x:Math.max(0,Math.min(r-1,t)),y:Math.max(0,Math.min(i-1,n)),cols:r,rows:i}}function fm(e,t){return!e||t<=0?e:{...e,y:Math.max(0,e.y-t)}}function pm(e){let t=rm(e),n=$p(e),r=e.session&&typeof e.session==`object`?e.session.output??``:e.output??``,i=tm(n),a=tm(r),o=cm(t),s=am(e),c=i?nm(n):sm(t),l=!i||um(i,o)?fm(dm(t),c):null;return{output:i||o,textOutput:a,cursor:l,outputSeq:em(e),cols:s.cols,rows:s.rows}}function mm(e,t){return typeof e==`number`&&Number.isFinite(e)&&t!==null&&e<=t}var hm=4,gm=80,_m=new Map,vm=6,ym=520,bm=.025,xm=3.2,Sm=.972,Cm=90,wm=.28,Tm=30,Em=240,Dm=3e4;function Om(){return L()}function km(e,t){Wp(e,t,()=>Pm(e.hostEl,t)),Mm(e)}function Am(e){for(let t of _m.values())if(!(t instanceof Promise)&&t.hostEl===e)return t;return null}function jm(e){e.disposed||(e.followOutputHandler=null,e.pathOpenHandler=null,e.pathResolveHandler=null,Nm(e),wg(e),Kp(e))}function Mm(e){e.disposed||!e.resizeObserver||e.resizeObserver.observe(e.hostEl)}function Nm(e){e.resizeObserver?.disconnect()}function Pm(e,t){let n=t.closest(`.code-terminal-grid.panes-1`);n&&n.querySelectorAll(`.terminal-session-host`).forEach(t=>{if(t===e||!(t instanceof HTMLDivElement))return;let n=Am(t);n?jm(n):Bp().appendChild(t)})}function Fm(e){let t=e.dataset.terminalFontSize,n=t?Number(t):NaN;return Number.isFinite(n)&&n>0?n:12}async function Im(e){let t=await fetch(n(`/api/agents/${e}/session-view`));if(!t.ok)throw Error(`Terminal session view failed: ${t.status}`);return pm(await t.json())}function Lm(e){return new Promise(t=>window.setTimeout(t,e))}function Rm(e){let t=Math.floor(Number(e.terminal.cols)),n=Math.floor(Number(e.terminal.rows));return!Number.isFinite(t)||!Number.isFinite(n)||t<40||n<10?null:{cols:t,rows:n}}function zm(e,t){let n=Rm(e);return!n||t.cols===null||t.rows===null?!0:t.cols===n.cols&&t.rows===n.rows}async function Bm(e){let t=await Im(e.agentId);for(let n=0;n<hm;n+=1){if(e.disposed||zm(e,t))return t;await Lm(gm),t=await Im(e.agentId)}return!zm(e,t)&&t.textOutput?{...t,output:t.textOutput,cursor:null,cols:null,rows:null}:t}async function Vm(e){if(e.disposed||e.fixtureOverrideActive||!e.bootstrappingSnapshot&&!e.pendingSnapshotReplay)return;let t=++e.bootstrapRefreshSeq;try{let n=await Bm(e);if(e.disposed||e.fixtureOverrideActive||e.bootstrapRefreshSeq!==t||mm(n.outputSeq,e.lastOutputSeq))return;n.output&&Date.now()>=e.suppressOutputUntil&&(e.snapshotOutput=n.output,e.snapshotCursor=n.cursor,e.snapshotOutputSeq=n.outputSeq)}catch{}}function Hm(e,t){if(wf(t))return t.focus(),!0;let n=e.querySelector(`textarea`);return n instanceof HTMLTextAreaElement?(nh(e,t),n.focus(),!0):(t.focus(),!1)}function Um(e){return e.disposed||e.attachedMount===null?!1:Hm(e.hostEl,e.terminal)}function Wm(e){let t=document.activeElement;return document.querySelector(`.code-composer.menu-open, .code-composer-menu`)?!1:!(t instanceof Element)||t===document.body||e.contains(t)?!0:!t.closest([`.code-composer`,`.code-composer-menu`,`.code-context-menu`,`.input-dialog-overlay`,`.code-overlay-dialog`,`.code-file-editor`,`.code-files-section`,`input`,`textarea`,`select`,`[contenteditable="true"]`,`[role="dialog"]`,`[role="menu"]`].join(`,`))}function Gm(e){return e instanceof Element?!!e.closest([`.code-composer`,`.code-terminal-search`,`.code-file-editor`,`.monaco-editor`,`input`,`textarea`,`select`,`[contenteditable="true"]`,`[role="dialog"]`,`[role="menu"]`].join(`,`)):!1}function Km(e,t){if(e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(Gm(n))return!1;let r=window.getSelection?.();if(!r||r.isCollapsed)return!0;let i=r.anchorNode,a=r.focusNode;return!!(i&&e.hostEl.contains(i)||a&&e.hostEl.contains(a))}function qm(e){return e.key.toLowerCase()!==`c`||e.altKey||e.shiftKey?!1:e.metaKey&&!e.ctrlKey?!0:!navigator.platform.toLowerCase().includes(`mac`)&&e.ctrlKey&&!e.metaKey}function Jm(e,t){if(!qm(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;if(n instanceof Node&&e.hostEl.contains(n))return!0;if(Gm(n))return!1;let r=window.getSelection?.();if(!r||r.isCollapsed)return!0;let i=r.anchorNode,a=r.focusNode;return!!(i&&e.hostEl.contains(i)||a&&e.hostEl.contains(a))}function Ym(e){return e.key.toLowerCase()!==`k`||e.altKey||e.shiftKey||e.ctrlKey?!1:navigator.platform.toLowerCase().includes(`mac`)&&e.metaKey}function Xm(e,t){if(!Ym(t)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function Zm(e,t){return Xm(e,t)?(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),bg(e),!0):!1}function Qm(e){return Vp(e)}function $m(e){return Qm(e)}function eh(e,t){if(t.type!==`keydown`||![`PageUp`,`PageDown`].includes(t.key)||e.disposed||e.attachedMount===null)return!1;let n=t.target;return n instanceof Node&&e.hostEl.contains(n)}function th(e,t){if(!eh(e,t))return!1;t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let n=gp(e.terminal,t.key===`PageUp`?`PageUp`:`PageDown`,10);return Dp(e,n),mp(e,n<=0,n<=0?!1:e.hasUnreadOutput,{allowClearUnread:n<=0}),pp(e),!0}function nh(e,t){let n=e.querySelector(`textarea`),r=t.renderer?.getMetrics?.(),i=t.wasmTerm?.getCursor?.();if(!(n instanceof HTMLTextAreaElement)||!r||!i)return;let a=Fm(e),o=Math.max(0,i.x*r.width),s=Math.max(0,i.y*r.height),c=Math.max(a+2,r.height),l=Math.max(r.width*8,120);n.classList.add(`terminal-ime-input`),n.style.position=`absolute`,n.style.left=`${o}px`,n.style.top=`${s}px`,n.style.width=`${l}px`,n.style.height=`${c}px`,n.style.lineHeight=`${c}px`,n.style.fontSize=`${a}px`,n.style.fontFamily=St,n.style.padding=`0`,n.style.margin=`0`,n.style.border=`0`,n.style.outline=`0`,n.style.background=`transparent`,n.style.clipPath=`none`,n.style.overflow=`hidden`,n.style.whiteSpace=`pre`,n.style.resize=`none`}function rh(e,t){return Hp(e,t)}function ih(e,t){if(e.fixtureOverrideActive||e.disposed||!e.pendingSnapshotReplay||!e.snapshotOutput||t!==void 0&&!rh(e,t))return;let n=e.snapshotOutput,r=e.snapshotCursor,i=e.snapshotOutputSeq;if(e.pendingSnapshotReplay=!1,e.snapshotCursor=null,mm(i,e.lastOutputSeq)){e.bootstrappingSnapshot=!1,dh(e),t!==void 0&&ah(e,t);return}zp(e,n,()=>{e.bootstrappingSnapshot=!1,i!==null&&(e.lastOutputSeq=Math.max(e.lastOutputSeq??0,i)),lh(e),dh(e),t!==void 0&&ah(e,t)},{cursor:r})}function ah(e,t){e.needsReconnectOutputSync&&requestAnimationFrame(()=>oh(e,t))}function oh(e,t){if(!e.needsReconnectOutputSync||e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.fixtureOverrideActive||!rh(e,t))return;let n=e.reconnectSnapshotSeq+1;e.reconnectSnapshotSeq=n,Bm(e).then(r=>{if(!(e.disposed||e.reconnectSnapshotSeq!==n||e.fixtureOverrideActive||!rh(e,t)||Date.now()<e.suppressOutputUntil)){if(!r.output||r.outputSeq===null||mm(r.outputSeq,e.lastOutputSeq)){e.needsReconnectOutputSync=!1;return}e.needsReconnectOutputSync=!1,zp(e,r.output,()=>{e.lastOutputSeq=Math.max(e.lastOutputSeq??0,r.outputSeq??0),_h(e)},{cursor:r.cursor})}}).catch(()=>{})}function sh(e,t){e.fixtureOverrideActive||Bm(e).then(n=>{e.disposed||e.fixtureOverrideActive||e.attachGeneration!==t||!n.output||n.outputSeq!==null&&mm(n.outputSeq,e.lastOutputSeq)||zp(e,n.output,()=>{typeof n.outputSeq==`number`&&Number.isFinite(n.outputSeq)&&(e.lastOutputSeq=Math.max(e.lastOutputSeq??0,n.outputSeq)),_h(e)},{cursor:n.cursor})}).catch(()=>{})}function ch(e){let t=e.attachGeneration;[120,400,1e3].forEach(n=>{window.setTimeout(()=>{e.disposed||e.attachGeneration!==t||sh(e,t)},n)})}function lh(e){let t=e.snapshotOutputSeq;t!==null&&(e.queuedOutput=e.queuedOutput.filter(e=>!mm(e.outputSeq,t)))}function uh(e,t,n,r){if(!mm(r,e.lastOutputSeq)){if(n){if(e.fixtureOverrideActive)return;zp(e,t,()=>_h(e)),typeof r==`number`&&Number.isFinite(r)&&(e.lastOutputSeq=r);return}t&&(Rp(e,t,void 0,{isOutputObserved:()=>Qm(e)}),typeof r==`number`&&Number.isFinite(r)&&(e.lastOutputSeq=r),_h(e))}}function dh(e){e.disposed||e.bootstrappingSnapshot||e.pendingSnapshotReplay||e.queuedOutput.splice(0).forEach(t=>uh(e,t.data,t.replace,t.outputSeq))}function fh(e){return e.terminal.getCellMetrics?.()??e.terminal.renderer?.getMetrics?.()}function ph(e){let t=e.terminal.getScreenElement?.();if(t instanceof HTMLElement)return t.getBoundingClientRect();let n=e.terminal.renderer?.getCanvas?.()||e.hostEl.querySelector(`canvas`);return n instanceof HTMLCanvasElement?n.getBoundingClientRect():null}function mh(e){let t=fp(e);mp(e,t,t?!1:e.hasUnreadOutput,{allowClearUnread:t})}function hh(e){e.queuedOutput=[],e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1}function gh(e){e.followCheckFrame!==null&&cancelAnimationFrame(e.followCheckFrame),e.followCheckFrame=requestAnimationFrame(()=>{if(e.followCheckFrame=null,e.disposed||!Qm(e))return;let t=fp(e);mp(e,t,t?!1:e.hasUnreadOutput,{allowClearUnread:t})})}function _h(e){e.imeComposing&&requestAnimationFrame(()=>{!e.disposed&&e.imeComposing&&nh(e.hostEl,e.terminal)})}function vh(e){return wf(e.terminal)?!1:e.imeComposing||e.suppressRendererCursor}function yh(e,t=!0){let n=e.terminal.renderer;if(!e.disposed){if(e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,vh(e)),!n){t&&Cp(e);return}vh(e)?n.cursorVisible=!1:!e.imeComposing&&e.rendererCursorWasVisible!==void 0&&(n.cursorVisible=e.rendererCursorWasVisible,e.rendererCursorWasVisible=void 0),t&&Cp(e)}}function bh(e,t){if(e.suppressRendererCursor===t){e.hostEl.classList.toggle(`terminal-renderer-cursor-suppressed`,vh(e));return}e.suppressRendererCursor=t,yh(e)}function xh(e,t){let n=e.terminal.renderer;if(!(e.disposed||!n)){if(t){e.imeComposing||(e.rendererCursorWasVisible=n.cursorVisible===void 0?void 0:!!n.cursorVisible),e.imeComposing=!0,yh(e);return}if(e.imeComposing){if(e.imeComposing=!1,e.suppressRendererCursor){n.cursorVisible=!1,Cp(e);return}n.cursorVisible=e.rendererCursorWasVisible??!0,e.rendererCursorWasVisible=void 0,Cp(e)}}}function Sh(e){let t=e.terminal.renderer;if(!t?.render||e.originalRender)return;let n=t.render.bind(t);e.originalRender=n,t.render=(r,i,a,o,s)=>{let c=Tp(s);if(!e.suspendRendering){if(!vh(e)){n(r,i,a,o,c);return}t.cursorVisible=!1,n(r,!0,a,o,c),t.cursorVisible=!1}}}function Ch(e){if(wf(e.terminal))return;let t=e.hostEl.querySelector(`textarea`);if(!(t instanceof HTMLTextAreaElement))return;let n=()=>{e.disposed||nh(e.hostEl,e.terminal)},r=()=>requestAnimationFrame(n),i=()=>{e.imeComposing&&r()},a=()=>{n(),e.hostEl.classList.add(`terminal-ime-active`),t.classList.add(`terminal-ime-composing`),xh(e,!0)},o=()=>{xh(e,!1),requestAnimationFrame(()=>{e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`),t.value=``,n()})},s=()=>{xh(e,!1),e.hostEl.classList.remove(`terminal-ime-active`),t.classList.remove(`terminal-ime-composing`)},c=e=>{(e.isComposing||e.keyCode===229)&&a()};t.addEventListener(`focus`,n),e.hostEl.addEventListener(`keydown`,c,!0),e.hostEl.addEventListener(`compositionstart`,a,!0),e.hostEl.addEventListener(`compositionupdate`,n,!0),e.hostEl.addEventListener(`compositionend`,o,!0),t.addEventListener(`input`,i),t.addEventListener(`blur`,s),e.imeKeydownHandler=c;let l=e.terminal.onCursorMove?.(i),u=e.terminal.onKey?.(i);e.imeOverlayDisposables.push(()=>t.removeEventListener(`focus`,n),()=>e.hostEl.removeEventListener(`keydown`,c,!0),()=>e.hostEl.removeEventListener(`compositionstart`,a,!0),()=>e.hostEl.removeEventListener(`compositionupdate`,n,!0),()=>e.hostEl.removeEventListener(`compositionend`,o,!0),()=>t.removeEventListener(`input`,i),()=>t.removeEventListener(`blur`,s),s),l&&e.imeOverlayDisposables.push(()=>l.dispose()),u&&e.imeOverlayDisposables.push(()=>u.dispose()),n()}function wh(e,t,n=12){rh(e,t)&&Wm(e.hostEl)&&(Um(e)||n<=0||requestAnimationFrame(()=>{wh(e,t,n-1)}))}function Th(e,t,n={}){try{let r=yp(e.hostEl,e.fitAddon);if(!r)return;Eh(e,r.cols,r.rows,t,n)}catch{}}function Eh(e,t,n,r=e.resizeHandler,i={}){Qm(e)&&bp(e,t,n,r,i)}function Dh(e){xp(e),e.needsReconnectOutputSync=!0,!e.disposed&&(!e.attachedMount||e.hostEl.parentElement!==e.attachedMount||(Th(e,e.resizeHandler,{force:!0}),oh(e,e.attachGeneration)))}function Oh(e,t){return Math.max(0,(typeof e?.length==`number`?e.length:t)-1)}function kh(e,t,n){return ep(e.getLine(t)?.getCell?.(n))}function Ah(e,t,n,r){if(n>0)return{row:t,col:n-1};let i=e.getLine(t);if(t<=0||!i?.isWrapped)return null;let a=e.getLine(t-1);return{row:t-1,col:Oh(a,r)}}function jh(e,t,n,r){if(n<Oh(e.getLine(t),r))return{row:t,col:n+1};let i=t+1;return e.getLine(i)?.isWrapped?{row:i,col:0}:null}function Mh(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof r.getLine!=`function`||typeof e.terminal.select!=`function`)return``;let a=dp(e.terminal)+n;if(!sp(kh(r,a,t)))return``;let o={row:a,col:t};for(;;){let e=Ah(r,o.row,o.col,i);if(!e||!sp(kh(r,e.row,e.col)))break;o=e}let s={row:a,col:t};for(;;){let e=jh(r,s.row,s.col,i);if(!e||!sp(kh(r,e.row,e.col)))break;s=e}return e.terminal.select(o.col,o.row,cp(o,s,i)),e.cachedSelection=ap(e.terminal),e.cachedSelection}function Nh(e,t,n){let r=e.terminal.buffer?.active,i=e.terminal.cols||80;if(!r||typeof e.terminal.select!=`function`)return``;let a=dp(e.terminal),o={row:a+t.row,col:t.col},s={row:a+n.row,col:n.col},c=o.row<s.row||o.row===s.row&&o.col<=s.col?{start:o,end:s}:{start:s,end:o};return e.terminal.select(c.start.col,c.start.row,cp(c.start,c.end,i)),e.cachedSelection=ap(e.terminal),e.cachedSelection}function Ph(e){let t=e.terminal.buffer?.active,n=e.terminal.cols||80;if(!t||typeof t.getLine!=`function`||typeof e.terminal.select!=`function`)return``;let r=typeof t.length==`number`?t.length:dp(e.terminal)+(e.terminal.rows||1),i=Math.max(0,r-1),a=Oh(t.getLine(i),n);return e.terminal.select(0,0,cp({row:0,col:0},{row:i,col:a},n)),e.cachedSelection=ap(e.terminal),e.cachedSelection}function Fh(e,t){let n=fh(e),r=ph(e);return!n||!r||t.clientX<r.left||t.clientX>r.right||t.clientY<r.top||t.clientY>r.bottom?null:{col:Math.max(0,Math.min(Math.floor((t.clientX-r.left)/n.width),(e.terminal.cols||1)-1)),row:Math.max(0,Math.min(Math.floor((t.clientY-r.top)/n.height),(e.terminal.rows||1)-1))}}function Ih(e,t,n,r=!0){let i=e.getLine(t);if(!i||typeof i.getCell!=`function`)return``;let a=Math.max(0,typeof i.length==`number`?i.length:n),o=``;for(let e=0;e<a;e+=1)o+=ep(i.getCell(e))||` `;return r?o.trimEnd():o}function Lh(e){return e.button===0&&(e.ctrlKey||e.metaKey)}function Rh(e){return e.ctrlKey||e.metaKey}function zh(e,t){return Rh(t)||e.openModifierActive}function Bh(e,t){if(!e.decorations){e.decorations=t;return}e.decorations.pointerCursor=t.pointerCursor,e.decorations.underline=t.underline}function Vh(e){return[e.path,e.lineNumber??``,e.column??``,e.endColumn??``].join(`\0`)}async function Hh(e,t){if(!e.pathResolveHandler)return t;let n=Vh(t),r=e.pathResolveCache.get(n);if(r&&Date.now()-r.resolvedAt<=Dm)return r.promise?await r.promise:r.target;let i=Promise.resolve(e.pathResolveHandler(e.agentId,t)).catch(()=>null);e.pathResolveCache.set(n,{resolvedAt:Date.now(),target:null,promise:i});let a=await i;return e.pathResolveCache.set(n,{resolvedAt:Date.now(),target:a}),a}async function Uh(e,t){return e.pathResolveHandler?(await Promise.all(t.map(async t=>{if(t.kind!==`path`||!t.pathTarget)return t;let n=await Hh(e,t.pathTarget);return n?{...t,pathTarget:n}:null}))).filter(e=>!!e):t}function Wh(e,t){if(!e.pathResolveHandler||t.kind!==`path`||!t.pathTarget)return t;let n=e.pathResolveCache.get(Vh(t.pathTarget));return!n||n.promise||Date.now()-n.resolvedAt>Dm?null:n.target?{...t,pathTarget:n.target}:null}function Gh(e){if(!wf(e.terminal)||typeof e.terminal.registerLinkProvider!=`function`)return;let t=e.terminal.registerLinkProvider({provideLinks:(t,n)=>{if(e.disposed){n(void 0);return}let r=qh(e,t-1);if(!r?.text){n(void 0);return}let i=Zf(r.text,!!e.pathOpenHandler);if(i.length===0){n(void 0);return}(async()=>{let t=await Uh(e,i);if(e.disposed){n(void 0);return}if(t.length===0){n(void 0);return}n(t.map(t=>{let n=t.kind===`path`&&!!(t.pathTarget&&e.pathOpenHandler),i={range:Qf(t,r),text:t.text,decorations:{pointerCursor:n,underline:n},activate:r=>{if(r.button!==0)return;let i=zh(e,r);Qm(e)&&(t.kind===`url`&&!i||t.kind===`path`&&!n||(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),t.kind===`url`?sg(t.text):t.pathTarget&&e.pathOpenHandler&&e.pathOpenHandler(e.agentId,t.pathTarget),e.suppressClickUntil=Date.now()+250))},hover:r=>{if(!$m(e)||Om())return;e.linkProviderHoverTarget={kind:t.kind,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},e.lastLinkHoverEvent=r;let a=n||zh(e,r);Bh(i,{pointerCursor:a,underline:n||t.kind===`url`||a}),pg(e,a)},leave:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null),Bh(i,{pointerCursor:n,underline:n}),ug(e)},dispose:()=>{e.linkProviderHoverTarget?.text===t.text&&(e.linkProviderHoverTarget=null)}};return i}))})()}});e.linkProviderDisposable=()=>t.dispose()}function Kh(e,t){let n=e.terminal.buffer?.active;if(!t||!n||typeof n.getLine!=`function`)return null;let r=dp(e.terminal)+t.row,i=e.terminal.cols||80,a=r;for(;a>0&&n.getLine(a)?.isWrapped;)--a;let o=r;for(;n.getLine(o+1)?.isWrapped;)o+=1;let s=[];for(let e=a;e<=o;e+=1)s.push(Ih(n,e,i,e===o));let c=(r-a)*i+t.col;return{text:s.join(``).trimEnd(),col:c,startRow:a,endRow:o,bufferRow:r,cols:i,buffer:n}}function qh(e,t){let n=e.terminal.buffer?.active;if(!n||typeof n.getLine!=`function`||!Number.isFinite(t)||t<0)return null;let r=e.terminal.cols||80,i=t;for(;i>0&&n.getLine(i)?.isWrapped;)--i;let a=t;for(;n.getLine(a+1)?.isWrapped;)a+=1;let o=[];for(let e=i;e<=a;e+=1)o.push(Ih(n,e,r,e===a));return{text:o.join(``).trimEnd(),col:0,startRow:i,endRow:a,bufferRow:t,cols:r,buffer:n}}function Jh(e,t){let n=Kh(e,t);return n?{text:n.text,col:n.col}:null}function Yh(e,t){let n=document.elementFromPoint(t.clientX,t.clientY);if(!(n instanceof HTMLElement))return null;let r=n.closest(`.xterm-rows > div`);if(!r||!e.hostEl.contains(r))return null;let i=fh(e),a=r.getBoundingClientRect();if(!i||i.width<=0||a.width<=0)return null;let o=(r.textContent||``).trimEnd();if(!o)return null;let s=Bf(t.clientX-a.left,i.width,o.length);return s===null?null:{text:o,col:s}}function Xh(e,t,n){let r=t;for(;r>0&&e.getLine(r)?.isWrapped;)--r;let i=[];for(let a=r;a<=t;a+=1)i.push({row:a,text:Ih(e,a,n,a===t),startCol:0});return{startRow:r,endRow:t,text:i.map(e=>e.text).join(``).trimEnd(),lastPhysicalText:i[i.length-1]?.text??``,segments:i}}function Zh(e,t,n){let r=``,i=-1;for(let a of e){if(a.row===t){let e=n-a.startCol;e>=0&&e<a.text.length&&(i=r.length+e)}r+=a.text}return i>=0?{text:r,col:i}:null}function Qh(e,t){let n=Kh(e,t);if(!n)return null;let{buffer:r,bufferRow:i,cols:a}=n,o=[];for(let e=n.startRow;e<=n.endRow;e+=1)o.push({row:e,text:Ih(r,e,a,e===n.endRow),startCol:0});for(;;){let e=o[0];if(!e||e.row<=0)break;let t=Xh(r,e.row-1,a),n=Uf(t.text),i=n?Jf(e.text,n.rawUrl):null;if(!n||Wf(n)||!i||!qf(t.lastPhysicalText,n.rawUrl,a))break;e.text=i.text,e.startCol=i.startCol,o.unshift(...t.segments)}for(;;){let e=o[o.length-1];if(!e)break;let t=Uf(o.map(e=>e.text).join(``));if(!t||Wf(t)||!qf(e.text,t.rawUrl,a)||!r.getLine(e.row+1))break;let n=Jf(Ih(r,e.row+1,a),t.rawUrl);if(!n)break;o.push({row:e.row+1,text:n.text,startCol:n.startCol})}return Zh(o,i,t.col)}function $h(e,t){let n=Fh(e,t);if(n){let t=Jh(e,n),r=t?zf(t.text,t.col):null;if(r)return r}let r=Yh(e,t);return r?zf(r.text,r.col):null}function eg(e,t){let n=$h(e,t);return n?Wh(e,n):null}function tg(e,t){return eg(e,t)?.pathTarget??null}function ng(e,t){let n=Fh(e,t);if(n){let t=Qh(e,n),r=t?Yf(t.text,t.col):null;if(r)return r}let r=Yh(e,t);return r?Yf(r.text,r.col):null}function rg(e){return op(e.terminal.getSelection()||``)}function ig(e,t){return(wf(e.terminal)?rg(e):op(ap(e.terminal)))||(!wf(e.terminal)&&t?.includeNativeFallback?op(og(e.hostEl)):``)}function ag(e,t){let n=e.terminal.getSelectionPosition?.();if(!n||!e.terminal.getSelection?.())return!1;let r=Fh(e,t);if(!r)return!1;let{start:i,end:a}=$f(n),o={x:r.col,y:dp(e.terminal)+r.row};return!(o.y<i.y||o.y>a.y||o.y===i.y&&o.x<i.x||o.y===a.y&&o.x>a.x)}function og(e){let t=window.getSelection?.();if(!t||t.isCollapsed)return``;let n=t.anchorNode,r=t.focusNode;return n&&!e.contains(n)||r&&!e.contains(r)?``:t.toString()}function sg(e){window.open(e,`_blank`,`noopener,noreferrer`)}function cg(e){let t=navigator.platform.toLowerCase().includes(`mac`)?`Cmd`:`Ctrl`;return(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`)?e===`url`?`按住 ${t} 点击打开链接`:`点击打开文件或文件夹`:e===`url`?`${t}-click to open link`:`Click to open file or folder`}function lg(e,t){e.hostEl.classList.toggle(`terminal-open-target-hover`,t!==null),e.hostEl.classList.toggle(`terminal-open-target-url`,t===`url`),e.hostEl.classList.toggle(`terminal-open-target-path`,t===`path`),t?(e.hostEl.dataset.terminalOpenTarget=t,e.hostEl.title=cg(t)):(delete e.hostEl.dataset.terminalOpenTarget,e.hostEl.removeAttribute(`title`))}function ug(e){e.openModifierActive=!1,e.lastLinkHoverEvent=null,e.linkProviderHoverTarget=null,lg(e,null)}function dg(e,t,n=zh(e,t)){return e.pathOpenHandler&&tg(e,t)?`path`:n&&ng(e,t)?`url`:null}async function fg(e,t){if(!e.pathOpenHandler)return null;let n=$h(e,t);if(!n?.pathTarget)return null;let r=await Hh(e,n.pathTarget);return r?{...n,pathTarget:r}:null}function pg(e,t){if(!$m(e)||Om()){lg(e,null);return}let n=e.linkProviderHoverTarget,r=t??e.openModifierActive;if(n){lg(e,n.kind===`path`||r?n.kind:null);return}if(!e.lastLinkHoverEvent){lg(e,null);return}lg(e,dg(e,e.lastLinkHoverEvent,r))}function mg(e){e.contextMenuCleanup?.(),e.contextMenuCleanup=null,e.contextMenuEl?.remove(),e.contextMenuEl=null,e.contextMenuSelection=``}function hg(e){let t=(document.documentElement.lang||navigator.language||``).toLowerCase().startsWith(`zh`);return e===`copy`?t?`复制`:`Copy`:e===`paste`?t?`粘贴`:`Paste`:e===`clear`?t?`清除`:`Clear`:t?`全选`:`Select All`}function gg(e,t,n=160,r=148){return{x:Math.max(8,Math.min(e,window.innerWidth-n-8)),y:Math.max(8,Math.min(t,window.innerHeight-r-8))}}function _g(e){e.querySelector(`button:not(:disabled)`)?.focus()}function vg(e,t,n={}){let r=document.createElement(`button`);return r.type=`button`,r.className=`terminal-context-menu-item`,r.setAttribute(`role`,`menuitem`),r.textContent=e,r.disabled=n.disabled===!0,r.addEventListener(`click`,()=>{r.disabled||t()}),r}function yg(e,t){return!t||e.disposed||e.attachedMount===null?!1:(e.fixtureOverrideActive=!1,kp(e,{allowClearUnread:!0}),e.lastTerminalDataAt=Date.now(),e.inputCount+=1,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.inputHandler(t),ch(e),!0)}function bg(e){e.disposed||e.attachedMount===null||(Cg(e),e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.terminal.clearSearch?.(),typeof e.terminal.clearBuffer==`function`?e.terminal.clearBuffer():e.terminal.reset(),mp(e,!0,!1,{allowClearUnread:!0}),fetch(n(`/api/control/agents/${encodeURIComponent(e.agentId)}/clear`),{method:`POST`}).catch(()=>{}))}function xg(e,t,n){mg(e);let r=gg(t.clientX,t.clientY),i=document.createElement(`div`);i.className=`terminal-context-menu terminal-context-menu-pooled`,i.setAttribute(`data-testid`,`code-terminal-context-menu`),i.setAttribute(`role`,`menu`),i.style.left=`${r.x}px`,i.style.top=`${r.y}px`;let a=vg(hg(`copy`),()=>{M(n).finally(()=>{mg(e),Om()||Um(e)})},{disabled:!n}),o=vg(hg(`paste`),()=>{ee().then(t=>{yg(e,t)}).finally(()=>{mg(e),Om()||Um(e)})}),s=vg(hg(`selectAll`),()=>{mg(e),Cg(e),requestAnimationFrame(()=>{if(e.disposed)return;let t=Ph(e);e.contextMenuSelection=t,e.lastNonEmptySelection=t||e.lastNonEmptySelection,Om()||Um(e)})},{disabled:typeof e.terminal.select!=`function`||!e.terminal.buffer?.active}),c=vg(hg(`clear`),()=>{mg(e),bg(e),Om()||Um(e)});i.addEventListener(`mousedown`,e=>e.stopPropagation()),i.addEventListener(`pointerdown`,e=>e.stopPropagation()),i.addEventListener(`keydown`,e=>{if(!(e.target instanceof HTMLButtonElement)||e.key!==`ArrowDown`&&e.key!==`ArrowUp`)return;let t=Array.from(i.querySelectorAll(`button:not(:disabled)`)),n=t.indexOf(e.target);n<0||t.length===0||(e.preventDefault(),t[(n+(e.key===`ArrowDown`?1:-1)+t.length)%t.length]?.focus())}),i.appendChild(a),i.appendChild(o),i.appendChild(s),i.appendChild(c),document.body.appendChild(i),e.contextMenuEl=i;let l=t=>{let n=t.target;n instanceof Node&&i.contains(n)||mg(e)},u=t=>{t.key===`Escape`&&(t.preventDefault(),mg(e),Om()||Um(e))},d=()=>mg(e);document.addEventListener(`mousedown`,l,!0),document.addEventListener(`pointerdown`,l,!0),document.addEventListener(`keydown`,u,!0),window.addEventListener(`resize`,d),window.addEventListener(`scroll`,d,!0),e.contextMenuCleanup=()=>{document.removeEventListener(`mousedown`,l,!0),document.removeEventListener(`pointerdown`,l,!0),document.removeEventListener(`keydown`,u,!0),window.removeEventListener(`resize`,d),window.removeEventListener(`scroll`,d,!0)},requestAnimationFrame(()=>_g(i))}function Sg(e){let t=window.getSelection?.();if(!t||t.rangeCount===0)return;let n=t.anchorNode,r=t.focusNode;n&&!e.contains(n)||r&&!e.contains(r)||t.removeAllRanges()}function Cg(e){e.cachedSelection=``,e.contextMenuSelection=``,e.lastNonEmptySelection=``,e.dragSelection=null,e.terminal.clearTerminalSelection?.(),Sg(e.hostEl)}function wg(e){mg(e),ug(e),Cg(e)}function Tg(e){wg(e),wf(e.terminal)&&(e.terminal.reattach?.(),e.terminal.syncAppearanceTheme?.(),e.terminal.forceRedraw?.()),Ep(e),requestAnimationFrame(()=>{e.disposed||e.attachedMount===null||(wf(e.terminal)&&e.terminal.forceRedraw?.(),Cp(e))})}function Eg(e,t){let n=ig(e)||e.contextMenuSelection||e.lastNonEmptySelection,r=ng(e,t),i=e.pathOpenHandler?eg(e,t):null,a=!!n&&ag(e,t),o=n.replace(/\s+/g,``);if(r&&(!a||r.includes(o)))return r;if(i?.text&&(!a||i.text.includes(o)))return i.text;if(n)return n;let s=Fh(e,t);return s?Mh(e,s.col,s.row):``}function Dg(e,t){let n=n=>{if(!(n.target instanceof Node)||!e.hostEl.contains(n.target))return;let r=e.pathOpenHandler?$h(e,n):null;if(r?.pathTarget){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),Hh(e,r.pathTarget).then(t=>{if(!e.disposed){if(t){xg(e,n,r.text);return}xg(e,n,Eg(e,n))}});return}if(e.pathOpenHandler&&Lh(n)){let r=tg(e,n);if(r){n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),e.pathOpenHandler(t,r);return}}let i=Eg(e,n);n.preventDefault(),n.stopPropagation(),n.stopImmediatePropagation(),xg(e,n,i)},r=t=>{if(!(!(t.target instanceof Node)||!e.hostEl.contains(t.target))){if(t.button===0){e.contextMenuSelection=``,e.lastNonEmptySelection=``;return}t.button===2&&(e.contextMenuSelection=ig(e)||op(e.cachedSelection)||e.lastNonEmptySelection)}};window.addEventListener(`mousedown`,r,!0),window.addEventListener(`contextmenu`,n,!0),e.hostEl.addEventListener(`mousedown`,r,!0),e.hostEl.addEventListener(`contextmenu`,n,!0),e.contextMenuMouseDownHandler=r,e.contextMenuHandler=n}function Og(e){let t=null,n=0,r=0,i=0,a=0,o=0,s=0,c=!1,l=null,u=0,d=[],f=0,p=null,m=null,h=null,g=e=>Math.max(-xm,Math.min(xm,e)),_=()=>{m!==null&&(window.clearTimeout(m),m=null),h=null},v=()=>e.hostEl.querySelector(`.xterm-screen`),y=()=>{p!==null&&(window.clearTimeout(p),p=null)},b=(e,t=!1)=>{let n=v();f=e,n&&(y(),n.style.transition=t?`transform ${Em}ms cubic-bezier(0.22, 0.75, 0.28, 1)`:`none`,n.style.transform=e===0?``:`translate3d(0, ${e}px, 0)`,t&&(p=window.setTimeout(()=>{n.style.transition=``,n.style.transform=``,p=null},Em)))},x=e=>{b(Math.max(-Tm,Math.min(Tm,f+e*wm)))},S=(e=!0)=>{f===0&&p===null||b(0,e)},C=(e,t)=>{d.push({y:e,at:t});let n=t-Cm;for(;d.length>2&&d[0].at<n;)d.shift()},w=()=>{let e=d[0],t=d[d.length-1];return!e||!t||t.at<=e.at?o:g((t.y-e.y)/(t.at-e.at))},T=()=>{let t=h;if(_(),!t||e.disposed||c)return;let n=Eg(e,t);n&&xg(e,t,n)},E=t=>{let n=Math.max(8,fh(e)?.height||16);s+=t;let r=Math.trunc(s/n);if(r===0)return!1;s-=r*n;let i=up(e.terminal);Dp(e,i+r);let a=up(e.terminal)!==i;return a&&(mh(e),mg(e)),a},D=()=>{l!==null&&(window.cancelAnimationFrame(l),l=null),u=0,o=0,s=0},O=t=>{if(e.disposed){l=null;return}let n=u===0?16:Math.min(48,Math.max(1,t-u));u=t;let r=o*n,i=E(r);if(o*=Sm**(n/16),!i||Math.abs(o)<bm){i||x(r),D(),S();return}l=window.requestAnimationFrame(O)},k=()=>{if(Math.abs(o)<bm){o=0;return}u=0,l=window.requestAnimationFrame(O)},A=o=>{if(o.pointerType===`touch`){D(),S(!1),t=o.pointerId,n=o.clientX,r=o.clientY,i=o.clientY,a=o.timeStamp||performance.now(),d=[],C(o.clientY,a),s=0,c=!1,h=o,m=window.setTimeout(T,ym);try{e.hostEl.setPointerCapture(o.pointerId)}catch{}}},ee=e=>{if(t===null||e.pointerId!==t)return;Math.hypot(e.clientX-n,e.clientY-r)>vm&&(c=!0,_());let s=e.clientY-i,l=e.timeStamp||performance.now(),u=Math.max(1,l-a);if(i=e.clientY,a=l,Math.abs(s)<.5)return;C(e.clientY,l);let d=s/u;o=g(w()*.72+d*.28);let p=E(s);!p&&c?x(s):p&&f!==0&&S(!1),(c||p)&&(e.preventDefault(),e.stopPropagation())},j=n=>{if(t===null||n.pointerId!==t)return;let r=c;t=null,_(),r?(n.preventDefault(),n.stopPropagation(),mh(e),o=w(),n.type===`pointerup`&&f===0?k():(D(),S())):(o=0,s=0,S()),d=[];try{e.hostEl.releasePointerCapture(n.pointerId)}catch{}};e.hostEl.addEventListener(`pointerdown`,A,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointermove`,ee,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointerup`,j,{capture:!0,passive:!1}),e.hostEl.addEventListener(`pointercancel`,j,{capture:!0,passive:!1}),e.hostEl.addEventListener(`lostpointercapture`,j,{capture:!0,passive:!1}),e.touchInteraction={pointerDownHandler:A,pointerMoveHandler:ee,pointerUpHandler:j,stopTouchMomentum:D}}function kg(){typeof window>`u`||!window.__FARMING_E2E__||window.__farmingTerminalTest||(window.__farmingTerminalTest={async writeFixture(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.bootstrapRefreshSeq+=1,r.reconnectSnapshotSeq+=1,r.snapshotOutput=``,r.snapshotOutputSeq=null,r.snapshotCursor=null,r.pendingSnapshotReplay=!1,r.bootstrappingSnapshot=!1,r.needsReconnectOutputSync=!1,r.fixtureOverrideActive=!0,r.queuedOutput=[],r.suppressOutputUntil=Date.now()+1500,r.terminal.reset(),r.terminal.viewportY=0,r.terminal.scrollToLine?.(0),await new Promise(e=>r.terminal.write(t,e)),r.terminal.viewportY=0,r.terminal.scrollToLine?.(0),mp(r,fp(r),!1,{allowClearUnread:!0}),Cp(r),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},getSelection(e){return Ig(e)},getCellCenter(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=fh(r),a=ph(r);return!i||!a?null:{x:a.left+(t+.5)*i.width,y:a.top+(n+.5)*i.height}},getRows(e,t=6){let n=_m.get(e);if(!n||n instanceof Promise||n.disposed)return[];let r=n.terminal.buffer?.active;if(!r||typeof r.getLine!=`function`)return[];let i=[],a=dp(n.terminal);for(let e=0;e<t;e+=1){let t=r.getLine(a+e),o=[],s=n.terminal.cols||t?.length||0;for(let e=0;e<s;e+=1){let n=t?.getCell?.(e);tp(n)||o.push(ep(n)||` `)}i.push(o.join(``).trimEnd())}return i},getHostDiagnostics(){return Array.from(document.querySelectorAll(`.terminal-session-host`)).map(e=>{let t=e,n=Am(t),r=t.getBoundingClientRect(),i=t.parentElement,a=i?.classList.contains(`terminal-container`)?i:null;return{agentId:t.dataset.agentId||``,paneAgentId:t.closest(`[data-testid="code-terminal-pane"]`)?.getAttribute(`data-agent-id`)||``,inParkingLot:t.closest(`#terminal-session-parking-lot`)!==null,recordAttached:n?Qm(n):!1,attachedMountMatchesParent:n?n.attachedMount!==null&&n.hostEl.parentElement===n.attachedMount:!1,visible:r.width>0&&r.height>0&&getComputedStyle(t).display!==`none`,hostCountInMount:a?a.querySelectorAll(`.terminal-session-host`).length:0}})},doubleClickCell(e,t,n){let r=_m.get(e);return!r||r instanceof Promise||r.disposed?``:Mh(r,t,n)},getUrlAtCell(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=Qh(r,{col:t,row:n});return i?Yf(i.text,i.col):null},isReady(e){let t=_m.get(e);return!!(t&&!(t instanceof Promise)&&!t.disposed&&!t.bootstrappingSnapshot&&!t.pendingSnapshotReplay)},getPathAtCell(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed)return null;let i=Jh(r,{col:t,row:n});return i?If(i.text,i.col)??Lf(i.text,i.col):null},openPathAtCell(e,t,n){let r=_m.get(e);if(!r||r instanceof Promise||r.disposed||!r.pathOpenHandler)return!1;let i=Jh(r,{col:t,row:n}),a=i?If(i.text,i.col)??Lf(i.text,i.col):null;return a?(r.pathOpenHandler(e,a),!0):!1},getCursor(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:t.terminal.wasmTerm?.getCursor?.()??null},getCursorVisible(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return;let n=t.terminal.wasmTerm?.getCursor?.().visible;return n===void 0?void 0:!!n},getRendererCursorVisible(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return;let n=t.terminal.renderer?.cursorVisible;return n===void 0?void 0:!!n},getCursorCellPixel(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`),r=fh(t),i=t.terminal.wasmTerm?.getCursor?.();if(!(n instanceof HTMLCanvasElement)||!r||!i){let e=t.hostEl.querySelector(`.xterm-cursor`);if(!(e instanceof HTMLElement))return null;let n=(getComputedStyle(e).backgroundColor||xt.cursor).match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);return n?{r:Number(n[1]??36),g:Number(n[2]??41),b:Number(n[3]??47),a:Math.round(Number(n[4]??1)*255)}:{r:36,g:41,b:47,a:255}}let a=n.width/Math.max(1,n.getBoundingClientRect().width),o=n.height/Math.max(1,n.getBoundingClientRect().height),s=Math.min(n.width-1,Math.max(0,Math.floor((i.x+.5)*r.width*a))),c=Math.min(n.height-1,Math.max(0,Math.floor((i.y+.5)*r.height*o))),l=n.getContext(`2d`)?.getImageData(s,c,1,1).data;return l?{r:l[0]??0,g:l[1]??0,b:l[2]??0,a:l[3]??0}:null},getCanvasInkPixelCount(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return 0;let n=t.terminal.renderer?.getCanvas?.()||t.hostEl.querySelector(`canvas`);if(!(n instanceof HTMLCanvasElement))return(t.hostEl.querySelector(`.xterm-rows`)?.textContent?.trim()??``).length*8;let r=n.getContext(`2d`);if(!r)return 0;let i=r.getImageData(0,0,n.width,n.height).data,a=0;for(let e=0;e<i.length;e+=4){let t=i[e]??255,n=i[e+1]??255,r=i[e+2]??255;(i[e+3]??0)>0&&!(t>248&&n>248&&r>245)&&(a+=1)}return a},async writeRaw(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);await new Promise(e=>Rp(r,t,e,{isOutputObserved:()=>Qm(r)})),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeSequenced(e,t,n){let r=_m.get(e),i=r instanceof Promise?await r:r;if(!i||i.disposed)throw Error(`Terminal session not found: ${e}`);uh(i,t,!1,n),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e())))},async writeRawAndSampleViewport(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);let i=up(r.terminal),a=lp(r.terminal),o=i;return await new Promise(e=>{Rp(r,t,e,{isOutputObserved:()=>Qm(r)}),o=up(r.terminal)}),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(()=>e()))),{before:i,during:o,after:up(r.terminal),beforeScrollbackLength:a,afterScrollbackLength:lp(r.terminal),following:r.followOutput,hasUnreadOutput:r.hasUnreadOutput}},getViewport(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:{viewportY:up(t.terminal),scrollbackLength:lp(t.terminal),following:t.followOutput,hasUnreadOutput:t.hasUnreadOutput}},getInputCount(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?0:t.inputCount},getLastNotifiedResize(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastNotifiedResize},getResizeNotificationCount(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?0:t.resizeNotificationCount},notifyResizeForTest(e,t,n){let r=_m.get(e);return!r||r instanceof Promise||r.disposed?0:(Eh(r,t,n),r.resizeNotificationCount)},getLastOutputSeq(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?null:t.lastOutputSeq},getBufferDiagnostics(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return null;let n=t.terminal.buffer?.active;return{engine:t.terminal.__farmingTerminalEngine,cols:t.terminal.cols||0,rows:t.terminal.rows||0,viewportY:up(t.terminal),scrollbackLength:lp(t.terminal),visibleBufferBase:dp(t.terminal),bufferViewportY:typeof n?.viewportY==`number`?n.viewportY:void 0,bufferBaseY:typeof n?.baseY==`number`?n.baseY:void 0,bufferLength:typeof n?.length==`number`?n.length:void 0}},async scrollToLine(e,t){let n=_m.get(e),r=n instanceof Promise?await n:n;if(!r||r.disposed)throw Error(`Terminal session not found: ${e}`);r.touchInteraction?.stopTouchMomentum(),Op(r,t);let i=fp(r);mp(r,i,i?!1:r.hasUnreadOutput,{allowClearUnread:i}),await new Promise(e=>requestAnimationFrame(()=>e()))},async scrollToBottom(e){let t=_m.get(e),n=t instanceof Promise?await t:t;if(!n||n.disposed)throw Error(`Terminal session not found: ${e}`);n.touchInteraction?.stopTouchMomentum(),kp(n,{allowClearUnread:!0}),await new Promise(e=>requestAnimationFrame(()=>e()))},async search(e,t,n=`next`,r={}){return Hg(e,t,n,r)},async clearSearch(e){await Ug(e)},dispatchPasteToTextarea(e,t){let n=_m.get(e);if(!n||n instanceof Promise||n.disposed)return{prevented:!1};let r=n.hostEl.querySelector(`textarea`);if(!(r instanceof HTMLTextAreaElement))return{prevented:!1};let i=new window.DataTransfer;i.setData(`text/plain`,t);let a=new window.ClipboardEvent(`paste`,{clipboardData:i,bubbles:!0,cancelable:!0});return r.dispatchEvent(a),{prevented:a.defaultPrevented}},dispatchCopyFromTextarea(e){let t=_m.get(e);if(!t||t instanceof Promise||t.disposed)return{prevented:!1,text:``};let n=t.hostEl.querySelector(`textarea`);if(!(n instanceof HTMLTextAreaElement))return{prevented:!1,text:``};let r=new window.DataTransfer,i=new window.ClipboardEvent(`copy`,{clipboardData:r,bubbles:!0,cancelable:!0});return n.dispatchEvent(i),{prevented:i.defaultPrevented,text:r.getData(`text/plain`)}}})}async function Ag(e,t){let n=Om()?11:12,r=await Ef({fontSize:n});if(!r)throw Error(`Failed to create terminal for ${e}`);let i=document.createElement(`div`);i.className=`terminal-session-host`,i.dataset.agentId=e,i.dataset.terminalFontSize=String(n),i.style.width=`100%`,i.style.height=`100%`,i.style.position=`relative`,i.style.overflow=`hidden`;let{terminal:a,fitAddon:o}=r;a.loadAddon(o);let s={agentId:e,hostEl:i,attachedMount:null,attachGeneration:0,terminal:a,fitAddon:o,unsubscribeOutput:null,selectionChangeDisposable:null,imeOverlayDisposables:[],resizeObserver:null,scrollChangeDisposable:null,backendConnectedHandler:null,clickHandler:null,pointerDownSelectionHandler:null,pointerMoveSelectionHandler:null,pointerUpSelectionHandler:null,mouseDownOpenTargetHandler:null,mouseDownSelectionHandler:null,mouseMoveSelectionHandler:null,mouseUpSelectionHandler:null,mouseUpOpenTargetHandler:null,doubleClickHandler:null,copyHandler:null,copyKeyHandler:null,clearKeyHandler:null,pasteHandler:null,inputFallbackKeydownHandler:null,inputFallbackHandler:null,inputFallbackTimer:null,lastTerminalDataAt:0,lastLinkHoverEvent:null,openModifierActive:!1,linkHoverHandler:null,linkHoverLeaveHandler:null,linkHoverKeyHandler:null,linkHoverBlurHandler:null,linkProviderDisposable:null,linkProviderHoverTarget:null,contextMenuHandler:null,contextMenuMouseDownHandler:null,contextMenuEl:null,contextMenuCleanup:null,contextMenuSelection:``,imeKeydownHandler:null,scrollIntentHandler:null,scrollKeyHandler:null,touchInteraction:null,inputHandler:t.onInput,resizeHandler:t.onResize,lastNotifiedResize:null,resizeNotificationCount:0,followOutputHandler:t.onFollowOutputChange??null,pathOpenHandler:t.onPathOpen??null,pathResolveHandler:t.onPathResolve??null,pathResolveCache:new Map,originalRender:null,snapshotOutput:``,snapshotOutputSeq:null,lastOutputSeq:null,terminalWriteQueue:Promise.resolve(),terminalWriteResolvers:new Set,snapshotCursor:null,bootstrapRefreshSeq:0,reconnectSnapshotSeq:0,needsReconnectOutputSync:!1,pendingSnapshotReplay:!1,bootstrappingSnapshot:!0,fixtureOverrideActive:!1,queuedOutput:[],suspendRendering:!1,cachedSelection:``,lastNonEmptySelection:``,openTargetMouseDown:null,dragSelection:null,suppressClickUntil:0,suppressOutputUntil:0,imeComposing:!1,suppressRendererCursor:!!t.suppressRendererCursor,rendererCursorWasVisible:void 0,inputCount:0,followOutput:!0,hasUnreadOutput:!1,preserveUnreadOutputUntilJump:!1,followCheckFrame:null,disposed:!1,bootstrapped:!0};a.onData(e=>{s.disposed||s.attachedMount===null||(s.fixtureOverrideActive=!1,s.lastTerminalDataAt=Date.now(),s.inputCount+=1,s.contextMenuSelection=``,s.lastNonEmptySelection=``,s.inputHandler(e))}),a.onResize(({cols:e,rows:t})=>{Eh(s,e,t)}),Dg(s,e),a.open(i),Gh(s),a.syncAppearanceTheme?.(),requestAnimationFrame(()=>{s.disposed||a.syncAppearanceTheme?.()}),Sh(s),yh(s,!1);let c=a.onSelectionChange?.(()=>{s.cachedSelection=ap(a),s.cachedSelection&&(s.lastNonEmptySelection=op(s.cachedSelection))});s.selectionChangeDisposable=c?()=>c.dispose():null;let l=a.onScroll?.(()=>{gh(s)}),u=a.onRender?.(()=>{gh(s)});s.scrollChangeDisposable=l||u?()=>{l?.dispose(),u?.dispose()}:null;let d=()=>Dh(s);window.addEventListener(`farming:backend-connected`,d),s.backendConnectedHandler=d,Ch(s);let f=e=>{wf(a)||Xp(e.target)};i.addEventListener(`keydown`,f,!1),s.inputFallbackKeydownHandler=f;let p=e=>{if(s.imeComposing||typeof a.input!=`function`)return;let t=e.target;if(!Xp(t))return;let n=Date.now();s.inputFallbackTimer!==null&&window.clearTimeout(s.inputFallbackTimer),s.inputFallbackTimer=window.setTimeout(()=>{if(s.inputFallbackTimer=null,!Zp({isXterm:wf(a),imeComposing:s.imeComposing,text:t.value,terminal:a}))return;let e=a.input;if(typeof e!=`function`)return;let r=t.value;r&&(t.value=``,!Qp(s.lastTerminalDataAt,n)&&e(r,!0))},80)};i.addEventListener(`input`,p,!1),s.inputFallbackHandler=p;let m=t=>{let n=zh(s,t),r=t.button===0&&n?ng(s,t):null;if(r)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),sg(r),s.suppressClickUntil=Date.now()+250,!0;if(s.pathOpenHandler&&t.button===0){let n=tg(s,t);if(n)return t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),s.pathOpenHandler(e,n),s.suppressClickUntil=Date.now()+250,!0}return!1},h=(e,t)=>{if(Om()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return!1;let n=Fh(s,e);return n?(s.dragSelection={start:n,active:!0,moved:!1,pointerId:t},!0):!1},g=e=>{let t=s.dragSelection;if(!t?.active||`pointerId`in e&&t.pointerId!==void 0&&e.pointerId!==t.pointerId)return!1;let n=Fh(s,e);return!n||n.col===t.start.col&&n.row===t.start.row&&!t.moved?!1:(t.moved=!0,Nh(s,t.start,n),e.preventDefault(),e.stopPropagation(),!0)},_=e=>{let t=s.dragSelection;return!t?.active||`pointerId`in e&&t.pointerId!==void 0&&e.pointerId!==t.pointerId||(s.dragSelection=null,!t.moved)?!1:(s.suppressClickUntil=Date.now()+250,s.cachedSelection=ap(a),e.preventDefault(),e.stopPropagation(),!0)},v=e=>{if(s.openTargetMouseDown=null,Om()||e.button!==0||e.ctrlKey||e.metaKey||e.altKey)return;let t=s.pathOpenHandler?$h(s,e):null;t?.pathTarget&&(s.openTargetMouseDown={x:e.clientX,y:e.clientY,pathTarget:t.pathTarget})};i.addEventListener(`mousedown`,v,!0),s.mouseDownOpenTargetHandler=v;let y=t=>{if(Om()||t.button!==0)return;if(zh(s,t)){let e=ng(s,t);if(e){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),sg(e),s.suppressClickUntil=Date.now()+250;return}}let n=s.openTargetMouseDown;if(s.openTargetMouseDown=null,n){if(Math.hypot(t.clientX-n.x,t.clientY-n.y)>4){s.suppressClickUntil=Date.now()+250;return}ig(s)||m(t)||(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Hh(s,n.pathTarget).then(t=>{if(!s.disposed){if(!t){Um(s);return}s.pathOpenHandler?.(e,t),s.suppressClickUntil=Date.now()+250}}))}};i.addEventListener(`mouseup`,y,!0),s.mouseUpOpenTargetHandler=y;let b=e=>{if(e.pointerType!==`touch`&&h(e,e.pointerId))try{s.hostEl.setPointerCapture(e.pointerId)}catch{}};if(!wf(a)){i.addEventListener(`pointerdown`,b,!0),s.pointerDownSelectionHandler=b;let e=e=>{e.pointerType!==`touch`&&g(e)};window.addEventListener(`pointermove`,e,!0),s.pointerMoveSelectionHandler=e;let t=e=>{if(e.pointerType===`touch`)return;let t=_(e);if(t||m(e),t||Date.now()<s.suppressClickUntil)try{s.hostEl.releasePointerCapture(e.pointerId)}catch{}};window.addEventListener(`pointerup`,t,!0),window.addEventListener(`pointercancel`,t,!0),s.pointerUpSelectionHandler=t;let n=e=>{s.dragSelection||h(e)};i.addEventListener(`mousedown`,n,!0),s.mouseDownSelectionHandler=n;let r=e=>{g(e)};window.addEventListener(`mousemove`,r,!0),s.mouseMoveSelectionHandler=r;let a=e=>{_(e)};window.addEventListener(`mouseup`,a,!0),s.mouseUpSelectionHandler=a}let x=e=>{if(!Om()){if(Date.now()<s.suppressClickUntil){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}m(e)||Um(s)}};i.addEventListener(`click`,x,!0),s.clickHandler=x;let S=e=>{if(wf(a)||Om())return;let t=Fh(s,e);t&&Mh(s,t.col,t.row)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())};i.addEventListener(`dblclick`,S,!0),s.doubleClickHandler=S;let C=e=>{if(!Km(s,e))return;let t=ig(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),e.clipboardData?.setData(`text/plain`,t))};i.addEventListener(`copy`,C,!0),document.addEventListener(`copy`,C,!0),s.copyHandler=C;let w=e=>{if(!Jm(s,e))return;let t=ig(s,{includeNativeFallback:!0});t&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),M(t))};document.addEventListener(`keydown`,w,!0),s.copyKeyHandler=w;let T=e=>{Zm(s,e)};a.attachCustomKeyEventHandler||(document.addEventListener(`keydown`,T,!0),s.clearKeyHandler=T);let E=e=>{let t=Qm(s);if(Jp(s.hostEl,e,t)){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();return}Yp(s.hostEl,e,t)&&(wf(s.terminal)||yg(s,e.clipboardData?.getData(`text/plain`)||``)&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()))};window.addEventListener(`paste`,E,!0),i.addEventListener(`paste`,E,!0),s.pasteHandler=E;let D=e=>{if(!$m(s)){ug(s);return}s.lastLinkHoverEvent=e,dg(s,e)||(s.linkProviderHoverTarget=null,lg(s,null)),pg(s),fg(s,e).then(t=>{!t||s.disposed||s.lastLinkHoverEvent!==e||(s.linkProviderHoverTarget={kind:`path`,text:t.text,...t.pathTarget?{pathTarget:t.pathTarget}:{}},lg(s,`path`))})};i.addEventListener(`mousemove`,D,!0),s.linkHoverHandler=D;let O=()=>{ug(s)};i.addEventListener(`mouseleave`,O,!0),s.linkHoverLeaveHandler=O;let k=e=>{if(!$m(s)){ug(s);return}e.type===`keydown`&&[`Control`,`Meta`].includes(e.key)?s.openModifierActive=!0:s.openModifierActive=Rh(e),s.lastLinkHoverEvent&&(![`Control`,`Meta`].includes(e.key)&&!s.openModifierActive||pg(s,s.openModifierActive))};window.addEventListener(`keydown`,k,!0),window.addEventListener(`keyup`,k,!0),s.linkHoverKeyHandler=k;let A=()=>{ug(s)};window.addEventListener(`blur`,A),s.linkHoverBlurHandler=A;let ee=e=>{e instanceof WheelEvent&&e.deltaY<0&&mp(s,!1,s.hasUnreadOutput),gh(s),window.setTimeout(()=>gh(s),80)};i.addEventListener(`wheel`,ee,!0),i.addEventListener(`pointerup`,ee,!0),s.scrollIntentHandler=ee;let j=e=>{th(s,e)};return a.attachCustomKeyEventHandler?a.attachCustomKeyEventHandler(e=>!(Zm(s,e)||th(s,e))):(document.addEventListener(`keydown`,j,!0),i.addEventListener(`keydown`,j,!0),s.scrollKeyHandler=j),Og(s),s.resizeObserver=new ResizeObserver(()=>{requestAnimationFrame(()=>{if(!s.disposed)try{o.fit(),Th(s,t.onResize)}catch{}})}),s.unsubscribeOutput=t.onSessionOutput(e,(e,t,n)=>{if(!s.disposed&&!(Date.now()<s.suppressOutputUntil)){if(s.bootstrappingSnapshot||s.pendingSnapshotReplay){s.queuedOutput.push({data:e,replace:t,outputSeq:n});return}uh(s,e,t,n)}}),kg(),s}async function jg(e,t){let n=_m.get(e);if(n)return n instanceof Promise?n:Promise.resolve(n);let r=Ag(e,t).then(t=>(_m.set(e,t),t)).catch(n=>{throw _m.delete(e),t.onError?.(n instanceof Error?n:Error(String(n))),n});return _m.set(e,r),r}function Mg(e,t,n){let r=e.followOutput,i=up(e.terminal),a=lp(e.terminal),o=e.hasUnreadOutput;requestAnimationFrame(()=>{if(rh(e,n)){try{e.fitAddon.fit()}catch{}Th(e,t.onResize),Mp(e,i,a,r,o),Ep(e),t.autoFocus&&!Om()&&Wm(e.hostEl)&&wh(e,n),requestAnimationFrame(()=>{if(rh(e,n)){try{e.fitAddon.fit()}catch{}Th(e,t.onResize),Mp(e,i,a,r,o),Ep(e),window.setTimeout(()=>{rh(e,n)&&Vm(e).finally(()=>{rh(e,n)&&(e.snapshotOutput&&Date.now()>=e.suppressOutputUntil?(e.pendingSnapshotReplay=!0,ih(e,n)):(e.bootstrappingSnapshot=!1,e.pendingSnapshotReplay=!1,dh(e),ah(e,n)),t.onReady?.())})},120)}})}})}async function Ng(e,t){if(t.signal?.aborted)return;let n=await jg(e,t);if(n.disposed||t.signal?.aborted||_m.get(e)!==n)return;let r=Up(n);km(n,t.mountEl),Tg(n),n.inputHandler=t.onInput,n.resizeHandler=t.onResize,n.followOutputHandler=t.onFollowOutputChange??null,n.pathOpenHandler=t.onPathOpen??null,n.pathResolveHandler=t.onPathResolve??null,pp(n),bh(n,!!t.suppressRendererCursor),Mg(n,t,r),ah(n,r)}async function Pg(e,t){let n=_m.get(e);if(!n)return;let r=await n;r.disposed||_m.get(e)===r&&Gp(r,t)&&jm(r)}async function Fg(e){let t=_m.get(e);if(!t)return``;let n=await t;return n.disposed?``:(n.cachedSelection=ap(n.terminal),n.cachedSelection&&(n.lastNonEmptySelection=op(n.cachedSelection)),n.cachedSelection)}function Ig(e){let t=_m.get(e);return!t||t instanceof Promise||t.disposed?``:(t.cachedSelection=ap(t.terminal),t.cachedSelection&&(t.lastNonEmptySelection=op(t.cachedSelection)),t.cachedSelection)}async function Lg(e){let t=_m.get(e);if(!t)return;_m.delete(e);let n=await t;n.disposed||(n.disposed=!0,hh(n),Fp(n),n.unsubscribeOutput?.(),n.selectionChangeDisposable?.(),n.scrollChangeDisposable?.(),n.backendConnectedHandler&&window.removeEventListener(`farming:backend-connected`,n.backendConnectedHandler),n.imeOverlayDisposables.forEach(e=>e()),n.resizeObserver?.disconnect(),n.followCheckFrame!==null&&cancelAnimationFrame(n.followCheckFrame),n.clickHandler&&n.hostEl.removeEventListener(`click`,n.clickHandler,!0),n.pointerDownSelectionHandler&&n.hostEl.removeEventListener(`pointerdown`,n.pointerDownSelectionHandler,!0),n.pointerMoveSelectionHandler&&window.removeEventListener(`pointermove`,n.pointerMoveSelectionHandler,!0),n.pointerUpSelectionHandler&&(window.removeEventListener(`pointerup`,n.pointerUpSelectionHandler,!0),window.removeEventListener(`pointercancel`,n.pointerUpSelectionHandler,!0)),n.mouseDownOpenTargetHandler&&n.hostEl.removeEventListener(`mousedown`,n.mouseDownOpenTargetHandler,!0),n.mouseDownSelectionHandler&&n.hostEl.removeEventListener(`mousedown`,n.mouseDownSelectionHandler,!0),n.mouseMoveSelectionHandler&&window.removeEventListener(`mousemove`,n.mouseMoveSelectionHandler,!0),n.mouseUpSelectionHandler&&window.removeEventListener(`mouseup`,n.mouseUpSelectionHandler,!0),n.mouseUpOpenTargetHandler&&n.hostEl.removeEventListener(`mouseup`,n.mouseUpOpenTargetHandler,!0),n.doubleClickHandler&&n.hostEl.removeEventListener(`dblclick`,n.doubleClickHandler,!0),n.copyHandler&&(n.hostEl.removeEventListener(`copy`,n.copyHandler,!0),document.removeEventListener(`copy`,n.copyHandler,!0)),n.copyKeyHandler&&document.removeEventListener(`keydown`,n.copyKeyHandler,!0),n.clearKeyHandler&&document.removeEventListener(`keydown`,n.clearKeyHandler,!0),n.pasteHandler&&(window.removeEventListener(`paste`,n.pasteHandler,!0),n.hostEl.removeEventListener(`paste`,n.pasteHandler,!0)),n.inputFallbackKeydownHandler&&n.hostEl.removeEventListener(`keydown`,n.inputFallbackKeydownHandler,!1),n.inputFallbackHandler&&n.hostEl.removeEventListener(`input`,n.inputFallbackHandler,!1),n.inputFallbackTimer!==null&&(window.clearTimeout(n.inputFallbackTimer),n.inputFallbackTimer=null),n.linkHoverHandler&&n.hostEl.removeEventListener(`mousemove`,n.linkHoverHandler,!0),n.linkHoverLeaveHandler&&n.hostEl.removeEventListener(`mouseleave`,n.linkHoverLeaveHandler,!0),n.linkHoverKeyHandler&&(window.removeEventListener(`keydown`,n.linkHoverKeyHandler,!0),window.removeEventListener(`keyup`,n.linkHoverKeyHandler,!0)),n.linkHoverBlurHandler&&window.removeEventListener(`blur`,n.linkHoverBlurHandler),n.linkProviderDisposable?.(),n.contextMenuHandler&&(n.hostEl.removeEventListener(`contextmenu`,n.contextMenuHandler,!0),window.removeEventListener(`contextmenu`,n.contextMenuHandler,!0)),n.contextMenuMouseDownHandler&&(n.hostEl.removeEventListener(`mousedown`,n.contextMenuMouseDownHandler,!0),window.removeEventListener(`mousedown`,n.contextMenuMouseDownHandler,!0)),mg(n),n.scrollIntentHandler&&(n.hostEl.removeEventListener(`wheel`,n.scrollIntentHandler,!0),n.hostEl.removeEventListener(`pointerup`,n.scrollIntentHandler,!0)),n.scrollKeyHandler&&(document.removeEventListener(`keydown`,n.scrollKeyHandler,!0),n.hostEl.removeEventListener(`keydown`,n.scrollKeyHandler,!0)),n.touchInteraction&&(n.touchInteraction.stopTouchMomentum(),n.hostEl.removeEventListener(`pointerdown`,n.touchInteraction.pointerDownHandler,!0),n.hostEl.removeEventListener(`pointermove`,n.touchInteraction.pointerMoveHandler,!0),n.hostEl.removeEventListener(`pointerup`,n.touchInteraction.pointerUpHandler,!0),n.hostEl.removeEventListener(`pointercancel`,n.touchInteraction.pointerUpHandler,!0),n.hostEl.removeEventListener(`lostpointercapture`,n.touchInteraction.pointerUpHandler,!0)),n.originalRender&&n.terminal.renderer&&(n.terminal.renderer.render=n.originalRender),n.terminal.dispose(),n.hostEl.remove())}async function Rg(e){let t=new Set(e),n=[..._m.keys()].filter(e=>!t.has(e));await Promise.all(n.map(e=>Lg(e)))}function zg(e){let t=_m.get(e);if(!t)return Promise.resolve(!1);if(typeof t.then!=`function`){let e=t;return Promise.resolve(Um(e))}return t.then(e=>Um(e))}async function Bg(e,t={}){let n=_m.get(e);if(!n)return!1;let r=await n;if(r.disposed||!Qm(r))return!1;let i=r.followOutput,a=up(r.terminal),o=lp(r.terminal),s=r.hasUnreadOutput,c=()=>{if(!(r.disposed||!Qm(r))){try{r.fitAddon.fit()}catch{}Th(r,r.resizeHandler,{force:!0}),Mp(r,a,o,i,s),Ep(r),t.autoFocus&&!Om()&&Wm(r.hostEl)&&wh(r,r.attachGeneration)}};return requestAnimationFrame(()=>{c(),requestAnimationFrame(c)}),!0}async function Vg(e){let t=_m.get(e);if(!t)return;let n=await t;n.disposed||(n.touchInteraction?.stopTouchMomentum(),kp(n,{allowClearUnread:!0}))}async function Hg(e,t,n=`next`,r={}){let i=_m.get(e);if(!i)return{found:!1,resultIndex:0,resultCount:0};let a=await i;return a.disposed||typeof a.terminal.search!=`function`?{found:!1,resultIndex:0,resultCount:0}:a.terminal.search(t,n,r)}async function Ug(e){let t=_m.get(e);if(!t)return;let n=await t;n.disposed||n.terminal.clearSearch?.()}function Wg({agentId:e,containerRef:t,onInput:n,onResize:r,onSessionOutput:i,suppressRendererCursor:a=!1,onFollowOutputChange:o,onPathOpen:s,onPathResolve:c,onReady:l,onError:u}){let d=(0,W.useRef)({onInput:n,onResize:r,onSessionOutput:i,onFollowOutputChange:o,onPathOpen:s,onPathResolve:c,onReady:l,onError:u});d.current={onInput:n,onResize:r,onSessionOutput:i,onFollowOutputChange:o,onPathOpen:s,onPathResolve:c,onReady:l,onError:u};let f=(0,W.useCallback)(e=>{d.current.onInput(e)},[]),p=(0,W.useCallback)((e,t)=>d.current.onResize(e,t),[]),m=(0,W.useCallback)((e,t)=>d.current.onSessionOutput(e,t),[]),h=(0,W.useCallback)(e=>{d.current.onFollowOutputChange?.(e)},[]),g=(0,W.useCallback)((e,t)=>{d.current.onPathOpen?.(e,t)},[]),_=(0,W.useCallback)((e,t)=>d.current.onPathResolve?.(e,t)??null,[]),v=(0,W.useCallback)(()=>{d.current.onReady?.()},[]),y=(0,W.useCallback)(e=>{d.current.onError?.(e)},[]);return(0,W.useEffect)(()=>{if(!e||!t.current)return;let n=t.current,r=new AbortController,i=!1;return n.replaceChildren(),Ng(e,{mountEl:n,onInput:f,onResize:p,onSessionOutput:m,suppressRendererCursor:a,onFollowOutputChange:h,onPathOpen:g,onPathResolve:_,onError:y,signal:r.signal,onReady:()=>{i||v()}}).catch(e=>{console.error(`Failed to attach terminal session:`,e),y(e instanceof Error?e:Error(String(e)))}),()=>{i=!0,r.abort(),Pg(e,n).catch(e=>{console.error(`Failed to detach terminal session:`,e)})}},[e,t,y,h,f,g,_,v,p,m,a]),{focus:(0,W.useCallback)(()=>{let n=t.current;!e||!n||zg(e).then(t=>{if(!t)return Ng(e,{mountEl:n,onInput:f,onResize:p,onSessionOutput:m,autoFocus:!0,suppressRendererCursor:a,onFollowOutputChange:h,onPathOpen:g,onPathResolve:_,onError:y,onReady:v})}).catch(e=>{console.error(`Failed to focus terminal session:`,e),y(e instanceof Error?e:Error(String(e)))})},[e,t,y,h,f,g,_,v,p,m,a]),refreshLayout:(0,W.useCallback)((t={})=>{e&&Bg(e,t).catch(e=>{console.error(`Failed to refresh terminal layout:`,e)})},[e]),getSelection:(0,W.useCallback)(async()=>e?Fg(e):``,[e]),getSelectionNow:(0,W.useCallback)(()=>e?Ig(e):``,[e]),scrollToBottom:(0,W.useCallback)(()=>{e&&Vg(e).catch(e=>{console.error(`Failed to scroll terminal session to bottom:`,e)})},[e]),search:(0,W.useCallback)((t,n=`next`,r)=>e?Hg(e,t,n,r):Promise.resolve({found:!1,resultIndex:0,resultCount:0}),[e]),clearSearch:(0,W.useCallback)(()=>e?Ug(e):Promise.resolve(),[e])}}function Gg(e){let t=String(e||``).trim().split(/\s+/)[0]||``;return[`claude`,`codex`,`qwen`,`opencode`,`qodercli`,`aider`,`github-copilot-cli`,`amazon-q`].includes(t)}function Kg(){return L()}function qg(e){return(e.metaKey&&!e.ctrlKey||e.ctrlKey&&!e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`}function Jg(e){return e.key===`F3`&&!e.metaKey&&!e.ctrlKey&&!e.altKey}function Yg(e){if(!e.altKey||e.metaKey||e.ctrlKey||e.shiftKey)return null;let t=e.code||`Key${e.key.toUpperCase()}`;return t===`KeyC`?`caseSensitive`:t===`KeyW`?`wholeWord`:t===`KeyR`?`regex`:null}function Xg(e,t){return!(e instanceof Node)||t?.contains(e)?!0:e===document.body||e===document.documentElement}function Zg(e,t,n){return!e.trim()||!t?``:t.found?typeof t.resultCount==`number`&&t.resultCount>0&&typeof t.resultIndex==`number`&&t.resultIndex>=0?n.terminalSearchResults(t.resultIndex+1,t.resultCount):``:n.terminalSearchNoResults}function Qg(e){let t=e.replace(/\r/g,``).trim();if(!t)return``;let n=t.split(`
73
+ `).map(e=>e.trim()).filter(Boolean);if(n.length!==1)return``;let r=n[0];return r?r.slice(0,240):``}function $g(e){return`code-terminal-search-button option${e?` active`:``}`}function e_({agent:e,active:t,focusSignal:n,onActivate:r,sendInput:i,resizeAgent:a,onSessionOutput:o,onOpenPath:s,onResolvePath:c,onFollowOutputChange:l,copy:u}){let d=(0,W.useRef)(null),f=(0,W.useRef)(null),p=(0,W.useRef)(null),[m,h]=(0,W.useState)({following:!0,hasUnreadOutput:!1}),[g,_]=(0,W.useState)(!1),[v,y]=(0,W.useState)(``),[b,x]=(0,W.useState)({}),[S,C]=(0,W.useState)(null),[w,T]=(0,W.useState)(null),E=e.codexCliObserverDeferred===!0,D=(0,W.useCallback)(t=>{E||i(t,e.id)},[e.id,E,i]),O=(0,W.useCallback)((t,n)=>a(e.id,t,n),[e.id,a]),k=(0,W.useCallback)(t=>{h(t),l?.(e.id,t)},[e.id,l]),A=(0,W.useCallback)(()=>{T(null)},[]),ee=(0,W.useCallback)(e=>{T(e.message||u.terminalSessionUnavailable)},[u.terminalSessionUnavailable]),{focus:j,refreshLayout:M,getSelectionNow:N,scrollToBottom:te,search:P,clearSearch:F}=Wg({agentId:e.id,containerRef:f,onInput:D,onResize:O,onSessionOutput:o,suppressRendererCursor:Gg(e.command),onFollowOutputChange:k,onPathOpen:s,onPathResolve:c,onReady:A,onError:ee}),ne=(0,W.useCallback)((e=!1)=>{window.requestAnimationFrame(()=>{M({autoFocus:e}),window.requestAnimationFrame(()=>M({autoFocus:e}))})},[M]);(0,W.useEffect)(()=>{t&&ne(!1)},[t,ne]),(0,W.useEffect)(()=>{!t||n<=0||Kg()||(ne(!0),j())},[t,j,n,ne]),(0,W.useEffect)(()=>()=>{F()},[F]);let I=(0,W.useCallback)((e,t=`next`,n)=>{let r=e.trim();if(!r){C(null),F();return}P(r,t,{...b,...n}).then(C).catch(e=>{console.error(`Failed to search terminal:`,e),C({found:!1,resultIndex:0,resultCount:0})})},[F,P,b]),L=(0,W.useCallback)(e=>{x(t=>({...t,[e]:t[e]!==!0}))},[]),re=(0,W.useCallback)(()=>{let e=Qg(N());e&&(y(e),I(e,`next`,{incremental:!0})),_(!0),window.requestAnimationFrame(()=>{let e=p.current;e?.focus(),e?.select()})},[N,I]),R=(0,W.useCallback)(()=>{_(!1),C(null),F(),Kg()||j()},[F,j]),z=(0,W.useCallback)(e=>{let t=Yg(e.nativeEvent);if(t){e.preventDefault(),e.stopPropagation(),L(t);return}e.target===p.current&&e.key===`Enter`&&(e.preventDefault(),I(v,e.shiftKey?`previous`:`next`)),e.key===`Escape`&&(e.preventDefault(),R())},[R,I,v,L]);(0,W.useEffect)(()=>{g&&I(v,`next`,{incremental:!0})},[I,g,v]);let ie=(0,W.useCallback)(e=>{if(Xg(e.target,d.current)){if(qg(e)){e.preventDefault(),e.stopPropagation(),re();return}if(g&&Jg(e)){e.preventDefault(),e.stopPropagation(),I(v,e.shiftKey?`previous`:`next`);return}g&&e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),R())}},[R,re,I,g,v]);(0,W.useEffect)(()=>{if(!t)return;let e=e=>{ie(e)};return window.addEventListener(`keydown`,e,!0),()=>{window.removeEventListener(`keydown`,e,!0)}},[t,ie]);let V=(0,W.useCallback)(n=>{let i=n?.target,a=i instanceof Element&&i.closest(`.xterm`),o=n&&`pointerType`in n?n.pointerType:``;if(n&&n.button!==0){t||r(e.id,{focusTerminal:!1});return}if(a){t||r(e.id,{focusTerminal:!1}),(!Kg()||o&&o!==`touch`)&&j();return}r(e.id),!(Kg()&&(!o||o===`touch`))&&j()},[t,e.id,j,r]),ae=(0,W.useCallback)(()=>{te(),!Kg()&&j()},[j,te]),oe=(0,W.useCallback)(()=>{T(null),j()},[j]),ce=!m.following||m.hasUnreadOutput,ue=Zg(v,S,u);return(0,K.jsxs)(`section`,{className:`code-terminal-pane ${t?`active`:``}`,"data-testid":`code-terminal-pane`,"data-agent-id":e.id,ref:d,onKeyDownCapture:ie,onPointerDown:V,children:[(0,K.jsx)(`div`,{className:`code-terminal-container terminal-container`,"data-testid":`code-terminal-container`,ref:f}),E?(0,K.jsx)(`div`,{className:`code-terminal-status-card`,"data-testid":`code-terminal-app-server-ready`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:(0,K.jsx)(`span`,{children:u.appServerWaitingForFirstMessage})}):w?(0,K.jsxs)(`div`,{className:`code-terminal-status-card`,"data-testid":`code-terminal-status-card`,title:w,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`span`,{children:u.terminalSessionUnavailable}),(0,K.jsx)(`button`,{type:`button`,onClick:oe,children:u.retry})]}):null,g?(0,K.jsxs)(`form`,{className:`code-terminal-search`,"data-testid":`code-terminal-search`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onSubmit:e=>{e.preventDefault(),I(v,`next`)},onKeyDown:z,children:[(0,K.jsx)(`input`,{ref:p,type:`search`,name:`farming-terminal-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:v,placeholder:u.terminalSearchPlaceholder,"aria-label":u.terminalSearchPlaceholder,"data-testid":`code-terminal-search-input`,spellCheck:!1,enterKeyHint:`search`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,onChange:e=>y(e.target.value)}),(0,K.jsx)(`span`,{className:`code-terminal-search-status ${S&&!S.found?`empty`:``}`,children:ue}),(0,K.jsx)(`button`,{type:`button`,className:$g(b.caseSensitive),"aria-label":u.terminalSearchCaseSensitive,"aria-pressed":b.caseSensitive===!0,title:u.terminalSearchCaseSensitive,"data-testid":`code-terminal-search-case-sensitive`,onClick:()=>L(`caseSensitive`),children:(0,K.jsx)(de,{})}),(0,K.jsx)(`button`,{type:`button`,className:$g(b.wholeWord),"aria-label":u.terminalSearchWholeWord,"aria-pressed":b.wholeWord===!0,title:u.terminalSearchWholeWord,"data-testid":`code-terminal-search-whole-word`,onClick:()=>L(`wholeWord`),children:(0,K.jsx)(B,{})}),(0,K.jsx)(`button`,{type:`button`,className:$g(b.regex),"aria-label":u.terminalSearchRegex,"aria-pressed":b.regex===!0,title:u.terminalSearchRegex,"data-testid":`code-terminal-search-regex`,onClick:()=>L(`regex`),children:(0,K.jsx)(se,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":u.terminalSearchPrevious,title:u.terminalSearchPrevious,onClick:()=>I(v,`previous`),children:(0,K.jsx)(he,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button`,"aria-label":u.terminalSearchNext,title:u.terminalSearchNext,onClick:()=>I(v,`next`),children:(0,K.jsx)(_e,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-search-button close`,"aria-label":u.terminalSearchClose,title:u.terminalSearchClose,onClick:R,children:(0,K.jsx)(le,{})})]}):null,ce?(0,K.jsx)(`button`,{type:`button`,className:`code-terminal-jump-bottom`,"data-testid":`code-terminal-jump-bottom`,"aria-label":`Jump to latest output`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),ae()},children:(0,K.jsx)(_e,{})}):null]})}function t_(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function n_(e){let t=e[e.length-1];if(String(t?.type||``).toLowerCase()===`thought`)return`thinking`;let n=t&&t_(t)?t:void 0;if(!n)for(let t=e.length-1;t>=0;--t){let r=e[t];if(r&&String(r.type||``).toLowerCase()!==`plan`&&t_(r)){n=r;break}}if(!n)return`processing`;let r=String(n.type||``).toLowerCase(),i=String(n.kind||``).toLowerCase();return i===`think`?`thinking`:r===`plan`?`plan`:r===`patch`||[`edit`,`delete`,`move`].includes(i)?`editing`:i===`execute`?`running`:i===`read`?`reading`:i===`search`?`searching`:i===`fetch`?`fetching`:r===`tool`?`tool`:`processing`}function r_(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n||String(n.type||``).toLowerCase()!==`plan`||!t_(n))continue;let r=Number(n.completedSteps),i=Number(n.totalSteps);return!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<=0||r>i?null:{completed:r,total:i}}return null}function i_(e,t=10){let n=r_(e);if(!n)return``;let r=[...e].reverse().find(e=>String(e.type||``).toLowerCase()===`plan`&&t_(e)),i=String(r?.currentStep||``).trim().replace(/\s+/g,` `);if(!i)return``;let a=`${n.completed}/${n.total} `,o=Math.max(0,t-[...a].length);if(o<=0)return a.trim();let s=[...i];return`${a}${s.length<=o?i:`${s.slice(0,Math.max(1,o-1)).join(``)}…`}`}function a_({terminalId:e,output:t,interactive:n,onInput:r,onResize:i}){let a=(0,W.useRef)(null),o=(0,W.useRef)(null),s=(0,W.useRef)(``),c=(0,W.useRef)(t),l=(0,W.useRef)(n),u=(0,W.useRef)(r),d=(0,W.useRef)(i),f=(0,W.useRef)(``),[p,m]=(0,W.useState)(``);return c.current=t,l.current=n,u.current=r,d.current=i,(0,W.useEffect)(()=>{let e=a.current;if(!e)return;let t=!1,n=null,r;return Cf({fontSize:12}).then(({terminal:i,fitAddon:a})=>{if(t){i.dispose(),a.dispose();return}i.loadAddon(a),i.open(e),e.querySelector(`textarea`)?.setAttribute(`aria-label`,`Terminal input`),o.current=i;let p=c.current;p&&i.write(p),s.current=p;let h=i.onData(e=>{!l.current||!u.current||u.current(e).then(()=>m(``)).catch(e=>{m(e instanceof Error?e.message:`Failed to send terminal input`)})}),g=()=>{if(!e.isConnected||e.clientWidth<=0||e.clientHeight<=0)return;a.fit();let t=Number(i.cols||0),n=Number(i.rows||0),r=`${t}x${n}`;!d.current||t<40||n<10||r===f.current||(f.current=r,d.current(t,n).catch(()=>{}))};n=new ResizeObserver(g),n.observe(e),window.requestAnimationFrame(g),r=()=>{n?.disconnect(),h.dispose(),a.dispose(),i.dispose()}}).catch(e=>{t||m(e instanceof Error?e.message:`Failed to start terminal view`)}),()=>{t=!0,o.current=null,r?.()}},[e]),(0,W.useEffect)(()=>{let e=o.current;!e||t===s.current||(t.startsWith(s.current)?e.write(t.slice(s.current.length)):(e.clearBuffer?.(),e.write(t)),s.current=t)},[t]),(0,K.jsxs)(`div`,{className:`code-acp-embedded-terminal ${n?`interactive`:`readonly`}`,"data-testid":`code-acp-embedded-terminal`,children:[(0,K.jsx)(`div`,{ref:a,className:`code-acp-embedded-terminal-host`,onClick:()=>o.current?.focus()}),(0,K.jsx)(`pre`,{className:`code-visually-hidden`,"aria-label":`Terminal output`,children:t}),p?(0,K.jsx)(`small`,{className:`code-codex-transcript-terminal-error`,role:`alert`,children:p}):null]})}var o_=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}};new class extends o_{};function s_(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function c_(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function l_(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function u_(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function d_(e,t){return l_(e,t,``)}function f_(e,t){return u_(e,t,``)}function p_(e,t){return t.slice(0,m_(e,t))}function m_(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function h_(e,t){let n=[];for(let r of Array.from(t.segment(e))){let e=r.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(e)?n[n.length-1]+=e:n.push(e)}return n}function g_(e,t){if(t)return v_(e,t)[1];let n;for(n=e.length-1;n>=0&&e[n].match(/\s/);n--);return e.substring(n+1)}function __(e,t){if(t)return v_(e,t)[0];let n=e.match(/^\s*/);return n?n[0]:``}function v_(e,t){if(!t)return[__(e),g_(e)];if(t.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);let n=h_(e,t),r=n[0],i=n[n.length-1];return[/\s/.test(r)?r:``,/\s/.test(i)?i:``]}var y_=`a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,b_=RegExp(`[${y_}]+|\\s+|[^${y_}]`,`ug`);new class extends o_{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=h_(e,r)}else n=e.match(b_)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&x_(n,i,r,e,t.intlSegmenter),n=e,r=null,i=null)}),(r||i)&&x_(n,i,r,null,t.intlSegmenter),e}};function x_(e,t,n,r,i){if(t&&n){let[a,o]=v_(t.value,i),[s,c]=v_(n.value,i);if(e){let r=s_(a,s);e.value=u_(e.value,s,r),t.value=d_(t.value,r),n.value=d_(n.value,r)}if(r){let e=c_(o,c);r.value=l_(r.value,c,e),t.value=f_(t.value,e),n.value=f_(n.value,e)}}else if(n){if(e){let e=__(n.value,i);n.value=n.value.substring(e.length)}if(r){let e=__(r.value,i);r.value=r.value.substring(e.length)}}else if(e&&r){let n=__(r.value,i),[a,o]=v_(t.value,i),s=s_(n,a);t.value=d_(t.value,s);let c=c_(d_(n,s),o);t.value=f_(t.value,c),r.value=l_(r.value,n,c),e.value=u_(e.value,n,n.slice(0,n.length-c.length))}else if(r){let e=__(r.value,i),n=p_(g_(t.value,i),e);t.value=f_(t.value,n)}else if(e){let n=p_(g_(e.value,i),__(t.value,i));t.value=d_(t.value,n)}}new class extends o_{tokenize(e){let t=RegExp(`(\\r?\\n)|[${y_}]+|[^\\S\\n\\r]+|[^${y_}]`,`ug`);return e.match(t)||[]}};var S_=new class extends o_{constructor(){super(...arguments),this.tokenize=w_}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
74
74
  `))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
75
75
  `))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
76
76
  `)&&(e=e.slice(0,-1)),t.endsWith(`
@@ -97,21 +97,21 @@ ${s.join(`
97
97
 
98
98
  `),detailTruncated:u.detailTruncated,status:$(e.status),...n.length>0?{terminalIds:n}:{},...d?{subagentSessionId:d}:{},...a.length>0?{images:a}:{},...o.length>0?{audios:o}:{},...s.length>0?{files:s}:{},...l.length>0?{changes:l}:{}}}if(e.type===`plan`){let t=nv(e.plan);if(!t)return null;let n=L_(I_(e.plan).entries).map(I_),r=n.filter(e=>e.status===`completed`).length,i=n.find(e=>[`in_progress`,`running`].includes($(e.status)));return{id:$(e.id),type:`plan`,title:`Plan`,detail:t,status:n.length>0&&n.every(e=>e.status===`completed`)?`completed`:`running`,completedSteps:r,totalSteps:n.length,currentStep:$(i?.content||i?.title)}}return e.type===`compaction`?{id:$(e.id),type:`compaction`,title:e.status===`completed`?`Context compacted`:`Compacting context`,detail:$(e.summary),status:$(e.status)||`completed`}:null}function av(e,t){return{id:e,internal:t,userMessage:``,userImages:[],userFiles:[],userAudios:[],finalMessage:``,startedAt:null,completedAt:null,durationMs:null,status:`completed`,processItems:[],assistantMessages:[]}}function ov(e,t){if(!e)return null;let n=e.assistantMessages[e.assistantMessages.length-1],r=e.processItems[e.processItems.length-1];e.internal&&n?.text?e.finalMessage=n.text:!t&&n?.text&&n.processItemId&&r?.id===n.processItemId&&(r.images||[]).length===0&&(r.audios||[]).length===0&&(r.files||[]).length===0&&(e.finalMessage=n.text,e.processItems.pop());let{internal:i,assistantMessages:a,...o}=e;return i&&(o.processItems=[]),o.userMessage||o.finalMessage||o.userImages.length>0||o.userAudios.length>0||o.userFiles.length>0||o.processItems.length>0?o:null}function sv(e,t={}){let n=I_(e),r=[],i=null,a=0,o=[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes($(n.state)),s=(e=!1)=>{let t=ov(i,e);t&&r.push(t),i=null};for(let e of L_(n.entries)){let t=I_(e);if(t.type===`message`&&t.role===`user`){s();let e=$(t.id)||String(++a);i=av(`acp-turn-${e}`,t.internal===!0),i.startedAt=t.turnStartedAt==null?null:Number(t.turnStartedAt),i.completedAt=t.turnCompletedAt==null?null:Number(t.turnCompletedAt),i.durationMs=Number.isFinite(Number(t.turnDurationMs))?Number(t.turnDurationMs):null,t.internal||(i.userMessage=R_(t.content),i.userImages=Y_(t.content,e),i.userAudios=X_(t.content,e),i.userFiles=Z_(t.content,e));continue}if(i||=av(`acp-segment-${++a}`,t.internal===!0),t.internal===!0&&!i.internal&&(s(),i=av(`acp-segment-${++a}`,!0)),t.type===`message`&&t.role===`assistant`){let e=z_(R_(t.content)),n=$(t.id)||`assistant`,r=Y_(t.content,n),o=X_(t.content,n),s=Z_(t.content,n),c=e?`acp-progress-${$(t.id)||String(++a)}`:``;i.assistantMessages.push({text:e,processItemId:c}),!i.internal&&(e||r.length>0||o.length>0||s.length>0)&&i.processItems.push({id:c,type:`progress`,title:`Progress update`,detail:e,status:`completed`,...r.length>0?{images:r}:{},...o.length>0?{audios:o}:{},...s.length>0?{files:s}:{}});continue}if(i.internal||t.internal===!0)continue;let n=iv(t);n&&i.processItems.push(n)}s(o);let c=r[r.length-1];c&&o?c.status=`inProgress`:c&&[`cancelled`,`canceled`,`max_tokens`,`max_turn_requests`,`refusal`,`error`,`cancel_error`].includes($(n.stopReason).toLowerCase())&&(c.status=`interrupted`);let l=Number.isFinite(Number(t.maxTurns))?Math.max(1,Math.floor(Number(t.maxTurns))):80,u=r.slice(-l);return{version:2,available:u.length>0,reason:u.length>0?void 0:`empty-acp-session`,sessionId:$(n.sessionId),title:$(n.title),updatedAt:$(n.updatedAt),source:`acp`,state:$(n.state),error:$(n.error),errorKind:$(n.errorKind),revision:Number(n.revision||0),delta:n.delta===!0,replaceFromTurnId:n.delta===!0?$(u[0]?.id):``,stopReason:$(n.stopReason),hasMoreBefore:n.hasMoreBefore===!0||r.length>u.length,turnLimit:l,truncated:n.truncated===!0,turns:u}}function cv(e){let t=String(e.type||``).trim().toLowerCase(),n=String(e.kind||``).trim().toLowerCase();return t===`thought`||t===`progress`||t===`plan`?null:t===`patch`||[`edit`,`delete`,`move`].includes(n)?`edit`:n===`read`||t===`file-read`||t===`read`?`read`:n===`search`||t===`search`||t===`web-search`?`search`:n===`execute`||t===`command`?`execute`:n===`fetch`?`fetch`:`tool`}function lv(e,t){return e===`edit`?t===1?`Edited a file`:`Edited files`:e===`read`?t===1?`Read a file`:`Read files`:e===`search`?t===1?`Searched code`:`Searched code ${t} times`:e===`execute`?t===1?`Ran a command`:`Ran commands`:e===`fetch`?t===1?`Fetched a resource`:`Fetched resources`:t===1?`Used a tool`:`Used tools`}function uv(e){let t=e.filter(e=>[`failed`,`rejected`,`cancelled`,`canceled`].includes(String(e.status||``).toLowerCase())).length;if(t>0)return t===1?`Action failed`:`${t} actions failed`;let n=new Map;for(let t of e){let e=cv(t);e&&n.set(e,(n.get(e)||0)+1)}return n.size===0?`Reasoning`:[...n.entries()].map(([e,t],n)=>{let r=lv(e,t);return n===0?r:`${r.charAt(0).toLowerCase()}${r.slice(1)}`}).join(`, `)}function dv(e){return String(e.type||``).trim().toLowerCase()===`progress`}function fv(e){return e.trim().replace(/\\/g,`/`)}function pv(e){return fv(e).replace(/\/+$/,``)}function mv(e){let t=pv(e);return/^\/Users\/[^/]+/.exec(t)?.[0]??``}function hv(e,t){let n=fv(e).replace(/\/+$/,``),r=pv(t);if(!n||!r)return null;if(n===r)return``;let i=`${r}/`;return n.startsWith(i)?n.slice(i.length):null}function gv(e,t){let n=fv(e);if(!n||n.startsWith(`../`))return null;if(n.startsWith(`./`))return n.replace(/^\.\/+/,``);if(n.startsWith(`~/`)){let e=mv(t);return e?hv(`${e}/${n.slice(2)}`,t):null}return n.startsWith(`/`)?hv(n,t):n}function _v(e,t){let n=e.processItems[e.processItems.length-1],r=t.processItems[t.processItems.length-1];return e.status!==`inProgress`&&t.status!==`inProgress`&&e.userMessage===t.userMessage&&e.finalMessage===t.finalMessage&&e.startedAt===t.startedAt&&e.completedAt===t.completedAt&&e.durationMs===t.durationMs&&e.userImages?.length===t.userImages?.length&&e.userAudios?.length===t.userAudios?.length&&e.userFiles?.length===t.userFiles?.length&&e.processItems.length===t.processItems.length&&n?.id===r?.id&&n?.status===r?.status&&n?.title===r?.title&&n?.detail===r?.detail}function vv(e,t){if(!e||!t||e.sessionId!==t.sessionId)return t;let n=new Map(e.turns.filter(e=>e.status!==`inProgress`).map(e=>[e.id,e]));return{...t,turns:t.turns.map(e=>{let t=n.get(e.id);return t&&_v(t,e)?t:e})}}function yv(e,t){if(!t?.delta)return vv(e,t);if(!e||e.sessionId!==t.sessionId)return t;if(!t.replaceFromTurnId||t.turns.length===0)return{...e,...t,available:e.available,hasMoreBefore:e.hasMoreBefore,turns:e.turns};let n=e.turns.findIndex(e=>e.id===t.replaceFromTurnId);if(n<0){let n=new Set(e.turns.map(e=>e.id)),r=t.turns.filter(e=>!n.has(e.id)),i=[...e.turns,...r],a=e.turnLimit&&i.length>e.turnLimit?i.slice(-e.turnLimit):i;return vv(e,{...e,...t,available:e.available||t.available,hasMoreBefore:e.hasMoreBefore||t.hasMoreBefore||a.length<i.length,turns:a})}return vv(e,{...t,available:e.available||t.available,hasMoreBefore:e.hasMoreBefore||t.hasMoreBefore,turns:[...e.turns.slice(0,n),...t.turns]})}var bv=new Map,xv=80,Sv=80,Cv=20,wv=20,Tv=1e3;function Ev(e){return e===`acp`?Cv:xv}var Dv=72,Ov=96;function kv(e){if(!e||!Number.isFinite(e)||e<1e3)return``;let t=Math.round(e/1e3);if(t<=0)return``;if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r?`${n}m ${r}s`:`${n}m`}function Av(e){let t=Number(e);if(!Number.isFinite(t)||t<=0)return``;let n=t<0xe8d4a51000?t*1e3:t;return kv(Math.max(0,Date.now()-n))}function jv(e,t){return{thinking:t.codexTranscriptThinking,running:t.codexTranscriptRunning,reading:t.codexTranscriptReading,searching:t.codexTranscriptSearching,editing:t.codexTranscriptEditing,plan:t.codexTranscriptPlanActive,fetching:t.codexTranscriptFetching,tool:t.codexTranscriptUsingTool,processing:t.codexTranscriptWorking}[n_(e.processItems)]}function Mv(e,t){let n=r_(e.processItems);return n?i_(e.processItems)||(n.total<=99?t.codexTranscriptPlanProgress(n.completed,n.total):t.codexTranscriptPlanActive):``}function Nv(e,t,n=t.codexTranscriptWorking,r=``){let i=kv(e.durationMs),a=e.status===`interrupted`?e.processItems.find(e=>e.type===`error`):void 0;return a?.title?a.title:i?t.codexTranscriptWorkedFor(i):e.status===`inProgress`?r||n:t.codexTranscriptProcess}function Pv(e,t){if(!(e.processItems.length<=0))return t.codexTranscriptProcessCount(e.processItems.length)}function Fv(e){let t=e.split(`
99
99
  `);return t.map((e,n)=>(0,K.jsxs)(`span`,{children:[e,n<t.length-1?(0,K.jsx)(`br`,{}):null]},n))}function Iv(e){return e.replace(/<oai-mem-citation>[\s\S]*?<\/oai-mem-citation>/g,``).trim()}function Lv(e){let t=e.trim();return Rv(t)?!1:/^[a-z][a-z\d+.-]*:/i.test(t)||zv(t)}function Rv(e){return/^[^/\s]+\.[A-Za-z0-9+_-]+:\d+(?::\d+(?:-\d+)?)?$/.test(e.trim())}function zv(e){return/^(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d+)?[/?#].*$/i.test(e.trim())}function Bv(e){let t=e.trim();return zv(t)?`https://${t}`:e}var Vv=new Set(`c.cc.cpp.cxx.h.hh.hpp.hxx.go.java.js.jsx.ts.tsx.mjs.cjs.json.jsonl.py.rb.rs.sh.bash.zsh.sql.md.mdx.txt.xml.html.css.scss.less.yaml.yml.toml.ini.conf.gradle.kt.kts.scala.proto.swift.vue.svelte.svg.png.jpg.jpeg.gif.webp`.split(`.`)),Hv=new Set([`BUILD`,`BUCK`,`Dockerfile`,`Makefile`,`WORKSPACE`]);function Uv(e){return e.replace(/:(\d+)(?::(\d+)(?:-(\d+))?)?$/,``)}function Wv(e){let t=e.split(/[\\/]/).filter(Boolean).pop()||e;if(Hv.has(t))return!0;let n=t.match(/\.([A-Za-z0-9+_-]+)$/);return n?Vv.has((n[1]||``).toLowerCase()):!1}function Gv(e){let t=e.trim();return!t||/\s/.test(t)||t.startsWith(`#`)||Lv(t)||/^[A-Z_][A-Z0-9_]*(?:\s+[A-Z_][A-Z0-9_]*)*$/.test(t)?!1:Wv(Uv(t))}function Kv(e){try{return decodeURI(e)}catch{return e}}function qv(e){let t=e.match(/:(\d+)(?::(\d+)(?:-(\d+))?)?$/);if(!t)return null;let n=Number(t[1]),r=t[2]?Number(t[2]):void 0,i=t[3]?Number(t[3]):void 0;return!Number.isFinite(n)||n<=0||r!==void 0&&(!Number.isFinite(r)||r<=0)||i!==void 0&&(!Number.isFinite(i)||i<=0)?null:{lineNumber:n,...r===void 0?{}:{column:r},...i===void 0?{}:{endColumn:i}}}function Jv(e,t){let n=Kv(e.trim()),r=Uv(n);if(!r.startsWith(`/`)||r.startsWith(`//`)||!Wv(r))return null;let i=gv(r,t||``),a=i?``:Ae(r);if(!i&&!a)return null;let o=qv(n);return{filePath:i||a,target:{...o||{},...!i&&a?{globalRoot:!0}:{}}}}function Yv(e,t){let n=e.trim();if(!n||n.startsWith(`#`)||Lv(n))return null;let r=Jv(n,t);if(r)return r;if(!Gv(n))return null;let i=Rf(n).find(e=>e.startIndex===0&&e.length===n.length&&e.pathTarget);if(!i?.pathTarget)return null;let a=i.pathTarget,o=gv(a.path,t||``);if(!o&&!a.path.startsWith(`/`))return null;let s=!o&&a.path.startsWith(`/`)?Ae(a.path):``;return!o&&!s?null:{filePath:o||s,target:{...a.lineNumber?{lineNumber:a.lineNumber,column:a.column,endColumn:a.endColumn}:{},...!o&&s?{globalRoot:!0}:{}}}}function Xv(e){let t=e.trim();if(!t)return!1;let n=Uv(t);return n.startsWith(`/`)||n.startsWith(`~/`)||n.startsWith(`./`)||n.startsWith(`../`)||n.includes(`/`)||/:(\d+)(?::(\d+)(?:-(\d+))?)?$/.test(t)}function Zv(e,t){let n=Uv(e.trim()).split(/[\\/]/).filter(Boolean).pop()||e.trim();return t&&t>1?`${n}:${t}`:n}function Qv(e){if(e==null||typeof e==`boolean`)return``;if(typeof e==`string`||typeof e==`number`)return String(e);if(Array.isArray(e))return e.map(Qv).join(``);if((0,W.isValidElement)(e)){let t=e.props;return Qv(t.children)}return``}function $v(e){return Qv(e).replace(/\n$/,``)}function ey(e){let t=W.Children.count(e)===1?W.Children.only(e):null;if(!(0,W.isValidElement)(t))return null;let n=t.props;return/\blanguage-mermaid\b/i.test(n.className||``)?$v(n.children):null}function ty(e,t){return t===`src`&&/^data:image\/(?:png|gif|jpe?g|webp|svg\+xml);base64,/i.test(e)||t===`href`&&Rv(e)?e:t===`href`&&zv(e)?Bv(e):Ce(e)}function ny({images:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-user-images`,"data-testid":`code-codex-transcript-user-images`,children:e.map(e=>(0,K.jsx)(`img`,{src:e.url,alt:e.alt||`Attached image`,loading:`lazy`,decoding:`async`},e.id))})}function ry(e){if(e.error)return e.error;if(e.resourceKind===`link`)return e.mimeType||`Resource link`;let t=e.content||``,n=t?t.split(`
100
- `).length:0,r=t.length;return`${n===1?`1 line`:`${n} lines`} · ${r===1?`1 char`:`${r} chars`}${e.truncated?` · truncated`:``}`}function iy(e){if(!e)return``;try{let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)?t.toString():``}catch{return``}}function ay({files:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-user-files`,"data-testid":`code-codex-transcript-user-files`,children:e.map(e=>{let t=e.content||``,n=!!t,r=e.resourceKind===`link`?iy(e.uri):``;return e.resourceKind===`link`?(0,K.jsxs)(`div`,{className:`code-codex-transcript-user-file code-codex-transcript-resource-link`,children:[(0,K.jsx)(oy,{filePath:e.name}),r?(0,K.jsx)(`a`,{href:r,target:`_blank`,rel:`noreferrer`,title:e.uri,children:e.name}):(0,K.jsx)(`span`,{title:e.uri,children:e.name}),(0,K.jsx)(`span`,{className:`code-codex-transcript-user-file-meta`,children:ry(e)})]},e.id):(0,K.jsxs)(`details`,{className:`code-codex-transcript-user-file ${e.error?`error`:``}`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(oy,{filePath:e.name}),(0,K.jsx)(`span`,{className:`code-codex-transcript-user-file-name`,title:e.name,children:e.name}),(0,K.jsx)(`span`,{className:`code-codex-transcript-user-file-meta`,children:ry(e)})]}),e.error?(0,K.jsx)(`div`,{className:`code-codex-transcript-user-file-error`,children:e.error}):n?(0,K.jsx)(`pre`,{children:t}):null]},e.id)})})}function oy({filePath:e}){let t=R(e);return(0,K.jsx)(`span`,{className:`code-codex-transcript-file-icon`,style:{WebkitMaskImage:`url("${t}")`,maskImage:`url("${t}")`},"aria-hidden":`true`})}function sy({children:e,filePath:t,lineNumber:n}){let r=Zv(t,n);return(0,K.jsxs)(`span`,{title:n&&n>1?`${t}:${n}`:t,children:[(0,K.jsx)(oy,{filePath:t}),(0,K.jsx)(`span`,{className:`code-codex-transcript-file-label`,children:r})]})}function cy({images:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-process-images`,"data-testid":`code-codex-transcript-process-images`,children:e.map(e=>(0,K.jsx)(`img`,{src:e.url,alt:e.alt||`Generated image`,loading:`lazy`,decoding:`async`},e.id))})}function ly({audios:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-audios`,"data-testid":`code-codex-transcript-audios`,children:e.map(e=>(0,K.jsxs)(`figure`,{children:[e.name?(0,K.jsx)(`figcaption`,{children:e.name}):null,(0,K.jsx)(`audio`,{controls:!0,preload:`metadata`,src:e.url,children:e.mimeType?(0,K.jsx)(`source`,{src:e.url,type:e.mimeType}):null})]},e.id))})}function uy(e){let t=e.terminal?.exitStatus;return t?t.signal?`Exited (${t.signal})`:`Exited ${t.exitCode??``}`.trim():e.terminal?.released?`Released`:`Running`}function dy(e){return[String(e.terminal?.command||``).trim(),...Array.isArray(e.terminal?.args)?e.terminal.args:[]].filter(Boolean).join(` `)||e.terminalId}function fy(e){return!Number.isFinite(e)||Number(e)<0?``:Number(e)<1e3?`${Math.round(Number(e))}ms`:`${(Number(e)/1e3).toFixed(+(Number(e)<1e4))}s`}function py({terminals:e,onStop:t,onInput:n,onResize:r}){let[i,a]=(0,W.useState)(``),[o,s]=(0,W.useState)(``),[c,l]=(0,W.useState)(``);return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-terminals`,"data-testid":`code-codex-transcript-terminals`,children:e.map(e=>{let u=dy(e),d=fy(e.terminal?.durationMs),f=e.terminal?.output||``;return(0,K.jsxs)(`section`,{className:`code-codex-transcript-terminal`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`code`,{title:u,children:u}),(0,K.jsx)(`span`,{children:uy(e)}),!e.terminal?.exitStatus&&!e.terminal?.released&&t?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-terminal-stop`,"data-testid":`code-acp-terminal-stop`,"aria-label":`Stop command`,title:`Stop command`,disabled:!!o,onClick:()=>{s(e.terminalId),l(``),t(e.terminalId).catch(e=>l(e instanceof Error?e.message:`Failed to stop command`)).finally(()=>s(``))},children:o===e.terminalId?(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`}):(0,K.jsx)(le,{})}):null,f?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-terminal-copy`,"aria-label":i===e.terminalId?`Copied terminal output`:`Copy terminal output`,title:i===e.terminalId?`Copied`:`Copy output`,onClick:()=>{Ky(f).then(t=>{t&&(a(e.terminalId),window.setTimeout(()=>a(t=>t===e.terminalId?``:t),1200))})},children:i===e.terminalId?(0,K.jsx)(me,{}):(0,K.jsx)(H,{})}):null]}),e.terminal?.cwd||d||e.terminal?.truncated?(0,K.jsxs)(`div`,{className:`code-codex-transcript-terminal-meta`,children:[e.terminal?.cwd?(0,K.jsx)(`span`,{title:e.terminal.cwd,children:e.terminal.cwd}):null,d?(0,K.jsx)(`span`,{children:d}):null,e.terminal?.truncated?(0,K.jsx)(`span`,{children:`Earlier output hidden`}):null]}):null,(0,K.jsx)(a_,{terminalId:e.terminalId,output:f,interactive:!!(e.terminal?.interactive&&!e.terminal.exitStatus&&!e.terminal.released&&n),onInput:n?t=>n(e.terminalId,t):void 0,onResize:r?(t,n)=>r(e.terminalId,t,n):void 0}),c?(0,K.jsx)(`div`,{className:`code-codex-transcript-terminal-error`,role:`alert`,children:c}):null]},e.terminalId)})})}function my({item:e}){let t=String(e.detail||``).trim(),n=e.changes||[],r=!!(t||n.length>0),i=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:e.title||`Action`}),_y(e.status)?(0,K.jsx)(`small`,{children:e.status}):null]});return r?(0,K.jsxs)(`details`,{className:`code-codex-transcript-subagent-action`,"data-testid":`code-codex-transcript-subagent-action`,children:[(0,K.jsxs)(`summary`,{children:[i,(0,K.jsx)(fe,{})]}),t?(0,K.jsx)(`div`,{className:`detail`,children:Fv(t)}):null,n.length>0?(0,K.jsx)(`div`,{className:`changes`,children:n.map((e,t)=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{title:e.path,children:e.path}),(0,K.jsxs)(`small`,{children:[e.added>0?`+${e.added}`:``,e.removed>0?` -${e.removed}`:``]})]},`${e.path}-${t}`))}):null]}):(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-action static`,children:i})}function hy({transcript:e,onStop:t}){let n=[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes(e.state||``),r=e.error?`Failed`:n?`Working`:`Completed`,i=e.turns.reduce((e,t)=>e+t.processItems.length,0),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.useState)(!1),[l,u]=(0,W.useState)(``);(0,W.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let d=(0,K.jsxs)(`div`,{className:`code-codex-transcript-subagent-entries`,children:[e.turns.map(e=>(0,K.jsxs)(`div`,{className:`code-codex-transcript-subagent-turn`,children:[e.userMessage?(0,K.jsx)(`div`,{className:`user`,children:Fv(e.userMessage)}):null,e.processItems.length>0?(0,K.jsx)(`div`,{className:`actions`,children:e.processItems.map(e=>(0,K.jsx)(my,{item:e},e.id))}):null,e.finalMessage?(0,K.jsx)(`div`,{className:`assistant`,children:Fv(e.finalMessage)}):null]},e.id)),e.turns.length===0?(0,K.jsx)(`div`,{className:`empty`,children:`No subagent output received yet`}):null]}),f=(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`span`,{children:e.title||`Subagent`}),(0,K.jsxs)(`span`,{className:`code-codex-transcript-subagent-meta`,title:e.sessionId,children:[e.turns.length,` `,e.turns.length===1?`turn`:`turns`,i>0?` · ${i} ${i===1?`action`:`actions`}`:``]}),(0,K.jsx)(`span`,{className:`code-codex-transcript-subagent-status ${e.error?`error`:n?`active`:``}`,children:r}),n&&t?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-subagent-control stop`,"data-testid":`code-acp-subagent-stop`,"aria-label":`Stop subagent`,title:`Stop subagent`,disabled:s,onClick:()=>{c(!0),u(``),t().catch(e=>u(e instanceof Error?e.message:`Failed to stop subagent`)).finally(()=>c(!1))},children:s?(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`}):(0,K.jsx)(le,{})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-subagent-control`,"data-testid":`code-acp-subagent-fullscreen`,"aria-label":a?`Close subagent details`:`Open subagent details`,title:a?`Close details`:`Open details`,onClick:()=>o(e=>!e),children:a?(0,K.jsx)(le,{}):(0,K.jsx)(`span`,{"aria-hidden":`true`,children:`↗`})})]});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`code-codex-transcript-subagent`,"data-testid":`code-codex-transcript-subagent`,children:[f,e.error?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`status`,children:e.error}):null,l?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`alert`,children:l}):null,d]}),a?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":`Subagent details`,children:(0,K.jsxs)(`div`,{className:`code-codex-transcript-subagent-dialog`,children:[f,e.error?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`status`,children:e.error}):null,l?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`alert`,children:l}):null,d]})}):null]})}function gy(e){let t=e.type.replace(/[^a-z0-9_-]/gi,``).toLowerCase()||`event`,n=(e.status||``).replace(/[^a-z0-9_-]/gi,``).toLowerCase();return[`code-codex-transcript-process-item`,t,n?`status-${n}`:``].filter(Boolean).join(` `)}function _y(e){let t=String(e||``).trim().toLowerCase();return!!t&&t!==`completed`&&t!==`success`}function vy(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function yy(e){return e.scrollHeight-e.clientHeight-e.scrollTop}function by(e){return yy(e)<=Ov}function xy(e){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?!1:!!(t.anchorNode&&e.contains(t.anchorNode)||t.focusNode&&e.contains(t.focusNode))}function Sy(e){let t=e.split(`
100
+ `).length:0,r=t.length;return`${n===1?`1 line`:`${n} lines`} · ${r===1?`1 char`:`${r} chars`}${e.truncated?` · truncated`:``}`}function iy(e){if(!e)return``;try{let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)?t.toString():``}catch{return``}}function ay({files:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-user-files`,"data-testid":`code-codex-transcript-user-files`,children:e.map(e=>{let t=e.content||``,n=!!t,r=e.resourceKind===`link`?iy(e.uri):``;return e.resourceKind===`link`?(0,K.jsxs)(`div`,{className:`code-codex-transcript-user-file code-codex-transcript-resource-link`,children:[(0,K.jsx)(oy,{filePath:e.name}),r?(0,K.jsx)(`a`,{href:r,target:`_blank`,rel:`noreferrer`,title:e.uri,children:e.name}):(0,K.jsx)(`span`,{title:e.uri,children:e.name}),(0,K.jsx)(`span`,{className:`code-codex-transcript-user-file-meta`,children:ry(e)})]},e.id):(0,K.jsxs)(`details`,{className:`code-codex-transcript-user-file ${e.error?`error`:``}`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(oy,{filePath:e.name}),(0,K.jsx)(`span`,{className:`code-codex-transcript-user-file-name`,title:e.name,children:e.name}),(0,K.jsx)(`span`,{className:`code-codex-transcript-user-file-meta`,children:ry(e)})]}),e.error?(0,K.jsx)(`div`,{className:`code-codex-transcript-user-file-error`,children:e.error}):n?(0,K.jsx)(`pre`,{children:t}):null]},e.id)})})}function oy({filePath:e}){let t=re(e);return(0,K.jsx)(`span`,{className:`code-codex-transcript-file-icon`,style:{WebkitMaskImage:`url("${t}")`,maskImage:`url("${t}")`},"aria-hidden":`true`})}function sy({children:e,filePath:t,lineNumber:n}){let r=Zv(t,n);return(0,K.jsxs)(`span`,{title:n&&n>1?`${t}:${n}`:t,children:[(0,K.jsx)(oy,{filePath:t}),(0,K.jsx)(`span`,{className:`code-codex-transcript-file-label`,children:r})]})}function cy({images:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-process-images`,"data-testid":`code-codex-transcript-process-images`,children:e.map(e=>(0,K.jsx)(`img`,{src:e.url,alt:e.alt||`Generated image`,loading:`lazy`,decoding:`async`},e.id))})}function ly({audios:e}){return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-audios`,"data-testid":`code-codex-transcript-audios`,children:e.map(e=>(0,K.jsxs)(`figure`,{children:[e.name?(0,K.jsx)(`figcaption`,{children:e.name}):null,(0,K.jsx)(`audio`,{controls:!0,preload:`metadata`,src:e.url,children:e.mimeType?(0,K.jsx)(`source`,{src:e.url,type:e.mimeType}):null})]},e.id))})}function uy(e){let t=e.terminal?.exitStatus;return t?t.signal?`Exited (${t.signal})`:`Exited ${t.exitCode??``}`.trim():e.terminal?.released?`Released`:`Running`}function dy(e){return[String(e.terminal?.command||``).trim(),...Array.isArray(e.terminal?.args)?e.terminal.args:[]].filter(Boolean).join(` `)||e.terminalId}function fy(e){return!Number.isFinite(e)||Number(e)<0?``:Number(e)<1e3?`${Math.round(Number(e))}ms`:`${(Number(e)/1e3).toFixed(+(Number(e)<1e4))}s`}function py({terminals:e,onStop:t,onInput:n,onResize:r}){let[i,a]=(0,W.useState)(``),[o,s]=(0,W.useState)(``),[c,l]=(0,W.useState)(``);return e.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-terminals`,"data-testid":`code-codex-transcript-terminals`,children:e.map(e=>{let u=dy(e),d=fy(e.terminal?.durationMs),f=e.terminal?.output||``;return(0,K.jsxs)(`section`,{className:`code-codex-transcript-terminal`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`code`,{title:u,children:u}),(0,K.jsx)(`span`,{children:uy(e)}),!e.terminal?.exitStatus&&!e.terminal?.released&&t?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-terminal-stop`,"data-testid":`code-acp-terminal-stop`,"aria-label":`Stop command`,title:`Stop command`,disabled:!!o,onClick:()=>{s(e.terminalId),l(``),t(e.terminalId).catch(e=>l(e instanceof Error?e.message:`Failed to stop command`)).finally(()=>s(``))},children:o===e.terminalId?(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`}):(0,K.jsx)(le,{})}):null,f?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-terminal-copy`,"aria-label":i===e.terminalId?`Copied terminal output`:`Copy terminal output`,title:i===e.terminalId?`Copied`:`Copy output`,onClick:()=>{Ky(f).then(t=>{t&&(a(e.terminalId),window.setTimeout(()=>a(t=>t===e.terminalId?``:t),1200))})},children:i===e.terminalId?(0,K.jsx)(me,{}):(0,K.jsx)(H,{})}):null]}),e.terminal?.cwd||d||e.terminal?.truncated?(0,K.jsxs)(`div`,{className:`code-codex-transcript-terminal-meta`,children:[e.terminal?.cwd?(0,K.jsx)(`span`,{title:e.terminal.cwd,children:e.terminal.cwd}):null,d?(0,K.jsx)(`span`,{children:d}):null,e.terminal?.truncated?(0,K.jsx)(`span`,{children:`Earlier output hidden`}):null]}):null,(0,K.jsx)(a_,{terminalId:e.terminalId,output:f,interactive:!!(e.terminal?.interactive&&!e.terminal.exitStatus&&!e.terminal.released&&n),onInput:n?t=>n(e.terminalId,t):void 0,onResize:r?(t,n)=>r(e.terminalId,t,n):void 0}),c?(0,K.jsx)(`div`,{className:`code-codex-transcript-terminal-error`,role:`alert`,children:c}):null]},e.terminalId)})})}function my({item:e}){let t=String(e.detail||``).trim(),n=e.changes||[],r=!!(t||n.length>0),i=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:e.title||`Action`}),_y(e.status)?(0,K.jsx)(`small`,{children:e.status}):null]});return r?(0,K.jsxs)(`details`,{className:`code-codex-transcript-subagent-action`,"data-testid":`code-codex-transcript-subagent-action`,children:[(0,K.jsxs)(`summary`,{children:[i,(0,K.jsx)(fe,{})]}),t?(0,K.jsx)(`div`,{className:`detail`,children:Fv(t)}):null,n.length>0?(0,K.jsx)(`div`,{className:`changes`,children:n.map((e,t)=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{title:e.path,children:e.path}),(0,K.jsxs)(`small`,{children:[e.added>0?`+${e.added}`:``,e.removed>0?` -${e.removed}`:``]})]},`${e.path}-${t}`))}):null]}):(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-action static`,children:i})}function hy({transcript:e,onStop:t}){let n=[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes(e.state||``),r=e.error?`Failed`:n?`Working`:`Completed`,i=e.turns.reduce((e,t)=>e+t.processItems.length,0),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.useState)(!1),[l,u]=(0,W.useState)(``);(0,W.useEffect)(()=>{if(!a)return;let e=e=>{e.key===`Escape`&&o(!1)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let d=(0,K.jsxs)(`div`,{className:`code-codex-transcript-subagent-entries`,children:[e.turns.map(e=>(0,K.jsxs)(`div`,{className:`code-codex-transcript-subagent-turn`,children:[e.userMessage?(0,K.jsx)(`div`,{className:`user`,children:Fv(e.userMessage)}):null,e.processItems.length>0?(0,K.jsx)(`div`,{className:`actions`,children:e.processItems.map(e=>(0,K.jsx)(my,{item:e},e.id))}):null,e.finalMessage?(0,K.jsx)(`div`,{className:`assistant`,children:Fv(e.finalMessage)}):null]},e.id)),e.turns.length===0?(0,K.jsx)(`div`,{className:`empty`,children:`No subagent output received yet`}):null]}),f=(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`span`,{children:e.title||`Subagent`}),(0,K.jsxs)(`span`,{className:`code-codex-transcript-subagent-meta`,title:e.sessionId,children:[e.turns.length,` `,e.turns.length===1?`turn`:`turns`,i>0?` · ${i} ${i===1?`action`:`actions`}`:``]}),(0,K.jsx)(`span`,{className:`code-codex-transcript-subagent-status ${e.error?`error`:n?`active`:``}`,children:r}),n&&t?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-subagent-control stop`,"data-testid":`code-acp-subagent-stop`,"aria-label":`Stop subagent`,title:`Stop subagent`,disabled:s,onClick:()=>{c(!0),u(``),t().catch(e=>u(e instanceof Error?e.message:`Failed to stop subagent`)).finally(()=>c(!1))},children:s?(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`}):(0,K.jsx)(le,{})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-subagent-control`,"data-testid":`code-acp-subagent-fullscreen`,"aria-label":a?`Close subagent details`:`Open subagent details`,title:a?`Close details`:`Open details`,onClick:()=>o(e=>!e),children:a?(0,K.jsx)(le,{}):(0,K.jsx)(`span`,{"aria-hidden":`true`,children:`↗`})})]});return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`code-codex-transcript-subagent`,"data-testid":`code-codex-transcript-subagent`,children:[f,e.error?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`status`,children:e.error}):null,l?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`alert`,children:l}):null,d]}),a?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":`Subagent details`,children:(0,K.jsxs)(`div`,{className:`code-codex-transcript-subagent-dialog`,children:[f,e.error?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`status`,children:e.error}):null,l?(0,K.jsx)(`div`,{className:`code-codex-transcript-subagent-error`,role:`alert`,children:l}):null,d]})}):null]})}function gy(e){let t=e.type.replace(/[^a-z0-9_-]/gi,``).toLowerCase()||`event`,n=(e.status||``).replace(/[^a-z0-9_-]/gi,``).toLowerCase();return[`code-codex-transcript-process-item`,t,n?`status-${n}`:``].filter(Boolean).join(` `)}function _y(e){let t=String(e||``).trim().toLowerCase();return!!t&&t!==`completed`&&t!==`success`}function vy(e){let t=String(e.status||``).trim().replace(/[_-]/g,``).toLowerCase();return[`running`,`inprogress`,`pending`,`started`,`active`].includes(t)}function yy(e){return e.scrollHeight-e.clientHeight-e.scrollTop}function by(e){return yy(e)<=Ov}function xy(e){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?!1:!!(t.anchorNode&&e.contains(t.anchorNode)||t.focusNode&&e.contains(t.focusNode))}function Sy(e){let t=e.split(`
101
101
  `).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.match(/^\[(x|>| )\]\s+(.+)$/i);if(!t)return null;let n=(t[1]||``).toLowerCase();return{status:n===`x`?`completed`:n===`>`?`running`:`pending`,text:t[2]||``}});return t.some(e=>e===null)?null:t}function Cy(e){return[`message`,`agent-message`,`progress`,`reasoning`,`thought`,`hook`,`warning`,`error`,`review`,`rollback`,`compaction`,`subagent`].includes(e.type)}function wy(e){return Cy(e)||e.type===`plan`||e.type===`user-steer`}function Ty(e){return!wy(e)}function Ey(e){let t=[],n=[],r=()=>{n.length>0&&t.push({kind:`group`,id:`group:${n.map(e=>e.id).join(`:`)}`,items:n}),n=[]};for(let i of e){if(Ty(i)){n.push(i);continue}r(),t.push({kind:`item`,item:i})}return r(),t}function Dy(e){let t=e.filter(e=>[`failed`,`rejected`,`cancelled`,`canceled`].includes(String(e.status||``).toLowerCase())).length;if(t>0)return t===1?`Action failed`:`${t} actions failed`;let n=e.reduce((e,t)=>{let n=t.type;return e[n]=(e[n]||0)+1,e},{}),r=n.command||0,i=(n[`file-read`]||0)+(n.read||0),a=(n[`web-search`]||0)+(n.search||0),o=n.patch||0;if(e.length===i+a&&(i>0||a>0)){let e=[];i>0&&e.push(i===1?`read a file`:`read ${i} files`),a>0&&e.push(`searched code`);let t=e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} and ${e[e.length-1]}`;return t?t.charAt(0).toUpperCase()+t.slice(1):`Completed actions`}return e.length===r?r===1?`Ran command`:`Ran ${r} commands`:e.length===i?i===1?`Read a file`:`Read ${i} files`:e.length===a?a===1?`Searched code`:`Searched ${a} times`:o>0&&o===e.length?o===1?`Edited files`:`Edited files ${o} times`:r>0?`Ran ${e.length} actions`:`Completed ${e.length} actions`}function Oy(e,t,n){return!!(t||n||(e.images||[]).length>0||(e.audios||[]).length>0||(e.files||[]).length>0||(e.terminals||[]).length>0||(e.terminalIds||[]).length>0||e.detailTruncated===!0||e.subagentSessionId||e.subagentTranscript)}function ky(e){return e.type===`patch`}function Ay(e){return e.type===`user-steer`}function jy(e){return String(e.detail||``).split(`
102
- `).map(e=>e.trim()).filter(Boolean).filter(e=>!e.startsWith(`Success.`)).filter(My).slice(0,16)}function My(e){let t=e.trim();return/^(add|added|delete|deleted|update|updated|move|moved|rename|renamed)\s+.+/i.test(t)||/^[AMDRC]\s+.+/.test(t)}function Ny(e){let t=e.trim(),n=t.match(/^([AMDRC])\s+(.+)$/);if(n)return{kind:n[1]||``,path:n[2]||t,added:``,removed:``};let r=t.match(/\s(\+\d+)(?:\s(-\d+))?$/),i=r?.[1]||``,a=r?.[2]||``,o=r?t.slice(0,r.index).trim():t,s=o.match(/^(add|added|delete|deleted|update|updated|move|moved|rename|renamed)\s+(.+)$/i);return{kind:s?.[1]||``,path:s?.[2]||o,added:i,removed:a}}function Py(e){return String(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`).trim()}function Fy(e,t){let n=Py(e),r=Py(t||``).replace(/\/+$/,``);if(!n||!r)return n;let i=[r];r.startsWith(`/private/`)&&i.push(r.slice(8)),(r.startsWith(`/var/`)||r.startsWith(`/tmp/`))&&i.push(`/private${r}`);for(let e of i){if(n===e)return``;if(n.startsWith(`${e}/`))return n.slice(e.length+1)}return n}function Iy(e,t){return Fy(e.path,t)||e.path}function Ly(e){return!!(e.added||e.removed)}function Ry(e,t){let n=[],r=new Map;for(let i of e){let e=Iy(i,t),a=e||i.path,o=r.get(a);if(o===void 0){r.set(a,n.length),n.push({...i,path:e||i.path});continue}let s=n[o];s&&(Ly(i)||!Ly(s))&&(n[o]={...i,path:e||i.path})}return n}function zy(e,t){return Ry(e.map(e=>({kind:e.kind,path:e.path,added:e.added>0?`+${e.added}`:``,removed:e.removed>0?`-${e.removed}`:``})),t)}function By(e,t){return Ry(e.flatMap(e=>e.changes?.length?zy(e.changes):jy(e).map(Ny)),t)}function Vy(e,t){return t?e===1?`Failed editing 1 file`:`Failed editing ${e} files`:e===1?`Edited 1 file`:`Edited ${e} files`}function Hy(e,t){return t?Vy(e,t):e===1?`1 file changed`:`${e} files changed`}function Uy(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)?`added`:e.startsWith(`-`)&&!e.startsWith(`---`)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`Index:`)||e.startsWith(`===`)?`meta`:``}function Wy(e){let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,`true`),t.setAttribute(`autocomplete`,`off`),t.setAttribute(`autocorrect`,`off`),t.setAttribute(`autocapitalize`,`none`),t.setAttribute(`spellcheck`,`false`),t.setAttribute(`data-lpignore`,`true`),t.setAttribute(`data-1p-ignore`,`true`),t.setAttribute(`data-bwignore`,`true`),t.setAttribute(`data-form-type`,`other`),t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`0`,document.body.appendChild(t),t.focus(),t.select();let n=!1;try{n=document.execCommand(`copy`)}catch{n=!1}return t.remove(),n}function Gy(e,t){let n=e.closest(`.code-codex-transcript-scroll`),r=e.getBoundingClientRect().top;t(),window.requestAnimationFrame(()=>{if(!n?.isConnected||!e.isConnected)return;let t=e.getBoundingClientRect().top-r;Math.abs(t)<.5||(n.scrollTop+=t)})}async function Ky(e){return navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):Wy(e)}function qy({item:e}){let t=(e.detail||e.title||``).trim(),n=e.images||[],r=e.audios||[],i=e.files||[],a=e.terminals||[];return!t&&n.length<=0&&r.length<=0&&i.length<=0&&a.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-steer`,"data-testid":`code-codex-transcript-steer`,children:(0,K.jsxs)(`div`,{className:`code-codex-transcript-user code-codex-transcript-steer-bubble`,children:[t?(0,K.jsx)(`div`,{children:Fv(t)}):null,(0,K.jsx)(ny,{images:n}),(0,K.jsx)(ly,{audios:r}),(0,K.jsx)(ay,{files:i}),(0,K.jsx)(py,{terminals:a})]})})}function Jy({item:e,copy:t,copied:n,detailOpen:r,onToggle:i,onCopy:a,onStopTerminal:o,onInputTerminal:s,onResizeTerminal:c,onStopSubagent:l}){if(Ay(e))return(0,K.jsx)(qy,{item:e});let u=e.detail&&e.detail.trim()!==e.title.trim()?e.detail:``,d=!!u,f=e.images||[],p=e.audios||[],m=e.files||[],h=e.terminals||[],g=e.type===`plan`&&u?Sy(u):null,_=Oy(e,u,g),v=(0,K.jsxs)(K.Fragment,{children:[g?(0,K.jsx)(`ul`,{className:`code-codex-transcript-plan-list`,children:g.map((e,t)=>(0,K.jsxs)(`li`,{className:e.status,children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-plan-marker`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:e.text})]},`${t}-${e.text}`))}):null,(0,K.jsx)(cy,{images:f}),(0,K.jsx)(ly,{audios:p}),(0,K.jsx)(ay,{files:m}),(0,K.jsx)(py,{terminals:h,onStop:o?t=>o(e.id,t):void 0,onInput:s?(t,n)=>s(e.id,t,n):void 0,onResize:c?(t,n,r)=>c(e.id,t,n,r):void 0}),e.subagentTranscript?(0,K.jsx)(hy,{transcript:e.subagentTranscript,onStop:e.subagentSessionId&&l?()=>l(e.subagentSessionId||``):void 0}):null,!g&&d&&Cy(e)?(0,K.jsx)(`div`,{className:`code-codex-transcript-process-detail`,children:Fv(u)}):!g&&d?(0,K.jsx)(`pre`,{children:u}):null]});return(0,K.jsxs)(`section`,{className:gy(e),"data-testid":`code-codex-transcript-process-item`,"data-process-item-id":e.id,"data-type":e.type,"data-status":e.status||``,children:[(0,K.jsxs)(`div`,{className:`code-codex-transcript-process-title`,children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-dot`,"aria-hidden":`true`}),_?(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-process-title-toggle`,"data-testid":`code-codex-transcript-process-item-toggle`,"aria-expanded":r,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),Gy(t.currentTarget,()=>i(e.id))},onKeyDown:t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),Gy(t.currentTarget,()=>i(e.id)))},children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-title-text`,children:e.title}),_y(e.status)?(0,K.jsx)(`span`,{className:`code-codex-transcript-process-status`,children:e.status}):null,(0,K.jsx)(fe,{className:`code-codex-transcript-process-item-chevron`})]}):(0,K.jsxs)(`span`,{className:`code-codex-transcript-process-title-static`,children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-title-text`,children:e.title}),_y(e.status)?(0,K.jsx)(`span`,{className:`code-codex-transcript-process-status`,children:e.status}):null]}),d?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-copy ${n?`copied`:``}`,"aria-label":n?t.codexTranscriptCopiedDetails:t.codexTranscriptCopyDetails,title:n?t.codexTranscriptCopiedDetails:t.codexTranscriptCopyDetails,"data-tooltip":n?t.codexTranscriptCopiedDetails:t.codexTranscriptCopyDetails,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:()=>a(e),children:n?(0,K.jsx)(me,{}):(0,K.jsx)(H,{})}):null]}),_&&r?v:null]})}function Yy({groupId:e,items:t,summaryLabel:n,copy:r,copiedItemId:i,detailOpen:a,openProcessItemIds:o,onToggleGroup:s,onToggleItem:c,onCopy:l,onStopTerminal:u,onInputTerminal:d,onResizeTerminal:f,onStopSubagent:p}){return(0,K.jsxs)(`section`,{className:`code-codex-transcript-process-group ${t.some(vy)?`running`:``}`,"data-testid":`code-codex-transcript-process-group`,"data-count":t.length,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-process-group-summary`,"data-testid":`code-codex-transcript-process-group-toggle`,"aria-expanded":a,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),Gy(t.currentTarget,()=>s(e))},onKeyDown:t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),Gy(t.currentTarget,()=>s(e)))},children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-dot`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`code-codex-transcript-process-title-text`,children:n||Dy(t)}),(0,K.jsx)(fe,{className:`code-codex-transcript-process-item-chevron`})]}),a?(0,K.jsx)(`div`,{className:`code-codex-transcript-process-group-list`,children:t.map(e=>(0,K.jsx)(Jy,{item:e,copy:r,copied:i===e.id,detailOpen:o.has(e.id),onToggle:c,onCopy:l,onStopTerminal:u,onInputTerminal:d,onResizeTerminal:f,onStopSubagent:p},e.id))}):null]})}function Xy({items:e,copy:t,onLoadPatchChanges:r,onCreateReview:i,onDecidePatch:a,source:o,workspaceRoot:s}){let[c,l]=(0,W.useState)(!1),[u,d]=(0,W.useState)(null),[f,p]=(0,W.useState)(``),m=(0,W.useMemo)(()=>Object.fromEntries(e.flatMap(e=>(e.changes||[]).flatMap(e=>e.decision?[[Fy(e.path,s)||e.path,e.decision]]:[]))),[e,s]),[h,g]=(0,W.useState)(m),[_,v]=(0,W.useState)(``),[y,b]=(0,W.useState)({});(0,W.useEffect)(()=>{g(e=>({...m,...e}))},[m]);let x=By(e,s),S=u?zy(u,s):[],C=new Map(S.map(e=>[e.path,e])),w=u?[...x.map(e=>C.get(e.path)||e),...S.filter(e=>!x.some(t=>t.path===e.path))]:x,T=e.some(e=>e.status===`failed`),E=w.reduce((e,t)=>e+Number(t.added.replace(`+`,``)||0),0),D=w.reduce((e,t)=>e+Number(t.removed.replace(`-`,``)||0),0),O=Hy(w.length,T),k=e.flatMap(e=>e.changes||[]),ee=new Set((u||[]).map(e=>e.path)),te=u?[...u,...k.filter(e=>!ee.has(Fy(e.path,s)||e.path))]:k,A=o===`acp`?w.map(e=>Fy(e.path,s)).filter(e=>e&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)):[],j=(0,W.useCallback)(t=>{let n=e.flatMap(e=>(e.changes||[]).filter(e=>(Fy(e.path,s)||e.path)===t).map(t=>({itemId:e.id,path:t.path})));return n.length===1?n[0]:null},[e,s]),M=(0,W.useCallback)((e,n)=>{let r=j(e);!r||!a||_||(v(e),b(t=>({...t,[e]:``})),a(r.itemId,r.path,n).then(t=>g(n=>({...n,[e]:t.action}))).catch(n=>b(r=>({...r,[e]:n instanceof Error?n.message:t.codexTranscriptUnavailable}))).finally(()=>v(``)))},[t.codexTranscriptUnavailable,_,a,j]),N=(0,W.useCallback)(()=>{if(!s||o===`acp`&&A.length===0)return;if(o===`acp`&&i){window.open(i(e.map(e=>e.id)),`_blank`,`noopener,noreferrer`);return}let t=new URLSearchParams({root:s});o===`acp`&&A.forEach(e=>t.append(`path`,e)),window.open(n(`/review?${t.toString()}`),`_blank`,`noopener,noreferrer`)},[e,i,A,o,s]),P=(0,W.useCallback)(n=>{if(o!==`acp`){N();return}Gy(n.currentTarget,()=>{l(e=>!e)}),!(c||u||!r)&&(p(``),r(e.map(e=>e.id)).then(d).catch(e=>p(e instanceof Error?e.message:t.codexTranscriptUnavailable)))},[t.codexTranscriptUnavailable,c,u,N,e,r,o]),F=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:O}),E?(0,K.jsxs)(`span`,{className:`added`,children:[`+`,E]}):null,D?(0,K.jsxs)(`span`,{className:`removed`,children:[`-`,D]}):null]});return(0,K.jsxs)(`section`,{className:`code-codex-transcript-result-card ${T?`failed`:``}`,"data-testid":`code-codex-transcript-result-card`,children:[s&&w.length>0?(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-result-summary`,"data-testid":`code-codex-transcript-result-summary`,"aria-label":`${O}. ${o===`acp`?t.codexTranscriptShowChanges:t.codexTranscriptReviewChanges}`,"aria-expanded":o===`acp`?c:void 0,onClick:P,children:[F,o===`acp`?(0,K.jsx)(fe,{className:`code-codex-transcript-result-chevron`}):null]}):(0,K.jsx)(`div`,{className:`code-codex-transcript-result-summary`,"aria-label":O,children:F}),o===`acp`&&c?(0,K.jsxs)(`div`,{className:`code-codex-transcript-result-details`,"data-testid":`code-codex-transcript-result-details`,children:[(0,K.jsx)(`div`,{className:`code-codex-transcript-result-files`,children:w.map(n=>{let r=Iy(n,s),i=te.filter(e=>(Fy(e.path,s)||e.path)===r),o=j(r),c=h[r];return(0,K.jsxs)(`details`,{className:`code-codex-transcript-result-file`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-result-file-path`,children:r}),(0,K.jsxs)(`span`,{className:`code-codex-transcript-result-file-stats`,children:[n.added?(0,K.jsx)(`span`,{className:`added`,children:n.added}):null,n.removed?(0,K.jsx)(`span`,{className:`removed`,children:n.removed}):null]})]}),i.map((e,t)=>e.diff?(0,K.jsx)(`pre`,{className:`code-codex-transcript-result-diff`,children:e.diff.split(`
102
+ `).map(e=>e.trim()).filter(Boolean).filter(e=>!e.startsWith(`Success.`)).filter(My).slice(0,16)}function My(e){let t=e.trim();return/^(add|added|delete|deleted|update|updated|move|moved|rename|renamed)\s+.+/i.test(t)||/^[AMDRC]\s+.+/.test(t)}function Ny(e){let t=e.trim(),n=t.match(/^([AMDRC])\s+(.+)$/);if(n)return{kind:n[1]||``,path:n[2]||t,added:``,removed:``};let r=t.match(/\s(\+\d+)(?:\s(-\d+))?$/),i=r?.[1]||``,a=r?.[2]||``,o=r?t.slice(0,r.index).trim():t,s=o.match(/^(add|added|delete|deleted|update|updated|move|moved|rename|renamed)\s+(.+)$/i);return{kind:s?.[1]||``,path:s?.[2]||o,added:i,removed:a}}function Py(e){return String(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`).trim()}function Fy(e,t){let n=Py(e),r=Py(t||``).replace(/\/+$/,``);if(!n||!r)return n;let i=[r];r.startsWith(`/private/`)&&i.push(r.slice(8)),(r.startsWith(`/var/`)||r.startsWith(`/tmp/`))&&i.push(`/private${r}`);for(let e of i){if(n===e)return``;if(n.startsWith(`${e}/`))return n.slice(e.length+1)}return n}function Iy(e,t){return Fy(e.path,t)||e.path}function Ly(e){return!!(e.added||e.removed)}function Ry(e,t){let n=[],r=new Map;for(let i of e){let e=Iy(i,t),a=e||i.path,o=r.get(a);if(o===void 0){r.set(a,n.length),n.push({...i,path:e||i.path});continue}let s=n[o];s&&(Ly(i)||!Ly(s))&&(n[o]={...i,path:e||i.path})}return n}function zy(e,t){return Ry(e.map(e=>({kind:e.kind,path:e.path,added:e.added>0?`+${e.added}`:``,removed:e.removed>0?`-${e.removed}`:``})),t)}function By(e,t){return Ry(e.flatMap(e=>e.changes?.length?zy(e.changes):jy(e).map(Ny)),t)}function Vy(e,t){return t?e===1?`Failed editing 1 file`:`Failed editing ${e} files`:e===1?`Edited 1 file`:`Edited ${e} files`}function Hy(e,t){return t?Vy(e,t):e===1?`1 file changed`:`${e} files changed`}function Uy(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)?`added`:e.startsWith(`-`)&&!e.startsWith(`---`)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`Index:`)||e.startsWith(`===`)?`meta`:``}function Wy(e){let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,`true`),t.setAttribute(`autocomplete`,`off`),t.setAttribute(`autocorrect`,`off`),t.setAttribute(`autocapitalize`,`none`),t.setAttribute(`spellcheck`,`false`),t.setAttribute(`data-lpignore`,`true`),t.setAttribute(`data-1p-ignore`,`true`),t.setAttribute(`data-bwignore`,`true`),t.setAttribute(`data-form-type`,`other`),t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`0`,document.body.appendChild(t),t.focus(),t.select();let n=!1;try{n=document.execCommand(`copy`)}catch{n=!1}return t.remove(),n}function Gy(e,t){let n=e.closest(`.code-codex-transcript-scroll`),r=e.getBoundingClientRect().top;t(),window.requestAnimationFrame(()=>{if(!n?.isConnected||!e.isConnected)return;let t=e.getBoundingClientRect().top-r;Math.abs(t)<.5||(n.scrollTop+=t)})}async function Ky(e){return navigator.clipboard?.writeText?(await navigator.clipboard.writeText(e),!0):Wy(e)}function qy({item:e}){let t=(e.detail||e.title||``).trim(),n=e.images||[],r=e.audios||[],i=e.files||[],a=e.terminals||[];return!t&&n.length<=0&&r.length<=0&&i.length<=0&&a.length<=0?null:(0,K.jsx)(`div`,{className:`code-codex-transcript-steer`,"data-testid":`code-codex-transcript-steer`,children:(0,K.jsxs)(`div`,{className:`code-codex-transcript-user code-codex-transcript-steer-bubble`,children:[t?(0,K.jsx)(`div`,{children:Fv(t)}):null,(0,K.jsx)(ny,{images:n}),(0,K.jsx)(ly,{audios:r}),(0,K.jsx)(ay,{files:i}),(0,K.jsx)(py,{terminals:a})]})})}function Jy({item:e,copy:t,copied:n,detailOpen:r,onToggle:i,onCopy:a,onStopTerminal:o,onInputTerminal:s,onResizeTerminal:c,onStopSubagent:l}){if(Ay(e))return(0,K.jsx)(qy,{item:e});let u=e.detail&&e.detail.trim()!==e.title.trim()?e.detail:``,d=!!u,f=e.images||[],p=e.audios||[],m=e.files||[],h=e.terminals||[],g=e.type===`plan`&&u?Sy(u):null,_=Oy(e,u,g),v=(0,K.jsxs)(K.Fragment,{children:[g?(0,K.jsx)(`ul`,{className:`code-codex-transcript-plan-list`,children:g.map((e,t)=>(0,K.jsxs)(`li`,{className:e.status,children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-plan-marker`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:e.text})]},`${t}-${e.text}`))}):null,(0,K.jsx)(cy,{images:f}),(0,K.jsx)(ly,{audios:p}),(0,K.jsx)(ay,{files:m}),(0,K.jsx)(py,{terminals:h,onStop:o?t=>o(e.id,t):void 0,onInput:s?(t,n)=>s(e.id,t,n):void 0,onResize:c?(t,n,r)=>c(e.id,t,n,r):void 0}),e.subagentTranscript?(0,K.jsx)(hy,{transcript:e.subagentTranscript,onStop:e.subagentSessionId&&l?()=>l(e.subagentSessionId||``):void 0}):null,!g&&d&&Cy(e)?(0,K.jsx)(`div`,{className:`code-codex-transcript-process-detail`,children:Fv(u)}):!g&&d?(0,K.jsx)(`pre`,{children:u}):null]});return(0,K.jsxs)(`section`,{className:gy(e),"data-testid":`code-codex-transcript-process-item`,"data-process-item-id":e.id,"data-type":e.type,"data-status":e.status||``,children:[(0,K.jsxs)(`div`,{className:`code-codex-transcript-process-title`,children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-dot`,"aria-hidden":`true`}),_?(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-process-title-toggle`,"data-testid":`code-codex-transcript-process-item-toggle`,"aria-expanded":r,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),Gy(t.currentTarget,()=>i(e.id))},onKeyDown:t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),Gy(t.currentTarget,()=>i(e.id)))},children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-title-text`,children:e.title}),_y(e.status)?(0,K.jsx)(`span`,{className:`code-codex-transcript-process-status`,children:e.status}):null,(0,K.jsx)(fe,{className:`code-codex-transcript-process-item-chevron`})]}):(0,K.jsxs)(`span`,{className:`code-codex-transcript-process-title-static`,children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-title-text`,children:e.title}),_y(e.status)?(0,K.jsx)(`span`,{className:`code-codex-transcript-process-status`,children:e.status}):null]}),d?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-copy ${n?`copied`:``}`,"aria-label":n?t.codexTranscriptCopiedDetails:t.codexTranscriptCopyDetails,title:n?t.codexTranscriptCopiedDetails:t.codexTranscriptCopyDetails,"data-tooltip":n?t.codexTranscriptCopiedDetails:t.codexTranscriptCopyDetails,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:()=>a(e),children:n?(0,K.jsx)(me,{}):(0,K.jsx)(H,{})}):null]}),_&&r?v:null]})}function Yy({groupId:e,items:t,summaryLabel:n,copy:r,copiedItemId:i,detailOpen:a,openProcessItemIds:o,onToggleGroup:s,onToggleItem:c,onCopy:l,onStopTerminal:u,onInputTerminal:d,onResizeTerminal:f,onStopSubagent:p}){return(0,K.jsxs)(`section`,{className:`code-codex-transcript-process-group ${t.some(vy)?`running`:``}`,"data-testid":`code-codex-transcript-process-group`,"data-count":t.length,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-process-group-summary`,"data-testid":`code-codex-transcript-process-group-toggle`,"aria-expanded":a,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),Gy(t.currentTarget,()=>s(e))},onKeyDown:t=>{t.key!==`Enter`&&t.key!==` `||(t.preventDefault(),t.stopPropagation(),Gy(t.currentTarget,()=>s(e)))},children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-process-dot`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`code-codex-transcript-process-title-text`,children:n||Dy(t)}),(0,K.jsx)(fe,{className:`code-codex-transcript-process-item-chevron`})]}),a?(0,K.jsx)(`div`,{className:`code-codex-transcript-process-group-list`,children:t.map(e=>(0,K.jsx)(Jy,{item:e,copy:r,copied:i===e.id,detailOpen:o.has(e.id),onToggle:c,onCopy:l,onStopTerminal:u,onInputTerminal:d,onResizeTerminal:f,onStopSubagent:p},e.id))}):null]})}function Xy({items:e,copy:t,onLoadPatchChanges:r,onCreateReview:i,onDecidePatch:a,source:o,workspaceRoot:s}){let[c,l]=(0,W.useState)(!1),[u,d]=(0,W.useState)(null),[f,p]=(0,W.useState)(``),m=(0,W.useMemo)(()=>Object.fromEntries(e.flatMap(e=>(e.changes||[]).flatMap(e=>e.decision?[[Fy(e.path,s)||e.path,e.decision]]:[]))),[e,s]),[h,g]=(0,W.useState)(m),[_,v]=(0,W.useState)(``),[y,b]=(0,W.useState)({});(0,W.useEffect)(()=>{g(e=>({...m,...e}))},[m]);let x=By(e,s),S=u?zy(u,s):[],C=new Map(S.map(e=>[e.path,e])),w=u?[...x.map(e=>C.get(e.path)||e),...S.filter(e=>!x.some(t=>t.path===e.path))]:x,T=e.some(e=>e.status===`failed`),E=w.reduce((e,t)=>e+Number(t.added.replace(`+`,``)||0),0),D=w.reduce((e,t)=>e+Number(t.removed.replace(`-`,``)||0),0),O=Hy(w.length,T),k=e.flatMap(e=>e.changes||[]),A=new Set((u||[]).map(e=>e.path)),ee=u?[...u,...k.filter(e=>!A.has(Fy(e.path,s)||e.path))]:k,j=o===`acp`?w.map(e=>Fy(e.path,s)).filter(e=>e&&!e.startsWith(`/`)&&!e.split(`/`).includes(`..`)):[],M=(0,W.useCallback)(t=>{let n=e.flatMap(e=>(e.changes||[]).filter(e=>(Fy(e.path,s)||e.path)===t).map(t=>({itemId:e.id,path:t.path})));return n.length===1?n[0]:null},[e,s]),N=(0,W.useCallback)((e,n)=>{let r=M(e);!r||!a||_||(v(e),b(t=>({...t,[e]:``})),a(r.itemId,r.path,n).then(t=>g(n=>({...n,[e]:t.action}))).catch(n=>b(r=>({...r,[e]:n instanceof Error?n.message:t.codexTranscriptUnavailable}))).finally(()=>v(``)))},[t.codexTranscriptUnavailable,_,a,M]),te=(0,W.useCallback)(()=>{if(!s||o===`acp`&&j.length===0)return;if(o===`acp`&&i){window.open(i(e.map(e=>e.id)),`_blank`,`noopener,noreferrer`);return}let t=new URLSearchParams({root:s});o===`acp`&&j.forEach(e=>t.append(`path`,e)),window.open(n(`/review?${t.toString()}`),`_blank`,`noopener,noreferrer`)},[e,i,j,o,s]),P=(0,W.useCallback)(n=>{if(o!==`acp`){te();return}Gy(n.currentTarget,()=>{l(e=>!e)}),!(c||u||!r)&&(p(``),r(e.map(e=>e.id)).then(d).catch(e=>p(e instanceof Error?e.message:t.codexTranscriptUnavailable)))},[t.codexTranscriptUnavailable,c,u,te,e,r,o]),F=(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`span`,{children:O}),E?(0,K.jsxs)(`span`,{className:`added`,children:[`+`,E]}):null,D?(0,K.jsxs)(`span`,{className:`removed`,children:[`-`,D]}):null]});return(0,K.jsxs)(`section`,{className:`code-codex-transcript-result-card ${T?`failed`:``}`,"data-testid":`code-codex-transcript-result-card`,children:[s&&w.length>0?(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-result-summary`,"data-testid":`code-codex-transcript-result-summary`,"aria-label":`${O}. ${o===`acp`?t.codexTranscriptShowChanges:t.codexTranscriptReviewChanges}`,"aria-expanded":o===`acp`?c:void 0,onClick:P,children:[F,o===`acp`?(0,K.jsx)(fe,{className:`code-codex-transcript-result-chevron`}):null]}):(0,K.jsx)(`div`,{className:`code-codex-transcript-result-summary`,"aria-label":O,children:F}),o===`acp`&&c?(0,K.jsxs)(`div`,{className:`code-codex-transcript-result-details`,"data-testid":`code-codex-transcript-result-details`,children:[(0,K.jsx)(`div`,{className:`code-codex-transcript-result-files`,children:w.map(n=>{let r=Iy(n,s),i=ee.filter(e=>(Fy(e.path,s)||e.path)===r),o=M(r),c=h[r];return(0,K.jsxs)(`details`,{className:`code-codex-transcript-result-file`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{className:`code-codex-transcript-result-file-path`,children:r}),(0,K.jsxs)(`span`,{className:`code-codex-transcript-result-file-stats`,children:[n.added?(0,K.jsx)(`span`,{className:`added`,children:n.added}):null,n.removed?(0,K.jsx)(`span`,{className:`removed`,children:n.removed}):null]})]}),i.map((e,t)=>e.diff?(0,K.jsx)(`pre`,{className:`code-codex-transcript-result-diff`,children:e.diff.split(`
103
103
  `).map((e,t)=>(0,K.jsxs)(`span`,{className:Uy(e),children:[e,`
104
- `]},`${t}:${e}`))},`${r}:${t}`):null),o&&a?(0,K.jsxs)(`div`,{className:`code-codex-transcript-result-decision`,"data-testid":`code-acp-patch-decision`,children:[c?(0,K.jsx)(`span`,{children:c===`reverted`?t.codexTranscriptChangeReverted:t.codexTranscriptChangeKept}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,disabled:!!_,onClick:()=>M(r,`keep`),children:t.codexTranscriptKeepChange}),(0,K.jsx)(`button`,{type:`button`,className:`revert`,disabled:!!_,onClick:()=>M(r,`revert`),children:t.codexTranscriptRevertChange})]}),y[r]?(0,K.jsx)(`small`,{role:`alert`,children:y[r]}):null]}):null]},`${e[0]?.id||`patch`}:${r}`)})}),!u&&!f?(0,K.jsx)(`div`,{className:`code-codex-transcript-result-loading`,children:t.codexTranscriptLoadingChanges}):null,f?(0,K.jsx)(`div`,{className:`code-codex-transcript-result-error`,children:f}):null,o!==`acp`||A.length>0?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-result-review`,"aria-label":`${t.codexTranscriptReviewChanges}: ${A.length} workspace ${A.length===1?`file`:`files`}`,onClick:N,children:t.codexTranscriptReviewChanges}):null]}):null]})}function Zy({turn:e,copy:t,onOpenFile:n,workspaceRoot:r,processOpen:i,groupProcessActions:a,source:o,onToggleProcess:s,onLoadProcessItemDetail:c,onLoadPatchChanges:l,onCreatePatchReview:u,onDecidePatch:d,onStopTerminal:f,onInputTerminal:p,onResizeTerminal:m,onStopSubagent:h,searchItemId:g}){let[_,v]=(0,W.useState)({}),y=(0,W.useRef)(new Set),b=(0,W.useMemo)(()=>e.processItems.map(e=>Object.prototype.hasOwnProperty.call(_,e.id)?{...e,detail:_[e.id]?.detail||``,terminals:_[e.id]?.terminals,subagentTranscript:_[e.id]?.subagentTranscript,detailTruncated:!1}:e),[_,e.processItems]),x=b.length>0,S=b.filter(ky),C=e.userImages||[],w=e.userAudios||[],T=e.userFiles||[],[E,D]=(0,W.useState)(``),[O,k]=(0,W.useState)(!1),[ee,te]=(0,W.useState)(()=>new Set),[A,j]=(0,W.useState)(()=>new Set),[,M]=(0,W.useState)(0),N=(0,W.useMemo)(()=>a?Ey(b):b.map(e=>({kind:`item`,item:e})),[a,b]),P=(0,W.useMemo)(()=>e.status===`inProgress`&&[...b].reverse().find(e=>[`reasoning`,`thought`].includes(e.type)&&!!String(e.detail||``).trim())?.id||``,[b,e.status]),F=L(),ne=(0,W.useMemo)(()=>Iv(e.finalMessage),[e.finalMessage]),I=e.status===`inProgress`&&!ne&&(!!e.userMessage||C.length>0||w.length>0||T.length>0||x);(0,W.useEffect)(()=>{if(e.status!==`inProgress`||!e.startedAt)return;let t=window.setInterval(()=>M(Date.now()),3e4);return()=>window.clearInterval(t)},[e.startedAt,e.status]);let R=e.status===`inProgress`?Av(e.startedAt):``,z=b===e.processItems?e:{...e,processItems:b},re=o===`acp`?jv(z,t):t.codexTranscriptWorking,B=o===`acp`?Mv(z,t):``,ie=(0,W.useCallback)(async(e,t=!1)=>{if(!e.detailTruncated&&!e.terminalIds?.length&&!e.subagentSessionId||!c)return{detail:e.detail||``,terminals:e.terminals,subagentTranscript:e.subagentTranscript};if(!t&&Object.prototype.hasOwnProperty.call(_,e.id))return _[e.id]||{detail:e.detail||``};if(y.current.has(e.id))return{detail:e.detail||``};y.current.add(e.id);try{let t=await c(e.id);return v(n=>({...n,[e.id]:t})),t}finally{y.current.delete(e.id)}},[_,c]);(0,W.useEffect)(()=>{if(!g)return;te(e=>{let t=new Set(e);t.add(g);for(let e of N)e.kind===`group`&&e.items.some(e=>e.id===g)&&t.add(e.id);return t});let e=b.find(e=>e.id===g);(e?.detailTruncated||e?.terminalIds?.length||e?.subagentSessionId)&&ie(e).catch(()=>{})},[ie,N,b,g]),(0,W.useEffect)(()=>{let e=b.filter(e=>e.terminalIds?.length&&vy(e)&&ee.has(e.id));if(e.length===0)return;let t=()=>e.forEach(e=>{ie(e,!0).catch(()=>{})});t();let n=window.setInterval(t,1e3);return()=>window.clearInterval(n)},[ie,ee,b]);let V=(0,W.useCallback)(e=>{ie(e).then(t=>{let n=[e.title,t.detail].filter(Boolean).join(`
104
+ `]},`${t}:${e}`))},`${r}:${t}`):null),o&&a?(0,K.jsxs)(`div`,{className:`code-codex-transcript-result-decision`,"data-testid":`code-acp-patch-decision`,children:[c?(0,K.jsx)(`span`,{children:c===`reverted`?t.codexTranscriptChangeReverted:t.codexTranscriptChangeKept}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,disabled:!!_,onClick:()=>N(r,`keep`),children:t.codexTranscriptKeepChange}),(0,K.jsx)(`button`,{type:`button`,className:`revert`,disabled:!!_,onClick:()=>N(r,`revert`),children:t.codexTranscriptRevertChange})]}),y[r]?(0,K.jsx)(`small`,{role:`alert`,children:y[r]}):null]}):null]},`${e[0]?.id||`patch`}:${r}`)})}),!u&&!f?(0,K.jsx)(`div`,{className:`code-codex-transcript-result-loading`,children:t.codexTranscriptLoadingChanges}):null,f?(0,K.jsx)(`div`,{className:`code-codex-transcript-result-error`,children:f}):null,o!==`acp`||j.length>0?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-result-review`,"aria-label":`${t.codexTranscriptReviewChanges}: ${j.length} workspace ${j.length===1?`file`:`files`}`,onClick:te,children:t.codexTranscriptReviewChanges}):null]}):null]})}function Zy({turn:e,copy:t,onOpenFile:n,workspaceRoot:r,processOpen:i,groupProcessActions:a,source:o,onToggleProcess:s,onLoadProcessItemDetail:c,onLoadPatchChanges:l,onCreatePatchReview:u,onDecidePatch:d,onStopTerminal:f,onInputTerminal:p,onResizeTerminal:m,onStopSubagent:h,searchItemId:g}){let[_,v]=(0,W.useState)({}),y=(0,W.useRef)(new Set),b=(0,W.useMemo)(()=>e.processItems.map(e=>Object.prototype.hasOwnProperty.call(_,e.id)?{...e,detail:_[e.id]?.detail||``,terminals:_[e.id]?.terminals,subagentTranscript:_[e.id]?.subagentTranscript,detailTruncated:!1}:e),[_,e.processItems]),x=b.length>0,S=b.filter(ky),C=e.userImages||[],w=e.userAudios||[],T=e.userFiles||[],[E,D]=(0,W.useState)(``),[O,k]=(0,W.useState)(!1),[A,ee]=(0,W.useState)(()=>new Set),[j,M]=(0,W.useState)(()=>new Set),[,N]=(0,W.useState)(0),te=(0,W.useMemo)(()=>a?Ey(b):b.map(e=>({kind:`item`,item:e})),[a,b]),P=(0,W.useMemo)(()=>e.status===`inProgress`&&[...b].reverse().find(e=>[`reasoning`,`thought`].includes(e.type)&&!!String(e.detail||``).trim())?.id||``,[b,e.status]),F=L(),ne=(0,W.useMemo)(()=>Iv(e.finalMessage),[e.finalMessage]),I=e.status===`inProgress`&&!ne&&(!!e.userMessage||C.length>0||w.length>0||T.length>0||x);(0,W.useEffect)(()=>{if(e.status!==`inProgress`||!e.startedAt)return;let t=window.setInterval(()=>N(Date.now()),3e4);return()=>window.clearInterval(t)},[e.startedAt,e.status]);let re=e.status===`inProgress`?Av(e.startedAt):``,R=b===e.processItems?e:{...e,processItems:b},z=o===`acp`?jv(R,t):t.codexTranscriptWorking,B=o===`acp`?Mv(R,t):``,ie=(0,W.useCallback)(async(e,t=!1)=>{if(!e.detailTruncated&&!e.terminalIds?.length&&!e.subagentSessionId||!c)return{detail:e.detail||``,terminals:e.terminals,subagentTranscript:e.subagentTranscript};if(!t&&Object.prototype.hasOwnProperty.call(_,e.id))return _[e.id]||{detail:e.detail||``};if(y.current.has(e.id))return{detail:e.detail||``};y.current.add(e.id);try{let t=await c(e.id);return v(n=>({...n,[e.id]:t})),t}finally{y.current.delete(e.id)}},[_,c]);(0,W.useEffect)(()=>{if(!g)return;ee(e=>{let t=new Set(e);t.add(g);for(let e of te)e.kind===`group`&&e.items.some(e=>e.id===g)&&t.add(e.id);return t});let e=b.find(e=>e.id===g);(e?.detailTruncated||e?.terminalIds?.length||e?.subagentSessionId)&&ie(e).catch(()=>{})},[ie,te,b,g]),(0,W.useEffect)(()=>{let e=b.filter(e=>e.terminalIds?.length&&vy(e)&&A.has(e.id));if(e.length===0)return;let t=()=>e.forEach(e=>{ie(e,!0).catch(()=>{})});t();let n=window.setInterval(t,1e3);return()=>window.clearInterval(n)},[ie,A,b]);let V=(0,W.useCallback)(e=>{ie(e).then(t=>{let n=[e.title,t.detail].filter(Boolean).join(`
105
105
 
106
- `);if(n)return Ky(n)}).then(t=>{t&&(D(e.id),window.setTimeout(()=>D(t=>t===e.id?``:t),1200))}).catch(()=>{})},[ie]),ae=(0,W.useCallback)(()=>{let e=ne.trim();e&&Ky(e).then(e=>{e&&(k(!0),window.setTimeout(()=>k(!1),1200))})},[ne]),oe=(0,W.useCallback)(()=>{s(e.id)},[s,e.id]),se=(0,W.useCallback)(e=>{if(e===P&&!ee.has(e)){j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return}if(!ee.has(e)){let t=b.find(t=>t.id===e);(t?.detailTruncated||t?.terminalIds?.length||t?.subagentSessionId)&&ie(t).catch(()=>{})}te(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[P,ie,ee,b]),ce=(0,W.useCallback)(async(e,t)=>{if(!f)return;await f(t);let n=b.find(t=>t.id===e);n&&await ie(n,!0)},[ie,f,b]),le=(0,W.useCallback)(async(e,t,n)=>{if(!p)return;await p(t,n);let r=b.find(t=>t.id===e);r&&await ie(r,!0)},[ie,p,b]),ue=(0,W.useCallback)(async(e,t,n,r)=>{m&&await m(t,n,r)},[m]),de=i,pe=(0,W.useMemo)(()=>({a:({href:e,children:t,onClick:i,...a})=>{let o=e?Yv(e,r):null,s=e?Lv(e):!1,c=e&&Bv(e),l=e=>{i?.(e),!(e.defaultPrevented||!o||!n)&&(e.preventDefault(),n(o.filePath,o.target))};return(0,K.jsx)(`a`,{...a,className:[a.className,o?`code-codex-transcript-markdown-file-link`:``].filter(Boolean).join(` `)||void 0,href:o?`#`:c,target:s?`_blank`:void 0,rel:s?`noreferrer`:void 0,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:l,children:o?(0,K.jsx)(sy,{filePath:o.filePath,lineNumber:o.target?.lineNumber,children:t}):t})},code:({className:e,children:t,...i})=>{let a=Qv(t),o=!(e||a.includes(`
107
- `))&&Xv(a)?Yv(a,r):null;return!o||!n?(0,K.jsx)(`code`,{className:e,...i,children:t}):(0,K.jsx)(`a`,{className:`code-codex-transcript-markdown-file-link`,href:`#`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),n(o.filePath,o.target)},children:(0,K.jsx)(sy,{filePath:o.filePath,lineNumber:o.target?.lineNumber,children:t})})},pre:({children:e,...n})=>{let r=ey(e);return r===null?(0,K.jsx)(`pre`,{...n,children:e}):(0,K.jsx)(U,{source:r,copy:t})}}),[t,n,r]);return(0,K.jsxs)(`article`,{className:`code-codex-transcript-turn ${e.status===`inProgress`?`running`:``}`,"data-turn-id":e.id,children:[e.userMessage||C.length>0||w.length>0||T.length>0?(0,K.jsxs)(`div`,{className:`code-codex-transcript-user`,children:[e.userMessage?(0,K.jsx)(`div`,{children:Fv(e.userMessage)}):null,(0,K.jsx)(ny,{images:C}),(0,K.jsx)(ly,{audios:w}),(0,K.jsx)(ay,{files:T})]}):null,x?(0,K.jsxs)(`div`,{className:`code-codex-transcript-process ${de?`expanded`:``}`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-process-summary`,"data-testid":`code-codex-transcript-process-summary`,"aria-expanded":de,title:Pv(e,t),onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Gy(e.currentTarget,oe)},onKeyDown:e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),e.stopPropagation(),Gy(e.currentTarget,oe))},children:[(0,K.jsx)(`span`,{children:Nv(e,t,re,B)}),(0,K.jsx)(fe,{className:`code-codex-transcript-chevron`})]}),de?(0,K.jsx)(`div`,{className:`code-codex-transcript-process-list`,children:N.map(e=>{if(e.kind===`group`){let n=ee.has(e.id)||o!==`acp`&&!F&&e.items.some(vy);return(0,K.jsx)(Yy,{groupId:e.id,items:e.items,summaryLabel:o===`acp`?uv(e.items):void 0,copy:t,copiedItemId:E,detailOpen:n,openProcessItemIds:P&&!A.has(P)?new Set([...ee,P]):ee,onToggleGroup:se,onToggleItem:se,onCopy:V,onStopTerminal:ce,onInputTerminal:le,onResizeTerminal:ue,onStopSubagent:h},e.id)}if(o===`acp`&&dv(e.item)){let t=String(e.item.detail||``).trim();return t?(0,K.jsx)(`div`,{className:`code-acp-progress-update code-markdown-preview`,"data-testid":`code-acp-progress-update`,children:(0,K.jsx)(je,{remarkPlugins:[Te,we],rehypePlugins:[Ee,De],components:pe,skipHtml:!0,urlTransform:ty,children:t})},e.item.id):null}return(0,K.jsx)(Jy,{item:e.item,copy:t,copied:E===e.item.id,detailOpen:ee.has(e.item.id)||e.item.id===P&&!A.has(e.item.id),onToggle:se,onCopy:V,onStopTerminal:ce,onInputTerminal:le,onResizeTerminal:ue,onStopSubagent:h},e.item.id)})}):null]}):null,ne?(0,K.jsxs)(`div`,{className:`code-codex-transcript-answer`,children:[(0,K.jsx)(`div`,{className:`code-codex-transcript-assistant code-markdown-preview`,children:(0,K.jsx)(je,{remarkPlugins:[Te,we],rehypePlugins:[Ee,De],components:pe,skipHtml:!0,urlTransform:ty,children:ne})}),(0,K.jsx)(`div`,{className:`code-codex-transcript-answer-actions`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-answer-action ${O?`copied`:``}`,"data-testid":`code-codex-transcript-copy-answer`,"aria-label":O?t.codexTranscriptCopiedAnswer:t.codexTranscriptCopyAnswer,title:O?t.codexTranscriptCopiedAnswer:t.codexTranscriptCopyAnswer,"data-tooltip":O?t.codexTranscriptCopiedAnswer:t.codexTranscriptCopyAnswer,onClick:ae,children:O?(0,K.jsx)(me,{}):(0,K.jsx)(H,{})})})]}):I?(0,K.jsx)(`div`,{className:`code-codex-transcript-placeholder`,children:t.codexTranscriptWaiting}):null,S.length>0||e.status===`inProgress`?(0,K.jsxs)(`div`,{className:`code-codex-transcript-results code-codex-transcript-status-row`,children:[S.length>0?(0,K.jsx)(Xy,{items:S,copy:t,onLoadPatchChanges:l,onCreateReview:u,onDecidePatch:d,source:o,workspaceRoot:r}):null,e.status===`inProgress`?(0,K.jsx)(`span`,{className:`code-codex-transcript-progress`,children:[re,R].filter(Boolean).join(` `)}):null]}):null]})}var Qy=(0,W.memo)(Zy);function $y({agentId:e,workspaceRoot:t,active:r,source:i=`legacy-jsonl`,refreshSignal:a=0,onOpenWorkspaceFilePath:o,onAvailabilityChange:s,onReadLatest:c,groupProcessActions:l=!0,copy:u}){let[d,f]=(0,W.useState)(null),p=(0,W.useRef)(null),[m,h]=(0,W.useState)(!0),[g,_]=(0,W.useState)(``),[v,y]=(0,W.useState)(()=>new Set),[b,x]=(0,W.useState)(()=>new Set),[S,C]=(0,W.useState)(()=>Ev(i)),[w,T]=(0,W.useState)(!1),[E,D]=(0,W.useState)(!1),[O,k]=(0,W.useState)(!1),[ee,te]=(0,W.useState)(``),[A,j]=(0,W.useState)(0),M=(0,W.useRef)(null),N=(0,W.useRef)(null),P=(0,W.useRef)(null),F=(0,W.useRef)(null),ne=(0,W.useRef)(!0),I=(0,W.useRef)(!1),L=(0,W.useRef)(null),R=(0,W.useRef)(!1),z=(0,W.useRef)(!1);(0,W.useEffect)(()=>{f(null),p.current=null,_(``),h(!0),T(!1),C(Ev(i)),y(new Set),x(new Set),D(!1),k(!1),te(``),j(0),ne.current=!0,R.current=!1,z.current=!1,F.current=null},[e,i]),(0,W.useEffect)(()=>()=>{L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),(0,W.useEffect)(()=>{if(!r)return;let e=()=>{let e=P.current;if(e){if(xy(e)){ne.current=!1,z.current=!0;return}R.current||z.current&&(z.current=!1,D(!by(e)&&e.scrollHeight>e.clientHeight+Ov))}},t=()=>{window.requestAnimationFrame(()=>{R.current=!1,e()})};return document.addEventListener(`selectionchange`,e),document.addEventListener(`pointerup`,t),document.addEventListener(`pointercancel`,t),()=>{document.removeEventListener(`selectionchange`,e),document.removeEventListener(`pointerup`,t),document.removeEventListener(`pointercancel`,t),R.current=!1,z.current=!1}},[r]),(0,W.useEffect)(()=>{if(!r)return;let t=!1,a=null,o=null,s=()=>{o?.abort(),o=new AbortController;let r=new URLSearchParams({maxTurns:String(S)}),a=p.current;i===`acp`&&a?.sessionId&&a.turnLimit===S&&Number.isFinite(a.revision)&&r.set(`sinceRevision`,String(a.revision)),fetch(n(`/api/agents/${encodeURIComponent(e)}/${i===`acp`?`acp-transcript`:i===`app-server`?`codex-app-server-transcript`:i===`json-cli`?`json-cli-transcript`:`codex-transcript`}?${r.toString()}`),{signal:o.signal}).then(e=>{if(!e.ok)throw Error(u.codexTranscriptUnavailable);return e.json()}).then(e=>{if(t)return;let n=i===`acp`&&e.transcript?sv(e.transcript,{maxTurns:S}):e.transcript||null;f(e=>{let t=i===`acp`?yv(e,n):vv(e,n);return p.current=t,t}),_(``),h(!1),T(!1)}).catch(e=>{t||e?.name===`AbortError`||(_(e?.message||u.codexTranscriptUnavailable),h(!1),T(!1))})};return s(),i!==`acp`&&(a=window.setInterval(s,3e3)),()=>{t=!0,o?.abort(),a&&window.clearInterval(a)}},[r,e,u.codexTranscriptUnavailable,a,i,S]);let re=(0,W.useMemo)(()=>d?.turns||[],[d]),B=(0,W.useMemo)(()=>{let e=ee.trim().toLocaleLowerCase();return e?re.flatMap(t=>{let n=[];[t.userMessage,t.finalMessage].join(`
106
+ `);if(n)return Ky(n)}).then(t=>{t&&(D(e.id),window.setTimeout(()=>D(t=>t===e.id?``:t),1200))}).catch(()=>{})},[ie]),ae=(0,W.useCallback)(()=>{let e=ne.trim();e&&Ky(e).then(e=>{e&&(k(!0),window.setTimeout(()=>k(!1),1200))})},[ne]),oe=(0,W.useCallback)(()=>{s(e.id)},[s,e.id]),se=(0,W.useCallback)(e=>{if(e===P&&!A.has(e)){M(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return}if(!A.has(e)){let t=b.find(t=>t.id===e);(t?.detailTruncated||t?.terminalIds?.length||t?.subagentSessionId)&&ie(t).catch(()=>{})}ee(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[P,ie,A,b]),ce=(0,W.useCallback)(async(e,t)=>{if(!f)return;await f(t);let n=b.find(t=>t.id===e);n&&await ie(n,!0)},[ie,f,b]),le=(0,W.useCallback)(async(e,t,n)=>{if(!p)return;await p(t,n);let r=b.find(t=>t.id===e);r&&await ie(r,!0)},[ie,p,b]),ue=(0,W.useCallback)(async(e,t,n,r)=>{m&&await m(t,n,r)},[m]),de=i,pe=(0,W.useMemo)(()=>({a:({href:e,children:t,onClick:i,...a})=>{let o=e?Yv(e,r):null,s=e?Lv(e):!1,c=e&&Bv(e),l=e=>{i?.(e),!(e.defaultPrevented||!o||!n)&&(e.preventDefault(),n(o.filePath,o.target))};return(0,K.jsx)(`a`,{...a,className:[a.className,o?`code-codex-transcript-markdown-file-link`:``].filter(Boolean).join(` `)||void 0,href:o?`#`:c,target:s?`_blank`:void 0,rel:s?`noreferrer`:void 0,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:l,children:o?(0,K.jsx)(sy,{filePath:o.filePath,lineNumber:o.target?.lineNumber,children:t}):t})},code:({className:e,children:t,...i})=>{let a=Qv(t),o=!(e||a.includes(`
107
+ `))&&Xv(a)?Yv(a,r):null;return!o||!n?(0,K.jsx)(`code`,{className:e,...i,children:t}):(0,K.jsx)(`a`,{className:`code-codex-transcript-markdown-file-link`,href:`#`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.preventDefault(),n(o.filePath,o.target)},children:(0,K.jsx)(sy,{filePath:o.filePath,lineNumber:o.target?.lineNumber,children:t})})},pre:({children:e,...n})=>{let r=ey(e);return r===null?(0,K.jsx)(`pre`,{...n,children:e}):(0,K.jsx)(U,{source:r,copy:t})}}),[t,n,r]);return(0,K.jsxs)(`article`,{className:`code-codex-transcript-turn ${e.status===`inProgress`?`running`:``}`,"data-turn-id":e.id,children:[e.userMessage||C.length>0||w.length>0||T.length>0?(0,K.jsxs)(`div`,{className:`code-codex-transcript-user`,children:[e.userMessage?(0,K.jsx)(`div`,{children:Fv(e.userMessage)}):null,(0,K.jsx)(ny,{images:C}),(0,K.jsx)(ly,{audios:w}),(0,K.jsx)(ay,{files:T})]}):null,x?(0,K.jsxs)(`div`,{className:`code-codex-transcript-process ${de?`expanded`:``}`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-codex-transcript-process-summary`,"data-testid":`code-codex-transcript-process-summary`,"aria-expanded":de,title:Pv(e,t),onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),Gy(e.currentTarget,oe)},onKeyDown:e=>{e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),e.stopPropagation(),Gy(e.currentTarget,oe))},children:[(0,K.jsx)(`span`,{children:Nv(e,t,z,B)}),(0,K.jsx)(fe,{className:`code-codex-transcript-chevron`})]}),de?(0,K.jsx)(`div`,{className:`code-codex-transcript-process-list`,children:te.map(e=>{if(e.kind===`group`){let n=A.has(e.id)||o!==`acp`&&!F&&e.items.some(vy);return(0,K.jsx)(Yy,{groupId:e.id,items:e.items,summaryLabel:o===`acp`?uv(e.items):void 0,copy:t,copiedItemId:E,detailOpen:n,openProcessItemIds:P&&!j.has(P)?new Set([...A,P]):A,onToggleGroup:se,onToggleItem:se,onCopy:V,onStopTerminal:ce,onInputTerminal:le,onResizeTerminal:ue,onStopSubagent:h},e.id)}if(o===`acp`&&dv(e.item)){let t=String(e.item.detail||``).trim();return t?(0,K.jsx)(`div`,{className:`code-acp-progress-update code-markdown-preview`,"data-testid":`code-acp-progress-update`,children:(0,K.jsx)(je,{remarkPlugins:[Te,we],rehypePlugins:[Ee,De],components:pe,skipHtml:!0,urlTransform:ty,children:t})},e.item.id):null}return(0,K.jsx)(Jy,{item:e.item,copy:t,copied:E===e.item.id,detailOpen:A.has(e.item.id)||e.item.id===P&&!j.has(e.item.id),onToggle:se,onCopy:V,onStopTerminal:ce,onInputTerminal:le,onResizeTerminal:ue,onStopSubagent:h},e.item.id)})}):null]}):null,ne?(0,K.jsxs)(`div`,{className:`code-codex-transcript-answer`,children:[(0,K.jsx)(`div`,{className:`code-codex-transcript-assistant code-markdown-preview`,children:(0,K.jsx)(je,{remarkPlugins:[Te,we],rehypePlugins:[Ee,De],components:pe,skipHtml:!0,urlTransform:ty,children:ne})}),(0,K.jsx)(`div`,{className:`code-codex-transcript-answer-actions`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-answer-action ${O?`copied`:``}`,"data-testid":`code-codex-transcript-copy-answer`,"aria-label":O?t.codexTranscriptCopiedAnswer:t.codexTranscriptCopyAnswer,title:O?t.codexTranscriptCopiedAnswer:t.codexTranscriptCopyAnswer,"data-tooltip":O?t.codexTranscriptCopiedAnswer:t.codexTranscriptCopyAnswer,onClick:ae,children:O?(0,K.jsx)(me,{}):(0,K.jsx)(H,{})})})]}):I?(0,K.jsx)(`div`,{className:`code-codex-transcript-placeholder`,children:t.codexTranscriptWaiting}):null,S.length>0||e.status===`inProgress`?(0,K.jsxs)(`div`,{className:`code-codex-transcript-results code-codex-transcript-status-row`,children:[S.length>0?(0,K.jsx)(Xy,{items:S,copy:t,onLoadPatchChanges:l,onCreateReview:u,onDecidePatch:d,source:o,workspaceRoot:r}):null,e.status===`inProgress`?(0,K.jsx)(`span`,{className:`code-codex-transcript-progress`,children:[z,re].filter(Boolean).join(` `)}):null]}):null]})}var Qy=(0,W.memo)(Zy);function $y({agentId:e,workspaceRoot:t,active:r,source:i=`legacy-jsonl`,refreshSignal:a=0,onOpenWorkspaceFilePath:o,onAvailabilityChange:s,onReadLatest:c,groupProcessActions:l=!0,copy:u}){let[d,f]=(0,W.useState)(null),p=(0,W.useRef)(null),[m,h]=(0,W.useState)(!0),[g,_]=(0,W.useState)(``),[v,y]=(0,W.useState)(()=>new Set),[b,x]=(0,W.useState)(()=>new Set),[S,C]=(0,W.useState)(()=>Ev(i)),[w,T]=(0,W.useState)(!1),[E,D]=(0,W.useState)(!1),[O,k]=(0,W.useState)(!1),[A,ee]=(0,W.useState)(``),[j,M]=(0,W.useState)(0),N=(0,W.useRef)(null),te=(0,W.useRef)(null),P=(0,W.useRef)(null),F=(0,W.useRef)(null),ne=(0,W.useRef)(!0),I=(0,W.useRef)(!1),L=(0,W.useRef)(null),re=(0,W.useRef)(!1),R=(0,W.useRef)(!1);(0,W.useEffect)(()=>{f(null),p.current=null,_(``),h(!0),T(!1),C(Ev(i)),y(new Set),x(new Set),D(!1),k(!1),ee(``),M(0),ne.current=!0,re.current=!1,R.current=!1,F.current=null},[e,i]),(0,W.useEffect)(()=>()=>{L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),(0,W.useEffect)(()=>{if(!r)return;let e=()=>{let e=P.current;if(e){if(xy(e)){ne.current=!1,R.current=!0;return}re.current||R.current&&(R.current=!1,D(!by(e)&&e.scrollHeight>e.clientHeight+Ov))}},t=()=>{window.requestAnimationFrame(()=>{re.current=!1,e()})};return document.addEventListener(`selectionchange`,e),document.addEventListener(`pointerup`,t),document.addEventListener(`pointercancel`,t),()=>{document.removeEventListener(`selectionchange`,e),document.removeEventListener(`pointerup`,t),document.removeEventListener(`pointercancel`,t),re.current=!1,R.current=!1}},[r]),(0,W.useEffect)(()=>{if(!r)return;let t=!1,a=null,o=null,s=()=>{o?.abort(),o=new AbortController;let r=new URLSearchParams({maxTurns:String(S)}),a=p.current;i===`acp`&&a?.sessionId&&a.turnLimit===S&&Number.isFinite(a.revision)&&r.set(`sinceRevision`,String(a.revision)),fetch(n(`/api/agents/${encodeURIComponent(e)}/${i===`acp`?`acp-transcript`:i===`app-server`?`codex-app-server-transcript`:i===`json-cli`?`json-cli-transcript`:`codex-transcript`}?${r.toString()}`),{signal:o.signal}).then(e=>{if(!e.ok)throw Error(u.codexTranscriptUnavailable);return e.json()}).then(e=>{if(t)return;let n=i===`acp`&&e.transcript?sv(e.transcript,{maxTurns:S}):e.transcript||null;f(e=>{let t=i===`acp`?yv(e,n):vv(e,n);return p.current=t,t}),_(``),h(!1),T(!1)}).catch(e=>{t||e?.name===`AbortError`||(_(e?.message||u.codexTranscriptUnavailable),h(!1),T(!1))})};return s(),i!==`acp`&&(a=window.setInterval(s,3e3)),()=>{t=!0,o?.abort(),a&&window.clearInterval(a)}},[r,e,u.codexTranscriptUnavailable,a,i,S]);let z=(0,W.useMemo)(()=>d?.turns||[],[d]),B=(0,W.useMemo)(()=>{let e=A.trim().toLocaleLowerCase();return e?z.flatMap(t=>{let n=[];[t.userMessage,t.finalMessage].join(`
108
108
  `).toLocaleLowerCase().includes(e)&&n.push({turnId:t.id});for(let r of t.processItems)[r.title,r.detail||``].join(`
109
- `).toLocaleLowerCase().includes(e)&&n.push({turnId:t.id,itemId:r.id});return n}):[]},[ee,re]);(0,W.useEffect)(()=>{O&&(C(Tv),window.requestAnimationFrame(()=>N.current?.focus({preventScroll:!0})))},[O]),(0,W.useEffect)(()=>{j(e=>Math.min(e,Math.max(0,B.length-1)))},[B.length]),(0,W.useEffect)(()=>{let e=M.current;if(!e)return;e.querySelectorAll(`.code-codex-transcript-turn.search-match`).forEach(e=>e.classList.remove(`search-match`)),e.querySelectorAll(`.code-codex-transcript-process-item.search-match`).forEach(e=>e.classList.remove(`search-match`));let t=B[A];!O||!t||(y(e=>new Set(e).add(t.turnId)),x(e=>{let n=new Set(e);return n.delete(t.turnId),n}),window.requestAnimationFrame(()=>{let n=e.querySelector(`[data-turn-id="${CSS.escape(t.turnId)}"]`),r=(t.itemId?n?.querySelector(`[data-process-item-id="${CSS.escape(t.itemId)}"]`):null)||n;r?.classList.add(`search-match`),r?.scrollIntoView({block:`center`})}))},[A,B,O]),(0,W.useEffect)(()=>{if(!r||!d?.available||re.length===0)return;let e=P.current,t=e?by(e):ne.current;e&&(R.current||xy(e))||t&&c?.()},[r,c,d?.available,d?.updatedAt,re.length]),(0,W.useLayoutEffect)(()=>{if(m||!d?.available||re.length===0)return;let t=P.current;if(!t||I.current)return;let n=xy(t);if(R.current||n){n&&(ne.current=!1,z.current=!0);return}let i=F.current;if(i){F.current=null,window.requestAnimationFrame(()=>{if(R.current||xy(t))return;let n=t.scrollHeight-i.scrollHeight+i.scrollTop;t.scrollTop=Math.max(0,n),bv.set(e,t.scrollTop)});return}if(ne.current){window.requestAnimationFrame(()=>{R.current||xy(t)||(t.scrollTop=t.scrollHeight,bv.set(e,t.scrollTop),D(!1),r&&c?.())});return}let a=bv.get(e);!a||a<=0||window.requestAnimationFrame(()=>{R.current||xy(t)||(t.scrollTop=Math.min(a,Math.max(0,t.scrollHeight-t.clientHeight)))})},[r,e,m,c,d?.available,d?.updatedAt,re.length]),(0,W.useEffect)(()=>()=>{let t=P.current;t&&bv.set(e,t.scrollTop)},[e]),(0,W.useEffect)(()=>{s?.({loading:m,hasContent:!!(d?.available&&re.length>0),available:!!d?.available})},[m,s,d?.available,re.length]);let V=(0,W.useCallback)((t,n)=>o?.(e,t,{...n,suppressSearchOnMiss:!0}),[e,o]),ae=(0,W.useCallback)(async t=>{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-tool-details/${encodeURIComponent(t)}`)),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||u.codexTranscriptUnavailable);return{detail:String(i.detail||``),terminals:Array.isArray(i.terminals)?i.terminals:void 0,subagentTranscript:i.subagentSession&&typeof i.subagentSession==`object`?sv(i.subagentSession,{maxTurns:12}):void 0}},[e,u.codexTranscriptUnavailable]),oe=(0,W.useCallback)(t=>Me(e,t),[e]),se=(0,W.useCallback)(t=>{let r=new URLSearchParams({agentId:e});return t.forEach(e=>r.append(`acpItem`,e)),n(`/review?${r.toString()}`)},[e]),ce=(0,W.useCallback)(async(t,r,i)=>{let a=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-patches/${encodeURIComponent(t)}/decision`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:r,decision:i})}),o=await a.json().catch(()=>({}));if(!a.ok||!o.action)throw Error(o.error||`Failed to decide file change`);return{action:o.action}},[e]),ue=(0,W.useCallback)(async t=>{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/kill`),{method:`POST`}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||`Failed to stop command`)},[e]),de=(0,W.useCallback)(async(t,r)=>{let i=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/input`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:r})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a.error||`Failed to send terminal input`)},[e]),fe=(0,W.useCallback)(async(t,r,i)=>{let a=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/resize`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cols:r,rows:i})}),o=await a.json().catch(()=>({}));if(!a.ok)throw Error(o.error||`Failed to resize terminal`)},[e]),pe=(0,W.useCallback)(async t=>{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-subagents/${encodeURIComponent(t)}/cancel`),{method:`POST`}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||`Failed to stop subagent`)},[e]),me=(0,W.useCallback)(e=>{!d?.hasMoreBefore||w||S>=Tv||(F.current={scrollTop:e.scrollTop,scrollHeight:e.scrollHeight},T(!0),C(e=>{let t=Math.min(Tv,e+(i===`acp`?wv:Sv));return t===e&&T(!1),t}))},[w,i,d?.hasMoreBefore,S]),H=(0,W.useCallback)(()=>{I.current=!0,L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),he=(0,W.useCallback)(()=>{L.current!==null&&window.clearTimeout(L.current),L.current=window.setTimeout(()=>{I.current=!1,L.current=null},420)},[]),ge=(0,W.useCallback)(()=>{H()},[H]),ve=(0,W.useCallback)(()=>{H()},[H]),ye=(0,W.useCallback)(()=>{he()},[he]),be=(0,W.useCallback)(()=>{let t=P.current;if(!t)return;if(bv.set(e,t.scrollTop),R.current||xy(t)){ne.current=!1,z.current=!0;return}let n=by(t);ne.current=n,D(!n&&t.scrollHeight>t.clientHeight+Ov),r&&n&&c?.(),t.scrollTop<=Dv&&me(t)},[r,e,c,me]),xe=(0,W.useCallback)(e=>{if(H(),he(),e.deltaY>=0)return;let t=P.current;!t||t.scrollTop>Dv||me(t)},[he,H,me]),Se=(0,W.useCallback)(e=>{if(e.button!==0||e.pointerType===`touch`)return;let t=e.target;t instanceof Element&&t.closest(`button, a, input, textarea, select, summary, [role="button"]`)||(R.current=!0)},[]),Ce=(0,W.useCallback)(e=>{let t=re.find(t=>t.id===e);if(i===`acp`&&t?.status===`inProgress`){x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return}y(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[i,re]),we=(0,W.useCallback)(()=>{let t=P.current;t&&(ne.current=!0,z.current=!1,t.scrollTop=t.scrollHeight,bv.set(e,t.scrollHeight),D(!1),c?.())},[e,c]);return(0,K.jsxs)(`div`,{className:`code-codex-transcript`,"data-testid":`code-codex-transcript`,ref:M,children:[i===`acp`&&d?.available?(0,K.jsx)(`div`,{className:`code-codex-transcript-search ${O?`open`:``}`,"data-testid":`code-acp-transcript-search`,children:O?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`input`,{ref:N,type:`search`,value:ee,"aria-label":`Search this chat`,placeholder:`Search chat`,onChange:e=>{te(e.target.value),j(0)},onKeyDown:e=>{e.key===`Escape`&&(k(!1),te(``)),e.key===`Enter`&&B.length>0&&j(t=>(t+(e.shiftKey?-1:1)+B.length)%B.length)}}),(0,K.jsx)(`span`,{children:B.length>0?`${A+1}/${B.length}`:`0/0`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Previous match`,disabled:B.length===0,onClick:()=>j(e=>(e-1+B.length)%B.length),children:`↑`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Next match`,disabled:B.length===0,onClick:()=>j(e=>(e+1)%B.length),children:`↓`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Close chat search`,onClick:()=>{k(!1),te(``)},children:(0,K.jsx)(le,{})})]}):(0,K.jsx)(`button`,{type:`button`,"aria-label":`Search this chat`,onClick:()=>k(!0),children:(0,K.jsx)(ie,{})})}):null,m?(0,K.jsx)(`div`,{className:`code-codex-transcript-state subtle`,children:u.codexTranscriptSyncing}):g?(0,K.jsx)(`div`,{className:`code-codex-transcript-state`,role:`status`,children:g}):d?.available?re.length===0?(0,K.jsx)(`div`,{className:`code-codex-transcript-blank`}):(0,K.jsx)(`div`,{className:`code-codex-transcript-scroll`,"data-testid":`code-codex-transcript-scroll`,ref:P,onPointerDown:Se,onScroll:be,onWheel:xe,onTouchStart:ge,onTouchMove:ve,onTouchEnd:ye,onTouchCancel:ye,children:re.map(e=>{let n=i===`acp`&&e.status===`inProgress`&&!b.has(e.id);return(0,K.jsx)(Qy,{turn:e,copy:u,onOpenFile:o?V:void 0,workspaceRoot:t,processOpen:v.has(e.id)||n,groupProcessActions:l,source:i,onToggleProcess:Ce,onLoadProcessItemDetail:i===`acp`?ae:void 0,onLoadPatchChanges:i===`acp`?oe:void 0,onCreatePatchReview:i===`acp`?se:void 0,onDecidePatch:i===`acp`?ce:void 0,onStopTerminal:i===`acp`?ue:void 0,onInputTerminal:i===`acp`?de:void 0,onResizeTerminal:i===`acp`?fe:void 0,onStopSubagent:i===`acp`?pe:void 0,searchItemId:O&&B[A]?.turnId===e.id?B[A]?.itemId:void 0},e.id)})}):(0,K.jsx)(`div`,{className:`code-codex-transcript-blank`}),E?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-jump-bottom`,"data-testid":`code-codex-transcript-jump-bottom`,"aria-label":`Jump to latest chat`,onClick:we,children:(0,K.jsx)(_e,{})}):null]})}function eb(e){return(0,K.jsx)($y,{...e,source:`app-server`})}function tb(e){return(0,K.jsx)($y,{...e,source:`json-cli`})}function nb(e){return(0,K.jsx)($y,{...e,source:`acp`,groupProcessActions:!0})}function rb(e){let t=(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e)),n=t?.split(`/`).pop()||``;return n===`codex`?`codex`:n===`claude`?`claude`:[`bash`,`zsh`,`sh`,`fish`].includes(n)?`shell`:t?`agent`:null}function ib(e){if(!e)return``;let t=typeof e.previewText==`string`?e.previewText:``;return t.trim()?t.toLowerCase():(e.output||``).slice(-1800).toLowerCase()}function ab(e,t){return t.reduce((t,n)=>Math.max(t,e.lastIndexOf(n)),-1)}function ob(e,t){let n=Array.from(e.matchAll(t));return(n.length>0?n[n.length-1]:void 0)?.index??-1}function sb(e){return ob(e,/(?:^|\n)\s*(?:gpt|codex)[^\n]*(?:·|•)\s*(?:~|\/)[^\n]*$/gim)}function cb(e){let t=ab(e,[`pursuing goal`,`esc to interrupt`,`press esc to interrupt`,`reconnecting`,`/stop to close`,`background terminal running`]),n=/\bworking\b/.test(e)?e.lastIndexOf(`working`):-1,r=ob(e,/step\s+\d+\s*\/\s*\d+/g);return Math.max(t,n,r)}function lb(e){let t=ab(e,[`pursuing goal`,`reconnecting`,`/stop to close`,`background terminal running`,`messages to be submitted after next tool call`,`stream disconnected before completion`]),n=/\bworking\b/.test(e)?e.lastIndexOf(`working`):-1,r=ob(e,/step\s+\d+\s*\/\s*\d+/g);return Math.max(t,n,r)}function ub(e){return ab(e,[`goal blocked`,`input exceeds the context window`,`please adjust your input and try again`])}function db(e){return e.trim().replace(/^[\s**✳✱✲✶·•:.\u2800-\u28FF]+/u,``).replace(/\s+/g,` `).toLowerCase()}function fb(e){let t=typeof e?.sessionTitle==`string`?e.sessionTitle.trim():``;if(!/^[\u2800-\u28ff]/u.test(t))return null;let n=e?.terminalStatus?.kind;return n===`codex`?{kind:`codex`,source:`terminal-title`}:n&&n!==`unknown`?null:rb(e?.command)===`codex`?{kind:`codex`,source:`terminal-title`}:null}function pb(e){let t=db(e?.sessionTitle||``);return t?/\bclaude(?:\s+code)?\b/.test(t)?{kind:`claude`,source:`terminal-title`}:/\bcodex\b/.test(t)?{kind:`codex`,source:`terminal-title`}:/^(?:bash|zsh|sh|fish)(?:\s|$)/.test(t)?{kind:`shell`,source:`terminal-title`}:null:null}function mb(e){let t=[],n=Math.max(sb(e),lb(e),ob(e,/(?:^|\n)\s*›\s/g));n>=0&&t.push({kind:`codex`,source:`terminal-output`,index:n});let r=Math.max(ab(e,[`claude code`]),ob(e,/(?:thinking|claude)[\s\S]*(?:esc|escape|ctrl\+c|ctrl-c) to interrupt/g));r>=0&&t.push({kind:`claude`,source:`terminal-output`,index:r});let i=ob(e,/(?:^|\n)\s*(?:[\w./~:@-]+\s*)?[$%#]\s*$/gm);i>=0&&t.push({kind:`shell`,source:`terminal-output`,index:i});let a=t.sort((e,t)=>t.index-e.index)[0];return a?{kind:a.kind,source:a.source}:null}function hb(e){if(!e)return{kind:null,source:`none`};let t=fb(e);if(t)return t;let n=e.terminalStatus?.kind;return n===`codex`||n===`claude`||n===`shell`?{kind:n,source:`terminal-status`}:n===`process`?{kind:`agent`,source:`terminal-status`}:mb(ib(e))||(e.terminalBusy===!0?{kind:`shell`,source:`terminal-busy`}:pb(e)||{kind:rb(e.command),source:e.command?`launch-command`:`none`})}function gb(e){return fb(e)?.kind===`codex`}function _b(e){if(!e)return!1;if(e.status===`pending`)return!0;if(e.status!==`running`)return!1;let t=ib(e);if(!t){let t=typeof e.startedAt==`number`?e.startedAt:0;return t>0&&Date.now()-t<5e3}let n=ub(t),r=t.lastIndexOf(`stream disconnected before completion`);if(n>=0&&n>=r)return!1;if(t.includes(`messages to be submitted after next tool call`)||gb(e)||r>=0)return!0;let i=cb(t);return i<0?!1:sb(t)<=i}function vb(e){if(!e)return!1;if(e.status===`pending`)return!0;if(e.status!==`running`)return!1;let t=ib(e);return t.includes(`esc to interrupt`)||t.includes(`escape to interrupt`)||t.includes(`ctrl+c to interrupt`)||t.includes(`ctrl-c to interrupt`)||t.includes(`press esc to interrupt`)}function yb(e){return!e||e.status!==`running`?!1:e.terminalStatus?.activity===`busy`?!0:e.terminalStatus?.activity===`idle`||e.terminalStatus?.activity===`exited`?!1:e.terminalBusy===!0}function bb(e){let t=hb(e),n=e?.terminalStatus?e.terminalStatus.busy===!0:e?.terminalBusy===!0,r=gb(e),i=!1;e?.terminalStatus?.activity===`busy`&&e.status===`running`?i=!0:e?.terminalStatus?.activity===`idle`||e?.terminalStatus?.activity===`exited`?i=!1:r&&e?.status===`running`?i=!0:t.kind===`codex`?i=_b(e):t.kind===`claude`?i=vb(e):(t.kind===`shell`||t.kind===`agent`)&&(i=yb(e));let a=e?.providerSessionProvider===`codex`&&e.codexRuntimeMode===`app-server`&&[`working`,`waiting-for-input`,`interrupting`].includes(e.codexAppServerState||``),o=e?.agentRuntimeMode===`json`&&e.jsonCliState===`working`,s=e?.agentRuntimeMode===`acp`&&[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes(e.acpState||``),c=e?.agentRuntimeMode===`acp`?s:a||o||i;return{kind:(a||o||s)&&e?.providerSessionProvider===`codex`?`codex`:t.kind,kindSource:t.source,turnActive:c,terminalBusy:n}}function xb(e){let t=bb(e);return t.kind===`codex`&&t.turnActive}function Sb(e){return bb(e).turnActive}function Cb(e){return e.providerSessionProvider===`codex`&&e.codexRuntimeMode===`app-server`}function wb({agent:e,active:t,switching:n,switchingKind:r,focusSignal:i,onActivate:a,sendInput:o,resizeAgent:s,onSessionOutput:c,onOpenPath:l,onResolvePath:u,onOpenWorkspaceFilePath:d,onFollowOutputChange:f,onReadLatest:p,onRuntimeModeChange:m,copy:h}){let g=Cb(e),_=e.agentRuntimeMode===`json`,v=e.agentRuntimeMode===`acp`,y=g||_||v,b=e.providerSessionProvider===`codex`&&e.agentRuntimeMode===`terminal`&&e.providerSessionTemporary===!0&&e.terminalInputReceived!==!0,x=[`codex`,`claude`,`opencode`,`qoder`].includes(e.providerSessionProvider||``)&&(e.providerSessionTemporary!==!0||b)&&!!e.providerSessionId,S=n||Sb(e),C=(0,W.useCallback)(n=>{n.button===0&&(t||a(e.id,{focusTerminal:!1}))},[t,e.id,a]);return(0,K.jsxs)(`section`,{className:`code-agent-work-pane ${t?`active`:``} ${x?`runtime-switchable`:``}`,"data-testid":`code-agent-work-pane`,"data-agent-id":e.id,"aria-busy":n,children:[x?(0,K.jsxs)(`div`,{className:`code-terminal-mode-toggle`,"data-testid":`code-terminal-mode-toggle`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{type:`button`,className:y?`active`:``,"aria-pressed":y,"aria-label":h.transcriptView,title:h.transcriptView,disabled:S,onClick:()=>!y&&m?.(e.id,`acp`),children:(0,K.jsx)(oe,{})}),(0,K.jsx)(`button`,{type:`button`,className:y?``:`active`,"aria-pressed":!y,"aria-label":h.terminalView,title:h.terminalView,disabled:S,onClick:()=>y&&m?.(e.id,`terminal`),children:(0,K.jsx)(V,{})})]}):null,y?null:(0,K.jsx)(`div`,{className:`code-agent-work-view terminal active`,"data-testid":`code-agent-terminal-view`,"aria-hidden":!1,children:(0,K.jsx)(e_,{agent:e,active:t,onActivate:a,onOpenPath:l,onResolvePath:u,onFollowOutputChange:f,sendInput:o,resizeAgent:s,onSessionOutput:c,focusSignal:i,copy:h})},`terminal`),y?(0,K.jsx)(`div`,{className:`code-agent-work-view transcript active`,"data-testid":`code-agent-chat-view`,"aria-hidden":!1,onPointerDown:C,children:v?(0,K.jsx)(nb,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,refreshSignal:Number(e.acpSessionRevision)||(e.acpSessionUpdatedAt?Date.parse(e.acpSessionUpdatedAt):0),onOpenWorkspaceFilePath:d,onReadLatest:()=>p?.(e.id),copy:h}):g?(0,K.jsx)(eb,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,onOpenWorkspaceFilePath:d,onReadLatest:()=>p?.(e.id),copy:h}):(0,K.jsx)(tb,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,refreshSignal:e.jsonCliTranscriptUpdatedAt?Date.parse(e.jsonCliTranscriptUpdatedAt):0,onOpenWorkspaceFilePath:d,onReadLatest:()=>p?.(e.id),copy:h})},`chat`):null,n?(0,K.jsxs)(`div`,{className:`code-permission-switching`,"data-testid":`code-permission-switching`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:r===`runtime`?h.runtimeModeRestarting:h.permissionProfileRestarting})]}):null]})}var Tb=`__farming_main_agent__`,Eb=`__agent_chats__`,Db=[{value:`gpt-5.5`,label:`5.5`,defaultEffort:`xhigh`,reasoningLevels:[{value:`low`,effort:`low`,label:`Low`},{value:`medium`,effort:`medium`,label:`Medium`},{value:`high`,effort:`high`,label:`High`},{value:`xhigh`,effort:`xhigh`,label:`Extra High`}],serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],source:`fallback`}];function Ob(e){return e.kind===`agent-session`?`${e.kind}:${e.provider}:${e.id}`:`${e.kind}:${e.id}`}function kb(e){let t=e.replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`Farming`}function Ab(e){return e.projectWorkspace?e.projectWorkspace:e.cwd||`Farming`}function jb(e){return e?kb(e):`Farming`}function Mb(e){return e||`No workspace`}function Nb(e){return e===`xhigh`?`Extra High`:e?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:`Config`}function Pb(e){if(!e||e===`config`)return{model:`gpt-5.5`,effort:`xhigh`};let[t=`gpt-5.5`,n=`xhigh`]=e.split(`:`);return{model:t,effort:n}}function Fb(e,t){return/^gpt-/i.test(t)?(e?.displayName||e?.label||t).replace(/^gpt-/i,``).replace(/^GPT-/i,``):e?.displayName?e.displayName:e?.label||t||`Model`}function Ib(e){let t=new Map;return e.forEach(e=>{let n=e.model||e.value.split(`:`)[0];if(!n)return;let r=t.get(n)??{value:n,label:n.replace(/^gpt-/i,``),defaultEffort:e.effort||`medium`,reasoningLevels:[],serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],source:e.source};e.effort&&!r.reasoningLevels?.some(t=>t.value===e.effort)&&(r.reasoningLevels=[...r.reasoningLevels??[],{value:e.effort,effort:e.effort,label:Nb(e.effort),description:e.description}]),t.set(n,r)}),Array.from(t.values())}function Lb(e){let t=Array.isArray(e.catalog)?e.catalog.filter(e=>e&&typeof e.value==`string`&&typeof e.label==`string`):[];if(t.length>0)return t;let n=Ib(Array.isArray(e.models)?e.models.filter(e=>e&&typeof e.value==`string`&&typeof e.label==`string`):[]);return n.length>0?n:Db}function Rb(e){let t=e.providerHomeId&&e.providerHomeId!==`default`?`home:${e.providerHomeId}:${e.id}`:e.id;return Ob({kind:`agent-session`,provider:e.provider,id:t})}function zb(e){let t=e.workspace||e.cwd;return t?ot(t):e.projectless?`Chats`:e.providerName||`Agent`}function Bb(e){return e.projectless?``:e.workspace||e.cwd||``}function Vb(e){return e.cwd||e.workspace||``}function Hb(e){return e.projectless?Eb:Bb(e)||`__agent_sessions__`}function Ub(e){if(e.projectless)return`Chats`;let t=Bb(e);return t?jb(t):`Agent Sessions`}function Wb(e){let t=Date.parse(e.updatedAt||e.createdAt||``);return Number.isFinite(t)?t:0}function Gb(e,t){return Wb(t)-Wb(e)}function Kb(e,t){let n=new Map;return e.forEach(e=>{let t=Ab(e),r=e.isMain?Tb:t,i=n.get(r)??{id:r,name:e.isMain?`Main Agent`:jb(t),workspace:t,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1};i.agents.push(e),i.hasMain||=e.isMain,i.hasProjectAgent||=!e.isMain,i.name=i.hasMain?`Main Agent`:jb(i.workspace),n.set(r,i)}),t.forEach(e=>{let t=Hb(e),r=Bb(e),i=n.get(t)??{id:t,name:Ub(e),workspace:r,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1};i.agentSessions.push(e),i.hasAgentSession=!0,n.set(t,i)}),Array.from(n.values()).map(e=>({...e,agents:e.agents.sort((e,t)=>{if(e.isMain!==t.isMain)return e.isMain?-1:1;let n=(t.projectOrder??0)-(e.projectOrder??0);return n===0?(t.startedAt??0)-(e.startedAt??0):n}),agentSessions:e.agentSessions.sort(Gb)})).sort((e,t)=>{let n=e.agents.some(e=>e.isMain);if(n!==t.agents.some(e=>e.isMain))return n?-1:1;let r=e.id===Eb;return r===(t.id===`__agent_chats__`)?e.name.localeCompare(t.name):r?1:-1})}function qb(e,t){return t||e.isComposing===!0||e.nativeEvent?.isComposing===!0||e.nativeEvent?.keyCode===229}function Jb(e,t,n=Date.now()){return e.key===`Enter`&&t>0&&n-t<=120}function Yb(e,t,n,r=Date.now()){return e.key!==`Enter`||e.shiftKey||qb(e,t)||Jb(e,n,r)?!1:e.ctrlKey||e.metaKey||e.altKey?(e.ctrlKey===!0||e.metaKey===!0)&&e.altKey!==!0:!0}function Xb(e,t){return e||t}function Zb(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Qb(e){return typeof e==`string`?e:``}function $b(e){return(Array.isArray(e.questions)?e.questions:[]).map(e=>{let t=Zb(e);return{id:Qb(t.id),header:Qb(t.header),question:Qb(t.question),isSecret:t.isSecret===!0,options:Array.isArray(t.options)?t.options.map(e=>{let t=Zb(e);return{label:Qb(t.label),description:Qb(t.description)}}).filter(e=>e.label):[]}}).filter(e=>e.id)}function ex(e){return e===`item/commandExecution/requestApproval`||e===`item/fileChange/requestApproval`||e===`item/permissions/requestApproval`}function tx(e,t){return ex(e)?{decision:t}:null}function nx({request:e,onRespond:t,onReject:n,copy:r}){let[i,a]=(0,W.useState)({}),o=(0,W.useMemo)(()=>$b(e?.params||{}),[e]);if((0,W.useEffect)(()=>{a({})},[e?.id]),!e)return null;let s=Zb(e.params),c=Qb(s.command),l=Qb(s.reason),u=ex(e.method),d=e.method===`item/tool/requestUserInput`&&o.length>0,f=d&&o.every(e=>(i[e.id]||``).trim());return(0,K.jsxs)(`section`,{className:`code-app-server-request`,"data-testid":`code-app-server-request`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:u?r.appServerApprovalRejectedTitle:r.appServerRequestTitle}),(0,K.jsx)(`span`,{children:e.method})]}),l&&(0,K.jsx)(`p`,{children:l}),u&&(0,K.jsx)(`p`,{children:r.appServerApprovalRejectedDescription}),c&&(0,K.jsxs)(`div`,{className:`code-app-server-request-command`,children:[(0,K.jsx)(`small`,{children:r.appServerRequestCommand}),(0,K.jsx)(`code`,{children:c})]}),d&&(0,K.jsx)(`div`,{className:`code-app-server-request-questions`,children:o.map(e=>(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:e.header||r.appServerRequestQuestion}),e.question&&(0,K.jsx)(`small`,{children:e.question}),e.options.length>0&&(0,K.jsx)(`div`,{className:`code-app-server-request-options`,children:e.options.map(t=>(0,K.jsxs)(`button`,{type:`button`,className:i[e.id]===t.label?`active`:``,onClick:()=>a(n=>({...n,[e.id]:t.label})),children:[t.label,t.description&&(0,K.jsx)(`small`,{children:t.description})]},t.label))}),(0,K.jsx)(`input`,{type:`text`,className:e.isSecret?`code-app-server-secret-input`:void 0,name:`farming-app-server-answer-${e.id}`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:i[e.id]||``,onChange:t=>a(n=>({...n,[e.id]:t.target.value}))})]},e.id))}),!u&&!d&&(0,K.jsx)(`p`,{children:r.appServerRequestUnsupported}),(0,K.jsxs)(`div`,{className:`code-app-server-request-actions`,children:[u&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.id,tx(e.method,`decline`)),children:r.appServerRequestDecline}),d&&(0,K.jsx)(`button`,{type:`button`,className:`approve`,disabled:!f,onClick:()=>t(e.id,{answers:Object.fromEntries(o.map(e=>[e.id,{answers:[String(i[e.id]??``).trim()]}]))}),children:r.appServerRequestSubmit}),!u&&!d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),children:r.appServerRequestDecline})]})]})}function rx({attachments:e,onRemove:t}){return e.length===0?null:(0,K.jsx)(`div`,{className:`code-composer-attachments`,"data-testid":`code-composer-attachments`,children:e.map(e=>{let n=e.kind===`image`&&!!e.previewUrl;return(0,K.jsxs)(`div`,{className:[`code-composer-attachment`,n?`image`:`chip`,e.status].join(` `),"data-testid":`code-composer-attachment`,children:[n?(0,K.jsx)(`div`,{className:`code-composer-attachment-preview`,"data-testid":`code-composer-attachment-preview`,children:(0,K.jsx)(`img`,{src:e.previewUrl,alt:e.name})}):(0,K.jsx)(`span`,{className:`code-composer-attachment-fallback`,"aria-hidden":`true`,children:(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{className:`code-composer-attachment-name`,title:e.name,children:e.name}),e.status!==`ready`&&(0,K.jsx)(`span`,{className:`code-composer-attachment-status`,children:e.status===`uploading`?`Uploading`:`Failed`}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-attachment-remove`,"aria-label":`Remove ${e.name}`,onClick:()=>t(e.id),children:(0,K.jsx)(le,{})})]},e.id)})})}function ix(e,t){let n=Math.max(0,Math.min(t,e.length)),r=e.lastIndexOf(`
110
- `,Math.max(0,n-1))+1,i=e.slice(r,n),a=i.match(/^(\s*)\/([A-Za-z0-9._:-]*)$/);if(a)return{start:r+(a[1]?.length??0),end:n,query:a[2]??``,trigger:`/`};let o=i.match(/(^|\s)\$([A-Za-z0-9._:-]*)$/);return o?{start:r+(o.index??0)+(o[1]?.length??0),end:n,query:o[2]??``,trigger:`$`}:null}function ax(e,t,n){let r=t.trim().toLowerCase();return e.command.startsWith(n)?r?e.command.slice(1).toLowerCase().startsWith(r)||e.label.toLowerCase().includes(r):!0:!1}function ox(e,t){let n=t.trim().toLowerCase();return n?+!e.command.slice(1).toLowerCase().startsWith(n):0}function sx(e){return`code-slash-command-${e.replace(/^[/$]/,``).replace(/[^A-Za-z0-9_-]+/g,`-`)||`root`}`}function cx(e){if(!e||typeof window>`u`)return 0;let t=window.getSelection();if(!t||t.rangeCount<=0)return(e.textContent||``).length;let n=t.getRangeAt(0);if(!e.contains(n.startContainer))return(e.textContent||``).length;let r=n.cloneRange();return r.selectNodeContents(e),r.setEnd(n.startContainer,n.startOffset),r.toString().length}function lx(e,t){if(!e||typeof window>`u`)return;e.normalize();let n=Math.max(0,Math.min(t,(e.textContent||``).length)),r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=n,a=r.nextNode();for(;a;){let e=a.textContent||``;if(i<=e.length){let e=document.createRange();e.setStart(a,i),e.collapse(!0);let t=window.getSelection();t?.removeAllRanges(),t?.addRange(e);return}i-=e.length,a=r.nextNode()}let o=document.createRange();o.selectNodeContents(e),o.collapse(!1);let s=window.getSelection();s?.removeAllRanges(),s?.addRange(o)}function ux(e){return e?(e.innerText||e.textContent||``).replace(/\u00a0/g,` `).replace(/\n$/,``):``}function dx({active:e,draft:t,placeholder:n,minHeight:r,maxHeight:i,editorRef:a,composerRef:o,onFocus:s,onBlur:c,onInput:l,onPaste:u,onCompositionStart:d,onCompositionEnd:f,onKeyDown:p,onSelectionIntent:m}){let h=(0,W.useRef)(null);return(0,W.useLayoutEffect)(()=>{let e=a.current,n=h.current,s=o.current;if(!e||!n||!s)return;(e.textContent||``)!==t&&(e.textContent=t),n.innerText=t||`M`,e.style.height=`auto`;let c=Math.max(n.scrollHeight,e.scrollHeight),l=Math.min(i,Math.max(r,c));e.style.height=`${l}px`;let u=s.closest(`.code-main`),d=s.getBoundingClientRect().height;if(d>0){let e=`${Math.ceil(d)}px`;s.style.setProperty(`--mobile-composer-current-height`,e),u?.style.setProperty(`--mobile-composer-current-height`,e)}},[o,t,a,i,r]),(0,W.useLayoutEffect)(()=>{let e=a.current;e&&(e.removeAttribute(`autocomplete`),e.removeAttribute(`aria-autocomplete`),e.removeAttribute(`inputmode`),e.setAttribute(`autocorrect`,`off`),e.setAttribute(`autocapitalize`,`none`),e.setAttribute(`spellcheck`,`false`))},[a]),(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{"data-testid":`code-composer-input`,ref:a,className:`code-composer-mobile-input`,"aria-disabled":!e,contentEditable:e?`true`:`false`,suppressContentEditableWarning:!0,enterKeyHint:`send`,tabIndex:e?0:-1,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,"data-placeholder":n,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,"data-gramm":`false`,"data-ms-editor":`false`,onFocus:s,onBlur:c,onInput:l,onPaste:u,onCompositionStart:d,onCompositionEnd:f,onKeyDown:p,onKeyUp:m,onMouseUp:m}),(0,K.jsx)(`div`,{ref:h,className:`code-composer-mobile-input-mirror`,"aria-hidden":`true`})]})}var fx=[`sol`,`terra`,`luna`],px=4,mx=240;function hx(e,t){let n=t.match(/^(.*?)[-\s](sol|terra|luna)$/i)?.[1]?.toLowerCase();if(!n)return null;let r=e.flatMap(e=>{let t=e.value.match(/^(.*?)[-\s](sol|terra|luna)$/i),r=t?.[1]?.toLowerCase(),i=t?.[2]?.toLowerCase();return!r||r!==n||!i?[]:[{...e,variant:i}]}).sort((e,t)=>fx.indexOf(e.variant)-fx.indexOf(t.variant));return r.length>=2?r:null}function gx(){return(0,K.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21Z`})})}function _x({label:e,active:t,disabled:n,unavailable:r,onChange:i}){let[a,o]=(0,W.useState)(!1);return(0,K.jsxs)(`div`,{className:`code-model-matrix-rocker is-ultra ${t?`is-active`:``} ${r?`is-disabled`:``}`,children:[(0,K.jsx)(`span`,{children:e}),(0,K.jsx)(`button`,{type:`button`,className:`code-model-matrix-rocker-button`,disabled:n||r,"aria-label":`Ultra reasoning`,"aria-pressed":t,onClick:()=>{o(!0),i(!t)},children:(0,K.jsxs)(`span`,{className:`code-model-matrix-rocker-control`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-slot`,children:(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-energy`})}),(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-knob-position`,children:(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-knob ${a?`is-kicked`:``}`,onAnimationEnd:()=>o(!1)})})]})})]})}function vx({active:e,available:t,disabled:n,onChange:r}){let[i,a]=(0,W.useState)(!1),o=!t,s=n||o;return(0,K.jsxs)(`button`,{type:`button`,className:`code-model-matrix-fast ${e?`is-active`:``} ${o?`is-disabled`:``}`,"aria-label":`Fast mode`,"aria-pressed":e,"aria-disabled":s,disabled:s,onClick:()=>{a(!0),r(!e)},children:[(0,K.jsx)(`span`,{className:`code-model-matrix-fast-bolt ${i?`is-kicked`:``}`,"aria-hidden":`true`,onAnimationEnd:()=>a(!1),children:(0,K.jsx)(gx,{})}),(0,K.jsx)(`span`,{children:`Fast`}),(0,K.jsx)(`small`,{children:t?e?`ON`:`OFF`:`—`})]})}function yx({models:e,currentModel:t,currentReasoning:n,fastAvailable:r,fast:i,disabled:a,onSelect:o,onFastChange:s,advanced:c}){let l=hx(e,t),u=!!l?.find(e=>e.value===t)?.reasoning.some(e=>e.value===n),[d,f]=(0,W.useState)(!u),[p,m]=(0,W.useState)(null),[h,g]=(0,W.useState)(null),[_,v]=(0,W.useState)(null),y=(0,W.useRef)(!!l),b=(0,W.useRef)(new Map),x=(0,W.useRef)(null),S=(0,W.useRef)(null),C=(0,W.useRef)(null),w=(0,W.useRef)(null),T=(0,W.useRef)(null),E=(0,W.useRef)(null),D=(0,W.useRef)(null);if((0,W.useEffect)(()=>{let e=!y.current&&!!l;y.current=!!l,e&&u&&(T.current=w.current?.getBoundingClientRect().height??null,f(!1))},[l,u]),(0,W.useEffect)(()=>{if(!h)return;if(t===h.model&&n===h.reasoning){g(null);return}let e=window.setTimeout(()=>g(null),5e3);return()=>window.clearTimeout(e)},[t,n,h]),(0,W.useEffect)(()=>{if(_===null)return;if(!r||i===_){v(null);return}let e=window.setTimeout(()=>v(null),5e3);return()=>window.clearTimeout(e)},[i,r,_]),(0,W.useEffect)(()=>()=>{C.current!==null&&window.cancelAnimationFrame(C.current),E.current!==null&&window.cancelAnimationFrame(E.current),D.current!==null&&window.clearTimeout(D.current)},[]),(0,W.useLayoutEffect)(()=>{let e=w.current,t=T.current;if(T.current=null,!e)return;E.current!==null&&window.cancelAnimationFrame(E.current),D.current!==null&&window.clearTimeout(D.current),E.current=null,D.current=null,e.style.height=`auto`;let n=e.getBoundingClientRect().height,r=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;if(t===null||r||Math.abs(t-n)<1){e.style.overflow=d?`visible`:`hidden`;return}e.style.height=`${t}px`,e.style.overflow=`hidden`,e.offsetHeight,E.current=window.requestAnimationFrame(()=>{e.style.height=`${n}px`,E.current=null}),D.current=window.setTimeout(()=>{e.style.height=`auto`,e.style.overflow=d?`visible`:`hidden`,D.current=null},mx+40)},[d]),!l)return c;let O=l.find(e=>e.value===t)??l[0],k=O.reasoning.filter(e=>e.value!==`ultra`);n!==`ultra`&&k.some(e=>e.value===n)&&b.current.set(O.value,n);let ee=b.current.get(O.value)||k[k.length-1]?.value||n,te=n===`ultra`?ee:n,A=Math.max(0,k.findIndex(e=>e.value===te)),j=O.reasoning.find(e=>e.value===n)?.label||n;function M(e,t){a||(g({model:e.value,reasoning:t}),b.current.set(e.value,t),o(e.value,t))}let N=l.map(e=>({model:e,reasoning:e.reasoning.filter(e=>e.value!==`ultra`)})),P=Math.max(0,N.findIndex(e=>e.model.value===t)),F=Math.max(0,N[P]?.reasoning.findIndex(e=>e.value===te)??0),ne=h?N.findIndex(e=>e.model.value===h.model):-1,I=ne>=0?N[ne]?.reasoning.findIndex(e=>e.value===h?.reasoning)??-1:-1,L=p??(ne>=0&&I>=0?{row:ne,column:I}:null)??{row:P,column:F},R=N[L.row]??N[0],z=Math.min(L.column,Math.max(0,R.reasoning.length-1)),re=R.reasoning[z],B=h?l.find(e=>e.value===h.model)??O:O,ie=h?.reasoning??n,V=B.reasoning.filter(e=>e.value!==`ultra`),ae=B.reasoning.find(e=>e.value===`ultra`),oe=b.current.get(B.value)||V[V.length-1]?.value||ie,se=B.reasoning.find(e=>e.value===ie)?.label||ie,ce=!!ae&&ie===`ultra`,le=_??i,ue=`${(typeof L.x==`number`?L.x:(z+.5)/Math.max(1,R.reasoning.length))*100}%`,de=typeof L.y==`number`?L.y:(L.row+.5)/Math.max(1,N.length),fe=`${de*100}%`,pe=`${Math.max(0,Math.min(1-1/Math.max(1,N.length),de-.5/Math.max(1,N.length)))*100}%`,me=`${100/Math.max(1,N.length)}%`;function H(e){let t=e.currentTarget.getBoundingClientRect(),n=Math.max(0,Math.min(1,(e.clientX-t.left)/Math.max(1,t.width))),r=Math.max(0,Math.min(1,(e.clientY-t.top)/Math.max(1,t.height))),i=Math.max(0,Math.min(N.length-1,Math.floor(r*N.length))),a=N[i]?.reasoning.length||1;return{row:i,column:Math.max(0,Math.min(a-1,Math.floor(n*a))),x:Math.max(.5/a,Math.min(1-.5/a,n)),y:Math.max(.5/N.length,Math.min(1-.5/N.length,r))}}function he(e){let t=N[e.row],n=t?.reasoning[e.column];t&&n&&M(t.model,n.value)}function _e(e){a||!r||le===e||(v(e),s(e))}function ve(e){if(a||!ae||ce===e)return;let t=e?ae.value:oe;g({model:B.value,reasoning:t}),e||b.current.set(B.value,t),o(B.value,t)}function ye(e){S.current=e,C.current===null&&(C.current=window.requestAnimationFrame(()=>{C.current=null;let e=S.current;S.current=null,e&&m(e)}))}function be(){S.current=null,C.current!==null&&(window.cancelAnimationFrame(C.current),C.current=null)}function xe(e,t=!0){let n=x.current;if(!n||n.pointerId!==e.pointerId)return;let r=H(e);x.current=null,be(),t&&he(r),m(null),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)}function Se(){T.current=w.current?.getBoundingClientRect().height??null,f(e=>!e)}return(0,K.jsxs)(`div`,{className:`code-model-matrix-shell is-${R.model.variant}`,"data-testid":`code-model-matrix-picker`,"data-advanced":d?`open`:`closed`,"data-fast":le?`on`:`off`,"data-ultra":ce?`on`:`off`,children:[(0,K.jsx)(`div`,{className:`code-model-matrix-stage`,ref:w,children:d?(0,K.jsx)(`div`,{className:`code-model-matrix-advanced`,"data-testid":`code-model-matrix-advanced`,children:c}):(0,K.jsxs)(`div`,{className:`code-model-matrix`,children:[(0,K.jsx)(`div`,{className:`code-model-matrix-head`,style:{"--matrix-columns":R.reasoning.length},"aria-hidden":`true`,children:R.reasoning.map(e=>(0,K.jsx)(`span`,{children:e.label},e.value))}),(0,K.jsx)(`div`,{className:`code-model-matrix-labels`,"aria-hidden":`true`,children:N.map(({model:e})=>(0,K.jsx)(`span`,{className:e.value===R.model.value?`selected`:``,"data-variant":e.variant,children:e.variant.charAt(0).toUpperCase()+e.variant.slice(1)},e.value))}),(0,K.jsxs)(`div`,{className:`code-model-matrix-surface ${p?`is-dragging`:``}`,role:`radiogroup`,"aria-label":`Model and reasoning`,style:{"--matrix-columns":k.length,"--matrix-rows":N.length,"--matrix-selection-x":ue,"--matrix-selection-y":fe,"--matrix-selection-row-top":pe,"--matrix-selection-row-height":me},onPointerDown:e=>{a||(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),x.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragged:!1})},onPointerMove:e=>{let t=x.current;if(!t||t.pointerId!==e.pointerId)return;if(e.pointerType===`mouse`&&e.buttons===0){xe(e);return}let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);!t.dragged&&n>=px&&(t.dragged=!0),t.dragged&&ye(H(e))},onPointerUp:e=>xe(e),onPointerCancel:e=>xe(e,!1),onLostPointerCapture:e=>{x.current?.pointerId===e.pointerId&&(x.current=null,be(),m(null))},children:[(0,K.jsx)(`span`,{className:`code-model-matrix-fill`,"data-variant":R.model.variant,"aria-hidden":`true`}),(0,K.jsx)(`div`,{className:`code-model-matrix-cells`,children:N.flatMap(({model:e,reasoning:t},n)=>t.map((r,i)=>{let o=n===L.row&&i===z;return(0,K.jsx)(`button`,{type:`button`,className:o?`selected`:``,role:`radio`,"data-matrix-cell":!0,"data-testid":`code-model-matrix-cell-${e.variant}-${r.value}`,"aria-label":`${e.label}, ${r.label}`,"aria-checked":o,disabled:a,style:{"--matrix-cell-left":`${i/Math.max(1,t.length)*100}%`,"--matrix-cell-top":`${n/Math.max(1,N.length)*100}%`,"--matrix-cell-width":`${100/Math.max(1,t.length)}%`,"--matrix-cell-height":`${100/Math.max(1,N.length)}%`},onClick:t=>{t.detail===0&&M(e,r.value)}},`${e.value}:${r.value}`)}))}),(0,K.jsx)(`span`,{className:`code-model-matrix-thumb`,"data-variant":R.model.variant,"aria-hidden":`true`})]}),(0,K.jsx)(`div`,{className:`code-model-matrix-rockers`,children:(0,K.jsx)(_x,{label:ae?.label||`Ultra`,active:ce,disabled:a,unavailable:!ae,onChange:ve})}),(0,K.jsx)(vx,{active:r&&le,available:r,disabled:a,onChange:_e}),(0,K.jsx)(`span`,{className:`code-model-matrix-current`,"aria-live":`polite`,children:p?`${R.model.label} · ${re?.label||``}`:h?`${B.label} · ${se}`:`${O.label} · ${j||k[A]?.label}`})]})}),(0,K.jsxs)(`button`,{type:`button`,className:`code-model-matrix-advanced-toggle`,"data-testid":`code-model-matrix-advanced-toggle`,"aria-expanded":d,onClick:Se,children:[(0,K.jsx)(`span`,{children:`Advanced`}),(0,K.jsx)(ge,{className:d?`expanded`:``})]})]})}function bx(e,t){return t===`goal`?e.goalMode:t===`plan`?e.planMode:e.messageMode}function xx(e,t,n){return t===`goal`?e.describeAgentGoal:t===`plan`?e.describePlanFirst:n===`shell`?e.shellCommandPlaceholder:e.askFollowUpChanges}function Sx(){return typeof window<`u`&&L()}function Cx(e){return e.trim().replace(/^gpt[-\s]*/i,``)||e}function wx(e,t){return e===`xhigh`&&t.trim().toLowerCase()===`extra high`?`XHigh`:t}function Tx(e){return!Number.isFinite(e)||e<0?`0`:e>=1e6?`${Math.round(e/1e5)/10}m`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function Ex(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}var Dx=[.28,.5,.72,.46,.9,.36,.62,.82,.42,.68,.95,.52,.33,.75,.57,.88,.4,.64,.93,.48,.7,.31,.58,.83],Ox=22,kx=22,Ax=66,jx=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM6 3.99951C6 2.89651 6.897 1.99951 8 1.99951C9.103 1.99951 10 2.89651 10 3.99951V7.99951C10 9.10251 9.103 9.99951 8 9.99951C6.897 9.99951 6 9.10251 6 7.99951V3.99951ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`,Mx=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`;function Nx({listening:e}){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:e?Mx:jx})})}function Px(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21ZM4.8 7.9h2.34a.55.55 0 0 1 .53.69l-.63 2.38L10.17 7.1H7.56a.55.55 0 0 1-.53-.7l.62-2.26L4.8 7.9Z`})})}function Fx({active:e,agentKind:t,capabilities:n,slashCommands:r,draft:i,attachments:a,composerMode:o,plusMenuOpen:s,approvalMenuOpen:c,modelMenuOpen:l,modelPickerPane:u,agentModelPreset:d,agentModel:f,agentReasoningEffort:p,agentServiceTier:m,agentModelOptions:h,currentPermissionMode:g,permissionModeDisabled:_,currentPermissionLabel:v,currentPermissionColor:y,permissionModeHint:b,currentModelLabel:x,currentReasoningLabel:S,currentSpeedLabel:C,currentReasoningOptions:w,currentServiceTierOptions:T,permissionModeOptions:E,contextWindow:D,pendingFollowUp:O,appServerRequest:k,appServerNotice:ee,submitAction:te,speechSupported:A,speechListening:j,textareaRef:M,attachmentInputRef:N,plusMenuRef:P,approvalMenuRef:F,modelMenuRef:ne,onDraftChange:I,onNavigateHistory:R,onRemoveAttachment:z,onSubmit:re,onInterrupt:B,onSteerPendingFollowUp:ie,onDiscardPendingFollowUp:V,onRespondToAppServerRequest:ae,onRejectAppServerRequest:oe,onPasteAttachment:se,onAttachmentFiles:ce,onChooseAttachmentFile:ue,onActivateComposerMode:de,onClearComposerMode:pe,onTogglePlusMenu:H,onToggleApprovalMenu:ge,onToggleModelMenu:_e,onCloseMenus:ve,onSetModelPickerPane:ye,onComposerMenuKeyDown:be,onComposerMenuBlur:Ce,onUpdatePermissionMode:we,onUpdateModel:Te,onUpdateReasoningEffort:Ee,onUpdateServiceTier:De,onUpdateModelProfile:Oe,onUpdateServiceTierInline:ke,onToggleSpeechInput:Ae,copy:U}){let je=e&&n.plusMenu,Me=e&&n.permissionMode,Ne=e&&n.modelPicker,Pe=n.serviceTier&&T.length>0,Fe=h.map(e=>({value:e.value,label:Fb(e,e.value),reasoning:(e.reasoningLevels||[]).map(e=>({value:e.value,label:U.reasoningOptionLabel(e.value,e.label)}))})),G=t===`codex`&&!!hx(Fe,f),[Ie,Le]=(0,W.useState)(Sx),[Re,ze]=(0,W.useState)(0),[Be,Ve]=(0,W.useState)(!1),[He,Ue]=(0,W.useState)(i.length),[We,Ge]=(0,W.useState)(!1),[Ke,qe]=(0,W.useState)(null),[Je,Ye]=(0,W.useState)(0),Xe=e&&n.speechInput&&(!Ie||A),Ze=(0,W.useRef)(new Map),Qe=(0,W.useRef)(null),$e=(0,W.useRef)(null),et=(0,W.useRef)(!1),tt=(0,W.useRef)(0),nt=(0,W.useRef)(i),rt=(0,W.useRef)(!1),it=s||c||l,at=(0,W.useMemo)(()=>ix(i,He),[i,He]),ot=at?`${at.trigger}:${at.start}:${at.end}:${at.query}`:``,st=(0,W.useMemo)(()=>at?r.filter(e=>ax(e,at.query,at.trigger)).sort((e,t)=>ox(e,at.query)-ox(t,at.query)):[],[r,at]),ct=e&&Be&&!it&&!!at&&ot!==Ke&&st.length>0,lt=it||ct,ut=st[Je]??st[0]??null,dt=U.permissionModeLabel(g,v),ft=U.reasoningOptionLabel(p,S),pt=U.serviceTierLabel(m,C),mt=Cx(x),ht=wx(p,ft),gt=D?`Context window: ${D.percentUsed}% used (${D.percentLeft}% left), ${Tx(D.usedTokens)} / ${Tx(D.limitTokens)} tokens used`:``,_t=!e||te===`disabled`,vt=e&&te===`interrupt`,yt=at?.trigger===`$`?`Skills`:`Commands`,bt=Ie&&j&&Xe,xt=A||Ie,St=()=>{(Ie||L())&&Ge(!0),Ae()},Ct=()=>{if(rt.current){rt.current=!1;return}St()},wt=e=>{e.pointerType!==`mouse`&&(e.preventDefault(),rt.current=!0,St())};function Tt(t){if(!Ie||!e||t instanceof Element&&t.closest(`.code-composer-menu, button, input, select, [role="menuitem"]`))return;let n=$e.current;if(n){n.focus({preventScroll:!0}),Ue(cx(n)||(n.textContent||``).length);return}let r=M.current;!r||r.disabled||(r.focus({preventScroll:!0}),kt(r))}let Et=e=>{Tt(e.target)},Dt=e=>{Tt(e.target)},Ot=e=>{Tt(e.target)};(0,W.useEffect)(()=>{Ye(0)},[at?.query,st.length]),(0,W.useEffect)(()=>{nt.current=i},[i]),(0,W.useEffect)(()=>()=>{let e=Qe.current;e?.style.removeProperty(`--mobile-composer-current-height`),(e?.closest(`.code-main`))?.style.removeProperty(`--mobile-composer-current-height`)},[]),(0,W.useEffect)(()=>{at||qe(null)},[at]),(0,W.useEffect)(()=>{e||(Ve(!1),qe(null))},[e]),(0,W.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 980px)`),t=()=>Le(Sx());return t(),window.addEventListener(`resize`,t),e.addEventListener(`change`,t),()=>{window.removeEventListener(`resize`,t),e.removeEventListener(`change`,t)}},[]),(0,W.useEffect)(()=>{if(Ie)return;let e=Qe.current,t=e?.closest(`.code-main`);e?.style.removeProperty(`--mobile-composer-current-height`),t?.style.removeProperty(`--mobile-composer-current-height`)},[Ie]),(0,W.useEffect)(()=>{if(j||!We)return;let e=window.setTimeout(()=>Ge(!1),3600);return()=>window.clearTimeout(e)},[We,j]),(0,W.useEffect)(()=>{j&&Ge(!1)},[j]),(0,W.useEffect)(()=>{if(!j){ze(0);return}let e=Date.now();ze(0);let t=window.setInterval(()=>{ze(Math.floor((Date.now()-e)/1e3))},250);return()=>window.clearInterval(t)},[j]),(0,W.useEffect)(()=>{!ct||!ut||Ze.current.get(ut.command)?.scrollIntoView({block:`nearest`})},[ct,ut]);function kt(e=M.current){e&&Ue(e.selectionStart??i.length)}function At(){Ue(cx($e.current))}function q(e){if(!at)return;let t=`${e.command} `,n=`${i.slice(0,at.start)}${t}${i.slice(at.end)}`,r=at.start+t.length;I(n),Ue(r),qe(null),window.requestAnimationFrame(()=>{if(Ie){let e=$e.current;if(!e)return;e.focus({preventScroll:!0}),lx(e,r),Ue(r);return}let e=M.current;e&&(e.focus({preventScroll:!0}),e.setSelectionRange(r,r),kt(e))})}let jt=e&&!!(k||ee);return(0,K.jsxs)(`footer`,{ref:Qe,className:[`code-composer`,lt?`menu-open`:``,bt?`recording`:``,a.length>0?`has-attachments`:``,O&&e?`has-pending-followup`:``,jt?`has-app-server-request`:``].filter(Boolean).join(` `),"data-testid":`code-composer`,onPointerDownCapture:Et,onTouchStartCapture:Dt,onMouseDownCapture:Ot,onClickCapture:Ot,children:[O&&e&&(0,K.jsx)(`div`,{className:`code-pending-followup`,"data-testid":`code-pending-followup`,children:O.messages.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row`,"data-testid":`code-pending-followup-row`,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"aria-hidden":`true`,children:(0,K.jsx)(xe,{})}),(0,K.jsx)(`p`,{children:e.text}),(0,K.jsxs)(`div`,{className:`code-pending-followup-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-pending-followup-steer`,onClick:()=>ie(e.id),children:[(0,K.jsx)(xe,{}),(0,K.jsx)(`span`,{children:U.steerQueuedMessage})]}),(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-pending-followup-discard`,"aria-label":U.discardQueuedMessage,onClick:()=>V(e.id),children:(0,K.jsx)(le,{})})]})]},e.id))}),e&&k&&(0,K.jsx)(nx,{request:k,onRespond:ae,onReject:oe,copy:U}),e&&ee&&ee.kind===`approval-rejected`&&(0,K.jsxs)(`section`,{className:`code-app-server-request code-app-server-notice`,"data-testid":`code-app-server-notice`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:U.appServerApprovalRejectedTitle}),ee.method?(0,K.jsx)(`span`,{children:ee.method}):null]}),(0,K.jsx)(`p`,{children:U.appServerApprovalRejectedDescription})]}),ct&&(0,K.jsxs)(`div`,{className:`code-slash-menu code-composer-menu`,"data-testid":`code-slash-menu`,role:`listbox`,"aria-label":yt,children:[(0,K.jsx)(`div`,{className:`code-slash-menu-header`,children:yt}),st.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`code-slash-command ${t===Je?`active`:``}`,"data-testid":sx(e.command),role:`option`,"aria-selected":t===Je,ref:t=>{t?Ze.current.set(e.command,t):Ze.current.delete(e.command)},onMouseMove:()=>Ye(t),onMouseDown:e=>e.preventDefault(),onClick:()=>q(e),children:[(0,K.jsx)(`span`,{className:`code-slash-command-icon`,"aria-hidden":`true`,children:at?.trigger??`/`}),(0,K.jsxs)(`span`,{className:`code-slash-command-copy`,children:[(0,K.jsxs)(`span`,{className:`code-slash-command-title`,children:[(0,K.jsx)(`code`,{children:e.command}),(0,K.jsx)(`strong`,{children:e.label})]}),(0,K.jsx)(`small`,{children:e.description})]}),e.scope&&(0,K.jsx)(`span`,{className:`code-slash-command-source`,children:e.scope})]},e.command))]}),Ie?(0,K.jsx)(dx,{active:e,draft:i,placeholder:e?xx(U,o,t):U.openAgentTerminalFirst,minHeight:Be||lt||a.length>0||O&&e?kx:Ox,maxHeight:Ax,editorRef:$e,composerRef:Qe,onFocus:()=>{ve(),Ve(!0),Ue(cx($e.current))},onBlur:()=>Ve(!1),onInput:e=>{let t=ux(e.currentTarget);nt.current=t,I(t),qe(null),Ue(cx(e.currentTarget))},onPaste:se,onCompositionStart:()=>{et.current=!0},onCompositionEnd:e=>{et.current=!1,tt.current=Date.now();let t=ux(e.currentTarget);nt.current=t,I(t),Ue(cx(e.currentTarget))},onKeyDown:e=>{let t=et.current;if(!qb(e,t)){if(Jb(e,tt.current)){e.preventDefault(),e.stopPropagation();return}if(ct&&(e.key===`Enter`||e.key===`Tab`)&&ut){e.preventDefault(),e.stopPropagation(),q(ut);return}e.key!==`Enter`||e.shiftKey||(e.preventDefault(),e.stopPropagation(),re(Xb(ux(e.currentTarget),nt.current)))}},onSelectionIntent:At}):(0,K.jsx)(`textarea`,{"data-testid":`code-composer-input`,ref:M,enterKeyHint:`send`,name:`farming-chat-message`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:i,onFocus:e=>{ve(),Ve(!0),kt(e.currentTarget)},onBlur:()=>Ve(!1),onClick:e=>kt(e.currentTarget),onKeyUp:e=>kt(e.currentTarget),onSelect:e=>kt(e.currentTarget),onCompositionStart:()=>{et.current=!0},onCompositionEnd:e=>{et.current=!1,tt.current=Date.now(),nt.current=e.currentTarget.value,kt(e.currentTarget)},onChange:e=>{nt.current=e.target.value,I(e.target.value),qe(null),kt(e.currentTarget)},onPaste:se,onKeyDown:e=>{let t=et.current;if(!qb(e,t)){if(Jb(e,tt.current)){e.preventDefault(),e.stopPropagation();return}if(ct){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=e.key===`ArrowDown`?1:-1;Ye(e=>(e+t+st.length)%st.length);return}if(e.key===`Home`){e.preventDefault(),e.stopPropagation(),Ye(0);return}if(e.key===`End`){e.preventDefault(),e.stopPropagation(),Ye(st.length-1);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),qe(ot);return}if((e.key===`Enter`||e.key===`Tab`)&&ut){e.preventDefault(),e.stopPropagation(),q(ut);return}}if(e.key===`ArrowUp`||e.key===`ArrowDown`){let t=e.key===`ArrowUp`?`previous`:`next`,n=R(t,{direction:t,value:e.currentTarget.value,selectionStart:e.currentTarget.selectionStart,selectionEnd:e.currentTarget.selectionEnd});if(n!==null){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=M.current;if(!e)return;let t=n.length;e.setSelectionRange(t,t),kt(e)});return}}Yb(e,t,tt.current)&&(e.preventDefault(),e.stopPropagation(),re(Xb(e.currentTarget.value,nt.current)))}},placeholder:e?xx(U,o,t):U.openAgentTerminalFirst,disabled:!e}),We&&!j&&(0,K.jsx)(`div`,{className:`code-composer-dictation-hint`,"data-testid":`code-composer-dictation-hint`,children:U.mobileDictationHint}),(0,K.jsx)(rx,{attachments:a,onRemove:z}),(0,K.jsx)(`input`,{ref:N,className:`code-composer-file-input`,"data-testid":`code-composer-file-input`,type:`file`,multiple:!0,onChange:ce}),(0,K.jsx)(`div`,{className:`code-composer-toolbar ${bt?`recording`:``}`,"data-testid":`code-composer-toolbar`,children:bt?(0,K.jsxs)(`div`,{className:`code-composer-recording-bar`,"data-testid":`code-composer-recording`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-recording-stop`,"data-testid":`code-composer-recording-stop`,"aria-label":U.stopDictation,onPointerDown:wt,onClick:Ct,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsx)(`div`,{className:`code-composer-recording-wave`,"aria-hidden":`true`,children:Dx.map((e,t)=>(0,K.jsx)(`span`,{style:{"--voice-bar-scale":e,"--voice-bar-delay":`${t*38}ms`}},t))}),(0,K.jsx)(`span`,{className:`code-composer-recording-time`,children:Ex(Re)}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${vt?`interrupt`:``}`,"data-testid":`code-composer-send`,"data-action":te,"aria-label":vt?U.interruptAgent:U.sendMessage,onClick:vt?B:()=>re(nt.current),disabled:_t,children:vt?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(he,{})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-composer-left-tools`,"data-testid":`code-composer-left-tools`,children:[je&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-add`,"data-testid":`code-composer-add`,"aria-label":U.addContext,"aria-haspopup":`menu`,"aria-expanded":s,disabled:!e,onClick:H,children:(0,K.jsx)(Se,{})}),s&&(0,K.jsxs)(`div`,{className:`code-plus-menu code-composer-menu`,role:`menu`,"data-testid":`code-composer-plus-menu`,ref:P,onKeyDown:be,onBlur:Ce,onMouseDown:e=>e.preventDefault(),children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-attach-file`,onClick:ue,children:[(0,K.jsx)(`span`,{children:U.attachFile}),(0,K.jsx)(`small`,{children:U.fileContext})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-goal-mode`,onClick:()=>de(`goal`),children:[(0,K.jsx)(`span`,{children:U.goalMode}),(0,K.jsx)(`small`,{children:U.setObjective})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-plan-mode`,onClick:()=>de(`plan`),children:[(0,K.jsx)(`span`,{children:U.planMode}),(0,K.jsx)(`small`,{children:U.planFirst})]})]})]}),o!==`default`&&(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-mode-chip`,"data-testid":`code-composer-mode-chip`,"aria-label":U.clearComposerMode,onClick:pe,children:[(0,K.jsx)(`span`,{children:bx(U,o)}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:(0,K.jsx)(le,{})})]}),Me&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-approval ${y}`,"data-testid":`code-composer-approval`,"aria-label":U.agentPermissionMode,"aria-haspopup":`menu`,"aria-expanded":c,disabled:_,onClick:ge,children:[(0,K.jsx)(`span`,{className:`code-tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Ix,{mode:g})}),(0,K.jsx)(`span`,{className:`code-composer-approval-label`,children:dt}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(Lx,{})})]}),c&&(0,K.jsxs)(`div`,{className:`code-approval-menu code-composer-menu`,role:`menu`,"data-testid":`code-approval-menu`,ref:F,onKeyDown:be,onBlur:Ce,onMouseDown:e=>e.preventDefault(),children:[(0,K.jsxs)(`div`,{className:`code-approval-menu-header`,children:[(0,K.jsx)(`span`,{children:U.permissionsPrompt}),(0,K.jsx)(`small`,{children:b})]}),E.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-approval-option ${e.value===g?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===g,onClick:()=>we(e.value),children:[(0,K.jsx)(`span`,{className:`code-approval-option-icon ${e.color??`muted`}`,"aria-hidden":`true`,children:(0,K.jsx)(Ix,{mode:e.value})}),(0,K.jsxs)(`span`,{className:`code-approval-option-copy`,children:[(0,K.jsx)(`span`,{children:U.permissionModeLabel(e.value,e.label)}),(0,K.jsx)(`small`,{children:U.permissionModeDescription(e.value,e.description)})]}),e.value===g&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value))]})]})]}),(0,K.jsxs)(`div`,{className:`code-composer-right-tools`,"data-testid":`code-composer-right-tools`,children:[D&&(0,K.jsxs)(`div`,{className:`code-composer-context-window`,"data-testid":`code-composer-context-window`,tabIndex:0,role:`img`,"aria-label":gt,children:[(0,K.jsx)(`span`,{className:`code-context-window-ring`,"aria-hidden":`true`,style:{"--context-percent":D.percentUsed}}),(0,K.jsxs)(`div`,{className:`code-context-window-popover`,role:`tooltip`,children:[(0,K.jsx)(`span`,{children:`Context window:`}),(0,K.jsxs)(`strong`,{children:[D.percentUsed,`% used (`,D.percentLeft,`% left)`]}),(0,K.jsxs)(`strong`,{children:[Tx(D.usedTokens),` / `,Tx(D.limitTokens),` tokens used`]})]})]}),Ne&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor model-picker`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-model-picker`,"data-testid":`code-composer-model-picker`,"data-agent-model-preset":d,"aria-label":U.modelAndReasoning,"aria-haspopup":`menu`,"aria-expanded":l,title:[x,ft,pt].filter(Boolean).join(` · `),onClick:_e,children:[m===`priority`&&(0,K.jsx)(`span`,{className:`code-composer-speed-active`,"aria-hidden":`true`,children:(0,K.jsx)(Px,{})}),(0,K.jsx)(`span`,{className:`code-composer-model-label desktop`,children:x}),(0,K.jsx)(`span`,{className:`code-composer-model-label mobile`,children:mt}),(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted desktop`,children:ft}),(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted mobile`,children:ht}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(Lx,{})})]}),l&&(0,K.jsx)(`div`,{className:`code-model-picker-menu code-composer-menu ${G?`has-matrix`:``}`,role:`menu`,"data-testid":`code-model-menu`,ref:ne,onKeyDown:be,onBlur:Ce,onMouseDown:e=>e.preventDefault(),children:(0,K.jsx)(yx,{models:Fe,currentModel:f,currentReasoning:p,fastAvailable:Pe&&T.some(e=>e.value===`priority`),fast:m===`priority`,onSelect:Oe,onFastChange:e=>ke(e?`priority`:`default`),advanced:(0,K.jsxs)(K.Fragment,{children:[w.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:U.reasoning}),w.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===p?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===p,onClick:()=>Ee(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:U.reasoningOptionLabel(e.value,e.label)})}),e.value===p&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value)),(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`})]}),(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${u===`model`?`selected`:``}`,role:`menuitem`,"data-testid":`code-model-submenu-trigger`,onClick:()=>ye(u===`model`?null:`model`),children:[(0,K.jsx)(`span`,{children:x}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),u===`model`&&(0,K.jsx)(`div`,{className:`code-model-submenu code-composer-menu`,role:`menu`,"data-testid":`code-model-submenu`,onKeyDown:be,children:h.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===f?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===f,onClick:()=>Te(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:Fb(e,e.value)})}),e.value===f&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value))})]}),Pe&&(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${u===`speed`?`selected`:``}`,role:`menuitem`,"data-testid":`code-speed-submenu-trigger`,onClick:()=>ye(u===`speed`?null:`speed`),children:[(0,K.jsx)(`span`,{children:U.speed}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),u===`speed`&&(0,K.jsx)(`div`,{className:`code-speed-submenu code-composer-menu`,role:`menu`,"data-testid":`code-speed-submenu`,onKeyDown:be,children:T.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===m?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===m,onClick:()=>De(e.value),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsxs)(`span`,{className:`code-speed-option-label`,children:[e.value===`priority`&&(0,K.jsx)(`span`,{className:`code-speed-option-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Px,{})}),(0,K.jsx)(`span`,{children:U.serviceTierLabel(e.value,e.label)})]}),e.description&&(0,K.jsx)(`small`,{children:U.serviceTierDescription(e.value,e.description)})]}),e.value===m&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value))})]})]})})})]}),Xe&&(0,K.jsx)(`button`,{type:`button`,className:`code-composer-mic ${j?`listening`:``}`,"data-testid":`code-composer-mic`,"aria-label":j?U.stopDictation:A?U.startDictation:U.mobileDictationHint,"aria-pressed":j,onPointerDown:wt,onClick:Ct,disabled:!e||!xt,title:xt?j?U.stopDictation:A?U.startDictation:U.mobileDictationHint:U.speechUnsupported,children:(0,K.jsx)(Nx,{listening:j})}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${vt?`interrupt`:``}`,"data-testid":`code-composer-send`,"data-action":te,"aria-label":vt?U.interruptAgent:U.sendMessage,onClick:vt?B:()=>re(nt.current),disabled:_t,children:vt?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(he,{})})]})]})})]})}function Ix({mode:e}){return e===`ask`?(0,K.jsx)(ye,{className:`code-approval-hand-glyph`}):e===`custom`?(0,K.jsx)(`svg`,{className:`filled`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M7.99997 6C6.89497 6 5.99997 6.895 5.99997 8C5.99997 9.105 6.89497 10 7.99997 10C9.10497 10 9.99997 9.105 9.99997 8C9.99997 6.895 9.10497 6 7.99997 6ZM7.99997 9C7.44797 9 6.99997 8.552 6.99997 8C6.99997 7.448 7.44797 7 7.99997 7C8.55197 7 8.99997 7.448 8.99997 8C8.99997 8.552 8.55197 9 7.99997 9ZM14.565 9.715L13.279 8.628C13.245 8.599 13.213 8.567 13.184 8.533C12.888 8.186 12.931 7.667 13.279 7.372L14.565 6.285C14.693 6.177 14.742 6.003 14.691 5.844C14.386 4.903 13.882 4.04 13.219 3.308C13.139 3.22 13.027 3.172 12.912 3.172C12.865 3.172 12.818 3.18 12.773 3.196L11.186 3.761C11.144 3.776 11.1 3.788 11.056 3.796C11.006 3.805 10.956 3.81 10.907 3.81C10.515 3.81 10.167 3.532 10.094 3.134L9.79097 1.482C9.76097 1.318 9.63397 1.188 9.46997 1.153C8.98997 1.051 8.49897 1 8.00097 1C7.50297 1 7.01097 1.052 6.53097 1.153C6.36697 1.188 6.23997 1.318 6.20997 1.482L5.90797 3.134C5.89997 3.178 5.88797 3.221 5.87297 3.263C5.75197 3.6 5.43397 3.81 5.09397 3.81C5.00197 3.81 4.90797 3.794 4.81597 3.762L3.22897 3.197C3.18397 3.181 3.13597 3.173 3.08997 3.173C2.97497 3.173 2.86297 3.221 2.78297 3.309C2.11897 4.041 1.61597 4.904 1.30997 5.845C1.25797 6.004 1.30797 6.178 1.43597 6.286L2.72197 7.373C2.75597 7.402 2.78797 7.434 2.81697 7.468C3.11297 7.815 3.06997 8.334 2.72197 8.629L1.43597 9.716C1.30797 9.824 1.25897 9.998 1.30997 10.157C1.61497 11.098 2.11897 11.961 2.78297 12.693C2.86297 12.781 2.97497 12.829 3.08997 12.829C3.13697 12.829 3.18397 12.821 3.22897 12.805L4.81597 12.24C4.85797 12.225 4.90197 12.213 4.94597 12.205C4.99597 12.196 5.04597 12.192 5.09497 12.192C5.48697 12.192 5.83497 12.47 5.90797 12.868L6.20997 14.52C6.23997 14.684 6.36697 14.814 6.53097 14.849C7.01097 14.951 7.50297 15.002 8.00097 15.002C8.49897 15.002 8.99097 14.95 9.46997 14.849C9.63397 14.814 9.76097 14.684 9.79097 14.52L10.094 12.868C10.102 12.824 10.114 12.781 10.129 12.739C10.25 12.402 10.568 12.192 10.908 12.192C11 12.192 11.094 12.208 11.186 12.24L12.772 12.805C12.818 12.821 12.865 12.829 12.911 12.829C13.026 12.829 13.138 12.781 13.218 12.693C13.882 11.961 14.385 11.098 14.69 10.157C14.742 9.998 14.692 9.824 14.564 9.716L14.565 9.715ZM12.728 11.726L11.521 11.296C11.323 11.226 11.117 11.19 10.908 11.19C10.139 11.19 9.44697 11.676 9.18797 12.399C9.15397 12.492 9.12897 12.588 9.11097 12.686L8.88097 13.937C8.59097 13.979 8.29597 14 8.00097 14C7.70597 14 7.41097 13.979 7.11997 13.936L6.89097 12.685C6.73197 11.818 5.97697 11.189 5.09497 11.189C4.98697 11.189 4.87697 11.199 4.76597 11.219C4.66897 11.237 4.57397 11.262 4.47997 11.295L3.27297 11.725C2.90497 11.264 2.61097 10.759 2.39397 10.214L3.36797 9.391C3.74097 9.076 3.96797 8.634 4.00797 8.148C4.04797 7.662 3.89497 7.19 3.57797 6.818C3.51397 6.743 3.44297 6.672 3.36797 6.608L2.39397 5.785C2.61097 5.24 2.90497 4.734 3.27297 4.274L4.47997 4.704C4.67797 4.774 4.88397 4.81 5.09397 4.81C5.86297 4.81 6.55497 4.324 6.81397 3.601C6.84797 3.507 6.87297 3.411 6.89097 3.314L7.11997 2.063C7.41097 2.021 7.70597 1.999 8.00097 1.999C8.29597 1.999 8.59097 2.02 8.88097 2.062L9.10997 3.313C9.26897 4.18 10.024 4.809 10.906 4.809C11.014 4.809 11.124 4.799 11.234 4.779C11.331 4.761 11.427 4.736 11.521 4.703L12.728 4.273C13.096 4.733 13.39 5.239 13.607 5.784L12.634 6.607C12.261 6.922 12.033 7.364 11.994 7.85C11.954 8.336 12.107 8.809 12.424 9.18C12.489 9.256 12.559 9.326 12.635 9.39L13.609 10.213C13.392 10.758 13.098 11.264 12.73 11.724L12.728 11.726Z`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 3.6 19 6v5.5c0 4.2-2.7 7.6-7 8.9-4.3-1.3-7-4.7-7-8.9V6l7-2.4Z`}),e===`full`||e===`bypassPermissions`?(0,K.jsx)(`path`,{d:`M12 8v5`}):(0,K.jsx)(`path`,{d:`M9.5 12.4 11.3 14l3.5-4`}),e===`full`||e===`bypassPermissions`?(0,K.jsx)(`path`,{d:`M12 16.4h.01`}):null]})}function Lx(){return(0,K.jsx)(ge,{})}function Rx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function zx({request:e,onRespond:t,copy:n}){let r=e.toolCall?.title||n.acpPermissionTool,i=e.options.filter(e=>e.kind.startsWith(`allow`)),a=e.options.filter(e=>e.kind.startsWith(`reject`)),[o,s]=(0,W.useState)(i.find(e=>e.kind===`allow_once`)?.optionId||i[0]?.optionId||``),[c,l]=(0,W.useState)(!1),u={...e._meta||{},...e.toolCall?._meta||{}},d=Rx(u.sandbox_authorization),f=Rx(u.sandbox_fallback_authorization),p=u.sandbox_not_applied,m=Array.isArray(d?.network_hosts)?d.network_hosts.map(String):[],h=Array.isArray(d?.write_paths)?d.write_paths.map(String):[],g=e.securityWarnings||[],_=g.length>0&&!c,v=[];return e.toolCall?.rawInput!==void 0&&v.push([`Input`,e.toolCall.rawInput]),e.toolCall?.content!==void 0&&v.push([`Content`,e.toolCall.content]),e.toolCall?.locations!==void 0&&v.push([`Locations`,e.toolCall.locations]),(0,K.jsxs)(`section`,{className:`code-app-server-request`,"data-testid":`code-acp-permission-request`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:n.acpPermissionTitle}),(0,K.jsx)(`span`,{children:e.origin===`subagent`?`Subagent · ${e.toolCall?.kind||`tool`}`:e.toolCall?.kind||`tool`})]}),(0,K.jsx)(`p`,{children:r}),v.length>0?(0,K.jsxs)(`details`,{className:`code-acp-permission-details`,children:[(0,K.jsx)(`summary`,{children:`Details`}),v.map(([e,t])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e}),(0,K.jsx)(`pre`,{children:typeof t==`string`?t:JSON.stringify(t,null,2)})]},e))]}):null,d?(0,K.jsxs)(`section`,{className:`code-acp-sandbox-details`,"data-testid":`code-acp-sandbox-details`,children:[d.reason?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Reason from Agent`}),(0,K.jsx)(`span`,{children:d.reason})]}):null,d.unsandboxed?(0,K.jsxs)(`p`,{className:`warning`,children:[(0,K.jsx)(`strong`,{children:`Sandbox`}),(0,K.jsx)(`span`,{children:`Runs without the OS sandbox`})]}):null,d.network_all_hosts||d.network?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Network`}),(0,K.jsx)(`span`,{children:`Any host`})]}):m.length>0?(0,K.jsxs)(`details`,{children:[(0,K.jsxs)(`summary`,{children:[`Network · `,m.length,` `,m.length===1?`host`:`hosts`]}),(0,K.jsx)(`ul`,{children:m.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(`code`,{children:e})},e))})]}):null,d.allow_fs_write_all?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Write access`}),(0,K.jsx)(`span`,{children:`Unrestricted workspace writes`})]}):h.length>0?(0,K.jsxs)(`details`,{children:[(0,K.jsxs)(`summary`,{children:[`Write access · `,h.length,` `,h.length===1?`path`:`paths`]}),(0,K.jsx)(`ul`,{children:h.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(`code`,{children:e})},e))})]}):null,d.command?(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{children:`Command`}),(0,K.jsx)(`pre`,{children:d.command})]}):null]}):null,f?(0,K.jsxs)(`section`,{className:`code-acp-sandbox-details warning`,"data-testid":`code-acp-sandbox-fallback`,children:[(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Sandbox unavailable`}),(0,K.jsx)(`span`,{children:f.reason||`The command may run without OS sandboxing.`})]}),f.command?(0,K.jsx)(`pre`,{children:f.command}):null]}):null,p?(0,K.jsx)(`section`,{className:`code-acp-sandbox-details warning`,"data-testid":`code-acp-sandbox-not-applied`,children:(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Sandbox not applied`}),(0,K.jsx)(`span`,{children:typeof p==`string`?p:JSON.stringify(p)})]})}):null,g.length>0?(0,K.jsxs)(`label`,{className:`code-acp-permission-risk`,"data-testid":`code-acp-permission-risk`,children:[(0,K.jsx)(`strong`,{children:`Potentially misleading Unicode`}),g.map(e=>(0,K.jsxs)(`span`,{className:`code-acp-permission-risk-finding`,children:[(0,K.jsx)(`code`,{children:e.displayValue}),e.characters.map(e=>(0,K.jsxs)(`small`,{children:[e.character?`‘${e.character}’ `:``,e.codePoint,` · `,e.description]},`${e.codePoint}:${e.kind}`))]},`${e.targetType}:${e.value}`)),(0,K.jsx)(`input`,{type:`checkbox`,checked:c,onChange:e=>l(e.target.checked)}),(0,K.jsx)(`span`,{children:`I reviewed these targets and wish to proceed.`})]}):null,(0,K.jsxs)(`div`,{className:`code-app-server-request-actions`,children:[i.length>1?(0,K.jsx)(`select`,{"aria-label":`Permission scope`,value:o,onChange:e=>s(e.target.value),children:i.map(e=>(0,K.jsx)(`option`,{value:e.optionId,children:e.name},e.optionId))}):null,i.length>0?(0,K.jsx)(`button`,{type:`button`,className:`approve`,disabled:_,onClick:()=>t(e.requestId,o||i[0].optionId,!1),children:i.length===1?i[0].name:n.appServerRequestApprove}):null,a.map(n=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,n.optionId,!1),children:n.name},n.optionId)),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,void 0,!0),children:n.cancel})]})]})}function Bx(e){return Array.isArray(e.oneOf)?e.oneOf.map(e=>({value:e.const,label:e.title})):Array.isArray(e.enum)?e.enum.map(e=>({value:e,label:e})):Array.isArray(e.items?.anyOf)?e.items.anyOf.map(e=>({value:e.const,label:e.title})):Array.isArray(e.items?.enum)?e.items.enum.map(e=>({value:e,label:e})):[]}function Vx(e){return e.type===`boolean`?e.default===!0:e.type===`array`?Array.isArray(e.default)?e.default:[]:e.type===`number`||e.type===`integer`?typeof e.default==`number`?e.default:``:typeof e.default==`string`?e.default:Bx(e)[0]?.value||``}function Hx({request:e,onRespond:t}){let n=e.requestedSchema?.properties||{},r=new Set(e.requestedSchema?.required||[]),[i,a]=(0,W.useState)(()=>Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Vx(t)]))),[o,s]=(0,W.useState)(``),c=e.requestedSchema?.title||`Input requested`,l=e.mode===`url`&&e.status===`accepted`,u=(0,W.useMemo)(()=>{if(e.mode!==`url`||!e.url)return``;try{let t=new URL(e.url);return[`http:`,`https:`].includes(t.protocol)?t.toString():``}catch{return``}},[e.mode,e.url]);return(0,K.jsxs)(`form`,{className:`code-app-server-request code-acp-elicitation`,"data-testid":`code-acp-elicitation`,"data-status":e.status||`pending`,onSubmit:a=>{a.preventDefault();for(let[e,t]of Object.entries(n)){let n=i[e];if(t.type!==`array`)continue;let a=Array.isArray(n)?n:[],o=Math.max(+!!r.has(e),Number(t.minItems||0));if(a.length<o){s(`${t.title||e} needs at least ${o} selection${o===1?``:`s`}.`);return}if(Number.isFinite(t.maxItems)&&a.length>Number(t.maxItems)){s(`${t.title||e} allows at most ${t.maxItems} selections.`);return}}s(``);let o=Object.fromEntries(Object.entries(i).filter(([e,t])=>r.has(e)||(Array.isArray(t)?t.length>0:t!==``)));t(e.requestId,`accept`,o)},children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:c}),(0,K.jsx)(`span`,{children:e.origin===`subagent`?`Subagent · ${e.mode}`:e.mode})]}),(0,K.jsx)(`p`,{children:e.message}),e.requestedSchema?.description?(0,K.jsx)(`small`,{children:e.requestedSchema.description}):null,o?(0,K.jsx)(`small`,{className:`code-acp-elicitation-error`,role:`alert`,children:o}):null,e.mode===`url`?u?(0,K.jsx)(`a`,{className:`code-acp-elicitation-link`,href:u,target:`_blank`,rel:`noreferrer`,children:`Open secure link`}):(0,K.jsx)(`small`,{role:`alert`,children:`The Agent provided an unsupported link.`}):(0,K.jsx)(`div`,{className:`code-app-server-request-questions`,children:Object.entries(n).map(([e,t])=>{let n=Bx(t),o=t.title||e;return t.type===`boolean`?(0,K.jsxs)(`label`,{className:`code-acp-elicitation-checkbox`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:i[e]===!0,onChange:t=>a(n=>({...n,[e]:t.target.checked}))}),(0,K.jsx)(`span`,{children:o}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e):t.type===`array`?(0,K.jsxs)(`fieldset`,{children:[(0,K.jsx)(`legend`,{children:o}),n.map(t=>{let n=Array.isArray(i[e])?i[e]:[];return(0,K.jsxs)(`label`,{className:`code-acp-elicitation-checkbox`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:n.includes(t.value),onChange:r=>a(i=>({...i,[e]:r.target.checked?[...n,t.value]:n.filter(e=>e!==t.value)}))}),(0,K.jsx)(`span`,{children:t.label})]},t.value)})]},e):(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:o}),n.length>0?(0,K.jsx)(`select`,{value:String(i[e]??``),required:r.has(e),onChange:t=>a(n=>({...n,[e]:t.target.value})),children:n.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,K.jsx)(`input`,{type:t.type===`number`||t.type===`integer`?`number`:t.format===`email`?`email`:t.format===`date`?`date`:t.format===`date-time`?`datetime-local`:t.format===`uri`?`url`:`text`,value:String(i[e]??``),required:r.has(e),min:t.minimum??void 0,max:t.maximum??void 0,minLength:t.minLength??void 0,maxLength:t.maxLength??void 0,pattern:t.pattern??void 0,step:t.type===`integer`?1:t.type===`number`?`any`:void 0,onChange:n=>a(r=>({...r,[e]:t.type===`number`||t.type===`integer`?n.target.value===``?``:n.target.valueAsNumber:n.target.value}))}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e)})}),l?(0,K.jsx)(`small`,{className:`code-acp-elicitation-waiting`,children:`Waiting for the Agent to confirm completion…`}):(0,K.jsxs)(`div`,{className:`code-app-server-request-actions`,children:[(0,K.jsx)(`button`,{type:`submit`,className:`approve`,disabled:e.mode===`url`&&!u,children:e.mode===`url`?`Continue`:`Submit`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,`decline`),children:`Decline`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,`cancel`),children:`Cancel`})]})]})}function Ux(e){return e.ctrlKey&&e.key.toLowerCase()===`c`?``:e.key===`Tab`?` `:e.key===`Escape`?`\x1B`:e.key===`ArrowUp`?`\x1B[A`:e.key===`ArrowDown`?`\x1B[B`:``}function Wx({agentId:e,authTerminal:t}){let[r,i]=(0,W.useState)(``),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.useState)(``),l=(0,W.useRef)(null),u=t.terminal,d=t.state===`running`&&!u?.exitStatus&&u?.interactive===!0;(0,W.useEffect)(()=>{let e=l.current;e&&(e.scrollTop=e.scrollHeight)},[u?.output]);let f=async r=>{if(!(!d||!r||a)){o(!0);try{let i=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t.terminalId)}/input`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:r})}),a=await i.json().catch(()=>null);if(!i.ok)throw Error(a?.error||`Failed to send terminal input (${i.status})`);c(``)}catch(e){c(e instanceof Error?e.message:`Failed to send terminal input`)}finally{o(!1)}}};return(0,K.jsxs)(`div`,{className:`code-acp-auth-terminal`,"data-testid":`code-acp-auth-terminal`,children:[(0,K.jsxs)(`div`,{className:`code-acp-auth-terminal-heading`,children:[(0,K.jsx)(`strong`,{children:t.name||`Sign in`}),(0,K.jsx)(`span`,{children:t.state===`running`?`Waiting for sign-in`:t.state})]}),(0,K.jsx)(`pre`,{ref:l,"data-testid":`code-acp-auth-terminal-output`,children:u?.output||`Starting sign-in…`}),d?(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=r;t&&(i(``),f(`${t}\r`))},children:[(0,K.jsx)(`input`,{"aria-label":`Terminal sign-in input`,autoComplete:`off`,"data-testid":`code-acp-auth-terminal-input`,disabled:a,value:r,onChange:e=>i(e.currentTarget.value),onKeyDown:e=>{let t=Ux(e);t&&(e.preventDefault(),f(t))}}),(0,K.jsx)(`button`,{type:`submit`,disabled:a||!r,children:`Send`})]}):null,t.error||s?(0,K.jsx)(`small`,{className:`code-acp-auth-terminal-error`,children:t.error||s}):null]})}function Gx({agentId:e,methods:t,authTerminal:n,agentName:r,authenticatingId:i,onAuthenticate:a}){if(t.length===0&&!n)return null;let o=t.filter(e=>!e.type||e.type===`agent`||e.type===`terminal`),s=t.filter(e=>e.type===`env_var`);return(0,K.jsxs)(`section`,{className:`code-app-server-request code-acp-authentication`,"data-testid":`code-acp-authentication`,role:`alert`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsxs)(`strong`,{children:[`Sign in to `,r||`Agent`]}),(0,K.jsx)(`span`,{children:`Authentication required`})]}),(0,K.jsxs)(`div`,{className:`code-acp-authentication-methods`,children:[n?(0,K.jsx)(Wx,{agentId:e,authTerminal:n}):null,o.map(e=>(0,K.jsxs)(`div`,{className:`code-acp-authentication-method`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e.name||e.id}),e.description?(0,K.jsx)(`small`,{children:e.description}):null,e.link?(0,K.jsx)(`a`,{href:e.link,target:`_blank`,rel:`noreferrer`,children:`Get credentials`}):null]}),(0,K.jsx)(`button`,{type:`button`,disabled:!!i,onClick:()=>a(e.id),children:i===e.id||n?.methodId===e.id&&n.state===`running`?`Signing in…`:`Authenticate`})]},e.id)),s.map(e=>(0,K.jsx)(`div`,{className:`code-acp-authentication-method unsupported`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e.name||e.id}),e.description?(0,K.jsx)(`small`,{children:e.description}):null,e.type===`env_var`?(0,K.jsxs)(`small`,{children:[`Set `,e.vars?.map(e=>e.label||e.name).join(`, `)||`the requested environment variables`,` and restart the Agent.`]}):null,e.link?(0,K.jsx)(`a`,{href:e.link,target:`_blank`,rel:`noreferrer`,children:`Get credentials`}):null]})},e.id))]})]})}function Kx(e){return e.options.flatMap(e=>`options`in e?e.options:[e])}function qx(e,t){return t.test(`${e.id} ${e.name} ${e.category||``}`)}function Jx(e,t){return e.configOptions.find(e=>e.type===`select`&&qx(e,t))}function Yx(e,t){return e.configOptions.find(e=>e.type===`boolean`&&qx(e,t))}function Xx(e){return e?Kx(e).find(t=>t.value===e.currentValue):void 0}function Zx(e){return e.trim().replace(/^gpt[-\s]*/i,``)||e}function Qx({modeId:e}){return e===`read-only`||e===`plan`?(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M3.5 12s3.1-5 8.5-5 8.5 5 8.5 5-3.1 5-8.5 5-8.5-5-8.5-5Z`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.4`})]}):e===`default`?(0,K.jsx)(ye,{className:`code-approval-hand-glyph`}):(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 3.6 19 6v5.5c0 4.2-2.7 7.6-7 8.9-4.3-1.3-7-4.7-7-8.9V6l7-2.4Z`}),e===`agent-full-access`||e===`bypassPermissions`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M12 8v5`}),(0,K.jsx)(`path`,{d:`M12 16.4h.01`})]}):e===`dontAsk`?(0,K.jsx)(`path`,{d:`M9.5 12h5`}):[`agent`,`auto`,`acceptEdits`,`build`].includes(e)?(0,K.jsx)(`path`,{d:`m9.5 12.4 1.8 1.6 3.5-4`}):(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.4`})]})}function $x(e){return[`agent`,`auto`,`acceptEdits`,`build`].includes(e)?`blue`:[`agent-full-access`,`bypassPermissions`].includes(e)?`orange`:`muted`}function eS(e){return e.configOptions.find(e=>e.type===`select`&&(e.id===`mode`||e.category===`mode`))}function tS(e,t){return e.provider===`qoder`&&e.agentInfo?.version===`1.0.43`?t.filter(e=>e.id!==`plan`):t}function nS(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21Z`})})}function rS({option:e,currentValue:t,label:n,onSelect:r}){return Kx(e).map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===t?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===t,onClick:()=>r(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:n(e)})}),e.value===t?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},e.value))}function iS({session:e,updatingId:t,copy:n,open:r,onToggle:i,onSetMode:a,onSetConfigOption:o}){let s=e.modes?.availableModes||[],c=eS(e),l=s.length===0&&!!c,u=tS(e,s.length>0?s:c?Kx(c).map(e=>({id:e.value,name:e.name,description:e.description})):[]);if(u.length===0)return null;let d=e.currentModeId||e.modes?.currentModeId||c?.currentValue||``,f=u.find(e=>e.id===d)||u[0],p=n.acpModeLabel(f?.id||d,f?.name||d),m=f?.description?n.acpModeDescription(f.id,f.description):``;return(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-approval ${$x(d)}`,"data-testid":`code-acp-mode`,"data-acp-value":d,"aria-label":n.agentPermissionMode,"aria-haspopup":`menu`,"aria-expanded":r,disabled:!!t,onClick:i,children:[(0,K.jsx)(`span`,{className:`code-tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Qx,{modeId:d})}),(0,K.jsx)(`span`,{className:`code-composer-approval-label`,children:p}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(ge,{})})]}),r?(0,K.jsxs)(`div`,{className:`code-approval-menu code-composer-menu`,role:`menu`,"data-testid":`code-acp-mode-menu`,children:[(0,K.jsxs)(`div`,{className:`code-approval-menu-header`,children:[(0,K.jsx)(`span`,{children:n.agentPermissionMode}),m?(0,K.jsx)(`small`,{children:m}):null]}),u.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-approval-option ${e.id===d?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.id===d,onClick:()=>l&&c?o(c.id,e.id):a(e.id),children:[(0,K.jsx)(`span`,{className:`code-approval-option-icon ${$x(e.id)}`,"aria-hidden":`true`,children:(0,K.jsx)(Qx,{modeId:e.id})}),(0,K.jsxs)(`span`,{className:`code-approval-option-copy`,children:[(0,K.jsx)(`span`,{children:n.acpModeLabel(e.id,e.name)}),e.description?(0,K.jsx)(`small`,{children:n.acpModeDescription(e.id,e.description)}):null]}),e.id===d?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},e.id))]}):null]})}function aS({session:e,updatingId:t,copy:n,open:r,pane:i,onToggle:a,onSetPane:o,onSetConfigOption:s,onSetProfile:c,onSetFast:l}){let u=Jx(e,/(^|[\s_-])model([\s_-]|$)/i),d=Jx(e,/(reasoning|thought)/i),f=Yx(e,/(fast|speed)/i),p=e.configOptions.filter(e=>e!==u&&e!==d&&e!==f&&e.category!==`mode`&&e.id!==`mode`),m=Xx(u),h=Xx(d),g=u&&d?Kx(u).map(e=>({value:e.value,label:e.name,reasoning:Kx(d).map(e=>({value:e.value,label:n.reasoningOptionLabel(e.value,e.name)}))})):[],_=!!hx(g,u?.currentValue||``);if(!u&&!d&&!f&&p.length===0)return null;let v=!!t;return(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor model-picker`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-model-picker`,"data-testid":`code-acp-model-picker`,"data-agent-model-preset":`${u?.currentValue||``}:${d?.currentValue||``}`,"aria-label":n.modelAndReasoning,"aria-haspopup":`menu`,"aria-expanded":r,disabled:v,title:[m?.name,h?.name,f?.currentValue?f.name:``].filter(Boolean).join(` · `),onClick:a,children:[f?.currentValue?(0,K.jsx)(`span`,{className:`code-composer-speed-active`,"aria-hidden":`true`,children:(0,K.jsx)(nS,{})}):null,(0,K.jsx)(`span`,{className:`code-composer-model-label desktop`,children:Zx(m?.name||u?.currentValue||`Model`)}),(0,K.jsx)(`span`,{className:`code-composer-model-label mobile`,children:Zx(m?.name||u?.currentValue||`Model`)}),h?(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted desktop`,children:h.name}):null,h?(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted mobile`,children:h.name}):null,(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(ge,{})})]}),r?(0,K.jsx)(`div`,{className:`code-model-picker-menu code-composer-menu ${_?`has-matrix`:``}`,role:`menu`,"data-testid":`code-acp-model-menu`,children:(0,K.jsx)(yx,{models:g,currentModel:u?.currentValue||``,currentReasoning:d?.currentValue||``,fastAvailable:!!f,fast:f?.currentValue===!0,disabled:v,onSelect:(e,t)=>{u&&d&&c(u.id,e,d.id,t)},onFastChange:e=>{f&&l(f.id,e)},advanced:(0,K.jsxs)(K.Fragment,{children:[d?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:n.reasoning}),(0,K.jsx)(rS,{option:d,currentValue:d.currentValue,label:e=>n.reasoningOptionLabel(e.value,e.name),onSelect:e=>s(d.id,e)}),(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`})]}):null,u?(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${i===`model`?`selected`:``}`,role:`menuitem`,"data-testid":`code-acp-model-submenu-trigger`,onClick:()=>o(i===`model`?null:`model`),children:[(0,K.jsx)(`span`,{children:m?.name||u.currentValue}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),i===`model`?(0,K.jsx)(`div`,{className:`code-model-submenu code-composer-menu`,role:`menu`,"data-testid":`code-acp-model-submenu`,children:(0,K.jsx)(rS,{option:u,currentValue:u.currentValue,label:e=>e.name,onSelect:e=>s(u.id,e)})}):null]}):null,f?(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${i===`speed`?`selected`:``}`,role:`menuitem`,"data-testid":`code-acp-speed-submenu-trigger`,onClick:()=>o(i===`speed`?null:`speed`),children:[(0,K.jsx)(`span`,{children:n.speed}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),i===`speed`?(0,K.jsx)(`div`,{className:`code-speed-submenu code-composer-menu`,role:`menu`,"data-testid":`code-acp-speed-submenu`,children:[!1,!0].map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${f.currentValue===e?`selected`:``}`,role:`menuitemradio`,"aria-checked":f.currentValue===e,onClick:()=>s(f.id,e),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsxs)(`span`,{className:`code-speed-option-label`,children:[e?(0,K.jsx)(`span`,{className:`code-speed-option-icon`,"aria-hidden":`true`,children:(0,K.jsx)(nS,{})}):null,(0,K.jsx)(`span`,{children:e?f.name:n.serviceTierLabel(`default`,`Standard`)})]}),(0,K.jsx)(`small`,{children:e?f.description||n.serviceTierDescription(`priority`,``):n.serviceTierDescription(`default`,``)})]}),f.currentValue===e?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},String(e)))}):null]}):null,p.map(e=>e.type===`select`?(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`}),(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:e.name}),(0,K.jsx)(rS,{option:e,currentValue:e.currentValue,label:e=>e.name,onSelect:t=>s(e.id,t)})]},e.id):(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.currentValue?`selected`:``}`,role:`menuitemcheckbox`,"aria-checked":e.currentValue,onClick:()=>s(e.id,!e.currentValue),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsx)(`span`,{children:e.name}),e.description?(0,K.jsx)(`small`,{children:e.description}):null]}),e.currentValue?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},e.id))]})})}):null]})}function oS(e){let t=Number(e?.used),n=Number(e?.size);if(!Number.isFinite(t)||t<0||!Number.isFinite(n)||n<=0)return null;let r=t/n,i=Math.max(0,Math.min(100,Math.round(r*100))),a=Number(e?.cost?.amount),o=String(e?.cost?.currency||``).trim().toUpperCase(),s=Number.isFinite(a)&&a>=0&&/^[A-Z]{3}$/.test(o)?`${a.toLocaleString(`en-US`,{maximumFractionDigits:4})} ${o}`:``;return{usedTokens:t,limitTokens:n,percentUsed:i,percentLeft:100-i,costLabel:s,level:r>=1?`critical`:r>=.85?`warning`:`normal`}}function sS(e,t){if(!e)return e;let n=Array.isArray(t.configOptions)?t.configOptions:typeof t.configId==`string`&&(typeof t.value==`string`||typeof t.value==`boolean`)?[{configId:t.configId,value:t.value}]:[];if(n.length===0)return e;let r=new Map(n.flatMap(e=>e&&typeof e==`object`&&`configId`in e&&typeof e.configId==`string`&&`value`in e&&(typeof e.value==`string`||typeof e.value==`boolean`)?[[e.configId,e.value]]:[]));return r.size===0?e:{...e,configOptions:e.configOptions.map(e=>{let t=r.get(e.id);return t===void 0||typeof t!=typeof e.currentValue?e:{...e,currentValue:t}})}}function cS(e,t,r){let[i,a]=(0,W.useState)(null),[o,s]=(0,W.useState)(``),[c,l]=(0,W.useState)(``),[u,d]=(0,W.useState)(``),f=(0,W.useRef)(null);(0,W.useEffect)(()=>{f.current=i},[i]);let p=(0,W.useCallback)(async r=>{if(!(!e||!t))try{let t=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-session?includeEntries=0`),{signal:r}),i=await t.json().catch(()=>null);if(!t.ok||!i?.session)throw Error(i?.error||`Failed to read ACP session (${t.status})`);f.current=i.session,a(i.session),s(``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;s(e instanceof Error?e.message:`Failed to read ACP session`)}},[t,e]);(0,W.useEffect)(()=>{let e=new AbortController;return p(e.signal),()=>e.abort()},[p,r]),(0,W.useEffect)(()=>{if(!i?.authTerminal||![`running`,`completed`].includes(i.authTerminal.state))return;let e=window.setInterval(()=>{p()},500);return()=>window.clearInterval(e)},[p,i?.authTerminal?.state,i?.authTerminal?.terminalId]);let m=(0,W.useCallback)(async(t,r)=>{if(!e||c)return!1;let i=f.current,o=sS(i,r);o!==i&&(f.current=o,a(o)),l(t);try{let t=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-session`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)}),i=await t.json().catch(()=>null);if(!t.ok)throw Error(i?.error||`Failed to update ACP session (${t.status})`);return a(e=>{let t=e&&{...e,...i?.modeId?{currentModeId:i.modeId,modes:e.modes?{...e.modes,currentModeId:i.modeId}:e.modes}:{},...i?.configOptions?{configOptions:i.configOptions}:{}};return f.current=t,t}),s(``),!0}catch(e){return i&&(f.current=i,a(i)),s(e instanceof Error?e.message:`Failed to update ACP session`),!1}finally{l(``)}},[e,c]);return{session:i,error:o,updatingId:c,authenticatingId:u,setMode:(0,W.useCallback)(e=>m(`mode`,{modeId:e}),[m]),setConfigOption:(0,W.useCallback)((e,t)=>m(e,{configId:e,value:t}),[m]),setConfigOptions:(0,W.useCallback)(e=>m(e.map(e=>e.configId).join(`:`),{configOptions:e}),[m]),authenticate:(0,W.useCallback)(async t=>{if(!e||u)return!1;d(t);try{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-session/authenticate`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({methodId:t})}),i=await r.json().catch(()=>null);if(!r.ok)throw Error(i?.error||`Failed to authenticate ACP Agent (${r.status})`);return s(``),await p(),!0}catch(e){return s(e instanceof Error?e.message:`Failed to authenticate ACP Agent`),!1}finally{d(``)}},[e,u,p])}}var lS=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM6 3.99951C6 2.89651 6.897 1.99951 8 1.99951C9.103 1.99951 10 2.89651 10 3.99951V7.99951C10 9.10251 9.103 9.99951 8 9.99951C6.897 9.99951 6 9.10251 6 7.99951V3.99951ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`,uS=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`;function dS({listening:e}){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:e?uS:lS})})}function fS(e){return!Number.isFinite(e)||e<0?`0`:e>=1e6?`${Math.round(e/1e5)/10}m`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function pS(e,t){let n=ix(e,t);if(n)return n;let r=Math.max(0,Math.min(t,e.length)),i=e.lastIndexOf(`
111
- `,Math.max(0,r-1))+1,a=e.slice(i,r).match(/^(\s*)\/(\$[A-Za-z0-9._:-]*)$/);return a?{start:i+(a[1]?.length??0),end:r,query:a[2]??``,trigger:`/`}:null}function mS({active:e,agentId:t,runtimeState:n,sessionUpdatedAt:r,runtimeError:i,draft:a,attachments:o,composerMode:s,contextWindow:c,pendingFollowUp:l,submitAction:u,textareaRef:d,attachmentInputRef:f,permissions:p,elicitations:m,activeElicitations:h,speechSupported:g,speechListening:_,onDraftChange:v,onNavigateHistory:y,onRemoveAttachment:b,onSubmit:x,onInterrupt:S,onDiscardPendingFollowUp:C,onToggleSpeechInput:w,onPasteAttachment:T,onAttachmentFiles:E,onChooseAttachmentFile:D,onActivateComposerMode:O,onClearComposerMode:k,onRespondToPermission:ee,onRespondToElicitation:te,copy:A}){let j=(0,W.useRef)(!1),M=(0,W.useRef)(0),N=(0,W.useRef)(a),P=(0,W.useRef)(null),[F,ne]=(0,W.useState)(!1),[I,L]=(0,W.useState)(a.length),[R,z]=(0,W.useState)(0),[re,B]=(0,W.useState)(null),[ie,V]=(0,W.useState)(null),{session:ae,error:oe,updatingId:se,authenticatingId:ce,setMode:ue,setConfigOption:de,setConfigOptions:fe,authenticate:pe}=cS(t,e,`${n}:${r||``}`);N.current=a;let me=u===`interrupt`,H=u===`disabled`,ge=(0,W.useMemo)(()=>pS(a,I),[a,I]),_e=(0,W.useMemo)(()=>{if(!ge)return[];let e=ge.query.toLowerCase();return(ae?.availableCommands||[]).filter(t=>{let n=t.name.toLowerCase();return ge.trigger===`$`&&!n.startsWith(`$`)?!1:(ge.trigger===`$`?n.slice(1):n).startsWith(e)||t.description.toLowerCase().includes(e)}).slice(0,12)},[ge,ae?.availableCommands]),ve=e&&F&&_e.length>0,ye=_e[R]||_e[0]||null;(0,W.useEffect)(()=>z(0),[ge?.query,ge?.trigger,_e.length]),(0,W.useEffect)(()=>{if(!re)return;let e=e=>{e.target instanceof Node&&P.current?.contains(e.target)||(B(null),V(null))};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[re]);let be=e=>{if(!ge)return;let t=`/${e} `,n=`${a.slice(0,ge.start)}${t}${a.slice(ge.end)}`,r=ge.start+t.length;B(null),N.current=n,v(n),window.requestAnimationFrame(()=>{d.current?.focus({preventScroll:!0}),d.current?.setSelectionRange(r,r),L(r)})},Ce=e=>{if(ve&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;z(e=>(e+t+_e.length)%_e.length);return}if(ve&&e.key===`Home`){e.preventDefault(),z(0);return}if(ve&&e.key===`End`){e.preventDefault(),z(_e.length-1);return}if(ve&&(e.key===`Enter`||e.key===`Tab`)&&ye){e.preventDefault(),e.stopPropagation(),be(ye.name);return}if(e.key===`ArrowUp`||e.key===`ArrowDown`){let t=e.key===`ArrowUp`?`previous`:`next`,n=y(t,{direction:t,value:e.currentTarget.value,selectionStart:e.currentTarget.selectionStart,selectionEnd:e.currentTarget.selectionEnd});if(n!==null){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=d.current;if(!e)return;let t=n.length;e.setSelectionRange(t,t)});return}}Yb(e,j.current,M.current)&&(e.preventDefault(),e.stopPropagation(),x(Xb(e.currentTarget.value,N.current)))},we=e=>{B(t=>t===e?null:e),V(null)},Te=oS(ae?.usage),Ee=Te||c,De=Te?.level||(Ee&&Ee.percentUsed>=100?`critical`:Ee&&Ee.percentUsed>=85?`warning`:`normal`),Oe=Ee?[`Context window: ${Ee.percentUsed}% used (${Ee.percentLeft}% left), ${fS(Ee.usedTokens)} / ${fS(Ee.limitTokens)} tokens used`,De===`critical`?`Context window is full`:De===`warning`?`Context window is nearly full`:``,Te?.costLabel?`Session cost: ${Te.costLabel}`:``].filter(Boolean).join(`. `):``,ke=ae?.errorKind===`authentication`||/\b(?:auth(?:entication)?|login|sign[ -]?in|unauthorized|401)\b/i.test(i);return(0,K.jsxs)(`footer`,{ref:P,className:`code-composer code-acp-composer ${re?`menu-open`:``} ${o.length>0?`has-attachments`:``} ${l&&e?`has-pending-followup`:``}`,"data-testid":`code-acp-composer`,children:[l&&e?(0,K.jsx)(`div`,{className:`code-pending-followup`,"data-testid":`code-acp-pending-followup`,children:l.messages.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row`,"data-testid":`code-acp-pending-followup-row`,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"aria-hidden":`true`,children:(0,K.jsx)(xe,{})}),(0,K.jsx)(`p`,{children:e.text||e.attachments?.map(e=>e.name).join(`, `)}),(0,K.jsx)(`div`,{className:`code-pending-followup-actions`,children:(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-acp-pending-followup-discard`,"aria-label":A.discardQueuedMessage,onClick:()=>C(e.id),children:(0,K.jsx)(le,{})})})]},e.id))}):null,e?p.map(e=>(0,K.jsx)(zx,{request:e,onRespond:ee,copy:A},e.requestId)):null,e?m.map(e=>(0,K.jsx)(Hx,{request:e,onRespond:te},e.requestId)):null,e?h.map(e=>(0,K.jsx)(Hx,{request:e,onRespond:te},`active-${e.elicitationId||e.requestId}`)):null,e&&ke?(0,K.jsx)(Gx,{agentId:t,methods:ae?.authMethods||[],authTerminal:ae?.authTerminal||null,agentName:ae?.agentInfo?.title||ae?.agentInfo?.name||``,authenticatingId:ce,onAuthenticate:e=>{pe(e)}}):null,e&&oe?(0,K.jsxs)(`section`,{className:`code-app-server-request code-app-server-notice`,"data-testid":`code-acp-error`,role:`alert`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:`ACP`}),(0,K.jsx)(`span`,{children:n||`error`})]}),(0,K.jsx)(`p`,{children:oe})]}):null,ve?(0,K.jsxs)(`div`,{className:`code-slash-menu code-composer-menu`,"data-testid":`code-acp-command-menu`,role:`listbox`,"aria-label":`ACP commands`,children:[(0,K.jsx)(`div`,{className:`code-slash-menu-header`,children:ge?.trigger===`$`?`Skills`:`Agent commands`}),_e.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`code-slash-command ${t===R?`active`:``}`,"data-testid":`code-acp-command-${e.name}`,role:`option`,"aria-selected":t===R,onMouseDown:e=>e.preventDefault(),onMouseMove:()=>z(t),onClick:()=>be(e.name),children:[(0,K.jsx)(`span`,{className:`code-slash-command-icon`,"aria-hidden":`true`,children:`/`}),(0,K.jsxs)(`span`,{className:`code-slash-command-copy`,children:[(0,K.jsx)(`span`,{className:`code-slash-command-title`,children:(0,K.jsxs)(`code`,{children:[`/`,e.name]})}),(0,K.jsxs)(`small`,{children:[e.description,e.input?.hint?` · ${e.input.hint}`:``]})]})]},e.name))]}):null,(0,K.jsx)(`textarea`,{"data-testid":`code-acp-composer-input`,ref:d,name:`farming-acp-chat-message`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,value:a,placeholder:e?s===`goal`?A.describeAgentGoal:s===`plan`?A.describePlanFirst:A.askFollowUpChanges:A.openAgentTerminalFirst,disabled:!e,onFocus:e=>{ne(!0),L(e.currentTarget.selectionStart),B(null),V(null)},onBlur:()=>ne(!1),onClick:e=>L(e.currentTarget.selectionStart),onKeyUp:e=>L(e.currentTarget.selectionStart),onSelect:e=>L(e.currentTarget.selectionStart),onChange:e=>{L(e.currentTarget.selectionStart),v(e.currentTarget.value)},onPaste:T,onCompositionStart:()=>{j.current=!0},onCompositionEnd:e=>{j.current=!1,M.current=Date.now(),v(e.currentTarget.value)},onKeyDown:Ce,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`}),(0,K.jsx)(rx,{attachments:o,onRemove:b}),(0,K.jsx)(`input`,{ref:f,className:`code-composer-file-input`,"data-testid":`code-acp-composer-file-input`,type:`file`,multiple:!0,onChange:E}),(0,K.jsxs)(`div`,{className:`code-composer-toolbar`,"data-testid":`code-acp-composer-toolbar`,children:[(0,K.jsxs)(`div`,{className:`code-composer-left-tools`,"data-testid":`code-acp-composer-left-tools`,children:[(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-add`,"data-testid":`code-acp-composer-add`,"aria-label":A.addContext,"aria-haspopup":`menu`,"aria-expanded":re===`commands`,disabled:!e,onClick:()=>we(`commands`),children:(0,K.jsx)(Se,{})}),re===`commands`?(0,K.jsxs)(`div`,{className:`code-plus-menu code-composer-menu`,role:`menu`,"data-testid":`code-acp-plus-menu`,children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-attach-file`,onClick:()=>{B(null),D()},children:[(0,K.jsx)(`span`,{children:A.attachFile}),(0,K.jsx)(`small`,{children:A.fileContext})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-goal-mode`,onClick:()=>{B(null),O(`goal`)},children:[(0,K.jsx)(`span`,{children:A.goalMode}),(0,K.jsx)(`small`,{children:A.setObjective})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-plan-mode`,onClick:()=>{B(null),O(`plan`)},children:[(0,K.jsx)(`span`,{children:A.planMode}),(0,K.jsx)(`small`,{children:A.planFirst})]})]}):null]}),s===`default`?null:(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-mode-chip`,"data-testid":`code-acp-composer-mode-chip`,"aria-label":A.clearComposerMode,onClick:k,children:[(0,K.jsx)(`span`,{children:s===`goal`?A.goalMode:A.planMode}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:(0,K.jsx)(le,{})})]}),ae?(0,K.jsx)(iS,{session:ae,updatingId:se,copy:A,open:re===`mode`,onToggle:()=>we(`mode`),onSetMode:e=>{B(null),ue(e)},onSetConfigOption:(e,t)=>{B(null),de(e,t)}}):null]}),(0,K.jsxs)(`div`,{className:`code-composer-right-tools`,"data-testid":`code-acp-composer-right-tools`,children:[Ee?(0,K.jsxs)(`div`,{className:`code-composer-context-window`,"data-testid":`code-acp-context-window`,"data-level":De,tabIndex:0,role:`img`,"aria-label":Oe,children:[(0,K.jsx)(`span`,{className:`code-context-window-ring`,"aria-hidden":`true`,style:{"--context-percent":Ee.percentUsed}}),(0,K.jsxs)(`div`,{className:`code-context-window-popover`,role:`tooltip`,children:[(0,K.jsx)(`span`,{children:`Context window:`}),(0,K.jsxs)(`strong`,{children:[Ee.percentUsed,`% used (`,Ee.percentLeft,`% left)`]}),(0,K.jsxs)(`strong`,{children:[fS(Ee.usedTokens),` / `,fS(Ee.limitTokens),` tokens used`]}),De===`critical`?(0,K.jsx)(`strong`,{className:`warning`,children:`Context window is full`}):null,De===`warning`?(0,K.jsx)(`strong`,{className:`warning`,children:`Context window is nearly full`}):null,Te?.costLabel?(0,K.jsx)(`strong`,{children:Te.costLabel}):null]})]}):null,ae?(0,K.jsx)(aS,{session:ae,updatingId:se,copy:A,open:re===`model`,pane:ie,onToggle:()=>we(`model`),onSetPane:V,onSetConfigOption:(e,t)=>{B(null),V(null),de(e,t)},onSetProfile:(e,t,n,r)=>{fe([{configId:e,value:t},{configId:n,value:r}])},onSetFast:(e,t)=>{de(e,t)}}):null,g?(0,K.jsx)(`button`,{type:`button`,className:`code-composer-mic ${_?`listening`:``}`,"data-testid":`code-acp-composer-mic`,"aria-label":_?A.stopDictation:A.startDictation,"aria-pressed":_,onClick:w,disabled:!e,title:_?A.stopDictation:A.startDictation,children:(0,K.jsx)(dS,{listening:_})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${me?`interrupt`:``}`,"data-testid":`code-acp-composer-send`,"data-action":u,"aria-label":me?A.interruptAgent:A.sendMessage,onClick:me?S:()=>x(N.current),disabled:H,children:me?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(he,{})})]})]})]})}function hS(e){return!!e&&e?.providerSessionProvider===`codex`&&e?.codexRuntimeMode===`app-server`&&!!(e?.codexAppServerThreadId||e?.providerSessionId)}function gS(e){return e?.status===`active`?`paused`:`active`}async function _S(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error||`${e.status}`);return t}function vS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M11.6 1.65a1.55 1.55 0 0 1 2.19 2.19l-8.4 8.4-3.14.64.64-3.14 8.71-8.09Zm-.7 2.11-7.08 7.08-.22 1.08 1.08-.22 7.08-7.08-.86-.86Zm1.56-1.4-.86.86.86.86.62-.62a.55.55 0 0 0-.78-.78l-.84.84Z`})})}function yS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M4.5 3.4c0-.67.73-1.08 1.3-.72l6.1 3.78a.85.85 0 0 1 0 1.44l-6.1 3.78a.85.85 0 0 1-1.3-.72V3.4Z`})})}function bS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M4.25 3.25c0-.41.34-.75.75-.75h1c.41 0 .75.34.75.75v9.5c0 .41-.34.75-.75.75H5a.75.75 0 0 1-.75-.75v-9.5Zm5 0c0-.41.34-.75.75-.75h1c.41 0 .75.34.75.75v9.5c0 .41-.34.75-.75.75h-1a.75.75 0 0 1-.75-.75v-9.5Z`})})}function xS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M6.25 2h3.5l.5 1H13v1H3V3h2.75l.5-1ZM4.2 5h7.6l-.48 8.1A1 1 0 0 1 10.32 14H5.68a1 1 0 0 1-1-.9L4.2 5Zm2.05 1 .35 7h.95L7.2 6h-.95Zm2.2 0v7h.95V6h-.95Z`})})}function SS({agent:e,active:t,copy:r}){let i=hS(e),a=e?.id||``,o=(0,W.useRef)(null),[s,c]=(0,W.useState)(e?.codexAppServerGoal||null),[l,u]=(0,W.useState)(s?.objective||``),[d,f]=(0,W.useState)(!1),[p,m]=(0,W.useState)(!1),[h,g]=(0,W.useState)(``);(0,W.useEffect)(()=>{c(e?.codexAppServerGoal||null)},[e?.codexAppServerGoal]),(0,W.useEffect)(()=>{f(!1),g(``)},[a]),(0,W.useEffect)(()=>{d||u(s?.objective||``)},[d,s]),(0,W.useEffect)(()=>{d&&o.current?.focus({preventScroll:!0})},[d]),(0,W.useEffect)(()=>{if(!t||!i||!a)return;let e=new AbortController;return fetch(n(`/api/agents/${encodeURIComponent(a)}/codex-goal`),{signal:e.signal}).then(_S).then(e=>{c(e.goal||null),g(``)}).catch(e=>{e?.name!==`AbortError`&&g(e?.message||r.codexTranscriptUnavailable)}),()=>e.abort()},[t,a,i,r.codexTranscriptUnavailable]);let _=(0,W.useCallback)(e=>{!i||!a||p||(m(!0),g(``),fetch(n(`/api/agents/${encodeURIComponent(a)}/codex-goal`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}).then(_S).then(e=>{c(e.goal||null),f(!1),g(``)}).catch(e=>{g(e?.message||r.codexTranscriptUnavailable)}).finally(()=>m(!1)))},[a,r.codexTranscriptUnavailable,i,p]),v=(0,W.useCallback)(()=>{let e=l.trim();if(!e){g(r.codexGoalObjective);return}_({objective:e,status:s?.status||`active`})},[r.codexGoalObjective,s?.status,l,_]),y=(0,W.useCallback)(()=>{if(!s){f(!0);return}_({status:gS(s)})},[s,_]),b=(0,W.useCallback)(()=>{!i||!a||p||!s||(m(!0),g(``),fetch(n(`/api/agents/${encodeURIComponent(a)}/codex-goal`),{method:`DELETE`}).then(_S).then(()=>{c(null),u(``),f(!1),g(``)}).catch(e=>{g(e?.message||r.codexTranscriptUnavailable)}).finally(()=>m(!1)))},[a,r.codexTranscriptUnavailable,s,i,p]);if(!e||e.providerSessionProvider!==`codex`||!s&&!d)return null;let x=s?.status===`active`,S=!i||p;return(0,K.jsxs)(`section`,{className:`code-codex-goal-bar`,"data-testid":`code-codex-goal-bar`,children:[(0,K.jsx)(`textarea`,{ref:o,className:`code-codex-goal-input`,"data-testid":`code-codex-goal-input`,rows:1,value:l,placeholder:r.codexGoalEmpty,readOnly:!d,disabled:!i||p,"aria-label":r.codexGoalObjective,onChange:e=>u(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&v(),e.key===`Escape`&&(u(s?.objective||``),f(!1),g(``))}}),(0,K.jsxs)(`div`,{className:`code-codex-goal-icon-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button`,"data-testid":`code-codex-goal-edit`,disabled:S,title:d?r.codexGoalSave:r.codexGoalEdit,"aria-label":d?r.codexGoalSave:r.codexGoalEdit,onClick:d?v:()=>f(!0),children:d?(0,K.jsx)(me,{}):(0,K.jsx)(vS,{})}),d?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button`,"data-testid":`code-codex-goal-cancel`,disabled:p,title:r.cancel,"aria-label":r.cancel,onClick:()=>{u(s?.objective||``),f(!1),g(``)},children:(0,K.jsx)(le,{})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button`,"data-testid":`code-codex-goal-toggle`,disabled:S||!s&&!l.trim(),title:x?r.codexGoalStop:r.codexGoalStart,"aria-label":x?r.codexGoalStop:r.codexGoalStart,onClick:y,children:x?(0,K.jsx)(bS,{}):(0,K.jsx)(yS,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button danger`,"data-testid":`code-codex-goal-delete`,disabled:S||!s,title:r.codexGoalDelete,"aria-label":r.codexGoalDelete,onClick:b,children:(0,K.jsx)(xS,{})})]}),h?(0,K.jsx)(`div`,{className:`code-codex-goal-error`,children:h}):null]})}var CS=`farming.codex.sessionDisplayState.v1`,wS=50,TS=`tmp_uuid`;function ES(){return{promotedKeys:[],pinnedOverrides:{},archivedOverrides:{}}}function DS(){if(typeof window>`u`)return ES();try{let e=JSON.parse(window.localStorage.getItem(`farming.codex.sessionDisplayState.v1`)||`{}`),t=Array.isArray(e.promotedKeys)?e.promotedKeys.filter(e=>typeof e==`string`&&e.length>0):[],n={};e.pinnedOverrides&&typeof e.pinnedOverrides==`object`&&Object.entries(e.pinnedOverrides).forEach(([e,t])=>{typeof t==`boolean`&&(n[e]=t)});let r={};return e.archivedOverrides&&typeof e.archivedOverrides==`object`&&Object.entries(e.archivedOverrides).forEach(([e,t])=>{typeof t==`boolean`&&(r[e]=t)}),{promotedKeys:t,pinnedOverrides:n,archivedOverrides:r}}catch{return ES()}}function OS(e){typeof window>`u`||window.localStorage.setItem(CS,JSON.stringify(e))}function kS(e=[]){let t=[],n=new Set;return e.forEach(e=>{let r=typeof e==`string`?e.trim():``;if(!/^agent-session:[a-z][a-z0-9_-]*:.+$/i.test(r))return;let i=r.replace(/^agent-session:[^:]+:/i,``);i.startsWith(`-`)||i.startsWith(TS)||n.has(r)||(n.add(r),t.push(r))}),t.slice(0,wS)}function AS(e,t,n){return e.map(e=>{let r=Rb(e),i=r in t,a=r in n;if(!i&&!a)return e;let o=a?n[r]:e.archived;return{...e,pinned:o?!1:i?t[r]:e.pinned,archived:o}})}function jS(e,t,n=``){return n&&n!==`default`?`${e}-history:home:${n}:${t}`:`${e}-history:${t}`}function MS(e){let t=/^([a-z]+)-history(?:-fork)?:(?:(?:home:([A-Za-z0-9._-]+):)?(.+))$/.exec(e||``);if(!t)return null;let n=t[1],r=t[2]||`default`,i=t[3];return n&&i?{provider:n,providerHomeId:r,sessionId:i}:null}function NS(e){let t=MS(e);return t?Rb({provider:t.provider,id:t.sessionId,providerHomeId:t.providerHomeId}):``}function PS(e,t,n){return e.map(e=>{if(n||t.has(e.id)||e.agentSessions.length<=5)return{...e,hiddenAgentSessionCount:0,agentSessionsExpanded:t.has(e.id)};let r=e.agentSessions.filter(e=>e.pinned||e.unread),i=new Set(r.map(Rb)),a=e.agentSessions.filter(e=>!i.has(Rb(e))),o=Math.max(0,5-r.length),s=a.slice(0,o),c=a.length-s.length;return{...e,agentSessions:[...r,...s],hiddenAgentSessionCount:c,agentSessionsExpanded:!1}})}var FS=150;function IS(e){let t=String(e||``).trim().toLowerCase();return t===`codex`||t===`claude`||t===`qoder`?t:``}function LS(e){let t=MS(e);if(!t)return null;let n=IS(t.provider),r=String(t.sessionId||``).trim();return n&&r?{...t,provider:n,sessionId:r}:null}function RS(e){return e.title||e.task||e.command||`History agent`}function zS(e){return e.projectWorkspace||e.cwd||``}function BS(...e){return e.map(e=>String(e||``).trim()).filter(Boolean).join(` · `)}function VS(e){return BS(ot(zS(e)))}function HS(e){return BS(e.providerSessionProvider||e.engineName,ot(Ab(e)))}function US(e){return BS(e.providerName||e.provider,e.model,e.effort?Nb(e.effort):``,zb(e))}function WS(e){return Math.max(e.archivedAt||0,e.lastActivity||0,e.startedAt||0)}function GS(e){return Math.max(e.archivedAt||0,e.lastActivity||0,e.startedAt||0)}function KS(e){if(e.kind===`session`){let t=IS(e.session.provider),n=String(e.session.id||``).trim();return t&&n?{provider:t,sessionId:n,providerHomeId:e.session.providerHomeId||`default`}:null}if(e.kind===`agent`){let t=IS(e.agent.providerSessionProvider),n=String(e.agent.providerSessionId||``).trim();return t&&n&&e.agent.providerSessionTemporary!==!0?{provider:t,sessionId:n,providerHomeId:e.agent.providerHomeId||`default`}:LS(e.agent.source)}return LS(e.entry.source)}function qS(e){let t=KS(e);return t?`resume:${t.provider}:${t.providerHomeId||`default`}:${t.sessionId}`:``}function JS(e){return e.kind===`session`?30:e.kind===`agent`?20:10}function YS(e,t){return t.updatedAt===e.updatedAt?JS(t)>JS(e):t.updatedAt>e.updatedAt}function XS(e){if(e.kind!==`session`)return``;let t=String(e.session.title||``).trim().toLocaleLowerCase(),n=String(zb(e.session)||``).trim().toLocaleLowerCase(),r=IS(e.session.provider),i=String(e.session.providerHomeId||`default`).trim().toLocaleLowerCase();return t.length>4&&n?`${r}:${i}:${n}:${t}`:``}function ZS(e){let t=[],n=new Map;e.forEach(e=>{let r=qS(e);if(!r){t.push(e);return}let i=n.get(r);(!i||YS(i,e))&&n.set(r,e)});let r=[...t,...n.values()],i=new Map;return r.filter(e=>{let t=XS(e);if(!t)return!0;let n=i.get(t);return!n||YS(n,e)?(i.set(t,e),!0):!1}).filter(e=>{let t=XS(e);return!t||i.get(t)===e}).sort((e,t)=>t.updatedAt-e.updatedAt)}function QS(e,t,n){return ZS([...e.map(e=>({kind:`run`,historyKey:`run:${e.id}`,updatedAt:WS(e),entry:e})),...t.map(e=>({kind:`agent`,historyKey:`agent:${e.id}`,updatedAt:GS(e),agent:e})),...n.map(e=>({kind:`session`,historyKey:Rb(e),updatedAt:Wb(e),session:e}))])}function $S(e,t){let n=new Map(e.map(e=>[Rb(e),e]));return t.forEach(e=>n.set(Rb(e),e)),Array.from(n.values())}function eC(e){return String(e||``).normalize(`NFKC`).toLocaleLowerCase()}function tC(e,t){let n=eC(t).trim();return n?e.filter(e=>e.kind===`run`?eC([RS(e.entry),VS(e.entry),e.entry.command,e.entry.task].join(`
109
+ `).toLocaleLowerCase().includes(e)&&n.push({turnId:t.id,itemId:r.id});return n}):[]},[A,z]);(0,W.useEffect)(()=>{O&&(C(Tv),window.requestAnimationFrame(()=>te.current?.focus({preventScroll:!0})))},[O]),(0,W.useEffect)(()=>{M(e=>Math.min(e,Math.max(0,B.length-1)))},[B.length]),(0,W.useEffect)(()=>{let e=N.current;if(!e)return;e.querySelectorAll(`.code-codex-transcript-turn.search-match`).forEach(e=>e.classList.remove(`search-match`)),e.querySelectorAll(`.code-codex-transcript-process-item.search-match`).forEach(e=>e.classList.remove(`search-match`));let t=B[j];!O||!t||(y(e=>new Set(e).add(t.turnId)),x(e=>{let n=new Set(e);return n.delete(t.turnId),n}),window.requestAnimationFrame(()=>{let n=e.querySelector(`[data-turn-id="${CSS.escape(t.turnId)}"]`),r=(t.itemId?n?.querySelector(`[data-process-item-id="${CSS.escape(t.itemId)}"]`):null)||n;r?.classList.add(`search-match`),r?.scrollIntoView({block:`center`})}))},[j,B,O]),(0,W.useEffect)(()=>{if(!r||!d?.available||z.length===0)return;let e=P.current,t=e?by(e):ne.current;e&&(re.current||xy(e))||t&&c?.()},[r,c,d?.available,d?.updatedAt,z.length]),(0,W.useLayoutEffect)(()=>{if(m||!d?.available||z.length===0)return;let t=P.current;if(!t||I.current)return;let n=xy(t);if(re.current||n){n&&(ne.current=!1,R.current=!0);return}let i=F.current;if(i){F.current=null,window.requestAnimationFrame(()=>{if(re.current||xy(t))return;let n=t.scrollHeight-i.scrollHeight+i.scrollTop;t.scrollTop=Math.max(0,n),bv.set(e,t.scrollTop)});return}if(ne.current){window.requestAnimationFrame(()=>{re.current||xy(t)||(t.scrollTop=t.scrollHeight,bv.set(e,t.scrollTop),D(!1),r&&c?.())});return}let a=bv.get(e);!a||a<=0||window.requestAnimationFrame(()=>{re.current||xy(t)||(t.scrollTop=Math.min(a,Math.max(0,t.scrollHeight-t.clientHeight)))})},[r,e,m,c,d?.available,d?.updatedAt,z.length]),(0,W.useEffect)(()=>()=>{let t=P.current;t&&bv.set(e,t.scrollTop)},[e]),(0,W.useEffect)(()=>{s?.({loading:m,hasContent:!!(d?.available&&z.length>0),available:!!d?.available})},[m,s,d?.available,z.length]);let V=(0,W.useCallback)((t,n)=>o?.(e,t,{...n,suppressSearchOnMiss:!0}),[e,o]),ae=(0,W.useCallback)(async t=>{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-tool-details/${encodeURIComponent(t)}`)),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||u.codexTranscriptUnavailable);return{detail:String(i.detail||``),terminals:Array.isArray(i.terminals)?i.terminals:void 0,subagentTranscript:i.subagentSession&&typeof i.subagentSession==`object`?sv(i.subagentSession,{maxTurns:12}):void 0}},[e,u.codexTranscriptUnavailable]),oe=(0,W.useCallback)(t=>Me(e,t),[e]),se=(0,W.useCallback)(t=>{let r=new URLSearchParams({agentId:e});return t.forEach(e=>r.append(`acpItem`,e)),n(`/review?${r.toString()}`)},[e]),ce=(0,W.useCallback)(async(t,r,i)=>{let a=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-patches/${encodeURIComponent(t)}/decision`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:r,decision:i})}),o=await a.json().catch(()=>({}));if(!a.ok||!o.action)throw Error(o.error||`Failed to decide file change`);return{action:o.action}},[e]),ue=(0,W.useCallback)(async t=>{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/kill`),{method:`POST`}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||`Failed to stop command`)},[e]),de=(0,W.useCallback)(async(t,r)=>{let i=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/input`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:r})}),a=await i.json().catch(()=>({}));if(!i.ok)throw Error(a.error||`Failed to send terminal input`)},[e]),fe=(0,W.useCallback)(async(t,r,i)=>{let a=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t)}/resize`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cols:r,rows:i})}),o=await a.json().catch(()=>({}));if(!a.ok)throw Error(o.error||`Failed to resize terminal`)},[e]),pe=(0,W.useCallback)(async t=>{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-subagents/${encodeURIComponent(t)}/cancel`),{method:`POST`}),i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error||`Failed to stop subagent`)},[e]),me=(0,W.useCallback)(e=>{!d?.hasMoreBefore||w||S>=Tv||(F.current={scrollTop:e.scrollTop,scrollHeight:e.scrollHeight},T(!0),C(e=>{let t=Math.min(Tv,e+(i===`acp`?wv:Sv));return t===e&&T(!1),t}))},[w,i,d?.hasMoreBefore,S]),H=(0,W.useCallback)(()=>{I.current=!0,L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),he=(0,W.useCallback)(()=>{L.current!==null&&window.clearTimeout(L.current),L.current=window.setTimeout(()=>{I.current=!1,L.current=null},420)},[]),ge=(0,W.useCallback)(()=>{H()},[H]),ve=(0,W.useCallback)(()=>{H()},[H]),ye=(0,W.useCallback)(()=>{he()},[he]),be=(0,W.useCallback)(()=>{let t=P.current;if(!t)return;if(bv.set(e,t.scrollTop),re.current||xy(t)){ne.current=!1,R.current=!0;return}let n=by(t);ne.current=n,D(!n&&t.scrollHeight>t.clientHeight+Ov),r&&n&&c?.(),t.scrollTop<=Dv&&me(t)},[r,e,c,me]),xe=(0,W.useCallback)(e=>{if(H(),he(),e.deltaY>=0)return;let t=P.current;!t||t.scrollTop>Dv||me(t)},[he,H,me]),Se=(0,W.useCallback)(e=>{if(e.button!==0||e.pointerType===`touch`)return;let t=e.target;t instanceof Element&&t.closest(`button, a, input, textarea, select, summary, [role="button"]`)||(re.current=!0)},[]),Ce=(0,W.useCallback)(e=>{let t=z.find(t=>t.id===e);if(i===`acp`&&t?.status===`inProgress`){x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return}y(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[i,z]),we=(0,W.useCallback)(()=>{let t=P.current;t&&(ne.current=!0,R.current=!1,t.scrollTop=t.scrollHeight,bv.set(e,t.scrollHeight),D(!1),c?.())},[e,c]);return(0,K.jsxs)(`div`,{className:`code-codex-transcript`,"data-testid":`code-codex-transcript`,ref:N,children:[i===`acp`&&d?.available?(0,K.jsx)(`div`,{className:`code-codex-transcript-search ${O?`open`:``}`,"data-testid":`code-acp-transcript-search`,children:O?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`input`,{ref:te,type:`search`,value:A,"aria-label":`Search this chat`,placeholder:`Search chat`,onChange:e=>{ee(e.target.value),M(0)},onKeyDown:e=>{e.key===`Escape`&&(k(!1),ee(``)),e.key===`Enter`&&B.length>0&&M(t=>(t+(e.shiftKey?-1:1)+B.length)%B.length)}}),(0,K.jsx)(`span`,{children:B.length>0?`${j+1}/${B.length}`:`0/0`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Previous match`,disabled:B.length===0,onClick:()=>M(e=>(e-1+B.length)%B.length),children:`↑`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Next match`,disabled:B.length===0,onClick:()=>M(e=>(e+1)%B.length),children:`↓`}),(0,K.jsx)(`button`,{type:`button`,"aria-label":`Close chat search`,onClick:()=>{k(!1),ee(``)},children:(0,K.jsx)(le,{})})]}):(0,K.jsx)(`button`,{type:`button`,"aria-label":`Search this chat`,onClick:()=>k(!0),children:(0,K.jsx)(ie,{})})}):null,m?(0,K.jsx)(`div`,{className:`code-codex-transcript-state subtle`,children:u.codexTranscriptSyncing}):g?(0,K.jsx)(`div`,{className:`code-codex-transcript-state`,role:`status`,children:g}):d?.available?z.length===0?(0,K.jsx)(`div`,{className:`code-codex-transcript-blank`}):(0,K.jsx)(`div`,{className:`code-codex-transcript-scroll`,"data-testid":`code-codex-transcript-scroll`,ref:P,onPointerDown:Se,onScroll:be,onWheel:xe,onTouchStart:ge,onTouchMove:ve,onTouchEnd:ye,onTouchCancel:ye,children:z.map(e=>{let n=i===`acp`&&e.status===`inProgress`&&!b.has(e.id);return(0,K.jsx)(Qy,{turn:e,copy:u,onOpenFile:o?V:void 0,workspaceRoot:t,processOpen:v.has(e.id)||n,groupProcessActions:l,source:i,onToggleProcess:Ce,onLoadProcessItemDetail:i===`acp`?ae:void 0,onLoadPatchChanges:i===`acp`?oe:void 0,onCreatePatchReview:i===`acp`?se:void 0,onDecidePatch:i===`acp`?ce:void 0,onStopTerminal:i===`acp`?ue:void 0,onInputTerminal:i===`acp`?de:void 0,onResizeTerminal:i===`acp`?fe:void 0,onStopSubagent:i===`acp`?pe:void 0,searchItemId:O&&B[j]?.turnId===e.id?B[j]?.itemId:void 0},e.id)})}):(0,K.jsx)(`div`,{className:`code-codex-transcript-blank`}),E?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-transcript-jump-bottom`,"data-testid":`code-codex-transcript-jump-bottom`,"aria-label":`Jump to latest chat`,onClick:we,children:(0,K.jsx)(_e,{})}):null]})}function eb(e){return(0,K.jsx)($y,{...e,source:`app-server`})}function tb(e){return(0,K.jsx)($y,{...e,source:`json-cli`})}function nb(e){return(0,K.jsx)($y,{...e,source:`acp`,groupProcessActions:!0})}function rb(e){let t=(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e)),n=t?.split(`/`).pop()||``;return n===`codex`?`codex`:n===`claude`?`claude`:[`bash`,`zsh`,`sh`,`fish`].includes(n)?`shell`:t?`agent`:null}function ib(e){if(!e)return``;let t=typeof e.previewText==`string`?e.previewText:``;return t.trim()?t.toLowerCase():(e.output||``).slice(-1800).toLowerCase()}function ab(e,t){return t.reduce((t,n)=>Math.max(t,e.lastIndexOf(n)),-1)}function ob(e,t){let n=Array.from(e.matchAll(t));return(n.length>0?n[n.length-1]:void 0)?.index??-1}function sb(e){return ob(e,/(?:^|\n)\s*(?:gpt|codex)[^\n]*(?:·|•)\s*(?:~|\/)[^\n]*$/gim)}function cb(e){let t=ab(e,[`pursuing goal`,`esc to interrupt`,`press esc to interrupt`,`reconnecting`,`/stop to close`,`background terminal running`]),n=/\bworking\b/.test(e)?e.lastIndexOf(`working`):-1,r=ob(e,/step\s+\d+\s*\/\s*\d+/g);return Math.max(t,n,r)}function lb(e){let t=ab(e,[`pursuing goal`,`reconnecting`,`/stop to close`,`background terminal running`,`messages to be submitted after next tool call`,`stream disconnected before completion`]),n=/\bworking\b/.test(e)?e.lastIndexOf(`working`):-1,r=ob(e,/step\s+\d+\s*\/\s*\d+/g);return Math.max(t,n,r)}function ub(e){return ab(e,[`goal blocked`,`input exceeds the context window`,`please adjust your input and try again`])}function db(e){return e.trim().replace(/^[\s**✳✱✲✶·•:.\u2800-\u28FF]+/u,``).replace(/\s+/g,` `).toLowerCase()}function fb(e){let t=typeof e?.sessionTitle==`string`?e.sessionTitle.trim():``;if(!/^[\u2800-\u28ff]/u.test(t))return null;let n=e?.terminalStatus?.kind;return n===`codex`?{kind:`codex`,source:`terminal-title`}:n&&n!==`unknown`?null:rb(e?.command)===`codex`?{kind:`codex`,source:`terminal-title`}:null}function pb(e){let t=db(e?.sessionTitle||``);return t?/\bclaude(?:\s+code)?\b/.test(t)?{kind:`claude`,source:`terminal-title`}:/\bcodex\b/.test(t)?{kind:`codex`,source:`terminal-title`}:/^(?:bash|zsh|sh|fish)(?:\s|$)/.test(t)?{kind:`shell`,source:`terminal-title`}:null:null}function mb(e){let t=[],n=Math.max(sb(e),lb(e),ob(e,/(?:^|\n)\s*›\s/g));n>=0&&t.push({kind:`codex`,source:`terminal-output`,index:n});let r=Math.max(ab(e,[`claude code`]),ob(e,/(?:thinking|claude)[\s\S]*(?:esc|escape|ctrl\+c|ctrl-c) to interrupt/g));r>=0&&t.push({kind:`claude`,source:`terminal-output`,index:r});let i=ob(e,/(?:^|\n)\s*(?:[\w./~:@-]+\s*)?[$%#]\s*$/gm);i>=0&&t.push({kind:`shell`,source:`terminal-output`,index:i});let a=t.sort((e,t)=>t.index-e.index)[0];return a?{kind:a.kind,source:a.source}:null}function hb(e){if(!e)return{kind:null,source:`none`};let t=fb(e);if(t)return t;let n=e.terminalStatus?.kind;return n===`codex`||n===`claude`||n===`shell`?{kind:n,source:`terminal-status`}:n===`process`?{kind:`agent`,source:`terminal-status`}:mb(ib(e))||(e.terminalBusy===!0?{kind:`shell`,source:`terminal-busy`}:pb(e)||{kind:rb(e.command),source:e.command?`launch-command`:`none`})}function gb(e){return fb(e)?.kind===`codex`}function _b(e){if(!e)return!1;if(e.status===`pending`)return!0;if(e.status!==`running`)return!1;let t=ib(e);if(!t){let t=typeof e.startedAt==`number`?e.startedAt:0;return t>0&&Date.now()-t<5e3}let n=ub(t),r=t.lastIndexOf(`stream disconnected before completion`);if(n>=0&&n>=r)return!1;if(t.includes(`messages to be submitted after next tool call`)||gb(e)||r>=0)return!0;let i=cb(t);return i<0?!1:sb(t)<=i}function vb(e){if(!e)return!1;if(e.status===`pending`)return!0;if(e.status!==`running`)return!1;let t=ib(e);return t.includes(`esc to interrupt`)||t.includes(`escape to interrupt`)||t.includes(`ctrl+c to interrupt`)||t.includes(`ctrl-c to interrupt`)||t.includes(`press esc to interrupt`)}function yb(e){return!e||e.status!==`running`?!1:e.terminalStatus?.activity===`busy`?!0:e.terminalStatus?.activity===`idle`||e.terminalStatus?.activity===`exited`?!1:e.terminalBusy===!0}function bb(e){let t=hb(e),n=e?.terminalStatus?e.terminalStatus.busy===!0:e?.terminalBusy===!0,r=gb(e),i=!1;e?.terminalStatus?.activity===`busy`&&e.status===`running`?i=!0:e?.terminalStatus?.activity===`idle`||e?.terminalStatus?.activity===`exited`?i=!1:r&&e?.status===`running`?i=!0:t.kind===`codex`?i=_b(e):t.kind===`claude`?i=vb(e):(t.kind===`shell`||t.kind===`agent`)&&(i=yb(e));let a=e?.providerSessionProvider===`codex`&&e.codexRuntimeMode===`app-server`&&[`working`,`waiting-for-input`,`interrupting`].includes(e.codexAppServerState||``),o=e?.agentRuntimeMode===`json`&&e.jsonCliState===`working`,s=e?.agentRuntimeMode===`acp`&&[`working`,`waiting-for-permission`,`waiting-for-input`,`interrupting`].includes(e.acpState||``),c=e?.agentRuntimeMode===`acp`?s:a||o||i;return{kind:(a||o||s)&&e?.providerSessionProvider===`codex`?`codex`:t.kind,kindSource:t.source,turnActive:c,terminalBusy:n}}function xb(e){let t=bb(e);return t.kind===`codex`&&t.turnActive}function Sb(e){return bb(e).turnActive}function Cb(e){return e.providerSessionProvider===`codex`&&e.codexRuntimeMode===`app-server`}function wb({agent:e,active:t,switching:n,switchingKind:r,focusSignal:i,onActivate:a,sendInput:o,resizeAgent:s,onSessionOutput:c,onOpenPath:l,onResolvePath:u,onOpenWorkspaceFilePath:d,onFollowOutputChange:f,onReadLatest:p,onRuntimeModeChange:m,copy:h}){let g=Cb(e),_=e.agentRuntimeMode===`json`,v=e.agentRuntimeMode===`acp`,y=g||_||v,b=e.providerSessionProvider===`codex`&&e.agentRuntimeMode===`terminal`&&e.providerSessionTemporary===!0&&e.terminalInputReceived!==!0,x=[`codex`,`claude`,`opencode`,`qoder`].includes(e.providerSessionProvider||``)&&(e.providerSessionTemporary!==!0||b)&&!!e.providerSessionId,S=n||Sb(e),C=(0,W.useCallback)(n=>{n.button===0&&(t||a(e.id,{focusTerminal:!1}))},[t,e.id,a]);return(0,K.jsxs)(`section`,{className:`code-agent-work-pane ${t?`active`:``} ${x?`runtime-switchable`:``}`,"data-testid":`code-agent-work-pane`,"data-agent-id":e.id,"aria-busy":n,children:[x?(0,K.jsxs)(`div`,{className:`code-terminal-mode-toggle`,"data-testid":`code-terminal-mode-toggle`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{type:`button`,className:y?`active`:``,"aria-pressed":y,"aria-label":h.transcriptView,title:h.transcriptView,disabled:S,onClick:()=>!y&&m?.(e.id,`acp`),children:(0,K.jsx)(oe,{})}),(0,K.jsx)(`button`,{type:`button`,className:y?``:`active`,"aria-pressed":!y,"aria-label":h.terminalView,title:h.terminalView,disabled:S,onClick:()=>y&&m?.(e.id,`terminal`),children:(0,K.jsx)(V,{})})]}):null,y?null:(0,K.jsx)(`div`,{className:`code-agent-work-view terminal active`,"data-testid":`code-agent-terminal-view`,"aria-hidden":!1,children:(0,K.jsx)(e_,{agent:e,active:t,onActivate:a,onOpenPath:l,onResolvePath:u,onFollowOutputChange:f,sendInput:o,resizeAgent:s,onSessionOutput:c,focusSignal:i,copy:h})},`terminal`),y?(0,K.jsx)(`div`,{className:`code-agent-work-view transcript active`,"data-testid":`code-agent-chat-view`,"aria-hidden":!1,onPointerDown:C,children:v?(0,K.jsx)(nb,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,refreshSignal:Number(e.acpSessionRevision)||(e.acpSessionUpdatedAt?Date.parse(e.acpSessionUpdatedAt):0),onOpenWorkspaceFilePath:d,onReadLatest:()=>p?.(e.id),copy:h}):g?(0,K.jsx)(eb,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,onOpenWorkspaceFilePath:d,onReadLatest:()=>p?.(e.id),copy:h}):(0,K.jsx)(tb,{agentId:e.id,workspaceRoot:e.projectWorkspace||e.cwd,active:t,refreshSignal:e.jsonCliTranscriptUpdatedAt?Date.parse(e.jsonCliTranscriptUpdatedAt):0,onOpenWorkspaceFilePath:d,onReadLatest:()=>p?.(e.id),copy:h})},`chat`):null,n?(0,K.jsxs)(`div`,{className:`code-permission-switching`,"data-testid":`code-permission-switching`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`code-permission-switching-spinner`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:r===`runtime`?h.runtimeModeRestarting:h.permissionProfileRestarting})]}):null]})}var Tb=`__farming_main_agent__`,Eb=`__agent_chats__`,Db=[{value:`gpt-5.5`,label:`5.5`,defaultEffort:`xhigh`,reasoningLevels:[{value:`low`,effort:`low`,label:`Low`},{value:`medium`,effort:`medium`,label:`Medium`},{value:`high`,effort:`high`,label:`High`},{value:`xhigh`,effort:`xhigh`,label:`Extra High`}],serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],source:`fallback`}];function Ob(e){return e.kind===`agent-session`?`${e.kind}:${e.provider}:${e.id}`:`${e.kind}:${e.id}`}function kb(e){let t=e.replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`Farming`}function Ab(e){return e.projectWorkspace?e.projectWorkspace:e.cwd||`Farming`}function jb(e){return e?kb(e):`Farming`}function Mb(e){return e||`No workspace`}function Nb(e){return e===`xhigh`?`Extra High`:e?`${e.slice(0,1).toUpperCase()}${e.slice(1)}`:`Config`}function Pb(e){if(!e||e===`config`)return{model:`gpt-5.5`,effort:`xhigh`};let[t=`gpt-5.5`,n=`xhigh`]=e.split(`:`);return{model:t,effort:n}}function Fb(e,t){return/^gpt-/i.test(t)?(e?.displayName||e?.label||t).replace(/^gpt-/i,``).replace(/^GPT-/i,``):e?.displayName?e.displayName:e?.label||t||`Model`}function Ib(e){let t=new Map;return e.forEach(e=>{let n=e.model||e.value.split(`:`)[0];if(!n)return;let r=t.get(n)??{value:n,label:n.replace(/^gpt-/i,``),defaultEffort:e.effort||`medium`,reasoningLevels:[],serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],source:e.source};e.effort&&!r.reasoningLevels?.some(t=>t.value===e.effort)&&(r.reasoningLevels=[...r.reasoningLevels??[],{value:e.effort,effort:e.effort,label:Nb(e.effort),description:e.description}]),t.set(n,r)}),Array.from(t.values())}function Lb(e){let t=Array.isArray(e.catalog)?e.catalog.filter(e=>e&&typeof e.value==`string`&&typeof e.label==`string`):[];if(t.length>0)return t;let n=Ib(Array.isArray(e.models)?e.models.filter(e=>e&&typeof e.value==`string`&&typeof e.label==`string`):[]);return n.length>0?n:Db}function Rb(e){let t=e.providerHomeId&&e.providerHomeId!==`default`?`home:${e.providerHomeId}:${e.id}`:e.id;return Ob({kind:`agent-session`,provider:e.provider,id:t})}function zb(e){let t=e.workspace||e.cwd;return t?ot(t):e.projectless?`Chats`:e.providerName||`Agent`}function Bb(e){return e.projectless?``:e.workspace||e.cwd||``}function Vb(e){return e.cwd||e.workspace||``}function Hb(e){return e.projectless?Eb:Bb(e)||`__agent_sessions__`}function Ub(e){if(e.projectless)return`Chats`;let t=Bb(e);return t?jb(t):`Agent Sessions`}function Wb(e){let t=Date.parse(e.updatedAt||e.createdAt||``);return Number.isFinite(t)?t:0}function Gb(e,t){return Wb(t)-Wb(e)}function Kb(e,t){let n=new Map;return e.forEach(e=>{let t=Ab(e),r=e.isMain?Tb:t,i=n.get(r)??{id:r,name:e.isMain?`Main Agent`:jb(t),workspace:t,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1};i.agents.push(e),i.hasMain||=e.isMain,i.hasProjectAgent||=!e.isMain,i.name=i.hasMain?`Main Agent`:jb(i.workspace),n.set(r,i)}),t.forEach(e=>{let t=Hb(e),r=Bb(e),i=n.get(t)??{id:t,name:Ub(e),workspace:r,agents:[],agentSessions:[],hasMain:!1,hasProjectAgent:!1,hasAgentSession:!1};i.agentSessions.push(e),i.hasAgentSession=!0,n.set(t,i)}),Array.from(n.values()).map(e=>({...e,agents:e.agents.sort((e,t)=>{if(e.isMain!==t.isMain)return e.isMain?-1:1;let n=(t.projectOrder??0)-(e.projectOrder??0);return n===0?(t.startedAt??0)-(e.startedAt??0):n}),agentSessions:e.agentSessions.sort(Gb)})).sort((e,t)=>{let n=e.agents.some(e=>e.isMain);if(n!==t.agents.some(e=>e.isMain))return n?-1:1;let r=e.id===Eb;return r===(t.id===`__agent_chats__`)?e.name.localeCompare(t.name):r?1:-1})}function qb(e,t){return t||e.isComposing===!0||e.nativeEvent?.isComposing===!0||e.nativeEvent?.keyCode===229}function Jb(e,t,n=Date.now()){return e.key===`Enter`&&t>0&&n-t<=120}function Yb(e,t,n,r=Date.now()){return e.key!==`Enter`||e.shiftKey||qb(e,t)||Jb(e,n,r)?!1:e.ctrlKey||e.metaKey||e.altKey?(e.ctrlKey===!0||e.metaKey===!0)&&e.altKey!==!0:!0}function Xb(e,t){return e||t}function Zb(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function Qb(e){return typeof e==`string`?e:``}function $b(e){return(Array.isArray(e.questions)?e.questions:[]).map(e=>{let t=Zb(e);return{id:Qb(t.id),header:Qb(t.header),question:Qb(t.question),isSecret:t.isSecret===!0,options:Array.isArray(t.options)?t.options.map(e=>{let t=Zb(e);return{label:Qb(t.label),description:Qb(t.description)}}).filter(e=>e.label):[]}}).filter(e=>e.id)}function ex(e){return e===`item/commandExecution/requestApproval`||e===`item/fileChange/requestApproval`||e===`item/permissions/requestApproval`}function tx(e,t){return ex(e)?{decision:t}:null}function nx({request:e,onRespond:t,onReject:n,copy:r}){let[i,a]=(0,W.useState)({}),o=(0,W.useMemo)(()=>$b(e?.params||{}),[e]);if((0,W.useEffect)(()=>{a({})},[e?.id]),!e)return null;let s=Zb(e.params),c=Qb(s.command),l=Qb(s.reason),u=ex(e.method),d=e.method===`item/tool/requestUserInput`&&o.length>0,f=d&&o.every(e=>(i[e.id]||``).trim());return(0,K.jsxs)(`section`,{className:`code-app-server-request`,"data-testid":`code-app-server-request`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:u?r.appServerApprovalRejectedTitle:r.appServerRequestTitle}),(0,K.jsx)(`span`,{children:e.method})]}),l&&(0,K.jsx)(`p`,{children:l}),u&&(0,K.jsx)(`p`,{children:r.appServerApprovalRejectedDescription}),c&&(0,K.jsxs)(`div`,{className:`code-app-server-request-command`,children:[(0,K.jsx)(`small`,{children:r.appServerRequestCommand}),(0,K.jsx)(`code`,{children:c})]}),d&&(0,K.jsx)(`div`,{className:`code-app-server-request-questions`,children:o.map(e=>(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:e.header||r.appServerRequestQuestion}),e.question&&(0,K.jsx)(`small`,{children:e.question}),e.options.length>0&&(0,K.jsx)(`div`,{className:`code-app-server-request-options`,children:e.options.map(t=>(0,K.jsxs)(`button`,{type:`button`,className:i[e.id]===t.label?`active`:``,onClick:()=>a(n=>({...n,[e.id]:t.label})),children:[t.label,t.description&&(0,K.jsx)(`small`,{children:t.description})]},t.label))}),(0,K.jsx)(`input`,{type:`text`,className:e.isSecret?`code-app-server-secret-input`:void 0,name:`farming-app-server-answer-${e.id}`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:i[e.id]||``,onChange:t=>a(n=>({...n,[e.id]:t.target.value}))})]},e.id))}),!u&&!d&&(0,K.jsx)(`p`,{children:r.appServerRequestUnsupported}),(0,K.jsxs)(`div`,{className:`code-app-server-request-actions`,children:[u&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.id,tx(e.method,`decline`)),children:r.appServerRequestDecline}),d&&(0,K.jsx)(`button`,{type:`button`,className:`approve`,disabled:!f,onClick:()=>t(e.id,{answers:Object.fromEntries(o.map(e=>[e.id,{answers:[String(i[e.id]??``).trim()]}]))}),children:r.appServerRequestSubmit}),!u&&!d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>n(e.id),children:r.appServerRequestDecline})]})]})}function rx({attachments:e,onRemove:t}){return e.length===0?null:(0,K.jsx)(`div`,{className:`code-composer-attachments`,"data-testid":`code-composer-attachments`,children:e.map(e=>{let n=e.kind===`image`&&!!e.previewUrl;return(0,K.jsxs)(`div`,{className:[`code-composer-attachment`,n?`image`:`chip`,e.status].join(` `),"data-testid":`code-composer-attachment`,children:[n?(0,K.jsx)(`div`,{className:`code-composer-attachment-preview`,"data-testid":`code-composer-attachment-preview`,children:(0,K.jsx)(`img`,{src:e.previewUrl,alt:e.name})}):(0,K.jsx)(`span`,{className:`code-composer-attachment-fallback`,"aria-hidden":`true`,children:(0,K.jsx)(be,{})}),(0,K.jsx)(`span`,{className:`code-composer-attachment-name`,title:e.name,children:e.name}),e.status!==`ready`&&(0,K.jsx)(`span`,{className:`code-composer-attachment-status`,children:e.status===`uploading`?`Uploading`:`Failed`}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-attachment-remove`,"aria-label":`Remove ${e.name}`,onClick:()=>t(e.id),children:(0,K.jsx)(le,{})})]},e.id)})})}function ix(e,t){let n=Math.max(0,Math.min(t,e.length)),r=e.lastIndexOf(`
110
+ `,Math.max(0,n-1))+1,i=e.slice(r,n),a=i.match(/^(\s*)\/([A-Za-z0-9._:-]*)$/);if(a)return{start:r+(a[1]?.length??0),end:n,query:a[2]??``,trigger:`/`};let o=i.match(/(^|\s)\$([A-Za-z0-9._:-]*)$/);return o?{start:r+(o.index??0)+(o[1]?.length??0),end:n,query:o[2]??``,trigger:`$`}:null}function ax(e,t,n){let r=t.trim().toLowerCase();return e.command.startsWith(n)?r?e.command.slice(1).toLowerCase().startsWith(r)||e.label.toLowerCase().includes(r):!0:!1}function ox(e,t){let n=t.trim().toLowerCase();return n?+!e.command.slice(1).toLowerCase().startsWith(n):0}function sx(e){return`code-slash-command-${e.replace(/^[/$]/,``).replace(/[^A-Za-z0-9_-]+/g,`-`)||`root`}`}function cx(e){if(!e||typeof window>`u`)return 0;let t=window.getSelection();if(!t||t.rangeCount<=0)return(e.textContent||``).length;let n=t.getRangeAt(0);if(!e.contains(n.startContainer))return(e.textContent||``).length;let r=n.cloneRange();return r.selectNodeContents(e),r.setEnd(n.startContainer,n.startOffset),r.toString().length}function lx(e,t){if(!e||typeof window>`u`)return;e.normalize();let n=Math.max(0,Math.min(t,(e.textContent||``).length)),r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=n,a=r.nextNode();for(;a;){let e=a.textContent||``;if(i<=e.length){let e=document.createRange();e.setStart(a,i),e.collapse(!0);let t=window.getSelection();t?.removeAllRanges(),t?.addRange(e);return}i-=e.length,a=r.nextNode()}let o=document.createRange();o.selectNodeContents(e),o.collapse(!1);let s=window.getSelection();s?.removeAllRanges(),s?.addRange(o)}function ux(e){return e?(e.innerText||e.textContent||``).replace(/\u00a0/g,` `).replace(/\n$/,``):``}function dx({active:e,draft:t,placeholder:n,minHeight:r,maxHeight:i,editorRef:a,composerRef:o,onFocus:s,onBlur:c,onInput:l,onPaste:u,onCompositionStart:d,onCompositionEnd:f,onKeyDown:p,onSelectionIntent:m}){let h=(0,W.useRef)(null);return(0,W.useLayoutEffect)(()=>{let e=a.current,n=h.current,s=o.current;if(!e||!n||!s)return;(e.textContent||``)!==t&&(e.textContent=t),n.innerText=t||`M`,e.style.height=`auto`;let c=Math.max(n.scrollHeight,e.scrollHeight),l=Math.min(i,Math.max(r,c));e.style.height=`${l}px`;let u=s.closest(`.code-main`),d=s.getBoundingClientRect().height;if(d>0){let e=`${Math.ceil(d)}px`;s.style.setProperty(`--mobile-composer-current-height`,e),u?.style.setProperty(`--mobile-composer-current-height`,e)}},[o,t,a,i,r]),(0,W.useLayoutEffect)(()=>{let e=a.current;e&&(e.removeAttribute(`autocomplete`),e.removeAttribute(`aria-autocomplete`),e.removeAttribute(`inputmode`),e.setAttribute(`autocorrect`,`off`),e.setAttribute(`autocapitalize`,`none`),e.setAttribute(`spellcheck`,`false`))},[a]),(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{"data-testid":`code-composer-input`,ref:a,className:`code-composer-mobile-input`,"aria-disabled":!e,contentEditable:e?`true`:`false`,suppressContentEditableWarning:!0,enterKeyHint:`send`,tabIndex:e?0:-1,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,"data-placeholder":n,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,"data-gramm":`false`,"data-ms-editor":`false`,onFocus:s,onBlur:c,onInput:l,onPaste:u,onCompositionStart:d,onCompositionEnd:f,onKeyDown:p,onKeyUp:m,onMouseUp:m}),(0,K.jsx)(`div`,{ref:h,className:`code-composer-mobile-input-mirror`,"aria-hidden":`true`})]})}var fx=[`sol`,`terra`,`luna`],px=4,mx=240;function hx(e,t){let n=t.match(/^(.*?)[-\s](sol|terra|luna)$/i)?.[1]?.toLowerCase();if(!n)return null;let r=e.flatMap(e=>{let t=e.value.match(/^(.*?)[-\s](sol|terra|luna)$/i),r=t?.[1]?.toLowerCase(),i=t?.[2]?.toLowerCase();return!r||r!==n||!i?[]:[{...e,variant:i}]}).sort((e,t)=>fx.indexOf(e.variant)-fx.indexOf(t.variant));return r.length>=2?r:null}function gx(){return(0,K.jsx)(`svg`,{viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21Z`})})}function _x({label:e,active:t,disabled:n,unavailable:r,onChange:i}){let[a,o]=(0,W.useState)(!1),s=(0,W.useRef)(null);(0,W.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]);function c(){s.current!==null&&window.clearTimeout(s.current),o(!0),s.current=window.setTimeout(()=>{s.current=null,o(!1)},650)}function l(){s.current!==null&&window.clearTimeout(s.current),s.current=null,o(!1)}return(0,K.jsxs)(`div`,{className:`code-model-matrix-rocker is-ultra ${t?`is-active`:``} ${r?`is-disabled`:``}`,children:[(0,K.jsx)(`span`,{children:e}),(0,K.jsx)(`button`,{type:`button`,className:`code-model-matrix-rocker-button`,disabled:n||r,"aria-label":`Ultra reasoning`,"aria-pressed":t,onClick:()=>{t||c(),i(!t)},children:(0,K.jsxs)(`span`,{className:`code-model-matrix-rocker-control ${a?`is-kicked`:``}`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-slot`,children:(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-energy`})}),(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-knob-position`,children:(0,K.jsx)(`span`,{className:`code-model-matrix-rocker-knob ${a?`is-kicked`:``}`,onAnimationEnd:l})})]})})]})}function vx({active:e,available:t,disabled:n,onChange:r}){let[i,a]=(0,W.useState)(!1),o=!t,s=n||o;return(0,K.jsxs)(`button`,{type:`button`,className:`code-model-matrix-fast ${e?`is-active`:``} ${o?`is-disabled`:``}`,"aria-label":`Fast mode`,"aria-pressed":e,"aria-disabled":s,disabled:s,onClick:()=>{a(!0),r(!e)},children:[(0,K.jsx)(`span`,{className:`code-model-matrix-fast-bolt ${i?`is-kicked`:``}`,"aria-hidden":`true`,onAnimationEnd:()=>a(!1),children:(0,K.jsx)(gx,{})}),(0,K.jsx)(`span`,{children:`Fast`}),(0,K.jsx)(`small`,{children:t?e?`ON`:`OFF`:`—`})]})}function yx({models:e,currentModel:t,currentReasoning:n,fastAvailable:r,fast:i,disabled:a,onSelect:o,onFastChange:s,advanced:c}){let l=hx(e,t),u=!!l?.find(e=>e.value===t)?.reasoning.some(e=>e.value===n),[d,f]=(0,W.useState)(!u),[p,m]=(0,W.useState)(null),[h,g]=(0,W.useState)(null),[_,v]=(0,W.useState)(null),y=(0,W.useRef)(!!l),b=(0,W.useRef)(new Map),x=(0,W.useRef)(null),S=(0,W.useRef)(null),C=(0,W.useRef)(null),w=(0,W.useRef)(null),T=(0,W.useRef)(null),E=(0,W.useRef)(null),D=(0,W.useRef)(null),O=(0,W.useRef)(null),k=(0,W.useRef)(null);if((0,W.useEffect)(()=>{let e=!y.current&&!!l;y.current=!!l,e&&u&&(D.current=w.current?.getBoundingClientRect().height??null,f(!1))},[l,u]),(0,W.useEffect)(()=>{if(!h)return;if(t===h.model&&n===h.reasoning){g(null);return}let e=window.setTimeout(()=>g(null),5e3);return()=>window.clearTimeout(e)},[t,n,h]),(0,W.useEffect)(()=>{if(_===null)return;if(!r||i===_){v(null);return}let e=window.setTimeout(()=>v(null),5e3);return()=>window.clearTimeout(e)},[i,r,_]),(0,W.useEffect)(()=>()=>{C.current!==null&&window.cancelAnimationFrame(C.current),O.current!==null&&window.cancelAnimationFrame(O.current),k.current!==null&&window.clearTimeout(k.current)},[]),(0,W.useLayoutEffect)(()=>{let e=w.current,t=d?E.current:T.current,n=D.current;if(D.current=null,!e||!t)return;O.current!==null&&window.cancelAnimationFrame(O.current),k.current!==null&&window.clearTimeout(k.current),O.current=null,k.current=null;let r=t.getBoundingClientRect().height,i=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;if(n===null||i||Math.abs(n-r)<1){e.style.height=`${r}px`,e.style.overflow=d?`visible`:`hidden`;return}e.style.height=`${n}px`,e.style.overflow=`hidden`,e.offsetHeight,O.current=window.requestAnimationFrame(()=>{e.style.height=`${r}px`,O.current=null}),k.current=window.setTimeout(()=>{e.style.height=`${r}px`,e.style.overflow=d?`visible`:`hidden`,k.current=null},mx+40)},[d]),!l)return c;let A=l.find(e=>e.value===t)??l[0],ee=A.reasoning.filter(e=>e.value!==`ultra`);n!==`ultra`&&ee.some(e=>e.value===n)&&b.current.set(A.value,n);let j=b.current.get(A.value)||ee[ee.length-1]?.value||n,M=n===`ultra`?j:n,N=Math.max(0,ee.findIndex(e=>e.value===M)),te=A.reasoning.find(e=>e.value===n)?.label||n;function P(e,t){a||(g({model:e.value,reasoning:t}),b.current.set(e.value,t),o(e.value,t))}let F=l.map(e=>({model:e,reasoning:e.reasoning.filter(e=>e.value!==`ultra`)})),ne=Math.max(0,F.findIndex(e=>e.model.value===t)),I=Math.max(0,F[ne]?.reasoning.findIndex(e=>e.value===M)??0),L=h?F.findIndex(e=>e.model.value===h.model):-1,re=L>=0?F[L]?.reasoning.findIndex(e=>e.value===h?.reasoning)??-1:-1,R=p??(L>=0&&re>=0?{row:L,column:re}:null)??{row:ne,column:I},z=F[R.row]??F[0],B=Math.min(R.column,Math.max(0,z.reasoning.length-1)),ie=z.reasoning[B],V=h?l.find(e=>e.value===h.model)??A:A,ae=h?.reasoning??n,oe=V.reasoning.filter(e=>e.value!==`ultra`),se=V.reasoning.find(e=>e.value===`ultra`),ce=b.current.get(V.value)||oe[oe.length-1]?.value||ae,le=V.reasoning.find(e=>e.value===ae)?.label||ae,ue=!!se&&ae===`ultra`,de=_??i,fe=`${(typeof R.x==`number`?R.x:(B+.5)/Math.max(1,z.reasoning.length))*100}%`,pe=typeof R.y==`number`?R.y:(R.row+.5)/Math.max(1,F.length),me=`${pe*100}%`,H=`${Math.max(0,Math.min(1-1/Math.max(1,F.length),pe-.5/Math.max(1,F.length)))*100}%`,he=`${100/Math.max(1,F.length)}%`;function _e(e){let t=e.currentTarget.getBoundingClientRect(),n=Math.max(0,Math.min(1,(e.clientX-t.left)/Math.max(1,t.width))),r=Math.max(0,Math.min(1,(e.clientY-t.top)/Math.max(1,t.height))),i=Math.max(0,Math.min(F.length-1,Math.floor(r*F.length))),a=F[i]?.reasoning.length||1;return{row:i,column:Math.max(0,Math.min(a-1,Math.floor(n*a))),x:Math.max(.5/a,Math.min(1-.5/a,n)),y:Math.max(.5/F.length,Math.min(1-.5/F.length,r))}}function ve(e){let t=F[e.row],n=t?.reasoning[e.column];t&&n&&P(t.model,n.value)}function ye(e){a||!r||de===e||(v(e),s(e))}function be(e){if(a||!se||ue===e)return;let t=e?se.value:ce;g({model:V.value,reasoning:t}),e||b.current.set(V.value,t),o(V.value,t)}function xe(e){S.current=e,C.current===null&&(C.current=window.requestAnimationFrame(()=>{C.current=null;let e=S.current;S.current=null,e&&m(e)}))}function Se(){S.current=null,C.current!==null&&(window.cancelAnimationFrame(C.current),C.current=null)}function Ce(e,t=!0){let n=x.current;if(!n||n.pointerId!==e.pointerId)return;let r=_e(e);x.current=null,Se(),t&&ve(r),m(null),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)}function we(){D.current=w.current?.getBoundingClientRect().height??null,f(e=>!e)}return(0,K.jsxs)(`div`,{className:`code-model-matrix-shell is-${z.model.variant}`,"data-testid":`code-model-matrix-picker`,"data-advanced":d?`open`:`closed`,"data-fast":de?`on`:`off`,"data-ultra":ue?`on`:`off`,children:[(0,K.jsxs)(`div`,{className:`code-model-matrix-stage`,ref:w,children:[(0,K.jsxs)(`div`,{ref:T,className:`code-model-matrix`,"aria-hidden":d,inert:d?!0:void 0,children:[(0,K.jsx)(`div`,{className:`code-model-matrix-head`,style:{"--matrix-columns":z.reasoning.length},"aria-hidden":`true`,children:z.reasoning.map(e=>(0,K.jsx)(`span`,{children:e.label},e.value))}),(0,K.jsx)(`div`,{className:`code-model-matrix-labels`,"aria-hidden":`true`,children:F.map(({model:e})=>(0,K.jsx)(`span`,{className:e.value===z.model.value?`selected`:``,"data-variant":e.variant,children:e.variant.charAt(0).toUpperCase()+e.variant.slice(1)},e.value))}),(0,K.jsxs)(`div`,{className:`code-model-matrix-surface ${p?`is-dragging`:``}`,role:`radiogroup`,"aria-label":`Model and reasoning`,style:{"--matrix-columns":ee.length,"--matrix-rows":F.length,"--matrix-selection-x":fe,"--matrix-selection-y":me,"--matrix-selection-row-top":H,"--matrix-selection-row-height":he},onPointerDown:e=>{a||(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),x.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragged:!1})},onPointerMove:e=>{let t=x.current;if(!t||t.pointerId!==e.pointerId)return;if(e.pointerType===`mouse`&&e.buttons===0){Ce(e);return}let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);!t.dragged&&n>=px&&(t.dragged=!0),t.dragged&&xe(_e(e))},onPointerUp:e=>Ce(e),onPointerCancel:e=>Ce(e,!1),onLostPointerCapture:e=>{x.current?.pointerId===e.pointerId&&(x.current=null,Se(),m(null))},children:[(0,K.jsx)(`span`,{className:`code-model-matrix-fill`,"data-variant":z.model.variant,"aria-hidden":`true`}),(0,K.jsx)(`div`,{className:`code-model-matrix-cells`,children:F.flatMap(({model:e,reasoning:t},n)=>t.map((r,i)=>{let o=n===R.row&&i===B;return(0,K.jsx)(`button`,{type:`button`,className:o?`selected`:``,role:`radio`,"data-matrix-cell":!0,"data-testid":`code-model-matrix-cell-${e.variant}-${r.value}`,"aria-label":`${e.label}, ${r.label}`,"aria-checked":o,disabled:a,style:{"--matrix-cell-left":`${i/Math.max(1,t.length)*100}%`,"--matrix-cell-top":`${n/Math.max(1,F.length)*100}%`,"--matrix-cell-width":`${100/Math.max(1,t.length)}%`,"--matrix-cell-height":`${100/Math.max(1,F.length)}%`},onClick:t=>{t.detail===0&&P(e,r.value)}},`${e.value}:${r.value}`)}))}),(0,K.jsx)(`span`,{className:`code-model-matrix-thumb`,"data-variant":z.model.variant,"aria-hidden":`true`})]}),(0,K.jsx)(`div`,{className:`code-model-matrix-rockers`,children:(0,K.jsx)(_x,{label:se?.label||`Ultra`,active:ue,disabled:a,unavailable:!se,onChange:be})}),(0,K.jsx)(vx,{active:r&&de,available:r,disabled:a,onChange:ye}),(0,K.jsx)(`span`,{className:`code-model-matrix-current`,"aria-live":`polite`,children:p?`${z.model.label} · ${ie?.label||``}`:h?`${V.label} · ${le}`:`${A.label} · ${te||ee[N]?.label}`})]}),(0,K.jsx)(`div`,{ref:E,className:`code-model-matrix-advanced`,"data-testid":`code-model-matrix-advanced`,"aria-hidden":!d,inert:d?void 0:!0,children:c})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-model-matrix-advanced-toggle`,"data-testid":`code-model-matrix-advanced-toggle`,"aria-expanded":d,onClick:we,children:[(0,K.jsx)(`span`,{children:`Advanced`}),(0,K.jsx)(ge,{className:d?`expanded`:``})]})]})}function bx(e,t){return t===`goal`?e.goalMode:t===`plan`?e.planMode:e.messageMode}function xx(e,t,n){return t===`goal`?e.describeAgentGoal:t===`plan`?e.describePlanFirst:n===`shell`?e.shellCommandPlaceholder:e.askFollowUpChanges}function Sx(){return typeof window<`u`&&L()}function Cx(e){return e.trim().replace(/^gpt[-\s]*/i,``)||e}function wx(e,t){return e===`xhigh`&&t.trim().toLowerCase()===`extra high`?`XHigh`:t}function Tx(e){return!Number.isFinite(e)||e<0?`0`:e>=1e6?`${Math.round(e/1e5)/10}m`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function Ex(e){let t=Math.max(0,Math.floor(e)),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}var Dx=[.28,.5,.72,.46,.9,.36,.62,.82,.42,.68,.95,.52,.33,.75,.57,.88,.4,.64,.93,.48,.7,.31,.58,.83],Ox=22,kx=22,Ax=66,jx=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM6 3.99951C6 2.89651 6.897 1.99951 8 1.99951C9.103 1.99951 10 2.89651 10 3.99951V7.99951C10 9.10251 9.103 9.99951 8 9.99951C6.897 9.99951 6 9.10251 6 7.99951V3.99951ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`,Mx=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`;function Nx({listening:e}){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:e?Mx:jx})})}function Px(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21ZM4.8 7.9h2.34a.55.55 0 0 1 .53.69l-.63 2.38L10.17 7.1H7.56a.55.55 0 0 1-.53-.7l.62-2.26L4.8 7.9Z`})})}function Fx({active:e,agentKind:t,capabilities:n,slashCommands:r,draft:i,attachments:a,composerMode:o,plusMenuOpen:s,approvalMenuOpen:c,modelMenuOpen:l,modelPickerPane:u,agentModelPreset:d,agentModel:f,agentReasoningEffort:p,agentServiceTier:m,agentModelOptions:h,currentPermissionMode:g,permissionModeDisabled:_,currentPermissionLabel:v,currentPermissionColor:y,permissionModeHint:b,currentModelLabel:x,currentReasoningLabel:S,currentSpeedLabel:C,currentReasoningOptions:w,currentServiceTierOptions:T,permissionModeOptions:E,contextWindow:D,pendingFollowUp:O,appServerRequest:k,appServerNotice:A,submitAction:ee,speechSupported:j,speechListening:M,textareaRef:N,attachmentInputRef:te,plusMenuRef:P,approvalMenuRef:F,modelMenuRef:ne,onDraftChange:I,onNavigateHistory:re,onRemoveAttachment:R,onSubmit:z,onInterrupt:B,onSteerPendingFollowUp:ie,onDiscardPendingFollowUp:V,onRespondToAppServerRequest:ae,onRejectAppServerRequest:oe,onPasteAttachment:se,onAttachmentFiles:ce,onChooseAttachmentFile:ue,onActivateComposerMode:de,onClearComposerMode:pe,onTogglePlusMenu:H,onToggleApprovalMenu:ge,onToggleModelMenu:_e,onCloseMenus:ve,onSetModelPickerPane:ye,onComposerMenuKeyDown:be,onComposerMenuBlur:Ce,onUpdatePermissionMode:we,onUpdateModel:Te,onUpdateReasoningEffort:Ee,onUpdateServiceTier:De,onUpdateModelProfile:Oe,onUpdateServiceTierInline:ke,onToggleSpeechInput:Ae,copy:U}){let je=e&&n.plusMenu,Me=e&&n.permissionMode,Ne=e&&n.modelPicker,Pe=n.serviceTier&&T.length>0,G=h.map(e=>({value:e.value,label:Fb(e,e.value),reasoning:(e.reasoningLevels||[]).map(e=>({value:e.value,label:U.reasoningOptionLabel(e.value,e.label)}))})),Fe=t===`codex`&&!!hx(G,f),[Ie,Le]=(0,W.useState)(Sx),[Re,ze]=(0,W.useState)(0),[Be,Ve]=(0,W.useState)(!1),[He,Ue]=(0,W.useState)(i.length),[We,Ge]=(0,W.useState)(!1),[Ke,qe]=(0,W.useState)(null),[Je,Ye]=(0,W.useState)(0),Xe=e&&n.speechInput&&(!Ie||j),Ze=(0,W.useRef)(new Map),Qe=(0,W.useRef)(null),$e=(0,W.useRef)(null),et=(0,W.useRef)(!1),tt=(0,W.useRef)(0),nt=(0,W.useRef)(i),rt=(0,W.useRef)(!1),it=s||c||l,at=(0,W.useMemo)(()=>ix(i,He),[i,He]),ot=at?`${at.trigger}:${at.start}:${at.end}:${at.query}`:``,st=(0,W.useMemo)(()=>at?r.filter(e=>ax(e,at.query,at.trigger)).sort((e,t)=>ox(e,at.query)-ox(t,at.query)):[],[r,at]),ct=e&&Be&&!it&&!!at&&ot!==Ke&&st.length>0,lt=it||ct,ut=st[Je]??st[0]??null,dt=U.permissionModeLabel(g,v),ft=U.reasoningOptionLabel(p,S),pt=U.serviceTierLabel(m,C),mt=Cx(x),ht=wx(p,ft),gt=D?`Context window: ${D.percentUsed}% used (${D.percentLeft}% left), ${Tx(D.usedTokens)} / ${Tx(D.limitTokens)} tokens used`:``,_t=!e||ee===`disabled`,vt=e&&ee===`interrupt`,yt=at?.trigger===`$`?`Skills`:`Commands`,bt=Ie&&M&&Xe,xt=j||Ie,St=()=>{(Ie||L())&&Ge(!0),Ae()},Ct=()=>{if(rt.current){rt.current=!1;return}St()},wt=e=>{e.pointerType!==`mouse`&&(e.preventDefault(),rt.current=!0,St())};function Tt(t){if(!Ie||!e||t instanceof Element&&t.closest(`.code-composer-menu, button, input, select, [role="menuitem"]`))return;let n=$e.current;if(n){n.focus({preventScroll:!0}),Ue(cx(n)||(n.textContent||``).length);return}let r=N.current;!r||r.disabled||(r.focus({preventScroll:!0}),kt(r))}let Et=e=>{Tt(e.target)},Dt=e=>{Tt(e.target)},Ot=e=>{Tt(e.target)};(0,W.useEffect)(()=>{Ye(0)},[at?.query,st.length]),(0,W.useEffect)(()=>{nt.current=i},[i]),(0,W.useEffect)(()=>()=>{let e=Qe.current;e?.style.removeProperty(`--mobile-composer-current-height`),(e?.closest(`.code-main`))?.style.removeProperty(`--mobile-composer-current-height`)},[]),(0,W.useEffect)(()=>{at||qe(null)},[at]),(0,W.useEffect)(()=>{e||(Ve(!1),qe(null))},[e]),(0,W.useEffect)(()=>{if(typeof window>`u`)return;let e=window.matchMedia(`(max-width: 980px)`),t=()=>Le(Sx());return t(),window.addEventListener(`resize`,t),e.addEventListener(`change`,t),()=>{window.removeEventListener(`resize`,t),e.removeEventListener(`change`,t)}},[]),(0,W.useEffect)(()=>{if(Ie)return;let e=Qe.current,t=e?.closest(`.code-main`);e?.style.removeProperty(`--mobile-composer-current-height`),t?.style.removeProperty(`--mobile-composer-current-height`)},[Ie]),(0,W.useEffect)(()=>{if(M||!We)return;let e=window.setTimeout(()=>Ge(!1),3600);return()=>window.clearTimeout(e)},[We,M]),(0,W.useEffect)(()=>{M&&Ge(!1)},[M]),(0,W.useEffect)(()=>{if(!M){ze(0);return}let e=Date.now();ze(0);let t=window.setInterval(()=>{ze(Math.floor((Date.now()-e)/1e3))},250);return()=>window.clearInterval(t)},[M]),(0,W.useEffect)(()=>{!ct||!ut||Ze.current.get(ut.command)?.scrollIntoView({block:`nearest`})},[ct,ut]);function kt(e=N.current){e&&Ue(e.selectionStart??i.length)}function At(){Ue(cx($e.current))}function q(e){if(!at)return;let t=`${e.command} `,n=`${i.slice(0,at.start)}${t}${i.slice(at.end)}`,r=at.start+t.length;I(n),Ue(r),qe(null),window.requestAnimationFrame(()=>{if(Ie){let e=$e.current;if(!e)return;e.focus({preventScroll:!0}),lx(e,r),Ue(r);return}let e=N.current;e&&(e.focus({preventScroll:!0}),e.setSelectionRange(r,r),kt(e))})}let jt=e&&!!(k||A);return(0,K.jsxs)(`footer`,{ref:Qe,className:[`code-composer`,lt?`menu-open`:``,bt?`recording`:``,a.length>0?`has-attachments`:``,O&&e?`has-pending-followup`:``,jt?`has-app-server-request`:``].filter(Boolean).join(` `),"data-testid":`code-composer`,onPointerDownCapture:Et,onTouchStartCapture:Dt,onMouseDownCapture:Ot,onClickCapture:Ot,children:[O&&e&&(0,K.jsx)(`div`,{className:`code-pending-followup`,"data-testid":`code-pending-followup`,children:O.messages.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row`,"data-testid":`code-pending-followup-row`,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"aria-hidden":`true`,children:(0,K.jsx)(xe,{})}),(0,K.jsx)(`p`,{children:e.text}),(0,K.jsxs)(`div`,{className:`code-pending-followup-actions`,children:[(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-pending-followup-steer`,onClick:()=>ie(e.id),children:[(0,K.jsx)(xe,{}),(0,K.jsx)(`span`,{children:U.steerQueuedMessage})]}),(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-pending-followup-discard`,"aria-label":U.discardQueuedMessage,onClick:()=>V(e.id),children:(0,K.jsx)(le,{})})]})]},e.id))}),e&&k&&(0,K.jsx)(nx,{request:k,onRespond:ae,onReject:oe,copy:U}),e&&A&&A.kind===`approval-rejected`&&(0,K.jsxs)(`section`,{className:`code-app-server-request code-app-server-notice`,"data-testid":`code-app-server-notice`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:U.appServerApprovalRejectedTitle}),A.method?(0,K.jsx)(`span`,{children:A.method}):null]}),(0,K.jsx)(`p`,{children:U.appServerApprovalRejectedDescription})]}),ct&&(0,K.jsxs)(`div`,{className:`code-slash-menu code-composer-menu`,"data-testid":`code-slash-menu`,role:`listbox`,"aria-label":yt,children:[(0,K.jsx)(`div`,{className:`code-slash-menu-header`,children:yt}),st.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`code-slash-command ${t===Je?`active`:``}`,"data-testid":sx(e.command),role:`option`,"aria-selected":t===Je,ref:t=>{t?Ze.current.set(e.command,t):Ze.current.delete(e.command)},onMouseMove:()=>Ye(t),onMouseDown:e=>e.preventDefault(),onClick:()=>q(e),children:[(0,K.jsx)(`span`,{className:`code-slash-command-icon`,"aria-hidden":`true`,children:at?.trigger??`/`}),(0,K.jsxs)(`span`,{className:`code-slash-command-copy`,children:[(0,K.jsxs)(`span`,{className:`code-slash-command-title`,children:[(0,K.jsx)(`code`,{children:e.command}),(0,K.jsx)(`strong`,{children:e.label})]}),(0,K.jsx)(`small`,{children:e.description})]}),e.scope&&(0,K.jsx)(`span`,{className:`code-slash-command-source`,children:e.scope})]},e.command))]}),Ie?(0,K.jsx)(dx,{active:e,draft:i,placeholder:e?xx(U,o,t):U.openAgentTerminalFirst,minHeight:Be||lt||a.length>0||O&&e?kx:Ox,maxHeight:Ax,editorRef:$e,composerRef:Qe,onFocus:()=>{ve(),Ve(!0),Ue(cx($e.current))},onBlur:()=>Ve(!1),onInput:e=>{let t=ux(e.currentTarget);nt.current=t,I(t),qe(null),Ue(cx(e.currentTarget))},onPaste:se,onCompositionStart:()=>{et.current=!0},onCompositionEnd:e=>{et.current=!1,tt.current=Date.now();let t=ux(e.currentTarget);nt.current=t,I(t),Ue(cx(e.currentTarget))},onKeyDown:e=>{let t=et.current;if(!qb(e,t)){if(Jb(e,tt.current)){e.preventDefault(),e.stopPropagation();return}if(ct&&(e.key===`Enter`||e.key===`Tab`)&&ut){e.preventDefault(),e.stopPropagation(),q(ut);return}e.key!==`Enter`||e.shiftKey||(e.preventDefault(),e.stopPropagation(),z(Xb(ux(e.currentTarget),nt.current)))}},onSelectionIntent:At}):(0,K.jsx)(`textarea`,{"data-testid":`code-composer-input`,ref:N,enterKeyHint:`send`,name:`farming-chat-message`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:i,onFocus:e=>{ve(),Ve(!0),kt(e.currentTarget)},onBlur:()=>Ve(!1),onClick:e=>kt(e.currentTarget),onKeyUp:e=>kt(e.currentTarget),onSelect:e=>kt(e.currentTarget),onCompositionStart:()=>{et.current=!0},onCompositionEnd:e=>{et.current=!1,tt.current=Date.now(),nt.current=e.currentTarget.value,kt(e.currentTarget)},onChange:e=>{nt.current=e.target.value,I(e.target.value),qe(null),kt(e.currentTarget)},onPaste:se,onKeyDown:e=>{let t=et.current;if(!qb(e,t)){if(Jb(e,tt.current)){e.preventDefault(),e.stopPropagation();return}if(ct){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let t=e.key===`ArrowDown`?1:-1;Ye(e=>(e+t+st.length)%st.length);return}if(e.key===`Home`){e.preventDefault(),e.stopPropagation(),Ye(0);return}if(e.key===`End`){e.preventDefault(),e.stopPropagation(),Ye(st.length-1);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),qe(ot);return}if((e.key===`Enter`||e.key===`Tab`)&&ut){e.preventDefault(),e.stopPropagation(),q(ut);return}}if(e.key===`ArrowUp`||e.key===`ArrowDown`){let t=e.key===`ArrowUp`?`previous`:`next`,n=re(t,{direction:t,value:e.currentTarget.value,selectionStart:e.currentTarget.selectionStart,selectionEnd:e.currentTarget.selectionEnd});if(n!==null){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=N.current;if(!e)return;let t=n.length;e.setSelectionRange(t,t),kt(e)});return}}Yb(e,t,tt.current)&&(e.preventDefault(),e.stopPropagation(),z(Xb(e.currentTarget.value,nt.current)))}},placeholder:e?xx(U,o,t):U.openAgentTerminalFirst,disabled:!e}),We&&!M&&(0,K.jsx)(`div`,{className:`code-composer-dictation-hint`,"data-testid":`code-composer-dictation-hint`,children:U.mobileDictationHint}),(0,K.jsx)(rx,{attachments:a,onRemove:R}),(0,K.jsx)(`input`,{ref:te,className:`code-composer-file-input`,"data-testid":`code-composer-file-input`,type:`file`,multiple:!0,onChange:ce}),(0,K.jsx)(`div`,{className:`code-composer-toolbar ${bt?`recording`:``}`,"data-testid":`code-composer-toolbar`,children:bt?(0,K.jsxs)(`div`,{className:`code-composer-recording-bar`,"data-testid":`code-composer-recording`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-recording-stop`,"data-testid":`code-composer-recording-stop`,"aria-label":U.stopDictation,onPointerDown:wt,onClick:Ct,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsx)(`div`,{className:`code-composer-recording-wave`,"aria-hidden":`true`,children:Dx.map((e,t)=>(0,K.jsx)(`span`,{style:{"--voice-bar-scale":e,"--voice-bar-delay":`${t*38}ms`}},t))}),(0,K.jsx)(`span`,{className:`code-composer-recording-time`,children:Ex(Re)}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${vt?`interrupt`:``}`,"data-testid":`code-composer-send`,"data-action":ee,"aria-label":vt?U.interruptAgent:U.sendMessage,onClick:vt?B:()=>z(nt.current),disabled:_t,children:vt?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(he,{})})]}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`code-composer-left-tools`,"data-testid":`code-composer-left-tools`,children:[je&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-add`,"data-testid":`code-composer-add`,"aria-label":U.addContext,"aria-haspopup":`menu`,"aria-expanded":s,disabled:!e,onClick:H,children:(0,K.jsx)(Se,{})}),s&&(0,K.jsxs)(`div`,{className:`code-plus-menu code-composer-menu`,role:`menu`,"data-testid":`code-composer-plus-menu`,ref:P,onKeyDown:be,onBlur:Ce,onMouseDown:e=>e.preventDefault(),children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-attach-file`,onClick:ue,children:[(0,K.jsx)(`span`,{children:U.attachFile}),(0,K.jsx)(`small`,{children:U.fileContext})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-goal-mode`,onClick:()=>de(`goal`),children:[(0,K.jsx)(`span`,{children:U.goalMode}),(0,K.jsx)(`small`,{children:U.setObjective})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-composer-plan-mode`,onClick:()=>de(`plan`),children:[(0,K.jsx)(`span`,{children:U.planMode}),(0,K.jsx)(`small`,{children:U.planFirst})]})]})]}),o!==`default`&&(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-mode-chip`,"data-testid":`code-composer-mode-chip`,"aria-label":U.clearComposerMode,onClick:pe,children:[(0,K.jsx)(`span`,{children:bx(U,o)}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:(0,K.jsx)(le,{})})]}),Me&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-approval ${y}`,"data-testid":`code-composer-approval`,"aria-label":U.agentPermissionMode,"aria-haspopup":`menu`,"aria-expanded":c,disabled:_,onClick:ge,children:[(0,K.jsx)(`span`,{className:`code-tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Ix,{mode:g})}),(0,K.jsx)(`span`,{className:`code-composer-approval-label`,children:dt}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(Lx,{})})]}),c&&(0,K.jsxs)(`div`,{className:`code-approval-menu code-composer-menu`,role:`menu`,"data-testid":`code-approval-menu`,ref:F,onKeyDown:be,onBlur:Ce,onMouseDown:e=>e.preventDefault(),children:[(0,K.jsxs)(`div`,{className:`code-approval-menu-header`,children:[(0,K.jsx)(`span`,{children:U.permissionsPrompt}),(0,K.jsx)(`small`,{children:b})]}),E.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-approval-option ${e.value===g?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===g,onClick:()=>we(e.value),children:[(0,K.jsx)(`span`,{className:`code-approval-option-icon ${e.color??`muted`}`,"aria-hidden":`true`,children:(0,K.jsx)(Ix,{mode:e.value})}),(0,K.jsxs)(`span`,{className:`code-approval-option-copy`,children:[(0,K.jsx)(`span`,{children:U.permissionModeLabel(e.value,e.label)}),(0,K.jsx)(`small`,{children:U.permissionModeDescription(e.value,e.description)})]}),e.value===g&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value))]})]})]}),(0,K.jsxs)(`div`,{className:`code-composer-right-tools`,"data-testid":`code-composer-right-tools`,children:[D&&(0,K.jsxs)(`div`,{className:`code-composer-context-window`,"data-testid":`code-composer-context-window`,tabIndex:0,role:`img`,"aria-label":gt,children:[(0,K.jsx)(`span`,{className:`code-context-window-ring`,"aria-hidden":`true`,style:{"--context-percent":D.percentUsed}}),(0,K.jsxs)(`div`,{className:`code-context-window-popover`,role:`tooltip`,children:[(0,K.jsx)(`span`,{children:`Context window:`}),(0,K.jsxs)(`strong`,{children:[D.percentUsed,`% used (`,D.percentLeft,`% left)`]}),(0,K.jsxs)(`strong`,{children:[Tx(D.usedTokens),` / `,Tx(D.limitTokens),` tokens used`]})]})]}),Ne&&(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor model-picker`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-model-picker`,"data-testid":`code-composer-model-picker`,"data-agent-model-preset":d,"aria-label":U.modelAndReasoning,"aria-haspopup":`menu`,"aria-expanded":l,title:[x,ft,pt].filter(Boolean).join(` · `),onClick:_e,children:[m===`priority`&&(0,K.jsx)(`span`,{className:`code-composer-speed-active`,"aria-hidden":`true`,children:(0,K.jsx)(Px,{})}),(0,K.jsx)(`span`,{className:`code-composer-model-label desktop`,children:x}),(0,K.jsx)(`span`,{className:`code-composer-model-label mobile`,children:mt}),(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted desktop`,children:ft}),(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted mobile`,children:ht}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(Lx,{})})]}),l&&(0,K.jsx)(`div`,{className:`code-model-picker-menu code-composer-menu ${Fe?`has-matrix`:``}`,role:`menu`,"data-testid":`code-model-menu`,ref:ne,onKeyDown:be,onBlur:Ce,onMouseDown:e=>e.preventDefault(),children:(0,K.jsx)(yx,{models:G,currentModel:f,currentReasoning:p,fastAvailable:Pe&&T.some(e=>e.value===`priority`),fast:m===`priority`,onSelect:Oe,onFastChange:e=>ke(e?`priority`:`default`),advanced:(0,K.jsxs)(K.Fragment,{children:[w.length>0&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:U.reasoning}),w.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===p?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===p,onClick:()=>Ee(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:U.reasoningOptionLabel(e.value,e.label)})}),e.value===p&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value)),(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`})]}),(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${u===`model`?`selected`:``}`,role:`menuitem`,"data-testid":`code-model-submenu-trigger`,onClick:()=>ye(u===`model`?null:`model`),children:[(0,K.jsx)(`span`,{children:x}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),u===`model`&&(0,K.jsx)(`div`,{className:`code-model-submenu code-composer-menu`,role:`menu`,"data-testid":`code-model-submenu`,onKeyDown:be,children:h.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===f?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===f,onClick:()=>Te(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:Fb(e,e.value)})}),e.value===f&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value))})]}),Pe&&(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${u===`speed`?`selected`:``}`,role:`menuitem`,"data-testid":`code-speed-submenu-trigger`,onClick:()=>ye(u===`speed`?null:`speed`),children:[(0,K.jsx)(`span`,{children:U.speed}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),u===`speed`&&(0,K.jsx)(`div`,{className:`code-speed-submenu code-composer-menu`,role:`menu`,"data-testid":`code-speed-submenu`,onKeyDown:be,children:T.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===m?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===m,onClick:()=>De(e.value),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsxs)(`span`,{className:`code-speed-option-label`,children:[e.value===`priority`&&(0,K.jsx)(`span`,{className:`code-speed-option-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Px,{})}),(0,K.jsx)(`span`,{children:U.serviceTierLabel(e.value,e.label)})]}),e.description&&(0,K.jsx)(`small`,{children:U.serviceTierDescription(e.value,e.description)})]}),e.value===m&&(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})})]},e.value))})]})]})})})]}),Xe&&(0,K.jsx)(`button`,{type:`button`,className:`code-composer-mic ${M?`listening`:``}`,"data-testid":`code-composer-mic`,"aria-label":M?U.stopDictation:j?U.startDictation:U.mobileDictationHint,"aria-pressed":M,onPointerDown:wt,onClick:Ct,disabled:!e||!xt,title:xt?M?U.stopDictation:j?U.startDictation:U.mobileDictationHint:U.speechUnsupported,children:(0,K.jsx)(Nx,{listening:M})}),(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${vt?`interrupt`:``}`,"data-testid":`code-composer-send`,"data-action":ee,"aria-label":vt?U.interruptAgent:U.sendMessage,onClick:vt?B:()=>z(nt.current),disabled:_t,children:vt?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(he,{})})]})]})})]})}function Ix({mode:e}){return e===`ask`?(0,K.jsx)(ye,{className:`code-approval-hand-glyph`}):e===`custom`?(0,K.jsx)(`svg`,{className:`filled`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M7.99997 6C6.89497 6 5.99997 6.895 5.99997 8C5.99997 9.105 6.89497 10 7.99997 10C9.10497 10 9.99997 9.105 9.99997 8C9.99997 6.895 9.10497 6 7.99997 6ZM7.99997 9C7.44797 9 6.99997 8.552 6.99997 8C6.99997 7.448 7.44797 7 7.99997 7C8.55197 7 8.99997 7.448 8.99997 8C8.99997 8.552 8.55197 9 7.99997 9ZM14.565 9.715L13.279 8.628C13.245 8.599 13.213 8.567 13.184 8.533C12.888 8.186 12.931 7.667 13.279 7.372L14.565 6.285C14.693 6.177 14.742 6.003 14.691 5.844C14.386 4.903 13.882 4.04 13.219 3.308C13.139 3.22 13.027 3.172 12.912 3.172C12.865 3.172 12.818 3.18 12.773 3.196L11.186 3.761C11.144 3.776 11.1 3.788 11.056 3.796C11.006 3.805 10.956 3.81 10.907 3.81C10.515 3.81 10.167 3.532 10.094 3.134L9.79097 1.482C9.76097 1.318 9.63397 1.188 9.46997 1.153C8.98997 1.051 8.49897 1 8.00097 1C7.50297 1 7.01097 1.052 6.53097 1.153C6.36697 1.188 6.23997 1.318 6.20997 1.482L5.90797 3.134C5.89997 3.178 5.88797 3.221 5.87297 3.263C5.75197 3.6 5.43397 3.81 5.09397 3.81C5.00197 3.81 4.90797 3.794 4.81597 3.762L3.22897 3.197C3.18397 3.181 3.13597 3.173 3.08997 3.173C2.97497 3.173 2.86297 3.221 2.78297 3.309C2.11897 4.041 1.61597 4.904 1.30997 5.845C1.25797 6.004 1.30797 6.178 1.43597 6.286L2.72197 7.373C2.75597 7.402 2.78797 7.434 2.81697 7.468C3.11297 7.815 3.06997 8.334 2.72197 8.629L1.43597 9.716C1.30797 9.824 1.25897 9.998 1.30997 10.157C1.61497 11.098 2.11897 11.961 2.78297 12.693C2.86297 12.781 2.97497 12.829 3.08997 12.829C3.13697 12.829 3.18397 12.821 3.22897 12.805L4.81597 12.24C4.85797 12.225 4.90197 12.213 4.94597 12.205C4.99597 12.196 5.04597 12.192 5.09497 12.192C5.48697 12.192 5.83497 12.47 5.90797 12.868L6.20997 14.52C6.23997 14.684 6.36697 14.814 6.53097 14.849C7.01097 14.951 7.50297 15.002 8.00097 15.002C8.49897 15.002 8.99097 14.95 9.46997 14.849C9.63397 14.814 9.76097 14.684 9.79097 14.52L10.094 12.868C10.102 12.824 10.114 12.781 10.129 12.739C10.25 12.402 10.568 12.192 10.908 12.192C11 12.192 11.094 12.208 11.186 12.24L12.772 12.805C12.818 12.821 12.865 12.829 12.911 12.829C13.026 12.829 13.138 12.781 13.218 12.693C13.882 11.961 14.385 11.098 14.69 10.157C14.742 9.998 14.692 9.824 14.564 9.716L14.565 9.715ZM12.728 11.726L11.521 11.296C11.323 11.226 11.117 11.19 10.908 11.19C10.139 11.19 9.44697 11.676 9.18797 12.399C9.15397 12.492 9.12897 12.588 9.11097 12.686L8.88097 13.937C8.59097 13.979 8.29597 14 8.00097 14C7.70597 14 7.41097 13.979 7.11997 13.936L6.89097 12.685C6.73197 11.818 5.97697 11.189 5.09497 11.189C4.98697 11.189 4.87697 11.199 4.76597 11.219C4.66897 11.237 4.57397 11.262 4.47997 11.295L3.27297 11.725C2.90497 11.264 2.61097 10.759 2.39397 10.214L3.36797 9.391C3.74097 9.076 3.96797 8.634 4.00797 8.148C4.04797 7.662 3.89497 7.19 3.57797 6.818C3.51397 6.743 3.44297 6.672 3.36797 6.608L2.39397 5.785C2.61097 5.24 2.90497 4.734 3.27297 4.274L4.47997 4.704C4.67797 4.774 4.88397 4.81 5.09397 4.81C5.86297 4.81 6.55497 4.324 6.81397 3.601C6.84797 3.507 6.87297 3.411 6.89097 3.314L7.11997 2.063C7.41097 2.021 7.70597 1.999 8.00097 1.999C8.29597 1.999 8.59097 2.02 8.88097 2.062L9.10997 3.313C9.26897 4.18 10.024 4.809 10.906 4.809C11.014 4.809 11.124 4.799 11.234 4.779C11.331 4.761 11.427 4.736 11.521 4.703L12.728 4.273C13.096 4.733 13.39 5.239 13.607 5.784L12.634 6.607C12.261 6.922 12.033 7.364 11.994 7.85C11.954 8.336 12.107 8.809 12.424 9.18C12.489 9.256 12.559 9.326 12.635 9.39L13.609 10.213C13.392 10.758 13.098 11.264 12.73 11.724L12.728 11.726Z`})}):(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 3.6 19 6v5.5c0 4.2-2.7 7.6-7 8.9-4.3-1.3-7-4.7-7-8.9V6l7-2.4Z`}),e===`full`||e===`bypassPermissions`?(0,K.jsx)(`path`,{d:`M12 8v5`}):(0,K.jsx)(`path`,{d:`M9.5 12.4 11.3 14l3.5-4`}),e===`full`||e===`bypassPermissions`?(0,K.jsx)(`path`,{d:`M12 16.4h.01`}):null]})}function Lx(){return(0,K.jsx)(ge,{})}function Rx(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function zx({request:e,onRespond:t,copy:n}){let r=e.toolCall?.title||n.acpPermissionTool,i=e.options.filter(e=>e.kind.startsWith(`allow`)),a=e.options.filter(e=>e.kind.startsWith(`reject`)),[o,s]=(0,W.useState)(i.find(e=>e.kind===`allow_once`)?.optionId||i[0]?.optionId||``),[c,l]=(0,W.useState)(!1),u={...e._meta||{},...e.toolCall?._meta||{}},d=Rx(u.sandbox_authorization),f=Rx(u.sandbox_fallback_authorization),p=u.sandbox_not_applied,m=Array.isArray(d?.network_hosts)?d.network_hosts.map(String):[],h=Array.isArray(d?.write_paths)?d.write_paths.map(String):[],g=e.securityWarnings||[],_=g.length>0&&!c,v=[];return e.toolCall?.rawInput!==void 0&&v.push([`Input`,e.toolCall.rawInput]),e.toolCall?.content!==void 0&&v.push([`Content`,e.toolCall.content]),e.toolCall?.locations!==void 0&&v.push([`Locations`,e.toolCall.locations]),(0,K.jsxs)(`section`,{className:`code-app-server-request`,"data-testid":`code-acp-permission-request`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:n.acpPermissionTitle}),(0,K.jsx)(`span`,{children:e.origin===`subagent`?`Subagent · ${e.toolCall?.kind||`tool`}`:e.toolCall?.kind||`tool`})]}),(0,K.jsx)(`p`,{children:r}),v.length>0?(0,K.jsxs)(`details`,{className:`code-acp-permission-details`,children:[(0,K.jsx)(`summary`,{children:`Details`}),v.map(([e,t])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e}),(0,K.jsx)(`pre`,{children:typeof t==`string`?t:JSON.stringify(t,null,2)})]},e))]}):null,d?(0,K.jsxs)(`section`,{className:`code-acp-sandbox-details`,"data-testid":`code-acp-sandbox-details`,children:[d.reason?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Reason from Agent`}),(0,K.jsx)(`span`,{children:d.reason})]}):null,d.unsandboxed?(0,K.jsxs)(`p`,{className:`warning`,children:[(0,K.jsx)(`strong`,{children:`Sandbox`}),(0,K.jsx)(`span`,{children:`Runs without the OS sandbox`})]}):null,d.network_all_hosts||d.network?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Network`}),(0,K.jsx)(`span`,{children:`Any host`})]}):m.length>0?(0,K.jsxs)(`details`,{children:[(0,K.jsxs)(`summary`,{children:[`Network · `,m.length,` `,m.length===1?`host`:`hosts`]}),(0,K.jsx)(`ul`,{children:m.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(`code`,{children:e})},e))})]}):null,d.allow_fs_write_all?(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Write access`}),(0,K.jsx)(`span`,{children:`Unrestricted workspace writes`})]}):h.length>0?(0,K.jsxs)(`details`,{children:[(0,K.jsxs)(`summary`,{children:[`Write access · `,h.length,` `,h.length===1?`path`:`paths`]}),(0,K.jsx)(`ul`,{children:h.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsx)(`code`,{children:e})},e))})]}):null,d.command?(0,K.jsxs)(`details`,{children:[(0,K.jsx)(`summary`,{children:`Command`}),(0,K.jsx)(`pre`,{children:d.command})]}):null]}):null,f?(0,K.jsxs)(`section`,{className:`code-acp-sandbox-details warning`,"data-testid":`code-acp-sandbox-fallback`,children:[(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Sandbox unavailable`}),(0,K.jsx)(`span`,{children:f.reason||`The command may run without OS sandboxing.`})]}),f.command?(0,K.jsx)(`pre`,{children:f.command}):null]}):null,p?(0,K.jsx)(`section`,{className:`code-acp-sandbox-details warning`,"data-testid":`code-acp-sandbox-not-applied`,children:(0,K.jsxs)(`p`,{children:[(0,K.jsx)(`strong`,{children:`Sandbox not applied`}),(0,K.jsx)(`span`,{children:typeof p==`string`?p:JSON.stringify(p)})]})}):null,g.length>0?(0,K.jsxs)(`label`,{className:`code-acp-permission-risk`,"data-testid":`code-acp-permission-risk`,children:[(0,K.jsx)(`strong`,{children:`Potentially misleading Unicode`}),g.map(e=>(0,K.jsxs)(`span`,{className:`code-acp-permission-risk-finding`,children:[(0,K.jsx)(`code`,{children:e.displayValue}),e.characters.map(e=>(0,K.jsxs)(`small`,{children:[e.character?`‘${e.character}’ `:``,e.codePoint,` · `,e.description]},`${e.codePoint}:${e.kind}`))]},`${e.targetType}:${e.value}`)),(0,K.jsx)(`input`,{type:`checkbox`,checked:c,onChange:e=>l(e.target.checked)}),(0,K.jsx)(`span`,{children:`I reviewed these targets and wish to proceed.`})]}):null,(0,K.jsxs)(`div`,{className:`code-app-server-request-actions`,children:[i.length>1?(0,K.jsx)(`select`,{"aria-label":`Permission scope`,value:o,onChange:e=>s(e.target.value),children:i.map(e=>(0,K.jsx)(`option`,{value:e.optionId,children:e.name},e.optionId))}):null,i.length>0?(0,K.jsx)(`button`,{type:`button`,className:`approve`,disabled:_,onClick:()=>t(e.requestId,o||i[0].optionId,!1),children:i.length===1?i[0].name:n.appServerRequestApprove}):null,a.map(n=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,n.optionId,!1),children:n.name},n.optionId)),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,void 0,!0),children:n.cancel})]})]})}function Bx(e){return Array.isArray(e.oneOf)?e.oneOf.map(e=>({value:e.const,label:e.title})):Array.isArray(e.enum)?e.enum.map(e=>({value:e,label:e})):Array.isArray(e.items?.anyOf)?e.items.anyOf.map(e=>({value:e.const,label:e.title})):Array.isArray(e.items?.enum)?e.items.enum.map(e=>({value:e,label:e})):[]}function Vx(e){return e.type===`boolean`?e.default===!0:e.type===`array`?Array.isArray(e.default)?e.default:[]:e.type===`number`||e.type===`integer`?typeof e.default==`number`?e.default:``:typeof e.default==`string`?e.default:Bx(e)[0]?.value||``}function Hx({request:e,onRespond:t}){let n=e.requestedSchema?.properties||{},r=new Set(e.requestedSchema?.required||[]),[i,a]=(0,W.useState)(()=>Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Vx(t)]))),[o,s]=(0,W.useState)(``),c=e.requestedSchema?.title||`Input requested`,l=e.mode===`url`&&e.status===`accepted`,u=(0,W.useMemo)(()=>{if(e.mode!==`url`||!e.url)return``;try{let t=new URL(e.url);return[`http:`,`https:`].includes(t.protocol)?t.toString():``}catch{return``}},[e.mode,e.url]);return(0,K.jsxs)(`form`,{className:`code-app-server-request code-acp-elicitation`,"data-testid":`code-acp-elicitation`,"data-status":e.status||`pending`,onSubmit:a=>{a.preventDefault();for(let[e,t]of Object.entries(n)){let n=i[e];if(t.type!==`array`)continue;let a=Array.isArray(n)?n:[],o=Math.max(+!!r.has(e),Number(t.minItems||0));if(a.length<o){s(`${t.title||e} needs at least ${o} selection${o===1?``:`s`}.`);return}if(Number.isFinite(t.maxItems)&&a.length>Number(t.maxItems)){s(`${t.title||e} allows at most ${t.maxItems} selections.`);return}}s(``);let o=Object.fromEntries(Object.entries(i).filter(([e,t])=>r.has(e)||(Array.isArray(t)?t.length>0:t!==``)));t(e.requestId,`accept`,o)},children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:c}),(0,K.jsx)(`span`,{children:e.origin===`subagent`?`Subagent · ${e.mode}`:e.mode})]}),(0,K.jsx)(`p`,{children:e.message}),e.requestedSchema?.description?(0,K.jsx)(`small`,{children:e.requestedSchema.description}):null,o?(0,K.jsx)(`small`,{className:`code-acp-elicitation-error`,role:`alert`,children:o}):null,e.mode===`url`?u?(0,K.jsx)(`a`,{className:`code-acp-elicitation-link`,href:u,target:`_blank`,rel:`noreferrer`,children:`Open secure link`}):(0,K.jsx)(`small`,{role:`alert`,children:`The Agent provided an unsupported link.`}):(0,K.jsx)(`div`,{className:`code-app-server-request-questions`,children:Object.entries(n).map(([e,t])=>{let n=Bx(t),o=t.title||e;return t.type===`boolean`?(0,K.jsxs)(`label`,{className:`code-acp-elicitation-checkbox`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:i[e]===!0,onChange:t=>a(n=>({...n,[e]:t.target.checked}))}),(0,K.jsx)(`span`,{children:o}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e):t.type===`array`?(0,K.jsxs)(`fieldset`,{children:[(0,K.jsx)(`legend`,{children:o}),n.map(t=>{let n=Array.isArray(i[e])?i[e]:[];return(0,K.jsxs)(`label`,{className:`code-acp-elicitation-checkbox`,children:[(0,K.jsx)(`input`,{type:`checkbox`,checked:n.includes(t.value),onChange:r=>a(i=>({...i,[e]:r.target.checked?[...n,t.value]:n.filter(e=>e!==t.value)}))}),(0,K.jsx)(`span`,{children:t.label})]},t.value)})]},e):(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:o}),n.length>0?(0,K.jsx)(`select`,{value:String(i[e]??``),required:r.has(e),onChange:t=>a(n=>({...n,[e]:t.target.value})),children:n.map(e=>(0,K.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,K.jsx)(`input`,{type:t.type===`number`||t.type===`integer`?`number`:t.format===`email`?`email`:t.format===`date`?`date`:t.format===`date-time`?`datetime-local`:t.format===`uri`?`url`:`text`,value:String(i[e]??``),required:r.has(e),min:t.minimum??void 0,max:t.maximum??void 0,minLength:t.minLength??void 0,maxLength:t.maxLength??void 0,pattern:t.pattern??void 0,step:t.type===`integer`?1:t.type===`number`?`any`:void 0,onChange:n=>a(r=>({...r,[e]:t.type===`number`||t.type===`integer`?n.target.value===``?``:n.target.valueAsNumber:n.target.value}))}),t.description?(0,K.jsx)(`small`,{children:t.description}):null]},e)})}),l?(0,K.jsx)(`small`,{className:`code-acp-elicitation-waiting`,children:`Waiting for the Agent to confirm completion…`}):(0,K.jsxs)(`div`,{className:`code-app-server-request-actions`,children:[(0,K.jsx)(`button`,{type:`submit`,className:`approve`,disabled:e.mode===`url`&&!u,children:e.mode===`url`?`Continue`:`Submit`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,`decline`),children:`Decline`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>t(e.requestId,`cancel`),children:`Cancel`})]})]})}function Ux(e){return e.ctrlKey&&e.key.toLowerCase()===`c`?``:e.key===`Tab`?` `:e.key===`Escape`?`\x1B`:e.key===`ArrowUp`?`\x1B[A`:e.key===`ArrowDown`?`\x1B[B`:``}function Wx({agentId:e,authTerminal:t}){let[r,i]=(0,W.useState)(``),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.useState)(``),l=(0,W.useRef)(null),u=t.terminal,d=t.state===`running`&&!u?.exitStatus&&u?.interactive===!0;(0,W.useEffect)(()=>{let e=l.current;e&&(e.scrollTop=e.scrollHeight)},[u?.output]);let f=async r=>{if(!(!d||!r||a)){o(!0);try{let i=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-terminals/${encodeURIComponent(t.terminalId)}/input`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({input:r})}),a=await i.json().catch(()=>null);if(!i.ok)throw Error(a?.error||`Failed to send terminal input (${i.status})`);c(``)}catch(e){c(e instanceof Error?e.message:`Failed to send terminal input`)}finally{o(!1)}}};return(0,K.jsxs)(`div`,{className:`code-acp-auth-terminal`,"data-testid":`code-acp-auth-terminal`,children:[(0,K.jsxs)(`div`,{className:`code-acp-auth-terminal-heading`,children:[(0,K.jsx)(`strong`,{children:t.name||`Sign in`}),(0,K.jsx)(`span`,{children:t.state===`running`?`Waiting for sign-in`:t.state})]}),(0,K.jsx)(`pre`,{ref:l,"data-testid":`code-acp-auth-terminal-output`,children:u?.output||`Starting sign-in…`}),d?(0,K.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=r;t&&(i(``),f(`${t}\r`))},children:[(0,K.jsx)(`input`,{"aria-label":`Terminal sign-in input`,autoComplete:`off`,"data-testid":`code-acp-auth-terminal-input`,disabled:a,value:r,onChange:e=>i(e.currentTarget.value),onKeyDown:e=>{let t=Ux(e);t&&(e.preventDefault(),f(t))}}),(0,K.jsx)(`button`,{type:`submit`,disabled:a||!r,children:`Send`})]}):null,t.error||s?(0,K.jsx)(`small`,{className:`code-acp-auth-terminal-error`,children:t.error||s}):null]})}function Gx({agentId:e,methods:t,authTerminal:n,agentName:r,authenticatingId:i,onAuthenticate:a}){if(t.length===0&&!n)return null;let o=t.filter(e=>!e.type||e.type===`agent`||e.type===`terminal`),s=t.filter(e=>e.type===`env_var`);return(0,K.jsxs)(`section`,{className:`code-app-server-request code-acp-authentication`,"data-testid":`code-acp-authentication`,role:`alert`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsxs)(`strong`,{children:[`Sign in to `,r||`Agent`]}),(0,K.jsx)(`span`,{children:`Authentication required`})]}),(0,K.jsxs)(`div`,{className:`code-acp-authentication-methods`,children:[n?(0,K.jsx)(Wx,{agentId:e,authTerminal:n}):null,o.map(e=>(0,K.jsxs)(`div`,{className:`code-acp-authentication-method`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e.name||e.id}),e.description?(0,K.jsx)(`small`,{children:e.description}):null,e.link?(0,K.jsx)(`a`,{href:e.link,target:`_blank`,rel:`noreferrer`,children:`Get credentials`}):null]}),(0,K.jsx)(`button`,{type:`button`,disabled:!!i,onClick:()=>a(e.id),children:i===e.id||n?.methodId===e.id&&n.state===`running`?`Signing in…`:`Authenticate`})]},e.id)),s.map(e=>(0,K.jsx)(`div`,{className:`code-acp-authentication-method unsupported`,children:(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:e.name||e.id}),e.description?(0,K.jsx)(`small`,{children:e.description}):null,e.type===`env_var`?(0,K.jsxs)(`small`,{children:[`Set `,e.vars?.map(e=>e.label||e.name).join(`, `)||`the requested environment variables`,` and restart the Agent.`]}):null,e.link?(0,K.jsx)(`a`,{href:e.link,target:`_blank`,rel:`noreferrer`,children:`Get credentials`}):null]})},e.id))]})]})}function Kx(e){return e.options.flatMap(e=>`options`in e?e.options:[e])}function qx(e,t){return t.test(`${e.id} ${e.name} ${e.category||``}`)}function Jx(e,t){return e.configOptions.find(e=>e.type===`select`&&qx(e,t))}function Yx(e,t){return e.configOptions.find(e=>e.type===`boolean`&&qx(e,t))}function Xx(e){return e?Kx(e).find(t=>t.value===e.currentValue):void 0}function Zx(e){return e.trim().replace(/^gpt[-\s]*/i,``)||e}function Qx({modeId:e}){return e===`read-only`||e===`plan`?(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M3.5 12s3.1-5 8.5-5 8.5 5 8.5 5-3.1 5-8.5 5-8.5-5-8.5-5Z`}),(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.4`})]}):e===`default`?(0,K.jsx)(ye,{className:`code-approval-hand-glyph`}):(0,K.jsxs)(`svg`,{viewBox:`0 0 24 24`,"aria-hidden":`true`,children:[(0,K.jsx)(`path`,{d:`M12 3.6 19 6v5.5c0 4.2-2.7 7.6-7 8.9-4.3-1.3-7-4.7-7-8.9V6l7-2.4Z`}),e===`agent-full-access`||e===`bypassPermissions`?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`path`,{d:`M12 8v5`}),(0,K.jsx)(`path`,{d:`M12 16.4h.01`})]}):e===`dontAsk`?(0,K.jsx)(`path`,{d:`M9.5 12h5`}):[`agent`,`auto`,`acceptEdits`,`build`].includes(e)?(0,K.jsx)(`path`,{d:`m9.5 12.4 1.8 1.6 3.5-4`}):(0,K.jsx)(`circle`,{cx:`12`,cy:`12`,r:`2.4`})]})}function $x(e){return[`agent`,`auto`,`acceptEdits`,`build`].includes(e)?`blue`:[`agent-full-access`,`bypassPermissions`].includes(e)?`orange`:`muted`}function eS(e){return e.configOptions.find(e=>e.type===`select`&&(e.id===`mode`||e.category===`mode`))}function tS(e,t){return e.provider===`qoder`&&e.agentInfo?.version===`1.0.43`?t.filter(e=>e.id!==`plan`):t}function nS(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M8.85 1.35a.55.55 0 0 1 .55.68L8.28 6.1h3.07a.55.55 0 0 1 .42.9l-5.5 6.6a.55.55 0 0 1-.96-.48l1.12-4.2H3.65a.55.55 0 0 1-.44-.88l5.2-6.48a.55.55 0 0 1 .44-.21Z`})})}function rS({option:e,currentValue:t,label:n,onSelect:r}){return Kx(e).map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.value===t?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.value===t,onClick:()=>r(e.value),children:[(0,K.jsx)(`span`,{className:`code-model-option-copy`,children:(0,K.jsx)(`span`,{children:n(e)})}),e.value===t?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},e.value))}function iS({session:e,updatingId:t,copy:n,open:r,onToggle:i,onSetMode:a,onSetConfigOption:o}){let s=e.modes?.availableModes||[],c=eS(e),l=s.length===0&&!!c,u=tS(e,s.length>0?s:c?Kx(c).map(e=>({id:e.value,name:e.name,description:e.description})):[]);if(u.length===0)return null;let d=e.currentModeId||e.modes?.currentModeId||c?.currentValue||``,f=u.find(e=>e.id===d)||u[0],p=n.acpModeLabel(f?.id||d,f?.name||d),m=f?.description?n.acpModeDescription(f.id,f.description):``;return(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-approval ${$x(d)}`,"data-testid":`code-acp-mode`,"data-acp-value":d,"aria-label":n.agentPermissionMode,"aria-haspopup":`menu`,"aria-expanded":r,disabled:!!t,onClick:i,children:[(0,K.jsx)(`span`,{className:`code-tool-icon`,"aria-hidden":`true`,children:(0,K.jsx)(Qx,{modeId:d})}),(0,K.jsx)(`span`,{className:`code-composer-approval-label`,children:p}),(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(ge,{})})]}),r?(0,K.jsxs)(`div`,{className:`code-approval-menu code-composer-menu`,role:`menu`,"data-testid":`code-acp-mode-menu`,children:[(0,K.jsxs)(`div`,{className:`code-approval-menu-header`,children:[(0,K.jsx)(`span`,{children:n.agentPermissionMode}),m?(0,K.jsx)(`small`,{children:m}):null]}),u.map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-approval-option ${e.id===d?`selected`:``}`,role:`menuitemradio`,"aria-checked":e.id===d,onClick:()=>l&&c?o(c.id,e.id):a(e.id),children:[(0,K.jsx)(`span`,{className:`code-approval-option-icon ${$x(e.id)}`,"aria-hidden":`true`,children:(0,K.jsx)(Qx,{modeId:e.id})}),(0,K.jsxs)(`span`,{className:`code-approval-option-copy`,children:[(0,K.jsx)(`span`,{children:n.acpModeLabel(e.id,e.name)}),e.description?(0,K.jsx)(`small`,{children:n.acpModeDescription(e.id,e.description)}):null]}),e.id===d?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},e.id))]}):null]})}function aS({session:e,updatingId:t,copy:n,open:r,pane:i,onToggle:a,onSetPane:o,onSetConfigOption:s,onSetProfile:c,onSetFast:l}){let u=Jx(e,/(^|[\s_-])model([\s_-]|$)/i),d=Jx(e,/(reasoning|thought)/i),f=Yx(e,/(fast|speed)/i),p=e.configOptions.filter(e=>e!==u&&e!==d&&e!==f&&e.category!==`mode`&&e.id!==`mode`),m=Xx(u),h=Xx(d),g=u&&d?Kx(u).map(e=>({value:e.value,label:e.name,reasoning:Kx(d).map(e=>({value:e.value,label:n.reasoningOptionLabel(e.value,e.name)}))})):[],_=!!hx(g,u?.currentValue||``);if(!u&&!d&&!f&&p.length===0)return null;let v=!!t;return(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor model-picker`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-model-picker`,"data-testid":`code-acp-model-picker`,"data-agent-model-preset":`${u?.currentValue||``}:${d?.currentValue||``}`,"aria-label":n.modelAndReasoning,"aria-haspopup":`menu`,"aria-expanded":r,disabled:v,title:[m?.name,h?.name,f?.currentValue?f.name:``].filter(Boolean).join(` · `),onClick:a,children:[f?.currentValue?(0,K.jsx)(`span`,{className:`code-composer-speed-active`,"aria-hidden":`true`,children:(0,K.jsx)(nS,{})}):null,(0,K.jsx)(`span`,{className:`code-composer-model-label desktop`,children:Zx(m?.name||u?.currentValue||`Model`)}),(0,K.jsx)(`span`,{className:`code-composer-model-label mobile`,children:Zx(m?.name||u?.currentValue||`Model`)}),h?(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted desktop`,children:h.name}):null,h?(0,K.jsx)(`span`,{className:`code-composer-model-picker-muted mobile`,children:h.name}):null,(0,K.jsx)(`span`,{className:`code-chevron`,"aria-hidden":`true`,children:(0,K.jsx)(ge,{})})]}),r?(0,K.jsx)(`div`,{className:`code-model-picker-menu code-composer-menu ${_?`has-matrix`:``}`,role:`menu`,"data-testid":`code-acp-model-menu`,children:(0,K.jsx)(yx,{models:g,currentModel:u?.currentValue||``,currentReasoning:d?.currentValue||``,fastAvailable:!!f,fast:f?.currentValue===!0,disabled:v,onSelect:(e,t)=>{u&&d&&c(u.id,e,d.id,t)},onFastChange:e=>{f&&l(f.id,e)},advanced:(0,K.jsxs)(K.Fragment,{children:[d?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:n.reasoning}),(0,K.jsx)(rS,{option:d,currentValue:d.currentValue,label:e=>n.reasoningOptionLabel(e.value,e.name),onSelect:e=>s(d.id,e)}),(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`})]}):null,u?(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${i===`model`?`selected`:``}`,role:`menuitem`,"data-testid":`code-acp-model-submenu-trigger`,onClick:()=>o(i===`model`?null:`model`),children:[(0,K.jsx)(`span`,{children:m?.name||u.currentValue}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),i===`model`?(0,K.jsx)(`div`,{className:`code-model-submenu code-composer-menu`,role:`menu`,"data-testid":`code-acp-model-submenu`,children:(0,K.jsx)(rS,{option:u,currentValue:u.currentValue,label:e=>e.name,onSelect:e=>s(u.id,e)})}):null]}):null,f?(0,K.jsxs)(`div`,{className:`code-model-nested-anchor`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-model-nested-trigger ${i===`speed`?`selected`:``}`,role:`menuitem`,"data-testid":`code-acp-speed-submenu-trigger`,onClick:()=>o(i===`speed`?null:`speed`),children:[(0,K.jsx)(`span`,{children:n.speed}),(0,K.jsx)(fe,{className:`code-menu-chevron-right`})]}),i===`speed`?(0,K.jsx)(`div`,{className:`code-speed-submenu code-composer-menu`,role:`menu`,"data-testid":`code-acp-speed-submenu`,children:[!1,!0].map(e=>(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${f.currentValue===e?`selected`:``}`,role:`menuitemradio`,"aria-checked":f.currentValue===e,onClick:()=>s(f.id,e),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsxs)(`span`,{className:`code-speed-option-label`,children:[e?(0,K.jsx)(`span`,{className:`code-speed-option-icon`,"aria-hidden":`true`,children:(0,K.jsx)(nS,{})}):null,(0,K.jsx)(`span`,{children:e?f.name:n.serviceTierLabel(`default`,`Standard`)})]}),(0,K.jsx)(`small`,{children:e?f.description||n.serviceTierDescription(`priority`,``):n.serviceTierDescription(`default`,``)})]}),f.currentValue===e?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},String(e)))}):null]}):null,p.map(e=>e.type===`select`?(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`}),(0,K.jsx)(`div`,{className:`code-model-menu-header`,children:e.name}),(0,K.jsx)(rS,{option:e,currentValue:e.currentValue,label:e=>e.name,onSelect:t=>s(e.id,t)})]},e.id):(0,K.jsxs)(`button`,{type:`button`,className:`code-model-option ${e.currentValue?`selected`:``}`,role:`menuitemcheckbox`,"aria-checked":e.currentValue,onClick:()=>s(e.id,!e.currentValue),children:[(0,K.jsxs)(`span`,{className:`code-model-option-copy`,children:[(0,K.jsx)(`span`,{children:e.name}),e.description?(0,K.jsx)(`small`,{children:e.description}):null]}),e.currentValue?(0,K.jsx)(`span`,{className:`code-menu-check`,"aria-hidden":`true`,children:(0,K.jsx)(me,{})}):null]},e.id))]})})}):null]})}function oS(e){let t=Number(e?.used),n=Number(e?.size);if(!Number.isFinite(t)||t<0||!Number.isFinite(n)||n<=0)return null;let r=t/n,i=Math.max(0,Math.min(100,Math.round(r*100))),a=Number(e?.cost?.amount),o=String(e?.cost?.currency||``).trim().toUpperCase(),s=Number.isFinite(a)&&a>=0&&/^[A-Z]{3}$/.test(o)?`${a.toLocaleString(`en-US`,{maximumFractionDigits:4})} ${o}`:``;return{usedTokens:t,limitTokens:n,percentUsed:i,percentLeft:100-i,costLabel:s,level:r>=1?`critical`:r>=.85?`warning`:`normal`}}function sS(e,t){if(!e)return e;let n=Array.isArray(t.configOptions)?t.configOptions:typeof t.configId==`string`&&(typeof t.value==`string`||typeof t.value==`boolean`)?[{configId:t.configId,value:t.value}]:[];if(n.length===0)return e;let r=new Map(n.flatMap(e=>e&&typeof e==`object`&&`configId`in e&&typeof e.configId==`string`&&`value`in e&&(typeof e.value==`string`||typeof e.value==`boolean`)?[[e.configId,e.value]]:[]));return r.size===0?e:{...e,configOptions:e.configOptions.map(e=>{let t=r.get(e.id);return t===void 0||typeof t!=typeof e.currentValue?e:{...e,currentValue:t}})}}function cS(e,t,r){let[i,a]=(0,W.useState)(null),[o,s]=(0,W.useState)(``),[c,l]=(0,W.useState)(``),[u,d]=(0,W.useState)(``),f=(0,W.useRef)(null);(0,W.useEffect)(()=>{f.current=i},[i]);let p=(0,W.useCallback)(async r=>{if(!(!e||!t))try{let t=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-session?includeEntries=0`),{signal:r}),i=await t.json().catch(()=>null);if(!t.ok||!i?.session)throw Error(i?.error||`Failed to read ACP session (${t.status})`);f.current=i.session,a(i.session),s(``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;s(e instanceof Error?e.message:`Failed to read ACP session`)}},[t,e]);(0,W.useEffect)(()=>{let e=new AbortController;return p(e.signal),()=>e.abort()},[p,r]),(0,W.useEffect)(()=>{if(!i?.authTerminal||![`running`,`completed`].includes(i.authTerminal.state))return;let e=window.setInterval(()=>{p()},500);return()=>window.clearInterval(e)},[p,i?.authTerminal?.state,i?.authTerminal?.terminalId]);let m=(0,W.useCallback)(async(t,r)=>{if(!e||c)return!1;let i=f.current,o=sS(i,r);o!==i&&(f.current=o,a(o)),l(t);try{let t=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-session`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)}),i=await t.json().catch(()=>null);if(!t.ok)throw Error(i?.error||`Failed to update ACP session (${t.status})`);return a(e=>{let t=e&&{...e,...i?.modeId?{currentModeId:i.modeId,modes:e.modes?{...e.modes,currentModeId:i.modeId}:e.modes}:{},...i?.configOptions?{configOptions:i.configOptions}:{}};return f.current=t,t}),s(``),!0}catch(e){return i&&(f.current=i,a(i)),s(e instanceof Error?e.message:`Failed to update ACP session`),!1}finally{l(``)}},[e,c]);return{session:i,error:o,updatingId:c,authenticatingId:u,setMode:(0,W.useCallback)(e=>m(`mode`,{modeId:e}),[m]),setConfigOption:(0,W.useCallback)((e,t)=>m(e,{configId:e,value:t}),[m]),setConfigOptions:(0,W.useCallback)(e=>m(e.map(e=>e.configId).join(`:`),{configOptions:e}),[m]),authenticate:(0,W.useCallback)(async t=>{if(!e||u)return!1;d(t);try{let r=await fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-session/authenticate`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({methodId:t})}),i=await r.json().catch(()=>null);if(!r.ok)throw Error(i?.error||`Failed to authenticate ACP Agent (${r.status})`);return s(``),await p(),!0}catch(e){return s(e instanceof Error?e.message:`Failed to authenticate ACP Agent`),!1}finally{d(``)}},[e,u,p])}}var lS=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM6 3.99951C6 2.89651 6.897 1.99951 8 1.99951C9.103 1.99951 10 2.89651 10 3.99951V7.99951C10 9.10251 9.103 9.99951 8 9.99951C6.897 9.99951 6 9.10251 6 7.99951V3.99951ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`,uS=`M8 10.9995C9.654 10.9995 11 9.65351 11 7.99951V3.99951C11 2.34551 9.654 0.999512 8 0.999512C6.346 0.999512 5 2.34551 5 3.99951V7.99951C5 9.65351 6.346 10.9995 8 10.9995ZM13 7.49951V7.99951C13 10.5855 11.02 12.6935 8.5 12.9485V14.4995C8.5 14.7755 8.276 14.9995 8 14.9995C7.724 14.9995 7.5 14.7755 7.5 14.4995V12.9485C4.98 12.6935 3 10.5845 3 7.99951V7.49951C3 7.22351 3.224 6.99951 3.5 6.99951C3.776 6.99951 4 7.22351 4 7.49951V7.99951C4 10.2055 5.794 11.9995 8 11.9995C10.206 11.9995 12 10.2055 12 7.99951V7.49951C12 7.22351 12.224 6.99951 12.5 6.99951C12.776 6.99951 13 7.22351 13 7.49951Z`;function dS({listening:e}){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:e?uS:lS})})}function fS(e){return!Number.isFinite(e)||e<0?`0`:e>=1e6?`${Math.round(e/1e5)/10}m`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function pS(e,t){let n=ix(e,t);if(n)return n;let r=Math.max(0,Math.min(t,e.length)),i=e.lastIndexOf(`
111
+ `,Math.max(0,r-1))+1,a=e.slice(i,r).match(/^(\s*)\/(\$[A-Za-z0-9._:-]*)$/);return a?{start:i+(a[1]?.length??0),end:r,query:a[2]??``,trigger:`/`}:null}function mS({active:e,agentId:t,runtimeState:n,sessionUpdatedAt:r,runtimeError:i,draft:a,attachments:o,composerMode:s,contextWindow:c,pendingFollowUp:l,submitAction:u,textareaRef:d,attachmentInputRef:f,permissions:p,elicitations:m,activeElicitations:h,speechSupported:g,speechListening:_,onDraftChange:v,onNavigateHistory:y,onRemoveAttachment:b,onSubmit:x,onInterrupt:S,onDiscardPendingFollowUp:C,onToggleSpeechInput:w,onPasteAttachment:T,onAttachmentFiles:E,onChooseAttachmentFile:D,onActivateComposerMode:O,onClearComposerMode:k,onRespondToPermission:A,onRespondToElicitation:ee,copy:j}){let M=(0,W.useRef)(!1),N=(0,W.useRef)(0),te=(0,W.useRef)(a),P=(0,W.useRef)(null),[F,ne]=(0,W.useState)(!1),[I,L]=(0,W.useState)(a.length),[re,R]=(0,W.useState)(0),[z,B]=(0,W.useState)(null),[ie,V]=(0,W.useState)(null),{session:ae,error:oe,updatingId:se,authenticatingId:ce,setMode:ue,setConfigOption:de,setConfigOptions:fe,authenticate:pe}=cS(t,e,`${n}:${r||``}`);te.current=a;let me=u===`interrupt`,H=u===`disabled`,ge=(0,W.useMemo)(()=>pS(a,I),[a,I]),_e=(0,W.useMemo)(()=>{if(!ge)return[];let e=ge.query.toLowerCase();return(ae?.availableCommands||[]).filter(t=>{let n=t.name.toLowerCase();return ge.trigger===`$`&&!n.startsWith(`$`)?!1:(ge.trigger===`$`?n.slice(1):n).startsWith(e)||t.description.toLowerCase().includes(e)}).slice(0,12)},[ge,ae?.availableCommands]),ve=e&&F&&_e.length>0,ye=_e[re]||_e[0]||null;(0,W.useEffect)(()=>R(0),[ge?.query,ge?.trigger,_e.length]),(0,W.useEffect)(()=>{if(!z)return;let e=e=>{e.target instanceof Node&&P.current?.contains(e.target)||(B(null),V(null))};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[z]);let be=e=>{if(!ge)return;let t=`/${e} `,n=`${a.slice(0,ge.start)}${t}${a.slice(ge.end)}`,r=ge.start+t.length;B(null),te.current=n,v(n),window.requestAnimationFrame(()=>{d.current?.focus({preventScroll:!0}),d.current?.setSelectionRange(r,r),L(r)})},Ce=e=>{if(ve&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault();let t=e.key===`ArrowDown`?1:-1;R(e=>(e+t+_e.length)%_e.length);return}if(ve&&e.key===`Home`){e.preventDefault(),R(0);return}if(ve&&e.key===`End`){e.preventDefault(),R(_e.length-1);return}if(ve&&(e.key===`Enter`||e.key===`Tab`)&&ye){e.preventDefault(),e.stopPropagation(),be(ye.name);return}if(e.key===`ArrowUp`||e.key===`ArrowDown`){let t=e.key===`ArrowUp`?`previous`:`next`,n=y(t,{direction:t,value:e.currentTarget.value,selectionStart:e.currentTarget.selectionStart,selectionEnd:e.currentTarget.selectionEnd});if(n!==null){e.preventDefault(),e.stopPropagation(),window.requestAnimationFrame(()=>{let e=d.current;if(!e)return;let t=n.length;e.setSelectionRange(t,t)});return}}Yb(e,M.current,N.current)&&(e.preventDefault(),e.stopPropagation(),x(Xb(e.currentTarget.value,te.current)))},we=e=>{B(t=>t===e?null:e),V(null)},Te=oS(ae?.usage),Ee=Te||c,De=Te?.level||(Ee&&Ee.percentUsed>=100?`critical`:Ee&&Ee.percentUsed>=85?`warning`:`normal`),Oe=Ee?[`Context window: ${Ee.percentUsed}% used (${Ee.percentLeft}% left), ${fS(Ee.usedTokens)} / ${fS(Ee.limitTokens)} tokens used`,De===`critical`?`Context window is full`:De===`warning`?`Context window is nearly full`:``,Te?.costLabel?`Session cost: ${Te.costLabel}`:``].filter(Boolean).join(`. `):``,ke=ae?.errorKind===`authentication`||/\b(?:auth(?:entication)?|login|sign[ -]?in|unauthorized|401)\b/i.test(i);return(0,K.jsxs)(`footer`,{ref:P,className:`code-composer code-acp-composer ${z?`menu-open`:``} ${o.length>0?`has-attachments`:``} ${l&&e?`has-pending-followup`:``}`,"data-testid":`code-acp-composer`,children:[l&&e?(0,K.jsx)(`div`,{className:`code-pending-followup`,"data-testid":`code-acp-pending-followup`,children:l.messages.map(e=>(0,K.jsxs)(`div`,{className:`code-pending-followup-row`,"data-testid":`code-acp-pending-followup-row`,children:[(0,K.jsx)(`span`,{className:`code-pending-followup-icon`,"aria-hidden":`true`,children:(0,K.jsx)(xe,{})}),(0,K.jsx)(`p`,{children:e.text||e.attachments?.map(e=>e.name).join(`, `)}),(0,K.jsx)(`div`,{className:`code-pending-followup-actions`,children:(0,K.jsx)(`button`,{type:`button`,className:`icon`,"data-testid":`code-acp-pending-followup-discard`,"aria-label":j.discardQueuedMessage,onClick:()=>C(e.id),children:(0,K.jsx)(le,{})})})]},e.id))}):null,e?p.map(e=>(0,K.jsx)(zx,{request:e,onRespond:A,copy:j},e.requestId)):null,e?m.map(e=>(0,K.jsx)(Hx,{request:e,onRespond:ee},e.requestId)):null,e?h.map(e=>(0,K.jsx)(Hx,{request:e,onRespond:ee},`active-${e.elicitationId||e.requestId}`)):null,e&&ke?(0,K.jsx)(Gx,{agentId:t,methods:ae?.authMethods||[],authTerminal:ae?.authTerminal||null,agentName:ae?.agentInfo?.title||ae?.agentInfo?.name||``,authenticatingId:ce,onAuthenticate:e=>{pe(e)}}):null,e&&oe?(0,K.jsxs)(`section`,{className:`code-app-server-request code-app-server-notice`,"data-testid":`code-acp-error`,role:`alert`,children:[(0,K.jsxs)(`header`,{children:[(0,K.jsx)(`strong`,{children:`ACP`}),(0,K.jsx)(`span`,{children:n||`error`})]}),(0,K.jsx)(`p`,{children:oe})]}):null,ve?(0,K.jsxs)(`div`,{className:`code-slash-menu code-composer-menu`,"data-testid":`code-acp-command-menu`,role:`listbox`,"aria-label":`ACP commands`,children:[(0,K.jsx)(`div`,{className:`code-slash-menu-header`,children:ge?.trigger===`$`?`Skills`:`Agent commands`}),_e.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`code-slash-command ${t===re?`active`:``}`,"data-testid":`code-acp-command-${e.name}`,role:`option`,"aria-selected":t===re,onMouseDown:e=>e.preventDefault(),onMouseMove:()=>R(t),onClick:()=>be(e.name),children:[(0,K.jsx)(`span`,{className:`code-slash-command-icon`,"aria-hidden":`true`,children:`/`}),(0,K.jsxs)(`span`,{className:`code-slash-command-copy`,children:[(0,K.jsx)(`span`,{className:`code-slash-command-title`,children:(0,K.jsxs)(`code`,{children:[`/`,e.name]})}),(0,K.jsxs)(`small`,{children:[e.description,e.input?.hint?` · ${e.input.hint}`:``]})]})]},e.name))]}):null,(0,K.jsx)(`textarea`,{"data-testid":`code-acp-composer-input`,ref:d,name:`farming-acp-chat-message`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,value:a,placeholder:e?s===`goal`?j.describeAgentGoal:s===`plan`?j.describePlanFirst:j.askFollowUpChanges:j.openAgentTerminalFirst,disabled:!e,onFocus:e=>{ne(!0),L(e.currentTarget.selectionStart),B(null),V(null)},onBlur:()=>ne(!1),onClick:e=>L(e.currentTarget.selectionStart),onKeyUp:e=>L(e.currentTarget.selectionStart),onSelect:e=>L(e.currentTarget.selectionStart),onChange:e=>{L(e.currentTarget.selectionStart),v(e.currentTarget.value)},onPaste:T,onCompositionStart:()=>{M.current=!0},onCompositionEnd:e=>{M.current=!1,N.current=Date.now(),v(e.currentTarget.value)},onKeyDown:Ce,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`}),(0,K.jsx)(rx,{attachments:o,onRemove:b}),(0,K.jsx)(`input`,{ref:f,className:`code-composer-file-input`,"data-testid":`code-acp-composer-file-input`,type:`file`,multiple:!0,onChange:E}),(0,K.jsxs)(`div`,{className:`code-composer-toolbar`,"data-testid":`code-acp-composer-toolbar`,children:[(0,K.jsxs)(`div`,{className:`code-composer-left-tools`,"data-testid":`code-acp-composer-left-tools`,children:[(0,K.jsxs)(`div`,{className:`code-composer-menu-anchor`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-composer-add`,"data-testid":`code-acp-composer-add`,"aria-label":j.addContext,"aria-haspopup":`menu`,"aria-expanded":z===`commands`,disabled:!e,onClick:()=>we(`commands`),children:(0,K.jsx)(Se,{})}),z===`commands`?(0,K.jsxs)(`div`,{className:`code-plus-menu code-composer-menu`,role:`menu`,"data-testid":`code-acp-plus-menu`,children:[(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-attach-file`,onClick:()=>{B(null),D()},children:[(0,K.jsx)(`span`,{children:j.attachFile}),(0,K.jsx)(`small`,{children:j.fileContext})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-goal-mode`,onClick:()=>{B(null),O(`goal`)},children:[(0,K.jsx)(`span`,{children:j.goalMode}),(0,K.jsx)(`small`,{children:j.setObjective})]}),(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-acp-composer-plan-mode`,onClick:()=>{B(null),O(`plan`)},children:[(0,K.jsx)(`span`,{children:j.planMode}),(0,K.jsx)(`small`,{children:j.planFirst})]})]}):null]}),s===`default`?null:(0,K.jsxs)(`button`,{type:`button`,className:`code-composer-mode-chip`,"data-testid":`code-acp-composer-mode-chip`,"aria-label":j.clearComposerMode,onClick:k,children:[(0,K.jsx)(`span`,{children:s===`goal`?j.goalMode:j.planMode}),(0,K.jsx)(`span`,{"aria-hidden":`true`,children:(0,K.jsx)(le,{})})]}),ae?(0,K.jsx)(iS,{session:ae,updatingId:se,copy:j,open:z===`mode`,onToggle:()=>we(`mode`),onSetMode:e=>{B(null),ue(e)},onSetConfigOption:(e,t)=>{B(null),de(e,t)}}):null]}),(0,K.jsxs)(`div`,{className:`code-composer-right-tools`,"data-testid":`code-acp-composer-right-tools`,children:[Ee?(0,K.jsxs)(`div`,{className:`code-composer-context-window`,"data-testid":`code-acp-context-window`,"data-level":De,tabIndex:0,role:`img`,"aria-label":Oe,children:[(0,K.jsx)(`span`,{className:`code-context-window-ring`,"aria-hidden":`true`,style:{"--context-percent":Ee.percentUsed}}),(0,K.jsxs)(`div`,{className:`code-context-window-popover`,role:`tooltip`,children:[(0,K.jsx)(`span`,{children:`Context window:`}),(0,K.jsxs)(`strong`,{children:[Ee.percentUsed,`% used (`,Ee.percentLeft,`% left)`]}),(0,K.jsxs)(`strong`,{children:[fS(Ee.usedTokens),` / `,fS(Ee.limitTokens),` tokens used`]}),De===`critical`?(0,K.jsx)(`strong`,{className:`warning`,children:`Context window is full`}):null,De===`warning`?(0,K.jsx)(`strong`,{className:`warning`,children:`Context window is nearly full`}):null,Te?.costLabel?(0,K.jsx)(`strong`,{children:Te.costLabel}):null]})]}):null,ae?(0,K.jsx)(aS,{session:ae,updatingId:se,copy:j,open:z===`model`,pane:ie,onToggle:()=>we(`model`),onSetPane:V,onSetConfigOption:(e,t)=>{B(null),V(null),de(e,t)},onSetProfile:(e,t,n,r)=>{fe([{configId:e,value:t},{configId:n,value:r}])},onSetFast:(e,t)=>{de(e,t)}}):null,g?(0,K.jsx)(`button`,{type:`button`,className:`code-composer-mic ${_?`listening`:``}`,"data-testid":`code-acp-composer-mic`,"aria-label":_?j.stopDictation:j.startDictation,"aria-pressed":_,onClick:w,disabled:!e,title:_?j.stopDictation:j.startDictation,children:(0,K.jsx)(dS,{listening:_})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-composer-send ${me?`interrupt`:``}`,"data-testid":`code-acp-composer-send`,"data-action":u,"aria-label":me?j.interruptAgent:j.sendMessage,onClick:me?S:()=>x(te.current),disabled:H,children:me?(0,K.jsx)(`span`,{className:`code-composer-stop-icon`,"aria-hidden":`true`}):(0,K.jsx)(he,{})})]})]})]})}function hS(e){return!!e&&e?.providerSessionProvider===`codex`&&e?.codexRuntimeMode===`app-server`&&!!(e?.codexAppServerThreadId||e?.providerSessionId)}function gS(e){return e?.status===`active`?`paused`:`active`}async function _S(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error||`${e.status}`);return t}function vS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M11.6 1.65a1.55 1.55 0 0 1 2.19 2.19l-8.4 8.4-3.14.64.64-3.14 8.71-8.09Zm-.7 2.11-7.08 7.08-.22 1.08 1.08-.22 7.08-7.08-.86-.86Zm1.56-1.4-.86.86.86.86.62-.62a.55.55 0 0 0-.78-.78l-.84.84Z`})})}function yS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M4.5 3.4c0-.67.73-1.08 1.3-.72l6.1 3.78a.85.85 0 0 1 0 1.44l-6.1 3.78a.85.85 0 0 1-1.3-.72V3.4Z`})})}function bS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M4.25 3.25c0-.41.34-.75.75-.75h1c.41 0 .75.34.75.75v9.5c0 .41-.34.75-.75.75H5a.75.75 0 0 1-.75-.75v-9.5Zm5 0c0-.41.34-.75.75-.75h1c.41 0 .75.34.75.75v9.5c0 .41-.34.75-.75.75h-1a.75.75 0 0 1-.75-.75v-9.5Z`})})}function xS(){return(0,K.jsx)(`svg`,{width:`15`,height:`15`,viewBox:`0 0 16 16`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M6.25 2h3.5l.5 1H13v1H3V3h2.75l.5-1ZM4.2 5h7.6l-.48 8.1A1 1 0 0 1 10.32 14H5.68a1 1 0 0 1-1-.9L4.2 5Zm2.05 1 .35 7h.95L7.2 6h-.95Zm2.2 0v7h.95V6h-.95Z`})})}function SS({agent:e,active:t,copy:r}){let i=hS(e),a=e?.id||``,o=(0,W.useRef)(null),[s,c]=(0,W.useState)(e?.codexAppServerGoal||null),[l,u]=(0,W.useState)(s?.objective||``),[d,f]=(0,W.useState)(!1),[p,m]=(0,W.useState)(!1),[h,g]=(0,W.useState)(``);(0,W.useEffect)(()=>{c(e?.codexAppServerGoal||null)},[e?.codexAppServerGoal]),(0,W.useEffect)(()=>{f(!1),g(``)},[a]),(0,W.useEffect)(()=>{d||u(s?.objective||``)},[d,s]),(0,W.useEffect)(()=>{d&&o.current?.focus({preventScroll:!0})},[d]),(0,W.useEffect)(()=>{if(!t||!i||!a)return;let e=new AbortController;return fetch(n(`/api/agents/${encodeURIComponent(a)}/codex-goal`),{signal:e.signal}).then(_S).then(e=>{c(e.goal||null),g(``)}).catch(e=>{e?.name!==`AbortError`&&g(e?.message||r.codexTranscriptUnavailable)}),()=>e.abort()},[t,a,i,r.codexTranscriptUnavailable]);let _=(0,W.useCallback)(e=>{!i||!a||p||(m(!0),g(``),fetch(n(`/api/agents/${encodeURIComponent(a)}/codex-goal`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}).then(_S).then(e=>{c(e.goal||null),f(!1),g(``)}).catch(e=>{g(e?.message||r.codexTranscriptUnavailable)}).finally(()=>m(!1)))},[a,r.codexTranscriptUnavailable,i,p]),v=(0,W.useCallback)(()=>{let e=l.trim();if(!e){g(r.codexGoalObjective);return}_({objective:e,status:s?.status||`active`})},[r.codexGoalObjective,s?.status,l,_]),y=(0,W.useCallback)(()=>{if(!s){f(!0);return}_({status:gS(s)})},[s,_]),b=(0,W.useCallback)(()=>{!i||!a||p||!s||(m(!0),g(``),fetch(n(`/api/agents/${encodeURIComponent(a)}/codex-goal`),{method:`DELETE`}).then(_S).then(()=>{c(null),u(``),f(!1),g(``)}).catch(e=>{g(e?.message||r.codexTranscriptUnavailable)}).finally(()=>m(!1)))},[a,r.codexTranscriptUnavailable,s,i,p]);if(!e||e.providerSessionProvider!==`codex`||!s&&!d)return null;let x=s?.status===`active`,S=!i||p;return(0,K.jsxs)(`section`,{className:`code-codex-goal-bar`,"data-testid":`code-codex-goal-bar`,children:[(0,K.jsx)(`textarea`,{ref:o,className:`code-codex-goal-input`,"data-testid":`code-codex-goal-input`,rows:1,value:l,placeholder:r.codexGoalEmpty,readOnly:!d,disabled:!i||p,"aria-label":r.codexGoalObjective,onChange:e=>u(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&v(),e.key===`Escape`&&(u(s?.objective||``),f(!1),g(``))}}),(0,K.jsxs)(`div`,{className:`code-codex-goal-icon-actions`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button`,"data-testid":`code-codex-goal-edit`,disabled:S,title:d?r.codexGoalSave:r.codexGoalEdit,"aria-label":d?r.codexGoalSave:r.codexGoalEdit,onClick:d?v:()=>f(!0),children:d?(0,K.jsx)(me,{}):(0,K.jsx)(vS,{})}),d?(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button`,"data-testid":`code-codex-goal-cancel`,disabled:p,title:r.cancel,"aria-label":r.cancel,onClick:()=>{u(s?.objective||``),f(!1),g(``)},children:(0,K.jsx)(le,{})}):null,(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button`,"data-testid":`code-codex-goal-toggle`,disabled:S||!s&&!l.trim(),title:x?r.codexGoalStop:r.codexGoalStart,"aria-label":x?r.codexGoalStop:r.codexGoalStart,onClick:y,children:x?(0,K.jsx)(bS,{}):(0,K.jsx)(yS,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-codex-goal-icon-button danger`,"data-testid":`code-codex-goal-delete`,disabled:S||!s,title:r.codexGoalDelete,"aria-label":r.codexGoalDelete,onClick:b,children:(0,K.jsx)(xS,{})})]}),h?(0,K.jsx)(`div`,{className:`code-codex-goal-error`,children:h}):null]})}var CS=`farming.codex.sessionDisplayState.v1`,wS=50,TS=`tmp_uuid`;function ES(){return{promotedKeys:[],pinnedOverrides:{},archivedOverrides:{}}}function DS(){if(typeof window>`u`)return ES();try{let e=JSON.parse(window.localStorage.getItem(`farming.codex.sessionDisplayState.v1`)||`{}`),t=Array.isArray(e.promotedKeys)?e.promotedKeys.filter(e=>typeof e==`string`&&e.length>0):[],n={};e.pinnedOverrides&&typeof e.pinnedOverrides==`object`&&Object.entries(e.pinnedOverrides).forEach(([e,t])=>{typeof t==`boolean`&&(n[e]=t)});let r={};return e.archivedOverrides&&typeof e.archivedOverrides==`object`&&Object.entries(e.archivedOverrides).forEach(([e,t])=>{typeof t==`boolean`&&(r[e]=t)}),{promotedKeys:t,pinnedOverrides:n,archivedOverrides:r}}catch{return ES()}}function OS(e){typeof window>`u`||window.localStorage.setItem(CS,JSON.stringify(e))}function kS(e=[]){let t=[],n=new Set;return e.forEach(e=>{let r=typeof e==`string`?e.trim():``;if(!/^agent-session:[a-z][a-z0-9_-]*:.+$/i.test(r))return;let i=r.replace(/^agent-session:[^:]+:/i,``);i.startsWith(`-`)||i.startsWith(TS)||n.has(r)||(n.add(r),t.push(r))}),t.slice(0,wS)}function AS(e,t,n){return e.map(e=>{let r=Rb(e),i=r in t,a=r in n;if(!i&&!a)return e;let o=a?n[r]:e.archived;return{...e,pinned:o?!1:i?t[r]:e.pinned,archived:o}})}function jS(e,t,n=``){return n&&n!==`default`?`${e}-history:home:${n}:${t}`:`${e}-history:${t}`}function MS(e){let t=/^([a-z]+)-history(?:-fork)?:(?:(?:home:([A-Za-z0-9._-]+):)?(.+))$/.exec(e||``);if(!t)return null;let n=t[1],r=t[2]||`default`,i=t[3];return n&&i?{provider:n,providerHomeId:r,sessionId:i}:null}function NS(e){let t=MS(e);return t?Rb({provider:t.provider,id:t.sessionId,providerHomeId:t.providerHomeId}):``}function PS(e,t,n){return e.map(e=>{if(n||t.has(e.id)||e.agentSessions.length<=5)return{...e,hiddenAgentSessionCount:0,agentSessionsExpanded:t.has(e.id)};let r=e.agentSessions.filter(e=>e.pinned||e.unread),i=new Set(r.map(Rb)),a=e.agentSessions.filter(e=>!i.has(Rb(e))),o=Math.max(0,5-r.length),s=a.slice(0,o),c=a.length-s.length;return{...e,agentSessions:[...r,...s],hiddenAgentSessionCount:c,agentSessionsExpanded:!1}})}var FS=150;function IS(e){let t=String(e||``).trim().toLowerCase();return t===`codex`||t===`claude`||t===`qoder`?t:``}function LS(e){let t=MS(e);if(!t)return null;let n=IS(t.provider),r=String(t.sessionId||``).trim();return n&&r?{...t,provider:n,sessionId:r}:null}function RS(e){return e.title||e.task||e.command||`History agent`}function zS(e){return e.projectWorkspace||e.cwd||``}function BS(...e){return e.map(e=>String(e||``).trim()).filter(Boolean).join(` · `)}function VS(e){return BS(ot(zS(e)))}function HS(e){return BS(e.providerSessionProvider||e.engineName,ot(Ab(e)))}function US(e){return BS(e.providerName||e.provider,e.model,e.effort?Nb(e.effort):``,zb(e))}function WS(e){return Math.max(e.archivedAt||0,e.lastActivity||0,e.startedAt||0)}function GS(e){return Math.max(e.archivedAt||0,e.lastActivity||0,e.startedAt||0)}function KS(e){if(e.kind===`session`){let t=IS(e.session.provider),n=String(e.session.id||``).trim();return t&&n?{provider:t,sessionId:n,providerHomeId:e.session.providerHomeId||`default`}:null}if(e.kind===`agent`){let t=IS(e.agent.providerSessionProvider),n=String(e.agent.providerSessionId||``).trim();return t&&n&&e.agent.providerSessionTemporary!==!0?{provider:t,sessionId:n,providerHomeId:e.agent.providerHomeId||`default`}:LS(e.agent.source)}return LS(e.entry.source)}function qS(e){let t=KS(e);return t?`resume:${t.provider}:${t.providerHomeId||`default`}:${t.sessionId}`:``}function JS(e){return e.kind===`session`?30:e.kind===`agent`?20:10}function YS(e,t){return t.updatedAt===e.updatedAt?JS(t)>JS(e):t.updatedAt>e.updatedAt}function XS(e){if(e.kind!==`session`)return``;let t=String(e.session.title||``).trim().toLocaleLowerCase(),n=String(zb(e.session)||``).trim().toLocaleLowerCase(),r=IS(e.session.provider),i=String(e.session.providerHomeId||`default`).trim().toLocaleLowerCase();return t.length>4&&n?`${r}:${i}:${n}:${t}`:``}function ZS(e){let t=[],n=new Map;e.forEach(e=>{let r=qS(e);if(!r){t.push(e);return}let i=n.get(r);(!i||YS(i,e))&&n.set(r,e)});let r=[...t,...n.values()],i=new Map;return r.filter(e=>{let t=XS(e);if(!t)return!0;let n=i.get(t);return!n||YS(n,e)?(i.set(t,e),!0):!1}).filter(e=>{let t=XS(e);return!t||i.get(t)===e}).sort((e,t)=>t.updatedAt-e.updatedAt)}function QS(e,t,n){return ZS([...e.map(e=>({kind:`run`,historyKey:`run:${e.id}`,updatedAt:WS(e),entry:e})),...t.map(e=>({kind:`agent`,historyKey:`agent:${e.id}`,updatedAt:GS(e),agent:e})),...n.map(e=>({kind:`session`,historyKey:Rb(e),updatedAt:Wb(e),session:e}))])}function $S(e,t){let n=new Map(e.map(e=>[Rb(e),e]));return t.forEach(e=>n.set(Rb(e),e)),Array.from(n.values())}function eC(e){return String(e||``).normalize(`NFKC`).toLocaleLowerCase()}function tC(e,t){let n=eC(t).trim();return n?e.filter(e=>e.kind===`run`?eC([RS(e.entry),VS(e.entry),e.entry.command,e.entry.task].join(`
112
112
  `)).includes(n):e.kind===`agent`?eC([h(e.agent),HS(e.agent),e.agent.command].join(`
113
113
  `)).includes(n):eC([e.session.title,US(e.session),e.session.provider].join(`
114
- `)).includes(n)):e}function nC({archivedRuns:e,archivedAgents:t,agentSessions:n,now:r,onResumeSession:i,onContinueRun:a,onOpenArchivedAgent:o,onRestoreArchivedAgent:c,searchAgentSessions:l,copy:u}){let[d,f]=(0,W.useState)(``),p=d.trim(),m=!!p,[g,_]=(0,W.useState)({query:``,sessions:[],loading:!1}),v=g.query===p?g.sessions:[],y=QS(e,t,m?$S(n,v):n),b=tC(y,p),x=y.length,S=m&&(g.query!==p||g.loading);return(0,W.useEffect)(()=>{if(!p){_({query:``,sessions:[],loading:!1});return}let e=new AbortController;_({query:p,sessions:[],loading:!0});let t=window.setTimeout(()=>{l(p,e.signal).then(t=>{e.signal.aborted||_({query:p,sessions:t,loading:!1})}).catch(t=>{t instanceof DOMException&&t.name===`AbortError`||e.signal.aborted||_({query:p,sessions:[],loading:!1})})},FS);return()=>{window.clearTimeout(t),e.abort()}},[p,l]),(0,K.jsxs)(`div`,{className:`code-history-panel`,"data-testid":`code-history-panel`,children:[(0,K.jsxs)(`div`,{className:`code-history-panel-header`,children:[(0,K.jsx)(`h2`,{children:u.history}),(0,K.jsxs)(`div`,{className:`code-search-panel-input code-history-search`,"data-testid":`code-history-search-box`,children:[(0,K.jsx)(`span`,{className:`code-search-panel-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ie,{})}),(0,K.jsx)(`input`,{type:`text`,role:`searchbox`,inputMode:`search`,value:d,onChange:e=>f(e.currentTarget.value),placeholder:u.searchHistory,"aria-label":u.searchHistory,autoComplete:`off`,spellCheck:!1}),d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>f(``),"aria-label":u.clearSearch,children:(0,K.jsx)(le,{})})]})]}),x===0?(0,K.jsxs)(`div`,{className:`code-empty-workspace`,children:[(0,K.jsx)(`h2`,{children:u.noHistoryYet}),(0,K.jsx)(`p`,{children:u.noHistoryDescription})]}):m&&S&&b.length===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-history-search-loading`,children:(0,K.jsx)(`h2`,{children:u.searching})}):m&&b.length===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-history-search`,children:(0,K.jsx)(`h2`,{children:u.noMatchingAgents})}):(0,K.jsx)(`div`,{className:`code-history-list`,children:(0,K.jsx)(`section`,{className:`code-history-section`,"data-testid":`code-history-agents`,children:b.map(e=>{if(e.kind===`run`){let{entry:t}=e;return(0,K.jsxs)(`article`,{className:`code-history-card archived`,"data-testid":`code-archived-run-card`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:RS(t)}),(0,K.jsx)(`p`,{children:VS(t)})]}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:s(e.updatedAt,r)}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-run-continue`,onClick:()=>a(t),"aria-label":u.continueRun,title:u.continueRun,children:(0,K.jsx)(pe,{})})]})]},e.historyKey)}if(e.kind===`agent`){let{agent:t}=e;return(0,K.jsxs)(`article`,{className:`code-history-card archived`,"data-testid":`code-archived-agent-card`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:h(t)}),(0,K.jsx)(`p`,{children:HS(t)})]}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:s(e.updatedAt,r)}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-agent-open`,onClick:()=>o(t.id),"aria-label":u.open,title:u.open,children:(0,K.jsx)(ae,{})}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-agent-restore`,onClick:()=>c(t.id),"aria-label":u.restore,title:u.restore,children:(0,K.jsx)(pe,{})})]})]},e.historyKey)}let{session:t}=e,n=t.title||u.sessionFallbackTitle(t.providerName);return(0,K.jsxs)(`article`,{className:`code-history-card code-session`,"data-testid":`code-session-history-card`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:n}),(0,K.jsx)(`p`,{children:US(t)})]}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:s(e.updatedAt,r)}),(0,K.jsx)(`button`,{type:`button`,"aria-label":u.resumeSessionAria(n),title:u.restore,onClick:()=>i(t.provider,t.id,t.providerHomeId),children:(0,K.jsx)(pe,{})})]})]},e.historyKey)})})})]})}var rC={plusMenu:!1,permissionMode:!1,modelPicker:!1,reasoningEffort:!1,serviceTier:!1,speechInput:!0},iC={plusMenu:!0,permissionMode:!0,modelPicker:!0,reasoningEffort:!0,serviceTier:!1,speechInput:!0},aC=[{command:`/goal`,label:`Goal`,description:`Set or update what this Codex session should keep working toward`,source:`codex`},{command:`/plan`,label:`Plan mode`,description:`Ask Codex to plan first before editing`,source:`codex`},{command:`/skills`,label:`Skills`,description:`Browse and use available Codex skills`,source:`codex`},{command:`/permissions`,label:`Permissions`,description:`Change what Codex can do without asking first`,source:`codex`},{command:`/model`,label:`Model`,description:`Change or inspect the active Codex model`,source:`codex`},{command:`/reasoning`,label:`Reasoning`,description:`Change the reasoning effort for this session`,source:`codex`},{command:`/mcp`,label:`MCP`,description:`Show MCP server status`,source:`codex`},{command:`/fast`,label:`Fast`,description:`Toggle Codex fast mode when available`,source:`codex`},{command:`/status`,label:`Status`,description:`Inspect the session, model, permissions, and token usage`,source:`codex`},{command:`/usage`,label:`Usage`,description:`View account token usage from Codex`,source:`codex`},{command:`/compact`,label:`Compact`,description:`Summarize long context to free tokens`,source:`codex`},{command:`/review`,label:`Review`,description:`Ask Codex to review the current working tree`,source:`codex`},{command:`/personality`,label:`Personality`,description:`Choose how Codex communicates in this session`,source:`codex`},{command:`/help`,label:`Help`,description:`Show available Codex slash commands`,source:`codex`}],oC=[{command:`/help`,label:`Help`,description:`Show available Claude Code slash commands`,source:`claude`},{command:`/model`,label:`Model`,description:`Change or inspect the active Claude model`,source:`claude`},{command:`/permissions`,label:`Permissions`,description:`Review or change Claude Code permission behavior`,source:`claude`},{command:`/cost`,label:`Cost`,description:`Show Claude Code usage for the current conversation`,source:`claude`},{command:`/compact`,label:`Compact`,description:`Compact the current Claude Code conversation`,source:`claude`},{command:`/clear`,label:`Clear`,description:`Clear the current Claude Code conversation`,source:`claude`},{command:`/config`,label:`Config`,description:`Open Claude Code configuration`,source:`claude`},{command:`/doctor`,label:`Doctor`,description:`Check Claude Code installation and account health`,source:`claude`},{command:`/memory`,label:`Memory`,description:`Edit or inspect Claude Code memory`,source:`claude`}];function sC(e){return e===`codex`?aC:e===`claude`?oC:[]}function cC(e){let t=new Set;return e.filter(e=>{let n=e.command.trim().toLowerCase();return!n||t.has(n)?!1:(t.add(n),!0)})}function lC(e){let t=bb(e).kind;return{kind:t,composer:t===`codex`?{...iC,serviceTier:!0}:t===`claude`?{...iC}:{...rC},actions:{pin:!!e,rename:!!e,archive:!!(e&&!e.isMain),markUnread:!!e,copyWorkingDirectory:!!e,forkSameWorktree:!!e,forkNewWorktree:e?.canForkNewWorktree===!0,kill:!!(e&&e.isMain)}}}function uC(e){return!!(e&&(e.agents.some(e=>!e.isMain)||e.agentSessions.length>0))}function dC(e){let t=lC(e),n=[t.actions.pin,t.actions.rename,t.actions.archive,t.actions.markUnread,t.actions.copyWorkingDirectory,t.actions.forkSameWorktree,t.actions.forkNewWorktree,t.actions.kill].filter(Boolean).length;return{itemCount:n,separatorCount:n>0?2:0}}function fC(e){return e.kind===`agent`?e.claimedSessionKey||`agent:${e.agent.id}`:Rb(e.session)}function pC(e){return!!e.parentAgentId&&e.source===`ui-fork-new-worktree`}function mC(e,t){return t||e===`pending`||e===`stopped`||e===`dead`}function hC(e){let t=e.replace(/\s+/g,` `).trim();return t.length>160?`${t.slice(0,157)}...`:t}function gC(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function _C(e){if(e===null||e<0)return``;let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}h ${i}m`:`${r}h`}function vC(e,t,n){let r=hC(e.terminalStatus?.runningCommand||e.shellCommand||``);if(r&&t){let t=gC(e.terminalStatus?.runningCommandStartedAt)??gC(e.shellCommandStartedAt),i=t===null?``:_C(n-t);return i?`Running ${i}: ${r}`:`Running: ${r}`}let i=hC(e.terminalStatus?.lastCommand||e.shellLastCommand||``);if(!i)return``;let a=e.terminalStatus?.lastExitCode,o=[_C(gC(e.terminalStatus?.lastCommandDurationMs)??gC(e.shellLastCommandDurationMs)),typeof a==`number`?`exit ${a}`:``].filter(Boolean).join(`, `);return o?`Last command: ${i} (${o})`:`Last command: ${i}`}function yC(e,t){let n=bb(e).turnActive,r=h(e),i=vC(e,n,t);return{kind:`agent`,title:r,rowTitle:[r,i,e.cwd].filter(Boolean).join(` · `),commandTitle:i,lifecycleStatus:e.status,turnActive:n,statusIndicatorVisible:mC(e.status,n),pinned:e.pinned===!0,unread:e.unread===!0,forkedToNewWorktree:pC(e),requiresResume:!1,scheduled:!1,scheduleTitle:``}}function bC(e,t){let n=e.schedule?.label||e.schedule?.name||e.schedule?.rrule||``;return{kind:`history`,title:e.title||t,rowTitle:[e.title||t,e.cwd||e.workspace].filter(Boolean).join(` · `),commandTitle:``,turnActive:!1,statusIndicatorVisible:!1,pinned:e.pinned===!0,unread:e.unread===!0,forkedToNewWorktree:!1,requiresResume:!0,scheduled:!!e.schedule,scheduleTitle:n}}function xC(e,t=Date.now()){return e.kind===`agent`?yC(e.agent,t):bC(e.session,e.fallbackTitle)}function SC({query:e,displayedProjects:t,hasQuery:n,loading:r,resultCount:i,selectedAgentId:a,selectedSessionHandle:o,inputRef:s,onQueryChange:c,onKeyDown:l,onClearSearch:u,onOpenAgent:d,onOpenSession:f,copy:p}){return(0,W.useEffect)(()=>{let e=s.current;e&&window.requestAnimationFrame(()=>{e.focus({preventScroll:!0})})},[s]),(0,K.jsxs)(`div`,{className:`code-search-panel`,"data-testid":`code-search-panel`,children:[(0,K.jsxs)(`div`,{className:`code-search-panel-header`,children:[(0,K.jsx)(`h2`,{children:p.search}),n?(0,K.jsx)(`span`,{children:p.resultsCount(i)}):null]}),(0,K.jsxs)(`div`,{className:`code-search-panel-input`,"data-testid":`code-search-box`,children:[(0,K.jsx)(`span`,{className:`code-search-panel-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ie,{})}),(0,K.jsx)(`input`,{ref:s,type:`text`,role:`searchbox`,name:`farming-workspace-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`search`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:e,onChange:e=>c(e.currentTarget.value),onKeyDown:l,placeholder:p.searchProjectsOrAgents,"aria-label":p.searchProjectsOrAgents}),e&&(0,K.jsx)(`button`,{type:`button`,onClick:u,"aria-label":p.clearSearch,children:(0,K.jsx)(le,{})})]}),n&&r&&i===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-search-loading`,children:(0,K.jsx)(`h2`,{children:p.searching})}):n&&i===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-search`,children:(0,K.jsx)(`h2`,{children:p.noMatchingAgents})}):n?(0,K.jsx)(`div`,{className:`code-search-results`,children:t.map(e=>(0,K.jsxs)(`section`,{className:`code-search-result-group`,children:[(0,K.jsx)(`h3`,{children:e.name}),e.agents.map(e=>(0,K.jsx)(CC,{agent:e,selected:e.id===a,onOpen:()=>d(e.id)},e.id)),e.agentSessions.map(e=>{let t=Rb(e);return(0,K.jsx)(`button`,{type:`button`,className:`code-search-result code-session-result ${t===o?`active`:``}`,"data-testid":`code-session-search-result`,onClick:()=>f(e),children:(0,K.jsxs)(`span`,{className:`code-search-result-copy`,children:[(0,K.jsx)(`strong`,{children:e.title||p.sessionFallbackTitle(e.providerName)}),(0,K.jsx)(`span`,{children:zb(e)})]})},t)})]},e.id))}):null]})}function CC({agent:e,selected:t,onOpen:n}){let r=xC({kind:`agent`,agent:e});return(0,K.jsxs)(`button`,{type:`button`,className:`code-search-result ${r.statusIndicatorVisible?``:`no-status`} ${t?`active`:``}`,"data-testid":`code-search-result`,title:r.rowTitle||r.title,onClick:n,children:[r.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${r.lifecycleStatus} ${r.turnActive?`turn-active`:``}`}),(0,K.jsxs)(`span`,{className:`code-search-result-copy`,children:[(0,K.jsx)(`strong`,{children:r.title}),(0,K.jsx)(`span`,{children:Mb(Ab(e))})]})]})}var wC=`farming.code.fileEditor.chunk-recovery`;function TC(){if(typeof window>`u`)return!1;try{return window.sessionStorage.getItem(wC)===`1`?!1:(window.sessionStorage.setItem(wC,`1`),window.location.reload(),!0)}catch{return!1}}function EC(){return o(()=>import(`./FileEditorPane-RWiFD2cq.js`).then(e=>{try{window.sessionStorage.removeItem(wC)}catch{}return{default:e.FileEditorPane}}),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).catch(e=>{if(TC())return new Promise(()=>{});throw e})}var DC=(0,W.lazy)(()=>EC());function OC(e){return e.split(`/`).filter(Boolean).pop()||e}function kC(e){return e.split(`/`).filter(Boolean)}function AC({openFile:e,onChangeDraft:t,copy:n}){let r=kC(e.file.path);return(0,K.jsxs)(`section`,{className:`code-file-editor fallback`,"data-testid":`code-file-editor`,"aria-label":n.editorFor(e.file.path),children:[(0,K.jsxs)(`header`,{className:`code-file-editor-header`,children:[(0,K.jsx)(`div`,{className:`code-file-editor-tabs`,role:`tablist`,children:(0,K.jsxs)(`div`,{className:`code-file-editor-tab active ${e.dirty?`dirty`:``} ${e.externalChanged?`warning`:``}`,title:e.file.path,role:`tab`,"aria-selected":`true`,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`code-file-editor-tab-name`,children:OC(e.file.path)}),(0,K.jsx)(`span`,{className:`code-file-editor-tab-tail`,children:(e.dirty||e.externalChanged)&&(0,K.jsx)(`span`,{className:`code-file-editor-dirty`,title:e.externalChanged?n.changedOnDisk:n.unsavedChanges})})]})}),(0,K.jsxs)(`div`,{className:`code-file-editor-bar`,children:[(0,K.jsx)(`nav`,{className:`code-file-editor-breadcrumbs`,title:e.file.path,"aria-label":n.filePath,children:r.map((e,t)=>(0,K.jsxs)(`span`,{className:`code-file-editor-breadcrumb ${t===r.length-1?`current`:``}`,children:[(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-name`,children:e}),t<r.length-1&&(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-separator`,"aria-hidden":`true`})]},`${t}-${e}`))}),(0,K.jsx)(`div`,{className:`code-file-editor-actions`,children:e.dirty&&(0,K.jsx)(`span`,{className:`code-file-editor-status`,children:n.unsavedChanges})})]})]}),(0,K.jsx)(`textarea`,{className:`code-file-editor-fallback-textarea`,"data-testid":`code-file-editor-fallback-textarea`,name:`farming-file-editor-fallback`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:e.draft,onChange:e=>t(e.currentTarget.value),spellCheck:!1,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,"aria-label":n.editorFor(e.file.path)}),(0,K.jsx)(`footer`,{className:`code-file-editor-statusbar`,children:(0,K.jsx)(`span`,{className:`code-file-editor-cursor-position`,children:n.cursorPosition(1,1)})})]})}function jC(e,t){return t===`search`?e.search:t===`history`?e.history:`Farming`}function MC({activeView:e,showFileEditor:t,openWorkspaceFile:n,openWorkspaceFiles:r,openAgentsCount:i,visibleOpenAgents:a,activeTerminalId:o,permissionSwitchingAgentId:s,agentSwitchingKind:c,terminalFocusRequest:l,agentCreationWorkspace:u,displayedProjects:d,searchQuery:f,searchHasQuery:p,searchLoading:m,visibleSearchTargetCount:h,selectedSearchAgentId:g,selectedSearchSessionHandle:_,searchInputRef:v,archivedRuns:y,archivedAgents:b,historyAgentSessions:x,canLoadMoreHistoryAgentSessions:S,now:C,composerProps:w,acpComposerProps:T,onNewAgent:E,onOpenTerminal:D,onOpenTerminalPath:O,onResolveTerminalPath:k,onTerminalFollowOutputChange:ee,onAgentReadLatest:te,onRuntimeModeChange:A,sendInput:j,resizeAgent:M,onSessionOutput:N,onOpenSearchAgent:P,onOpenSearchSession:F,onSearchQueryChange:ne,onSearchKeyDown:I,onCloseSearch:R,onLoadMoreHistoryAgentSessions:z,onSearchHistoryAgentSessions:re,onResumeHistorySession:B,onContinueArchivedRun:ie,onOpenArchivedAgent:V,onRestoreArchivedAgent:ae,onChangeWorkspaceFileDraft:oe,onUpdateOpenWorkspaceFile:se,onSelectOpenWorkspaceFile:ce,onOpenWorkspaceFilePath:le,canNavigateWorkspaceBack:ue,canNavigateWorkspaceForward:de,onNavigateWorkspaceHistory:fe,onCloseOpenWorkspaceFile:pe,onCloseOpenWorkspaceFiles:me,onRevealWorkspaceFileInExplorer:H,onFocusWorkspaceFilesSearch:he,onRecordWorkspaceNavigationCursor:_e,onBackToAgentFromFile:ye,copy:be}){let[xe,Se]=(0,W.useState)(!1),[Ce,we]=(0,W.useState)(!1),Te=(0,W.useCallback)(e=>{S&&e.scrollHeight-e.scrollTop-e.clientHeight<=320&&z()},[S,z]),Ee=o&&a.find(e=>e.id===o)||null,De=Ee?.agentRuntimeMode===`acp`,Oe=[`acp`,`json`].includes(Ee?.agentRuntimeMode||``)||Ee?.providerSessionProvider===`codex`&&Ee.codexRuntimeMode===`app-server`?`transcript`:`terminal`,ke=Ce&&e===`projects`&&!t&&i>0&&Oe===`terminal`,Ae=ke&&xe;(0,W.useEffect)(()=>{let e=window.matchMedia(`(hover: hover) and (pointer: fine)`),t=()=>we(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,W.useEffect)(()=>{!ke&&xe&&Se(!1)},[ke,xe]);let U=(0,W.useCallback)(e=>{if(!L())return;let t=e.target;if(t instanceof Element&&t.closest(`.code-composer`))return;let n=document.activeElement;n instanceof HTMLElement&&n.closest(`.code-composer`)&&(n instanceof HTMLTextAreaElement||n.isContentEditable||n.getAttribute(`role`)===`textbox`)&&n.blur()},[]);return(0,K.jsx)(`main`,{className:`code-main`,"data-testid":`code-main`,onPointerDownCapture:U,onTouchStartCapture:U,children:e===`projects`?t&&n?(0,K.jsx)(W.Suspense,{fallback:(0,K.jsx)(AC,{openFile:n,onChangeDraft:oe,copy:be}),children:(0,K.jsx)(DC,{openFile:n,openFiles:r,onChangeDraft:oe,onUpdateOpenFile:se,onSelectOpenFile:ce,onOpenFilePath:le,canNavigateBack:ue,canNavigateForward:de,onNavigateHistory:fe,onCloseOpenFile:pe,onCloseOpenFiles:me,onRevealInExplorer:H,onFocusFilesSearch:he,onRecordNavigationCursor:_e,onBackToAgent:ye,copy:be})}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-terminal-grid panes-1`,"data-testid":`code-terminal-grid`,children:i===0?(0,K.jsxs)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-workspace`,children:[(0,K.jsx)(`h2`,{children:be.startOrSelectAgent}),(0,K.jsx)(`p`,{children:be.startOrSelectAgentDescription}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(u),children:be.newAgent})]}):a.map(e=>(0,K.jsx)(wb,{agent:e,active:e.id===o,switching:e.id===s,switchingKind:e.id===s?c:null,onActivate:D,onOpenPath:O,onResolvePath:k,onOpenWorkspaceFilePath:le,onFollowOutputChange:ee,onReadLatest:te,onRuntimeModeChange:A,sendInput:j,resizeAgent:M,onSessionOutput:N,focusSignal:l?.agentId===e.id?l.nonce:0,copy:be},e.id))}),Ae?(0,K.jsx)(`div`,{className:`code-composer-restore-bar`,"data-testid":`code-composer-restore-bar`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-composer-restore`,"data-testid":`code-composer-restore`,"aria-label":be.restoreComposer,title:be.restoreComposer,onClick:()=>Se(!1),children:(0,K.jsx)(ve,{})})}):(0,K.jsxs)(`div`,{className:`code-composer-shell ${ke?`collapsible`:``}`,children:[ke?(0,K.jsx)(`div`,{className:`code-composer-collapse-zone`,"aria-hidden":`false`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-composer-collapse`,"data-testid":`code-composer-collapse`,"aria-label":be.collapseComposer,title:be.collapseComposer,onClick:()=>Se(!0),children:(0,K.jsx)(ge,{})})}):null,De?null:(0,K.jsx)(SS,{agent:Ee,active:e===`projects`&&!t&&!Ae,copy:be}),De?(0,K.jsx)(mS,{...T,copy:be}):(0,K.jsx)(Fx,{...w,copy:be})]})]}):(0,K.jsx)(`section`,{className:`code-side-view-panel ${e===`search`?`code-search-view`:``} ${e===`history`?`code-history-view`:``}`,"data-testid":`code-side-view-panel`,onScroll:e===`history`?e=>Te(e.currentTarget):void 0,children:e===`search`?(0,K.jsx)(SC,{query:f,displayedProjects:d,hasQuery:p,loading:m,resultCount:h,selectedAgentId:g,selectedSessionHandle:_,inputRef:v,onQueryChange:ne,onKeyDown:I,onClearSearch:R,onOpenAgent:P,onOpenSession:F,copy:be}):e===`history`?(0,K.jsx)(nC,{archivedRuns:y,archivedAgents:b,agentSessions:x,now:C,onResumeSession:B,onContinueRun:ie,onOpenArchivedAgent:V,onRestoreArchivedAgent:ae,searchAgentSessions:re,copy:be}):(0,K.jsx)(`h2`,{children:jC(be,e)})})})}function NC(){return{entries:[],cursor:null}}function PC(e,t,n=100){let r=t.trimEnd();if(!r)return{...e,cursor:null};let i=Math.max(1,n);return{entries:e.entries[e.entries.length-1]===r?e.entries:[...e.entries,r].slice(-i),cursor:null}}function FC(e){let t=e.value||``,n=Math.max(0,Math.min(e.selectionStart,t.length));return n===Math.max(0,Math.min(e.selectionEnd,t.length))?e.direction===`previous`?t.lastIndexOf(`
114
+ `)).includes(n)):e}function nC({archivedRuns:e,archivedAgents:t,agentSessions:n,now:r,onResumeSession:i,onContinueRun:a,onOpenArchivedAgent:o,onRestoreArchivedAgent:c,searchAgentSessions:l,copy:u}){let[d,f]=(0,W.useState)(``),p=d.trim(),m=!!p,[g,_]=(0,W.useState)({query:``,sessions:[],loading:!1}),v=g.query===p?g.sessions:[],y=QS(e,t,m?$S(n,v):n),b=tC(y,p),x=y.length,S=m&&(g.query!==p||g.loading);return(0,W.useEffect)(()=>{if(!p){_({query:``,sessions:[],loading:!1});return}let e=new AbortController;_({query:p,sessions:[],loading:!0});let t=window.setTimeout(()=>{l(p,e.signal).then(t=>{e.signal.aborted||_({query:p,sessions:t,loading:!1})}).catch(t=>{t instanceof DOMException&&t.name===`AbortError`||e.signal.aborted||_({query:p,sessions:[],loading:!1})})},FS);return()=>{window.clearTimeout(t),e.abort()}},[p,l]),(0,K.jsxs)(`div`,{className:`code-history-panel`,"data-testid":`code-history-panel`,children:[(0,K.jsxs)(`div`,{className:`code-history-panel-header`,children:[(0,K.jsx)(`h2`,{children:u.history}),(0,K.jsxs)(`div`,{className:`code-search-panel-input code-history-search`,"data-testid":`code-history-search-box`,children:[(0,K.jsx)(`span`,{className:`code-search-panel-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ie,{})}),(0,K.jsx)(`input`,{type:`text`,role:`searchbox`,inputMode:`search`,value:d,onChange:e=>f(e.currentTarget.value),placeholder:u.searchHistory,"aria-label":u.searchHistory,autoComplete:`off`,spellCheck:!1}),d&&(0,K.jsx)(`button`,{type:`button`,onClick:()=>f(``),"aria-label":u.clearSearch,children:(0,K.jsx)(le,{})})]})]}),x===0?(0,K.jsxs)(`div`,{className:`code-empty-workspace`,children:[(0,K.jsx)(`h2`,{children:u.noHistoryYet}),(0,K.jsx)(`p`,{children:u.noHistoryDescription})]}):m&&S&&b.length===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-history-search-loading`,children:(0,K.jsx)(`h2`,{children:u.searching})}):m&&b.length===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-history-search`,children:(0,K.jsx)(`h2`,{children:u.noMatchingAgents})}):(0,K.jsx)(`div`,{className:`code-history-list`,children:(0,K.jsx)(`section`,{className:`code-history-section`,"data-testid":`code-history-agents`,children:b.map(e=>{if(e.kind===`run`){let{entry:t}=e;return(0,K.jsxs)(`article`,{className:`code-history-card archived`,"data-testid":`code-archived-run-card`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:RS(t)}),(0,K.jsx)(`p`,{children:VS(t)})]}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:s(e.updatedAt,r)}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-run-continue`,onClick:()=>a(t),"aria-label":u.continueRun,title:u.continueRun,children:(0,K.jsx)(pe,{})})]})]},e.historyKey)}if(e.kind===`agent`){let{agent:t}=e;return(0,K.jsxs)(`article`,{className:`code-history-card archived`,"data-testid":`code-archived-agent-card`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:h(t)}),(0,K.jsx)(`p`,{children:HS(t)})]}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:s(e.updatedAt,r)}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-agent-open`,onClick:()=>o(t.id),"aria-label":u.open,title:u.open,children:(0,K.jsx)(ae,{})}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-archived-agent-restore`,onClick:()=>c(t.id),"aria-label":u.restore,title:u.restore,children:(0,K.jsx)(pe,{})})]})]},e.historyKey)}let{session:t}=e,n=t.title||u.sessionFallbackTitle(t.providerName);return(0,K.jsxs)(`article`,{className:`code-history-card code-session`,"data-testid":`code-session-history-card`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:n}),(0,K.jsx)(`p`,{children:US(t)})]}),(0,K.jsxs)(`div`,{className:`code-history-actions`,children:[(0,K.jsx)(`span`,{children:s(e.updatedAt,r)}),(0,K.jsx)(`button`,{type:`button`,"aria-label":u.resumeSessionAria(n),title:u.restore,onClick:()=>i(t.provider,t.id,t.providerHomeId),children:(0,K.jsx)(pe,{})})]})]},e.historyKey)})})})]})}var rC={plusMenu:!1,permissionMode:!1,modelPicker:!1,reasoningEffort:!1,serviceTier:!1,speechInput:!0},iC={plusMenu:!0,permissionMode:!0,modelPicker:!0,reasoningEffort:!0,serviceTier:!1,speechInput:!0},aC=[{command:`/goal`,label:`Goal`,description:`Set or update what this Codex session should keep working toward`,source:`codex`},{command:`/plan`,label:`Plan mode`,description:`Ask Codex to plan first before editing`,source:`codex`},{command:`/skills`,label:`Skills`,description:`Browse and use available Codex skills`,source:`codex`},{command:`/permissions`,label:`Permissions`,description:`Change what Codex can do without asking first`,source:`codex`},{command:`/model`,label:`Model`,description:`Change or inspect the active Codex model`,source:`codex`},{command:`/reasoning`,label:`Reasoning`,description:`Change the reasoning effort for this session`,source:`codex`},{command:`/mcp`,label:`MCP`,description:`Show MCP server status`,source:`codex`},{command:`/fast`,label:`Fast`,description:`Toggle Codex fast mode when available`,source:`codex`},{command:`/status`,label:`Status`,description:`Inspect the session, model, permissions, and token usage`,source:`codex`},{command:`/usage`,label:`Usage`,description:`View account token usage from Codex`,source:`codex`},{command:`/compact`,label:`Compact`,description:`Summarize long context to free tokens`,source:`codex`},{command:`/review`,label:`Review`,description:`Ask Codex to review the current working tree`,source:`codex`},{command:`/personality`,label:`Personality`,description:`Choose how Codex communicates in this session`,source:`codex`},{command:`/help`,label:`Help`,description:`Show available Codex slash commands`,source:`codex`}],oC=[{command:`/help`,label:`Help`,description:`Show available Claude Code slash commands`,source:`claude`},{command:`/model`,label:`Model`,description:`Change or inspect the active Claude model`,source:`claude`},{command:`/permissions`,label:`Permissions`,description:`Review or change Claude Code permission behavior`,source:`claude`},{command:`/cost`,label:`Cost`,description:`Show Claude Code usage for the current conversation`,source:`claude`},{command:`/compact`,label:`Compact`,description:`Compact the current Claude Code conversation`,source:`claude`},{command:`/clear`,label:`Clear`,description:`Clear the current Claude Code conversation`,source:`claude`},{command:`/config`,label:`Config`,description:`Open Claude Code configuration`,source:`claude`},{command:`/doctor`,label:`Doctor`,description:`Check Claude Code installation and account health`,source:`claude`},{command:`/memory`,label:`Memory`,description:`Edit or inspect Claude Code memory`,source:`claude`}];function sC(e){return e===`codex`?aC:e===`claude`?oC:[]}function cC(e){let t=new Set;return e.filter(e=>{let n=e.command.trim().toLowerCase();return!n||t.has(n)?!1:(t.add(n),!0)})}function lC(e){let t=bb(e).kind;return{kind:t,composer:t===`codex`?{...iC,serviceTier:!0}:t===`claude`?{...iC}:{...rC},actions:{pin:!!e,rename:!!e,archive:!!(e&&!e.isMain),markUnread:!!e,copyWorkingDirectory:!!e,forkSameWorktree:!!e,forkNewWorktree:e?.canForkNewWorktree===!0,kill:!!(e&&e.isMain)}}}function uC(e){return!!(e&&(e.agents.some(e=>!e.isMain)||e.agentSessions.length>0))}function dC(e){let t=lC(e),n=[t.actions.pin,t.actions.rename,t.actions.archive,t.actions.markUnread,t.actions.copyWorkingDirectory,t.actions.forkSameWorktree,t.actions.forkNewWorktree,t.actions.kill].filter(Boolean).length;return{itemCount:n,separatorCount:n>0?2:0}}function fC(e){return e.kind===`agent`?e.claimedSessionKey||`agent:${e.agent.id}`:Rb(e.session)}function pC(e){return!!e.parentAgentId&&e.source===`ui-fork-new-worktree`}function mC(e,t){return t||e===`pending`||e===`stopped`||e===`dead`}function hC(e){let t=e.replace(/\s+/g,` `).trim();return t.length>160?`${t.slice(0,157)}...`:t}function gC(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function _C(e){if(e===null||e<0)return``;let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);if(n<60)return`${n}m`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}h ${i}m`:`${r}h`}function vC(e,t,n){let r=hC(e.terminalStatus?.runningCommand||e.shellCommand||``);if(r&&t){let t=gC(e.terminalStatus?.runningCommandStartedAt)??gC(e.shellCommandStartedAt),i=t===null?``:_C(n-t);return i?`Running ${i}: ${r}`:`Running: ${r}`}let i=hC(e.terminalStatus?.lastCommand||e.shellLastCommand||``);if(!i)return``;let a=e.terminalStatus?.lastExitCode,o=[_C(gC(e.terminalStatus?.lastCommandDurationMs)??gC(e.shellLastCommandDurationMs)),typeof a==`number`?`exit ${a}`:``].filter(Boolean).join(`, `);return o?`Last command: ${i} (${o})`:`Last command: ${i}`}function yC(e,t){let n=bb(e).turnActive,r=h(e),i=vC(e,n,t);return{kind:`agent`,title:r,rowTitle:[r,i,e.cwd].filter(Boolean).join(` · `),commandTitle:i,lifecycleStatus:e.status,turnActive:n,statusIndicatorVisible:mC(e.status,n),pinned:e.pinned===!0,unread:e.unread===!0,forkedToNewWorktree:pC(e),requiresResume:!1,scheduled:!1,scheduleTitle:``}}function bC(e,t){let n=e.schedule?.label||e.schedule?.name||e.schedule?.rrule||``;return{kind:`history`,title:e.title||t,rowTitle:[e.title||t,e.cwd||e.workspace].filter(Boolean).join(` · `),commandTitle:``,turnActive:!1,statusIndicatorVisible:!1,pinned:e.pinned===!0,unread:e.unread===!0,forkedToNewWorktree:!1,requiresResume:!0,scheduled:!!e.schedule,scheduleTitle:n}}function xC(e,t=Date.now()){return e.kind===`agent`?yC(e.agent,t):bC(e.session,e.fallbackTitle)}function SC({query:e,displayedProjects:t,hasQuery:n,loading:r,resultCount:i,selectedAgentId:a,selectedSessionHandle:o,inputRef:s,onQueryChange:c,onKeyDown:l,onClearSearch:u,onOpenAgent:d,onOpenSession:f,copy:p}){return(0,W.useEffect)(()=>{let e=s.current;e&&window.requestAnimationFrame(()=>{e.focus({preventScroll:!0})})},[s]),(0,K.jsxs)(`div`,{className:`code-search-panel`,"data-testid":`code-search-panel`,children:[(0,K.jsxs)(`div`,{className:`code-search-panel-header`,children:[(0,K.jsx)(`h2`,{children:p.search}),n?(0,K.jsx)(`span`,{children:p.resultsCount(i)}):null]}),(0,K.jsxs)(`div`,{className:`code-search-panel-input`,"data-testid":`code-search-box`,children:[(0,K.jsx)(`span`,{className:`code-search-panel-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ie,{})}),(0,K.jsx)(`input`,{ref:s,type:`text`,role:`searchbox`,name:`farming-workspace-search`,inputMode:`search`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`search`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:e,onChange:e=>c(e.currentTarget.value),onKeyDown:l,placeholder:p.searchProjectsOrAgents,"aria-label":p.searchProjectsOrAgents}),e&&(0,K.jsx)(`button`,{type:`button`,onClick:u,"aria-label":p.clearSearch,children:(0,K.jsx)(le,{})})]}),n&&r&&i===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-search-loading`,children:(0,K.jsx)(`h2`,{children:p.searching})}):n&&i===0?(0,K.jsx)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-search`,children:(0,K.jsx)(`h2`,{children:p.noMatchingAgents})}):n?(0,K.jsx)(`div`,{className:`code-search-results`,children:t.map(e=>(0,K.jsxs)(`section`,{className:`code-search-result-group`,children:[(0,K.jsx)(`h3`,{children:e.name}),e.agents.map(e=>(0,K.jsx)(CC,{agent:e,selected:e.id===a,onOpen:()=>d(e.id)},e.id)),e.agentSessions.map(e=>{let t=Rb(e);return(0,K.jsx)(`button`,{type:`button`,className:`code-search-result code-session-result ${t===o?`active`:``}`,"data-testid":`code-session-search-result`,onClick:()=>f(e),children:(0,K.jsxs)(`span`,{className:`code-search-result-copy`,children:[(0,K.jsx)(`strong`,{children:e.title||p.sessionFallbackTitle(e.providerName)}),(0,K.jsx)(`span`,{children:zb(e)})]})},t)})]},e.id))}):null]})}function CC({agent:e,selected:t,onOpen:n}){let r=xC({kind:`agent`,agent:e});return(0,K.jsxs)(`button`,{type:`button`,className:`code-search-result ${r.statusIndicatorVisible?``:`no-status`} ${t?`active`:``}`,"data-testid":`code-search-result`,title:r.rowTitle||r.title,onClick:n,children:[r.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${r.lifecycleStatus} ${r.turnActive?`turn-active`:``}`}),(0,K.jsxs)(`span`,{className:`code-search-result-copy`,children:[(0,K.jsx)(`strong`,{children:r.title}),(0,K.jsx)(`span`,{children:Mb(Ab(e))})]})]})}var wC=`farming.code.fileEditor.chunk-recovery`;function TC(){if(typeof window>`u`)return!1;try{return window.sessionStorage.getItem(wC)===`1`?!1:(window.sessionStorage.setItem(wC,`1`),window.location.reload(),!0)}catch{return!1}}function EC(){return o(()=>import(`./FileEditorPane-RWiFD2cq.js`).then(e=>{try{window.sessionStorage.removeItem(wC)}catch{}return{default:e.FileEditorPane}}),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).catch(e=>{if(TC())return new Promise(()=>{});throw e})}var DC=(0,W.lazy)(()=>EC());function OC(e){return e.split(`/`).filter(Boolean).pop()||e}function kC(e){return e.split(`/`).filter(Boolean)}function AC({openFile:e,onChangeDraft:t,copy:n}){let r=kC(e.file.path);return(0,K.jsxs)(`section`,{className:`code-file-editor fallback`,"data-testid":`code-file-editor`,"aria-label":n.editorFor(e.file.path),children:[(0,K.jsxs)(`header`,{className:`code-file-editor-header`,children:[(0,K.jsx)(`div`,{className:`code-file-editor-tabs`,role:`tablist`,children:(0,K.jsxs)(`div`,{className:`code-file-editor-tab active ${e.dirty?`dirty`:``} ${e.externalChanged?`warning`:``}`,title:e.file.path,role:`tab`,"aria-selected":`true`,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`code-file-editor-tab-name`,children:OC(e.file.path)}),(0,K.jsx)(`span`,{className:`code-file-editor-tab-tail`,children:(e.dirty||e.externalChanged)&&(0,K.jsx)(`span`,{className:`code-file-editor-dirty`,title:e.externalChanged?n.changedOnDisk:n.unsavedChanges})})]})}),(0,K.jsxs)(`div`,{className:`code-file-editor-bar`,children:[(0,K.jsx)(`nav`,{className:`code-file-editor-breadcrumbs`,title:e.file.path,"aria-label":n.filePath,children:r.map((e,t)=>(0,K.jsxs)(`span`,{className:`code-file-editor-breadcrumb ${t===r.length-1?`current`:``}`,children:[(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-name`,children:e}),t<r.length-1&&(0,K.jsx)(`span`,{className:`code-file-editor-breadcrumb-separator`,"aria-hidden":`true`})]},`${t}-${e}`))}),(0,K.jsx)(`div`,{className:`code-file-editor-actions`,children:e.dirty&&(0,K.jsx)(`span`,{className:`code-file-editor-status`,children:n.unsavedChanges})})]})]}),(0,K.jsx)(`textarea`,{className:`code-file-editor-fallback-textarea`,"data-testid":`code-file-editor-fallback-textarea`,name:`farming-file-editor-fallback`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,value:e.draft,onChange:e=>t(e.currentTarget.value),spellCheck:!1,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,"aria-label":n.editorFor(e.file.path)}),(0,K.jsx)(`footer`,{className:`code-file-editor-statusbar`,children:(0,K.jsx)(`span`,{className:`code-file-editor-cursor-position`,children:n.cursorPosition(1,1)})})]})}function jC(e,t){return t===`search`?e.search:t===`history`?e.history:`Farming`}function MC({activeView:e,showFileEditor:t,openWorkspaceFile:n,openWorkspaceFiles:r,openAgentsCount:i,visibleOpenAgents:a,activeTerminalId:o,permissionSwitchingAgentId:s,agentSwitchingKind:c,terminalFocusRequest:l,agentCreationWorkspace:u,displayedProjects:d,searchQuery:f,searchHasQuery:p,searchLoading:m,visibleSearchTargetCount:h,selectedSearchAgentId:g,selectedSearchSessionHandle:_,searchInputRef:v,archivedRuns:y,archivedAgents:b,historyAgentSessions:x,canLoadMoreHistoryAgentSessions:S,now:C,composerProps:w,acpComposerProps:T,onNewAgent:E,onOpenTerminal:D,onOpenTerminalPath:O,onResolveTerminalPath:k,onTerminalFollowOutputChange:A,onAgentReadLatest:ee,onRuntimeModeChange:j,sendInput:M,resizeAgent:N,onSessionOutput:te,onOpenSearchAgent:P,onOpenSearchSession:F,onSearchQueryChange:ne,onSearchKeyDown:I,onCloseSearch:re,onLoadMoreHistoryAgentSessions:R,onSearchHistoryAgentSessions:z,onResumeHistorySession:B,onContinueArchivedRun:ie,onOpenArchivedAgent:V,onRestoreArchivedAgent:ae,onChangeWorkspaceFileDraft:oe,onUpdateOpenWorkspaceFile:se,onSelectOpenWorkspaceFile:ce,onOpenWorkspaceFilePath:le,canNavigateWorkspaceBack:ue,canNavigateWorkspaceForward:de,onNavigateWorkspaceHistory:fe,onCloseOpenWorkspaceFile:pe,onCloseOpenWorkspaceFiles:me,onRevealWorkspaceFileInExplorer:H,onFocusWorkspaceFilesSearch:he,onRecordWorkspaceNavigationCursor:_e,onBackToAgentFromFile:ye,copy:be}){let[xe,Se]=(0,W.useState)(!1),[Ce,we]=(0,W.useState)(!1),Te=(0,W.useCallback)(e=>{S&&e.scrollHeight-e.scrollTop-e.clientHeight<=320&&R()},[S,R]),Ee=o&&a.find(e=>e.id===o)||null,De=Ee?.agentRuntimeMode===`acp`,Oe=[`acp`,`json`].includes(Ee?.agentRuntimeMode||``)||Ee?.providerSessionProvider===`codex`&&Ee.codexRuntimeMode===`app-server`?`transcript`:`terminal`,ke=Ce&&e===`projects`&&!t&&i>0&&Oe===`terminal`,Ae=ke&&xe;(0,W.useEffect)(()=>{let e=window.matchMedia(`(hover: hover) and (pointer: fine)`),t=()=>we(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,W.useEffect)(()=>{!ke&&xe&&Se(!1)},[ke,xe]);let U=(0,W.useCallback)(e=>{if(!L())return;let t=e.target;if(t instanceof Element&&t.closest(`.code-composer`))return;let n=document.activeElement;n instanceof HTMLElement&&n.closest(`.code-composer`)&&(n instanceof HTMLTextAreaElement||n.isContentEditable||n.getAttribute(`role`)===`textbox`)&&n.blur()},[]);return(0,K.jsx)(`main`,{className:`code-main`,"data-testid":`code-main`,onPointerDownCapture:U,onTouchStartCapture:U,children:e===`projects`?t&&n?(0,K.jsx)(W.Suspense,{fallback:(0,K.jsx)(AC,{openFile:n,onChangeDraft:oe,copy:be}),children:(0,K.jsx)(DC,{openFile:n,openFiles:r,onChangeDraft:oe,onUpdateOpenFile:se,onSelectOpenFile:ce,onOpenFilePath:le,canNavigateBack:ue,canNavigateForward:de,onNavigateHistory:fe,onCloseOpenFile:pe,onCloseOpenFiles:me,onRevealInExplorer:H,onFocusFilesSearch:he,onRecordNavigationCursor:_e,onBackToAgent:ye,copy:be})}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`div`,{className:`code-terminal-grid panes-1`,"data-testid":`code-terminal-grid`,children:i===0?(0,K.jsxs)(`div`,{className:`code-empty-workspace`,"data-testid":`code-empty-workspace`,children:[(0,K.jsx)(`h2`,{children:be.startOrSelectAgent}),(0,K.jsx)(`p`,{children:be.startOrSelectAgentDescription}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(u),children:be.newAgent})]}):a.map(e=>(0,K.jsx)(wb,{agent:e,active:e.id===o,switching:e.id===s,switchingKind:e.id===s?c:null,onActivate:D,onOpenPath:O,onResolvePath:k,onOpenWorkspaceFilePath:le,onFollowOutputChange:A,onReadLatest:ee,onRuntimeModeChange:j,sendInput:M,resizeAgent:N,onSessionOutput:te,focusSignal:l?.agentId===e.id?l.nonce:0,copy:be},e.id))}),Ae?(0,K.jsx)(`div`,{className:`code-composer-restore-bar`,"data-testid":`code-composer-restore-bar`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-composer-restore`,"data-testid":`code-composer-restore`,"aria-label":be.restoreComposer,title:be.restoreComposer,onClick:()=>Se(!1),children:(0,K.jsx)(ve,{})})}):(0,K.jsxs)(`div`,{className:`code-composer-shell ${ke?`collapsible`:``}`,children:[ke?(0,K.jsx)(`div`,{className:`code-composer-collapse-zone`,"aria-hidden":`false`,children:(0,K.jsx)(`button`,{type:`button`,className:`code-composer-collapse`,"data-testid":`code-composer-collapse`,"aria-label":be.collapseComposer,title:be.collapseComposer,onClick:()=>Se(!0),children:(0,K.jsx)(ge,{})})}):null,De?null:(0,K.jsx)(SS,{agent:Ee,active:e===`projects`&&!t&&!Ae,copy:be}),De?(0,K.jsx)(mS,{...T,copy:be}):(0,K.jsx)(Fx,{...w,copy:be})]})]}):(0,K.jsx)(`section`,{className:`code-side-view-panel ${e===`search`?`code-search-view`:``} ${e===`history`?`code-history-view`:``}`,"data-testid":`code-side-view-panel`,onScroll:e===`history`?e=>Te(e.currentTarget):void 0,children:e===`search`?(0,K.jsx)(SC,{query:f,displayedProjects:d,hasQuery:p,loading:m,resultCount:h,selectedAgentId:g,selectedSessionHandle:_,inputRef:v,onQueryChange:ne,onKeyDown:I,onClearSearch:re,onOpenAgent:P,onOpenSession:F,copy:be}):e===`history`?(0,K.jsx)(nC,{archivedRuns:y,archivedAgents:b,agentSessions:x,now:C,onResumeSession:B,onContinueRun:ie,onOpenArchivedAgent:V,onRestoreArchivedAgent:ae,searchAgentSessions:z,copy:be}):(0,K.jsx)(`h2`,{children:jC(be,e)})})})}function NC(){return{entries:[],cursor:null}}function PC(e,t,n=100){let r=t.trimEnd();if(!r)return{...e,cursor:null};let i=Math.max(1,n);return{entries:e.entries[e.entries.length-1]===r?e.entries:[...e.entries,r].slice(-i),cursor:null}}function FC(e){let t=e.value||``,n=Math.max(0,Math.min(e.selectionStart,t.length));return n===Math.max(0,Math.min(e.selectionEnd,t.length))?e.direction===`previous`?t.lastIndexOf(`
115
115
  `,Math.max(0,n-1))===-1:t.indexOf(`
116
116
  `,n)===-1:!1}function IC(e,t,n){if(e.entries.length===0)return{history:{...e,cursor:null},value:n,changed:!1};let r=e.cursor,i=r!==null&&e.entries[r]===n;if(!i&&!(r===null&&n===``))return{history:{...e,cursor:null},value:n,changed:!1};if(t===`previous`){let t=i?Math.max(0,r):e.entries.length-1,a=i?Math.max(0,t-1):t,o=e.entries[a]||``;return{history:{...e,cursor:a},value:o,changed:o!==n||e.cursor!==a}}if(!i||r===null)return{history:{...e,cursor:null},value:n,changed:!1};let a=r+1;if(a>=e.entries.length)return{history:{...e,cursor:null},value:``,changed:n!==``||e.cursor!==null};let o=e.entries[a]||``;return{history:{...e,cursor:a},value:o,changed:o!==n||e.cursor!==a}}var LC={plusMenuOpen:!1,approvalMenuOpen:!1,modelMenuOpen:!1,modelPickerPane:null},RC=zC();function zC(){return{draft:``,attachments:[],mode:`default`,history:NC(),ui:{...LC}}}function BC(e,t=[]){return{id:`pending-${typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}`,text:e,createdAt:Date.now(),...t.length>0?{attachments:t}:{}}}function VC(e,t){if(!e)return;let n=e.messages.filter(e=>e.id!==t);return n.length>0?{...e,messages:n}:void 0}function HC(e){return!e.ui.plusMenuOpen&&!e.ui.approvalMenuOpen&&!e.ui.modelMenuOpen&&e.ui.modelPickerPane===null?e:{...e,ui:{...LC}}}function UC(e){return!e.plusMenuOpen&&!e.approvalMenuOpen&&!e.modelMenuOpen&&e.modelPickerPane===null}function WC(e,t){let n=[...e.pendingFollowUp?.messages||[],...t.pendingFollowUp?.messages||[]],r=Math.min(e.pendingFollowUp?.createdAt??1/0,t.pendingFollowUp?.createdAt??1/0);return{...e,draft:e.draft||t.draft,attachments:[...t.attachments,...e.attachments],mode:e.mode===`default`?t.mode:e.mode,history:{entries:[...t.history.entries,...e.history.entries].slice(-100),cursor:null},pendingFollowUp:n.length>0?{messages:n,createdAt:Number.isFinite(r)?r:Date.now()}:void 0,ui:UC(e.ui)?t.ui:e.ui}}function GC(e){return!e||e.providerSessionTemporary===!0?``:e.providerSessionKey?e.providerSessionKey:e.providerSessionProvider&&e.providerSessionId?Rb({provider:e.providerSessionProvider,id:e.providerSessionId,providerHomeId:e.providerHomeId}):NS(e.source)}function KC(e){return e?GC(e)||e.restartedFromAgentIds?.[0]||e.id:``}function qC(e){let t=new Set;e.id&&t.add(e.id),e.restartedFromAgentIds?.forEach(e=>t.add(e)),e.providerSessionKey&&t.add(e.providerSessionKey),e.providerSessionProvider&&e.providerSessionId&&t.add(Rb({provider:e.providerSessionProvider,id:e.providerSessionId,providerHomeId:e.providerHomeId}));let n=NS(e.source);return n&&t.add(n),Array.from(t)}var JC=5e4,YC={goal:`Goal mode: Treat the following as the working goal for this agent. Track progress toward it and report clearly when it is complete or blocked.`,plan:`Plan mode: Inspect the relevant context first and respond with a concise plan before making code changes. Do not edit files until the plan is clear.`};function XC(e){return!e||e===`/`?``:e.endsWith(`/`)?e.slice(0,-1):e}function ZC(e=`/`){let t=XC(`/farming/`),n=e.startsWith(`/`)?e:`/${e}`;return t?`${t}${n}`:n}function QC(e,t){let n=t.trimEnd();if(!n)return e;let r=e.trim()?`
117
117
 
@@ -119,6 +119,6 @@ ${s.join(`
119
119
 
120
120
  `)).trimEnd()}function cw(e,t){let n=t.filter(e=>!e.path).map(e=>e.messageBlock||``).filter(Boolean);return QC(e.trimEnd(),n.join(`
121
121
 
122
- `)).trimEnd()}function lw(e){return e.flatMap(e=>e.status===`ready`&&e.path?[{kind:`image`,path:e.path,name:e.name,type:e.type,size:e.size}]:[])}function uw(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(r.error??Error(`File read failed`)),r.onload=()=>t(typeof r.result==`string`?r.result:``),r.readAsText(e)})}async function dw(e){let t=await fetch(ZC(`/api/attachments/image`),{method:`POST`,headers:{"Content-Type":e.type||`image/png`},body:e});if(!t.ok)throw Error(`Image upload failed: ${t.status}`);return t.json()}async function fw(e){if(ew(e))return nw(await dw(e));try{return tw(e,await uw(e))}catch{return`Attached file: ${$C(e)}\n\n[Unable to read this file as text]`}}function pw(e){return ew(e)?`Attached image: ${$C(e,`pasted image`)}\n\n[Unable to upload this image]`:`Attached file: ${$C(e)}\n\n[Unable to read this file as text]`}function mw(e){if(!e)return[];let t=Array.from(e.files??[]).filter(ew);return t.length>0?t:Array.from(e.items??[]).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!(e&&ew(e)))}function hw(e,t){return e===`default`?t:`${YC[e]}\n\n${t}`}function gw({agent:e,composerKey:t,draft:n,attachments:r,composerMode:i,turnActive:a,sendMessage:o,updateComposerState:s}){let c=lw(r),l=hw(i,cw(n,r).trim());return!l&&c.length===0||!e||e.agentRuntimeMode!==`acp`||!t||!a&&!o(e,l,c)?!1:(s(t,e=>({...e,draft:``,attachments:[],mode:`default`,history:PC(e.history,n),...a?{pendingFollowUp:{messages:[...e.pendingFollowUp?.messages||[],BC(l,c)],createdAt:e.pendingFollowUp?.createdAt||Date.now()}}:{}})),r.forEach(aw),!0)}function _w(e,t,r,i=!1){return fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-permission`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,optionId:r,cancelled:i})})}function vw(e,t,r,i){return fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-elicitation`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,action:r,content:i})})}var yw=`acp:`;function bw(e){let t=KC(e);return t?`${yw}${t}`:``}function xw(e){return qC(e).map(e=>`${yw}${e}`)}function Sw(e){return e.startsWith(yw)}function Cw(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function ww(){return(0,K.jsx)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M10 13V3m0 0L6.5 6.5M10 3l3.5 3.5M4 9v6.5A1.5 1.5 0 0 0 5.5 17h9a1.5 1.5 0 0 0 1.5-1.5V9`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function Tw(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`rect`,{x:`3`,y:`3`,width:`14`,height:`14`,rx:`3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,K.jsx)(`path`,{d:`M10 6.5v7M6.5 10h7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`})]})}function Ew(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`rect`,{x:`6.5`,y:`6.5`,width:`9`,height:`9`,rx:`2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,K.jsx)(`path`,{d:`M13.5 6.5v-2A1.5 1.5 0 0 0 12 3H4.5A1.5 1.5 0 0 0 3 4.5V12A1.5 1.5 0 0 0 4.5 13.5h2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}function Dw({copy:e,title:t,url:n,onClose:r}){let i=Cw(),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.useState)(!1);(0,W.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]),(0,W.useEffect)(()=>{if(!a&&!s)return;let e=window.setTimeout(()=>{o(!1),c(!1)},1800);return()=>window.clearTimeout(e)},[a,s]);let l=(0,W.useCallback)(async()=>{let e=await j(n);o(e),c(!e)},[n]);return(0,K.jsx)(`div`,{className:`code-mobile-share-backdrop`,"data-testid":`code-mobile-share-sheet`,role:`presentation`,onPointerDown:r,children:(0,K.jsxs)(`section`,{className:`code-mobile-share-sheet`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-mobile-share-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsxs)(`header`,{className:`code-mobile-share-header`,children:[(0,K.jsx)(`h2`,{id:`code-mobile-share-title`,children:e.mobileShareTitle}),(0,K.jsx)(`button`,{type:`button`,"aria-label":e.cancel,onClick:r,children:`×`})]}),(0,K.jsxs)(`section`,{className:`code-mobile-share-choice code-mobile-share-forward`,children:[(0,K.jsxs)(`div`,{className:`code-mobile-share-choice-copy`,children:[(0,K.jsx)(`h3`,{children:e.mobileForwardTitle}),(0,K.jsx)(`p`,{children:e.mobileForwardHint})]}),(0,K.jsxs)(`div`,{className:`code-mobile-share-link-row`,children:[(0,K.jsx)(`span`,{className:`code-mobile-share-link`,title:t,children:n}),(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-mobile-share-copy-action`,onClick:()=>void l(),children:[(0,K.jsx)(Ew,{}),(0,K.jsx)(`span`,{children:a?e.mobileShareCopied:e.mobileShareCopyAction})]})]}),s&&(0,K.jsx)(`span`,{className:`code-mobile-share-status`,role:`status`,children:e.copyFailed})]}),(0,K.jsxs)(`section`,{className:`code-mobile-share-choice code-mobile-share-install-guide`,children:[(0,K.jsx)(`h3`,{children:e.mobileInstallTitle}),i?(0,K.jsx)(`p`,{className:`code-mobile-install-complete`,children:e.mobileShareInstalled}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`code-mobile-install-hint`,children:e.mobileInstallChromeHint}),(0,K.jsxs)(`div`,{className:`code-mobile-install-steps`,children:[(0,K.jsxs)(`div`,{className:`code-mobile-install-step`,children:[(0,K.jsxs)(`span`,{className:`code-mobile-install-controls`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{className:`code-mobile-install-control`,children:(0,K.jsx)(ww,{})}),(0,K.jsx)(`span`,{className:`code-mobile-install-or`,children:`/`}),(0,K.jsx)(`span`,{className:`code-mobile-install-control code-mobile-install-more`,children:`•••`})]}),(0,K.jsxs)(`span`,{children:[e.mobileInstallShareStep,(0,K.jsx)(`small`,{children:e.mobileInstallMoreStep})]})]}),(0,K.jsxs)(`div`,{className:`code-mobile-install-step`,children:[(0,K.jsx)(`span`,{className:`code-mobile-install-controls`,"aria-hidden":`true`,children:(0,K.jsx)(`span`,{className:`code-mobile-install-control`,children:(0,K.jsx)(Tw,{})})}),(0,K.jsxs)(`span`,{children:[e.mobileInstallAddStep,(0,K.jsx)(`small`,{children:e.mobileInstallOpenStep})]})]})]})]})]})]})})}function Ow(e){let t=e.filter(e=>!e.hidden),n=[];for(t.forEach(e=>{e.type===`separator`&&(n.length===0||n[n.length-1]?.type===`separator`)||n.push(e)});n[n.length-1]?.type===`separator`;)n.pop();return n}function kw({contextMenuAgent:e,contextMenuAgentSession:t,contextMenuProject:n,agentMenu:r,projectMenu:i,agentSessionMenu:a,renameDialog:o,killDialog:s,deleteWorktreeDialog:c,copyNotice:l,contextMenuRef:u,renameDialogRef:d,renameInputRef:f,killDialogRef:p,killCancelButtonRef:m,deleteWorktreeDialogRef:h,deleteWorktreeCancelButtonRef:g,onContextMenuKeyDown:_,onUpdateAgentFlags:v,onRenameAgent:y,onRenameProject:b,onCopyAgentWorkingDirectory:x,onForkAgent:S,onKillAgent:C,onOpenSession:w,onToggleSessionPinned:T,onArchiveSession:E,onCopySessionWorkingDirectory:D,onArchiveProject:O,onCloseRenameDialog:k,onRenameDialogTitleChange:ee,onSubmitRenameDialog:te,onCloseKillDialog:A,onSubmitKillDialog:j,onCloseDeleteWorktreeDialog:M,onSubmitDeleteWorktreeDialog:N,copy:P}){let F=lC(e),ne=uC(n),I=Ow([{type:`item`,id:`pin-agent`,label:e?.pinned?P.unpinAgent:P.pinAgent,hidden:!F.actions.pin,onSelect:()=>v({pinned:!e?.pinned})},{type:`item`,id:`rename-agent`,label:P.renameAgent,hidden:!F.actions.rename,onSelect:y},{type:`item`,id:`archive-agent`,label:P.archiveAgent,hidden:!F.actions.archive,onSelect:()=>v({archived:!0})},{type:`item`,id:`toggle-agent-unread`,label:e?.unread?P.markAsRead:P.markAsUnread,hidden:!F.actions.markUnread,onSelect:()=>v({unread:!e?.unread})},{type:`separator`,id:`agent-copy-separator`},{type:`item`,id:`copy-agent-working-directory`,label:P.copyWorkingDirectory,hidden:!F.actions.copyWorkingDirectory,onSelect:x},{type:`separator`,id:`agent-fork-separator`},{type:`item`,id:`fork-same-worktree`,label:P.forkSameWorktree,hidden:!F.actions.forkSameWorktree,onSelect:()=>S(`same-worktree`)},{type:`item`,id:`fork-new-worktree`,label:P.forkNewWorktree,hidden:!F.actions.forkNewWorktree,onSelect:()=>S(`new-worktree`)},{type:`item`,id:`kill-agent`,label:P.killAgent,danger:!0,hidden:!F.actions.kill,onSelect:C}]),L=Ow([{type:`item`,id:`open-session`,label:P.openSession,onSelect:()=>{t&&w(t.provider,t.id)}},{type:`item`,id:`toggle-session-pinned`,label:t?.pinned?P.unpinChat:P.pinChat,onSelect:T},{type:`item`,id:`archive-session`,label:P.archiveChat,onSelect:E},{type:`item`,id:`copy-session-working-directory`,label:P.copyWorkingDirectory,onSelect:D}]),R=Ow([{type:`item`,id:`rename-project`,label:P.renameProject,icon:`rename`,hidden:!n?.workspace,onSelect:b},{type:`item`,id:`archive-project`,label:P.archiveChats,icon:`archive`,disabled:!ne,onSelect:O}]);return(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(`div`,{className:`code-context-menu`,"data-testid":`code-agent-context-menu`,style:{left:r?.x??0,top:r?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(Aw,{entries:I})}),t&&(0,K.jsx)(`div`,{className:`code-context-menu`,"data-testid":`code-session-context-menu`,style:{left:a?.x??0,top:a?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(Aw,{entries:L})}),n&&(0,K.jsx)(`div`,{className:`code-context-menu code-project-context-menu`,"data-testid":`code-project-context-menu`,style:{left:i?.x??0,top:i?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(Aw,{entries:R})}),o&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-rename-backdrop`,onMouseDown:k,children:(0,K.jsxs)(`form`,{className:`code-rename-dialog`,"data-testid":`code-rename-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-rename-title`,ref:d,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>Mw(e,d.current),onKeyDown:e=>Mw(e,d.current),onSubmit:e=>{e.preventDefault(),te()},children:[(0,K.jsx)(`label`,{id:`code-rename-title`,htmlFor:`code-rename-input`,children:o.kind===`project`?P.renameProject:P.renameAgent}),(0,K.jsx)(`input`,{id:`code-rename-input`,ref:f,"data-testid":`code-rename-input`,type:`text`,name:`farming-rename-title`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:o.title,onChange:e=>ee(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),k())}}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:k,children:P.cancel}),(0,K.jsx)(`button`,{type:`submit`,className:`primary`,disabled:!o.title.trim(),children:P.save})]})]})}),s&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-kill-backdrop`,onMouseDown:A,children:(0,K.jsxs)(`div`,{className:`code-rename-dialog code-kill-dialog`,"data-testid":`code-kill-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-kill-title`,ref:p,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>Mw(e,p.current),onKeyDown:e=>Mw(e,p.current),children:[(0,K.jsx)(`h2`,{id:`code-kill-title`,children:P.killAgentQuestion}),(0,K.jsx)(`p`,{children:P.stopAgentDescription(s.title)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:m,onClick:A,autoFocus:!0,children:P.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:j,children:P.killAgent})]})]})}),c&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-delete-worktree-backdrop`,onMouseDown:M,children:(0,K.jsxs)(`div`,{className:`code-rename-dialog code-kill-dialog`,"data-testid":`code-delete-worktree-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-delete-worktree-title`,ref:h,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>Mw(e,h.current),onKeyDown:e=>Mw(e,h.current),children:[(0,K.jsx)(`h2`,{id:`code-delete-worktree-title`,children:P.deleteWorktreeQuestion}),(0,K.jsx)(`p`,{children:P.deleteWorktreeDirtyDescription(c.dirtyEntries.length)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:g,onClick:M,autoFocus:!0,children:P.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:N,children:P.forceDelete})]})]})}),l&&(0,K.jsx)(`div`,{className:`code-copy-toast ${l.kind}`,"data-testid":`code-copy-toast`,role:`status`,children:l.message})]})}function Aw({entries:e}){return(0,K.jsx)(K.Fragment,{children:e.map(e=>e.type===`separator`?(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`},e.id):(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,className:e.danger?`danger`:void 0,disabled:e.disabled,onClick:e.onSelect,children:[e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(jw,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}function jw({kind:e}){return e===`archive`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})}):(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M11.3536 1.64645C10.963 1.25592 10.3299 1.25592 9.93934 1.64645L3.14645 8.43934C3.05268 8.53311 2.99999 8.66029 2.99999 8.79289V11.5C2.99999 11.7761 3.22385 12 3.49999 12H6.2071C6.33971 12 6.46689 11.9473 6.56066 11.8536L13.3536 5.06066C13.7441 4.67014 13.7441 4.037 13.3536 3.64645L11.3536 1.64645ZM3.99999 9L8.99999 4L11 6L6 11H3.99999V9ZM9.7071 3.29289L10.6464 2.35355L12.6464 4.35355L11.7071 5.29289L9.7071 3.29289ZM2.5 14C2.22386 14 2 14.2239 2 14.5C2 14.7761 2.22386 15 2.5 15H13.5C13.7761 15 14 14.7761 14 14.5C14 14.2239 13.7761 14 13.5 14H2.5Z`})})}function Mw(e,t){if(e.key!==`Tab`||!t)return;let n=Array.from(t.querySelectorAll(`button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(n.length===0){e.preventDefault();return}let r=n[0],i=n[n.length-1];!r||!i||(e.shiftKey&&document.activeElement===r?(e.preventDefault(),i.focus()):!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus()))}var Nw=a(),Pw=`https://github.com/zhuwenzhuang/farming`;function Fw({copy:e,version:t,onClose:r}){let i=(0,W.useRef)(null);return(0,W.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;i.current?.focus({preventScroll:!0});let t=e=>{e.key===`Escape`&&r()};return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),e?.focus({preventScroll:!0})}},[r]),(0,Nw.createPortal)((0,K.jsx)(`div`,{className:`code-brand-backdrop`,"data-testid":`code-brand-dialog`,role:`presentation`,onPointerDown:r,children:(0,K.jsxs)(`section`,{className:`code-brand-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-brand-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{ref:i,type:`button`,className:`code-brand-close`,"aria-label":e.cancel,onClick:r,children:`×`}),(0,K.jsx)(`img`,{className:`code-brand-logo`,src:n(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-brand-heading`,children:[(0,K.jsx)(`h2`,{id:`code-brand-title`,children:`Farming Code`}),t&&(0,K.jsx)(`span`,{children:t})]}),(0,K.jsxs)(`div`,{className:`code-brand-story`,children:[(0,K.jsx)(`p`,{children:e.brandStoryOrigin}),(0,K.jsx)(`p`,{children:e.brandStoryPurpose})]}),(0,K.jsx)(`a`,{className:`code-brand-github`,href:Pw,target:`_blank`,rel:`noreferrer`,children:e.brandGithub})]})}),document.body)}var Iw=8,Lw=26,Rw=11,zw=10;function Bw(){return typeof window>`u`?{width:220+Iw*2,height:zw+Iw*2}:{width:window.innerWidth,height:window.innerHeight}}function Vw(e,t=0){return zw+e*Lw+t*Rw}function Hw(e,t,n,r=Bw(),i=220){let a=Math.max(Iw,r.width-i-Iw),o=Math.max(Iw,r.height-n-Iw);return{x:Math.max(Iw,Math.min(e,a)),y:Math.max(Iw,Math.min(t,o))}}function Uw(e,t,n=Bw(),r=220){let i=e.right+Iw,a=e.left-r-Iw,o=i+r<=n.width-Iw?i:a>=Iw?a:Hw(i,e.top,t,n,r).x;return{x:o,y:Hw(o,e.top,t,n,r).y}}function Ww(e,t,n=Bw(),r=220){let i=Math.max(Iw,n.width-r-Iw),a=Math.max(Iw,Math.min(e.right-r,i)),o=e.bottom+6,s=Math.max(Iw,n.height-t-Iw),c=e.top-t-6;return{x:a,y:o<=s?o:Math.max(Iw,Math.min(c,s))}}function Gw(e){let t=dC(e);return Vw(t.itemCount,t.separatorCount)}var Kw=140,qw=264,Jw=340,Yw=4,Xw=null;function Zw(e){if(typeof e==`function`)return e;if(typeof e.default==`function`)return e.default;if(typeof e.qrcode==`function`)return e.qrcode;throw Error(`QR renderer failed to load`)}function Qw(){return Xw||=o(()=>import(`./qrcode-DV-_rjU8.js`).then(e=>Zw(e)),[]),Xw}function $w(e){let t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}function eT(e,t){return!!(e&&e.expiresAt>t+1e3)}function tT(e){return e.split(`-`).map(e=>e.trim()).filter(Boolean)}async function nT(e){e?.code&&await fetch(n(`/api/share/qr-ticket/${encodeURIComponent(e.code)}`),{method:`DELETE`}).catch(()=>{})}function rT(e,t,n){let r=e<7,i=t<7,a=t>=n-7,o=e>=n-7;return r&&i||r&&a||o&&i}function iT(e,t,n,r){let i=Math.floor((n-r)/2),a=i+r;return e>=i&&e<a&&t>=i&&t<a}function aT(e,t){return(e+t)%11==0?`#6d8a63`:(e*3+t)%17==0?`#9b7a35`:`#263327`}function oT(e,t,n){return(0,K.jsxs)(`g`,{children:[(0,K.jsx)(`rect`,{x:e,y:t,width:`7`,height:`7`,rx:`1.45`,fill:`#263327`}),(0,K.jsx)(`rect`,{x:e+1,y:t+1,width:`5`,height:`5`,rx:`1`,fill:`#fbfaf2`}),(0,K.jsx)(`rect`,{x:e+2,y:t+2,width:`3`,height:`3`,rx:`0.72`,fill:`#263327`}),(0,K.jsx)(`rect`,{x:e+3.05,y:t+3.05,width:`0.9`,height:`0.9`,rx:`0.32`,fill:`#d9a735`})]},n)}function sT({value:e,badgeUrl:t,qrCodeFactory:n}){let r=(0,W.useId)().replace(/:/g,``),i=(0,W.useMemo)(()=>{let t=n(0,`H`);return t.addData(e),t.make(),t},[n,e]),a=i.getModuleCount(),o=a+Yw*2,s=Math.max(7,Math.min(11,Math.floor(a*.26)|1)),c=s+1.4,l=Yw+(a-c)/2,u=Yw+(a-c)/2,d=`farming-qr-badge-${r}`,f=[];for(let e=0;e<a;e+=1)for(let t=0;t<a;t+=1)i.isDark(e,t)&&(rT(e,t,a)||iT(e,t,a,s)||f.push((0,K.jsx)(`rect`,{x:Yw+t+.14,y:Yw+e+.14,width:`0.72`,height:`0.72`,rx:`0.24`,fill:aT(e,t)},`${e}-${t}`)));return(0,K.jsxs)(`svg`,{className:`code-share-qr-svg`,viewBox:`0 0 ${o} ${o}`,role:`img`,"aria-label":`QR code`,shapeRendering:`geometricPrecision`,children:[(0,K.jsx)(`defs`,{children:(0,K.jsx)(`clipPath`,{id:d,children:(0,K.jsx)(`rect`,{x:l+.55,y:u+.55,width:c-1.1,height:c-1.1,rx:`2.1`})})}),(0,K.jsx)(`rect`,{x:`0`,y:`0`,width:o,height:o,rx:`4`,fill:`#fbfaf2`}),f,oT(Yw,Yw,`top-left`),oT(Yw+a-7,Yw,`top-right`),oT(Yw,Yw+a-7,`bottom-left`),(0,K.jsx)(`rect`,{x:l,y:u,width:c,height:c,rx:`2.6`,fill:`#fbfaf2`}),(0,K.jsx)(`rect`,{x:l+.35,y:u+.35,width:c-.7,height:c-.7,rx:`2.25`,fill:`#ffffff`}),(0,K.jsx)(`image`,{href:t,x:l+.55,y:u+.55,width:c-1.1,height:c-1.1,preserveAspectRatio:`xMidYMid slice`,clipPath:`url(#${d})`})]})}function cT(){return(0,K.jsxs)(`svg`,{className:`code-share-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`path`,{d:`M2.5 2.5h4v4h-4zM9.5 2.5h4v4h-4zM2.5 9.5h4v4h-4z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M4 4h1v1H4zM11 4h1v1h-1zM4 11h1v1H4zM9.5 9.5h1.4v1.4H9.5zM12.1 9.5h1.4v1.4h-1.4zM9.5 12.1h1.4v1.4H9.5zM12.1 12.1h1.4v1.4h-1.4z`,fill:`currentColor`})]})}function lT({copy:e,sidebarCollapsed:t,shareTarget:r}){let[i,a]=(0,W.useState)(!1),[o,s]=(0,W.useState)(!1),[c,l]=(0,W.useState)(null),[u,d]=(0,W.useState)(!1),[f,p]=(0,W.useState)(``),[m,h]=(0,W.useState)(!1),[g,_]=(0,W.useState)(()=>Date.now()),[v,y]=(0,W.useState)({x:0,y:0}),b=(0,W.useRef)(null),x=(0,W.useRef)(null),S=(0,W.useRef)(null),C=(0,W.useRef)(null),w=(0,W.useRef)(null),T=(0,W.useRef)(0),D=(0,W.useRef)(null),O=(0,W.useRef)(null),[k,ee]=(0,W.useState)(!0),[te,A]=(0,W.useState)(null),M=n(`/farming-2/app-icon-v2-180.png`),N=E(r);(0,W.useEffect)(()=>{D.current=c},[c]);let P=(0,W.useCallback)(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),F=(0,W.useCallback)(()=>{let e=x.current?.getBoundingClientRect();if(!e)return;let t=e.right+8,n=e.left-qw-8;y({x:t+qw+10<=window.innerWidth?t:Math.max(8,n),y:Math.max(8,Math.min(e.top-4,window.innerHeight-Jw-8))})},[]),ne=(0,W.useCallback)(()=>{t||Qw().then(e=>A(()=>e)).catch(()=>p(e.shareLinkFailed))},[e.shareLinkFailed,t]),I=(0,W.useCallback)(async(t=!1)=>{let i=D.current;if(!t&&eT(i,Date.now()))return i;let a=T.current+1;T.current=a,d(!0),p(``);try{let t=await fetch(n(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r?{target:r}:{})}),i=await t.json();if(!t.ok||!(`shortUrl`in i))throw Error(`error`in i&&i.error?i.error:e.shareLinkFailed);return a===T.current?(l(i),_(Date.now()),h(!1),i):(await nT(i),null)}catch(t){return a===T.current&&p(t instanceof Error?t.message:e.shareLinkFailed),null}finally{a===T.current&&d(!1)}},[e.shareLinkFailed,r,N]),L=(0,W.useCallback)(()=>{P(),T.current+=1,a(!1),s(!1),p(``),h(!1),d(!1);let e=D.current;D.current=null,l(null),nT(e)},[P]),R=(0,W.useCallback)((e,t=!1)=>{P(),F(),a(!0),s(e),ne(),I(t)},[P,I,ne,F]),z=(0,W.useCallback)(()=>{!i||o||(P(),w.current=window.setTimeout(()=>{w.current=null,L()},Kw))},[P,L,i,o]),re=(0,W.useCallback)(()=>{if(i&&o){L();return}R(!0,!0)},[L,i,R,o]),B=(0,W.useCallback)(async()=>{let t=eT(D.current,Date.now())?D.current:await I(!0);if(t){if(!await j(t.longUrl)){p(e.copyFailed);return}h(!0),O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{h(!1),O.current=null},1800)}},[e.copyFailed,I]);(0,W.useLayoutEffect)(()=>{if(i)return F(),window.addEventListener(`resize`,F),()=>window.removeEventListener(`resize`,F)},[i,F]),(0,W.useEffect)(()=>{if(!i)return;let e=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(e)},[i]),(0,W.useEffect)(()=>{let e=D.current;e&&(D.current=null,l(null),h(!1),nT(e))},[N]),(0,W.useLayoutEffect)(()=>{if(!i)return;let e=()=>{let e=S.current,t=C.current;!e||!t||ee(t.scrollWidth<=e.clientWidth+1)};e();let t=typeof ResizeObserver<`u`?new ResizeObserver(e):null;return t&&S.current&&t.observe(S.current),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[i,c?.tokenLabel,c?.shortPath]),(0,W.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;t instanceof Node&&b.current?.contains(t)||L()},t=e=>{e.key===`Escape`&&L()};return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`keydown`,t,!0),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`keydown`,t,!0)}},[L,i]),(0,W.useEffect)(()=>()=>{P(),O.current!==null&&window.clearTimeout(O.current),T.current+=1,nT(D.current)},[P]);let ie=!!(c&&c.expiresAt<=g),V=c?$w(c.expiresAt-g):``,ae=c?.tokenLabel||c?.shortPath||e.copyFullShareLink,oe=tT(ae),se=k||oe.length<=1?[ae]:oe;return(0,K.jsxs)(`div`,{ref:b,className:`code-share-root`,onMouseEnter:ne,onMouseLeave:z,onFocus:()=>{P(),ne()},onBlur:e=>{!e.currentTarget.contains(e.relatedTarget)&&!o&&L()},children:[(0,K.jsx)(`button`,{ref:x,type:`button`,className:`code-share-button`,"data-testid":`code-share-button`,"aria-label":e.sharePage,title:e.sharePage,"aria-haspopup":`dialog`,"aria-expanded":i,onClick:re,children:(0,K.jsx)(cT,{})}),i&&(0,K.jsxs)(`div`,{className:`code-share-popover`,"data-testid":`code-share-popover`,role:`dialog`,"aria-label":e.scanToOpenOnPhone,style:{left:v.x,top:v.y},onMouseEnter:()=>{P()},onMouseLeave:z,onKeyDown:e=>{e.key===`Escape`&&(L(),x.current?.focus())},children:[(0,K.jsxs)(`div`,{className:`code-share-qr-frame`,"data-expired":ie?`true`:`false`,children:[(0,K.jsx)(`div`,{className:`code-share-qr-canvas`,children:c&&!u&&te?(0,K.jsx)(sT,{value:c.shortUrl,badgeUrl:M,qrCodeFactory:te}):(0,K.jsx)(`div`,{className:`code-share-qr-loading`,children:u?e.loading:e.shareLinkFailed})}),c&&(0,K.jsx)(`div`,{className:`code-share-countdown`,children:ie?e.shareLinkExpired:V}),ie&&(0,K.jsx)(`button`,{type:`button`,className:`code-share-refresh`,onClick:()=>void I(!0),children:e.refreshShareLink})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-share-copy-token`,"data-testid":`code-share-copy-link`,disabled:!c&&u,onClick:()=>void B(),children:[(0,K.jsxs)(`span`,{ref:S,className:`code-share-token ${k?`single-line`:``}`,"aria-label":ae,children:[(0,K.jsx)(`span`,{ref:C,className:`code-share-token-measure`,"aria-hidden":`true`,children:ae}),se.map((e,t)=>(0,K.jsx)(`span`,{className:`code-share-token-line`,children:e},`${t}-${e}`))]}),(0,K.jsx)(`span`,{className:`code-share-copy-action`,children:m?e.copiedShareLink:e.copyFullShareLink})]}),f&&(0,K.jsx)(`div`,{className:`code-share-error`,role:`status`,children:f})]})]})}function uT(e,t){return e&&t.some(t=>!t.isMain&&t.id===e)?e:t.find(e=>!e.isMain)?.id??null}function dT(e){return e&&(e.projectWorkspace||e.cwd)||``}function fT(e,t,n={}){return Kb(e,t).map(e=>{let t=e.workspace?n[e.workspace]?.trim():``;return t&&!e.hasMain?{...e,name:t}:e})}function pT(e,t,n,r=new Set,i=new Set){return t?PS(e.map(e=>{let n=[e.name,e.workspace].some(e=>e.toLowerCase().includes(t)),a=n?e.agents:e.agents.filter(e=>i.has(e.id)||h(e).toLowerCase().includes(t)),o=n?e.agentSessions:e.agentSessions.filter(e=>r.has(Rb(e))||e.title.toLowerCase().includes(t));return a.length>0||o.length>0?{...e,agents:a,agentSessions:o}:null}).filter(e=>!!e),n,!0):e}function mT(e,t,n){return e.flatMap(e=>t.has(e.id)&&!n?[]:[...e.agents.map(e=>({kind:`agent`,id:e.id})),...e.agentSessions.map(e=>({kind:`agent-session`,provider:e.provider,id:e.id,...e.providerHomeId?{providerHomeId:e.providerHomeId}:{}}))])}var hT=5,gT=5,_T=`__project_agent_drop_end__`;function vT(e){let t=e?.trim().toLowerCase()||``;if(t===`claude-code`)return`claude`;if([`codex`,`claude`,`opencode`,`qoder`,`bash`,`zsh`].includes(t))return t}function yT(e){return vT(e.providerSessionProvider)||vT(e.command.trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop())}function bT(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M3.75 3C3.33579 3 3 3.33579 3 3.75V5.5C3 5.77614 2.77614 6 2.5 6C2.22386 6 2 5.77614 2 5.5V3.75C2 2.7835 2.7835 2 3.75 2H5.5C5.77614 2 6 2.22386 6 2.5C6 2.77614 5.77614 3 5.5 3H3.75ZM10 2.5C10 2.22386 10.2239 2 10.5 2H12.25C13.2165 2 14 2.7835 14 3.75V5.5C14 5.77614 13.7761 6 13.5 6C13.2239 6 13 5.77614 13 5.5V3.75C13 3.33579 12.6642 3 12.25 3H10.5C10.2239 3 10 2.77614 10 2.5ZM2.5 10C2.77614 10 3 10.2239 3 10.5V12.25C3 12.6642 3.33579 13 3.75 13H5.5C5.77614 13 6 13.2239 6 13.5C6 13.7761 5.77614 14 5.5 14H3.75C2.7835 14 2 13.2165 2 12.25V10.5C2 10.2239 2.22386 10 2.5 10ZM13.5 10C13.7761 10 14 10.2239 14 10.5V12.25C14 13.2165 13.2165 14 12.25 14H10.5C10.2239 14 10 13.7761 10 13.5C10 13.2239 10.2239 13 10.5 13H12.25C12.6642 13 13 12.6642 13 12.25V10.5C13 10.2239 13.2239 10 13.5 10Z`})})}function xT(e){let t=e.trim().replace(/^v/i,``);if(!t)return``;let n=/^(\d+\.\d+\.\d+)-(\d+)-g[0-9a-f]+(?:-dirty)?$/i.exec(t);if(n)return`${n[1]}-${n[2]}`;let r=/^(\d+\.\d+\.\d+)-dirty$/i.exec(t);return r?`${r[1]}-1`:t.replace(/-dirty$/i,``)}var ST=(0,W.lazy)(()=>o(()=>import(`./ProjectFilesSection-Q4PDsWmM.js`).then(e=>({default:e.ProjectFilesSection})),__vite__mapDeps([14,1,5,6,15,12,13])));function CT({sidebarCollapsed:e,activeView:t,searchOpen:r,displayedProjects:i,collapsedProjectIds:a,normalizedSearch:o,hasProjectListItems:s,hasDisplayedProjectListItems:c,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:d,claimedAgentSessionKeyByAgentId:f,agentShortcutKeys:p,keyboardShortcutsEnabled:h,now:g,mainAgent:_,systemStats:v,usageSummary:y,shareTarget:b,agentLaunchOptions:x,agentCreationWorkspace:S,openWorkspaceFile:C,openWorkspaceFiles:w,fileRevealRequest:T,fileSearchFocusRequest:E,projectListRef:D,canLoadMoreAgentSessions:O,onLoadMoreAgentSessions:k,onNewAgent:ee,onStartAgent:te,onToggleSidebar:A,onOpenSearch:j,onOpenWorkspaceView:M,onOpenMainAgent:N,onRestartMainAgent:P,onProjectListKeyDown:F,onToggleProject:ne,onToggleProjectSessions:I,onOpenProjectContextMenu:L,onOpenProjectKeyboardMenu:R,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:V,onOpenAgentContextMenu:ae,onOpenAgentKeyboardMenu:oe,onResumeAgentSession:se,onOpenAgentSessionContextMenu:le,onOpenAgentSessionKeyboardMenu:ue,onOpenProjectFile:de,onSelectOpenWorkspaceFile:pe,onCloseOpenWorkspaceFile:me,onMoveWorkspaceEntries:H,onDeleteWorkspaceEntries:he,onOpenOptionsMenu:_e,copy:ve}){let[ye,be]=(0,W.useState)(null),xe=(0,W.useRef)(null),Se=(0,W.useRef)(!1),Ce=(0,W.useRef)(new Map),[we,Te]=(0,W.useState)(!0),[Ee,De]=(0,W.useState)(!1),[Ae,U]=(0,W.useState)(!1),je=(0,W.useCallback)(()=>U(!1),[]),[Me,Ne]=(0,W.useState)(!1),[Pe,Fe]=(0,W.useState)(!1),[G,Ie]=(0,W.useState)(!1),Le=(0,W.useCallback)(e=>{O&&e.scrollHeight-e.scrollTop-e.clientHeight<=240&&k()},[O,k]),Re=(0,W.useCallback)(()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),ze=(0,W.useCallback)(()=>{Re(),be(null)},[Re]),Be=(0,W.useCallback)(()=>{Se.current=!1,ze()},[ze]),Ve=(0,W.useCallback)((e,t,r=!1)=>{Re();let i=e.currentTarget,a=Se.current?0:r?450:1500;xe.current=window.setTimeout(()=>{if(xe.current=null,!i.matches(`:hover`))return;let e=i.getBoundingClientRect(),r=e.right+10,a=Math.min(320,window.innerWidth-r-12);if(a<200)return;let o=Math.max(8,Math.min(e.top-4,window.innerHeight-152)),s=t.agentId?Ce.current.get(t.agentId):void 0,c=s&&s.expiresAt>Date.now()?s.branch:``;Se.current=!0,be({...t,x:r,y:o,width:a,branch:c}),!(!t.agentId||c)&&fetch(n(`/api/files/branch?agentId=${encodeURIComponent(t.agentId)}`)).then(e=>e.ok?e.json():null).then(e=>{let n=typeof e?.branch==`string`?e.branch.trim():``;Ce.current.set(t.agentId,{branch:n,expiresAt:Date.now()+3e4}),be(e=>e?.key===t.key?{...e,branch:n}:e)}).catch(()=>{Ce.current.set(t.agentId,{branch:``,expiresAt:Date.now()+3e4})})},a)},[Re]);(0,W.useEffect)(()=>()=>Re(),[Re]),(0,W.useEffect)(()=>{Fe(!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen));let e=()=>{Ne(!!document.fullscreenElement)};return document.addEventListener(`fullscreenchange`,e),e(),()=>{document.removeEventListener(`fullscreenchange`,e)}},[]);let He=(0,W.useCallback)(()=>{if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>{})},[]),Ue=i.flatMap(e=>[...e.agents.filter(e=>e.pinned).map(e=>({kind:`agent`,agent:e})),...e.agentSessions.filter(e=>e.pinned).map(e=>({kind:`agent-session`,session:e}))]).sort((e,t)=>e.kind===`agent`&&t.kind===`agent`?(e.agent.pinnedOrder??0)-(t.agent.pinnedOrder??0)||(e.agent.startedAt??0)-(t.agent.startedAt??0):e.kind===t.kind?e.kind===`agent-session`&&t.kind===`agent-session`?Wb(t.session)-Wb(e.session):0:e.kind===`agent`?-1:1),We=i.filter(e=>e.agents.some(e=>!e.pinned||!e.isMain)||e.agentSessions.some(e=>!e.pinned)||(e.hiddenAgentSessionCount??0)>0),Ge=i.flatMap(e=>[...e.agents.filter(e=>!e.isMain).map(t=>({agent:t,projectName:e.name}))]),Ke=w.filter(e=>Oe(e.agentId)),qe=C&&Oe(C.agentId)?C:null,Je=T?.agentId===ke,Ye=Ke.length>0||Je;(0,W.useEffect)(()=>{Ye||Ie(!1)},[Ye]),(0,W.useEffect)(()=>{Je&&Ie(!1)},[Je]);let Xe=xT(`2.2.7`),Ze=Xe?`v${Xe}`:``,Qe=e;return(0,K.jsxs)(`aside`,{className:`code-sidebar ${e?`collapsed`:``}`,"data-testid":`code-sidebar`,onMouseLeave:Be,children:[(0,K.jsx)(`div`,{className:`code-nav`,children:(0,K.jsxs)(`div`,{className:`code-nav-top-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-nav-item primary`,"data-testid":`code-new-agent`,onClick:e=>ee(S,void 0,e.currentTarget),children:[(0,K.jsx)(`span`,{className:`code-nav-icon`,children:(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M14.452 1.548C14.087 1.183 13.608 1 13.13 1C12.652 1 12.173 1.183 11.808 1.548L6.979 6.377C6.697 6.659 6.498 7.011 6.401 7.398L6.027 8.896C5.883 9.473 6.329 10.002 6.886 10.002C6.958 10.002 7.031 9.993 7.106 9.975L8.604 9.601C8.99 9.504 9.343 9.305 9.625 9.023L14.454 4.194C15.184 3.464 15.184 2.28 14.454 1.549L14.452 1.548ZM13.745 3.485L8.916 8.314C8.763 8.467 8.57 8.576 8.36 8.629L7.04 8.962L7.371 7.64C7.424 7.43 7.532 7.237 7.686 7.084L12.516 2.255C12.68 2.091 12.899 2 13.131 2C13.363 2 13.582 2.091 13.746 2.255C14.085 2.594 14.085 3.146 13.746 3.486L13.745 3.485ZM13 7.768L14 6.768V11.5C14 12.878 12.879 14 11.5 14H4.5C3.121 14 2 12.878 2 11.5V4.5C2 3.122 3.121 2 4.5 2H9.236L8.236 3H4.5C3.673 3 3 3.673 3 4.5V11.5C3 12.327 3.673 13 4.5 13H11.5C12.327 13 13 12.327 13 11.5V7.768Z`})})}),(0,K.jsx)(`span`,{children:ve.newAgent}),h&&(0,K.jsx)(`kbd`,{children:`N`})]}),(0,K.jsx)(lT,{copy:ve,sidebarCollapsed:e,shareTarget:b}),Pe&&!e&&(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-focus-toggle ${Me?`active`:``}`,"data-testid":`code-sidebar-focus-toggle`,"aria-label":Me?ve.exitFocusMode:ve.enterFocusMode,title:Me?ve.exitFocusMode:ve.enterFocusMode,"aria-pressed":Me,onClick:He,children:(0,K.jsx)(`span`,{className:`code-sidebar-focus-icon`,children:(0,K.jsx)(bT,{})})}),!e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-search-toggle ${t===`search`||r?`active`:``}`,"data-testid":`code-nav-search`,"aria-label":ve.search,title:ve.search,"aria-pressed":t===`search`||r,onClick:j,children:(0,K.jsx)(`span`,{className:`code-sidebar-search-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ie,{})})}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-history-toggle ${t===`history`?`active`:``}`,"data-testid":`code-nav-history`,"aria-label":ve.history,title:ve.history,"aria-pressed":t===`history`,onClick:()=>M(`history`),children:(0,K.jsx)(`span`,{className:`code-sidebar-history-icon`,"aria-hidden":`true`,children:(0,K.jsx)(sE,{})})})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-toggle`,"data-testid":`code-sidebar-toggle`,"aria-label":e?ve.expandSidebar:ve.collapseSidebar,title:e?ve.expandSidebar:ve.collapseSidebar,onClick:A,children:(0,K.jsx)(`span`,{className:`code-sidebar-toggle-icon ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(fe,{}):(0,K.jsx)(ce,{})})})]})}),e&&Ge.length>0&&(0,K.jsx)(GT,{items:Ge,activeTerminalId:l,now:g,onOpenAgent:z,onShowPreview:Ve,onHidePreview:ze,copy:ve}),(0,K.jsxs)(`div`,{className:`code-project-list`,"data-testid":`code-project-list`,ref:D,tabIndex:0,onKeyDown:F,onScroll:e=>Le(e.currentTarget),"aria-label":ve.projectsAndAgents,children:[!s&&(0,K.jsx)(`div`,{className:`code-empty-project`,children:ve.noAgentsYet}),s&&!c&&(0,K.jsx)(`div`,{className:`code-empty-project`,"data-testid":`code-empty-search`,children:ve.noMatchingProjectsOrAgents}),Ue.length>0&&(0,K.jsx)(YT,{items:Ue,collapsed:Ee,compressed:Qe,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:d,claimedAgentSessionKeyByAgentId:f,agentShortcutKeys:p,keyboardShortcutsEnabled:h,now:g,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:V,onOpenAgentContextMenu:ae,onOpenAgentKeyboardMenu:oe,onResumeAgentSession:se,onOpenAgentSessionContextMenu:le,onOpenAgentSessionKeyboardMenu:ue,onShowAgentPreview:Ve,onHideAgentPreview:ze,onToggleCollapsed:()=>De(e=>!e),copy:ve}),Ye&&(0,K.jsxs)(`section`,{className:`code-project-group code-root-files-group`,"data-testid":`code-root-files-group`,children:[(0,K.jsx)(`div`,{className:`code-project-row code-root-files-row`,children:(0,K.jsxs)(`button`,{type:`button`,className:`code-project-title`,"data-testid":`code-root-files-title`,"aria-expanded":!G,onClick:()=>Ie(e=>!e),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${G?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:G?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:`/`})]})}),!G&&(0,K.jsx)(`div`,{className:`code-project-expanded`,children:(0,K.jsx)(W.Suspense,{fallback:null,children:(0,K.jsx)(ST,{projectId:`__farming_global_files_project__`,projectWorkspace:`/`,agentId:`__farming_global_files__`,agentLaunchOptions:[],activeFilePath:qe?.file.path,openFiles:Ke.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:m(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:T?.agentId===`__farming_global_files__`?T:void 0,focusSearchRequest:E?.agentId===`__farming_global_files__`?E:void 0,onOpenFile:de,onSelectOpenFile:pe,onCloseOpenFile:me,onMoveEntries:H,onDeleteEntries:he,readOnly:!0,copy:ve})})})]}),We.map(e=>(0,K.jsx)(XT,{project:e,collapsed:a.has(e.id)&&!o,compactAgents:Qe,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:d,claimedAgentSessionKeyByAgentId:f,agentShortcutKeys:p,keyboardShortcutsEnabled:h,now:g,openWorkspaceFile:C,openWorkspaceFiles:w,agentLaunchOptions:x,fileRevealRequest:T,fileSearchFocusRequest:E,onToggleProject:ne,onToggleProjectSessions:I,onNewAgent:ee,onStartAgent:te,onOpenProjectContextMenu:L,onOpenProjectKeyboardMenu:R,onOpenAgent:z,onUpdateAgentFlags:B,onReorderAgent:V,onOpenAgentContextMenu:ae,onOpenAgentKeyboardMenu:oe,onResumeAgentSession:se,onOpenAgentSessionContextMenu:le,onOpenAgentSessionKeyboardMenu:ue,onShowAgentPreview:Ve,onHideAgentPreview:ze,onOpenProjectFile:de,onSelectOpenWorkspaceFile:pe,onCloseOpenWorkspaceFile:me,onMoveWorkspaceEntries:H,onDeleteWorkspaceEntries:he,copy:ve},e.id))]}),(0,K.jsxs)(`div`,{className:`code-sidebar-footer`,children:[(0,K.jsxs)(`div`,{className:`code-product-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-product-mark`,"data-testid":`code-product-mark`,title:`Farming Code`,"aria-label":`Farming Code`,onClick:()=>U(!0),children:[(0,K.jsx)(`img`,{className:`code-product-logo`,src:n(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-product-mark-copy`,children:[(0,K.jsxs)(`span`,{className:`code-product-mark-main-slot`,children:[(0,K.jsx)(`span`,{className:`code-product-mark-main code-product-mark-main-full`,children:`Farming Code`}),(0,K.jsx)(`span`,{className:`code-product-mark-main code-product-mark-main-short`,"aria-hidden":`true`,children:`Farming`})]}),Ze&&(0,K.jsx)(`span`,{className:`code-product-mark-badge`,children:Ze})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-options`,"data-testid":`code-sidebar-options`,"aria-label":ve.openSettings,title:ve.openSettings,onClick:_e,children:(0,K.jsx)(re,{})})]}),(y||v||_)&&(0,K.jsx)(K.Fragment,{children:!e&&(y||v||_)&&(0,K.jsx)(UT,{collapsed:we,mainAgent:_,usageSummary:y,systemStats:v,onToggleCollapsed:()=>Te(e=>!e),onOpenMainAgent:N,onRestartMainAgent:P})})]}),ye&&(0,K.jsx)(nE,{preview:ye,now:g}),Ae&&(0,K.jsx)(Fw,{copy:ve,version:Ze,onClose:je})]})}function wT(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`Window`:t===10080?`Weekly`:t%1440==0?`${t/1440}d`:t%60==0?`${t/60}h`:`${t}m`}function TT(e){let t=Number(e);return Number.isFinite(t)?`${Math.round(t)}%`:`--`}function ET(e){let t=Number(e);if(!Number.isFinite(t))return`-- left`;let n=Math.max(0,Math.min(100,100-t));return`${Math.round(n)}% left`}function DT(e){let t=e.forecast?.remainingTokens,n=t==null?null:Number(t);return typeof n==`number`&&Number.isFinite(n)&&n>=0?`${AT(Math.round(n))} tok left`:ET(e.usedPercent)}function OT(e){return DT(e)}function kT(e,t){let n=[e],r=TT(t.usedPercent),i=DT(t);return r!==`--`&&n.push(`${r} used`),i!==`-- left`&&n.push(i),n.filter(Boolean).join(` / `)}function AT(e){if(e>=1e6){let t=e/1e6;return`${t>=10?Math.round(t):Math.round(t*10)/10}M`}if(e>=1e3){let t=e/1e3;return`${t>=10?Math.round(t):Math.round(t*10)/10}k`}return`${e}`}function jT(e,t=!1){let n=Number(e);if(!Number.isFinite(n))return`-- tok/min`;let r=n<10?Math.round(n*10)/10:Math.round(n);return`${t?`~`:``}${AT(r)} tok/min`}function MT(e){let t=e.auth?.status||``;return e.auth?.available?/logged in/i.test(t)?`logged in`:t||`available`:`offline`}function NT(e){return e?.providers.length?e.providers.reduce((e,t)=>{let n=Number(t.tokenUsage.tokensPerMinute);return e+(Number.isFinite(n)?n:0)},0):null}function PT(e){let t=e.forecast?.remainingPercent;if(typeof t==`number`&&Number.isFinite(t))return Math.max(0,Math.min(100,t));let n=Number(e.usedPercent);return Number.isFinite(n)?Math.max(0,Math.min(100,100-n)):null}function FT(e){let t=Number(e.windowMinutes);return Number.isFinite(t)&&t>=10020?0:Number.isFinite(t)&&t>=285&&t<=315?1:2}function IT(e){return[e.quota.primary,e.quota.secondary].filter(e=>!!e).map(e=>({label:wT(e.windowMinutes),limit:e,remaining:PT(e),exhaustedAt:typeof e.forecast?.projectedExhaustedAt==`number`&&Number.isFinite(e.forecast.projectedExhaustedAt)?e.forecast.projectedExhaustedAt:null})).filter(e=>e.remaining!==null).sort((e,t)=>FT(e.limit)-FT(t.limit))}function LT(e){let t=Number(e.tokenUsage.tokensPerMinute);return Number.isFinite(t)&&t>0}function RT(e){return e?.providers.length?e.providers.filter(e=>LT(e)&&e.quota.available).map(e=>{let t=IT(e),n=t.filter(e=>e.remaining!==null&&e.remaining<50);return n.length?{provider:e,limits:t,earliestExhaustedAt:n.reduce((e,t)=>t.exhaustedAt===null?e:e===null?t.exhaustedAt:Math.min(e,t.exhaustedAt),null),lowestRemaining:n.reduce((e,t)=>Math.min(e,t.remaining??100),100)}:null}).filter(e=>!!e).sort((e,t)=>e.earliestExhaustedAt!==null&&t.earliestExhaustedAt!==null?e.earliestExhaustedAt-t.earliestExhaustedAt:e.earliestExhaustedAt===null?t.earliestExhaustedAt===null?e.lowestRemaining-t.lowestRemaining:1:-1)[0]??null:null}function zT(e){let t=RT(e);return t?[t.provider.providerName,...t.limits.map(e=>`${e.label} ${Math.round(e.remaining??0)}%`)].join(` · `):null}function BT(e,t){let n=[],r=NT(e);return r!==null&&n.push(jT(r)),t&&n.push(`CPU ${t.cpu}% / MEM ${t.memory.percentage}%`),n.join(` · `)||`5m`}function VT(e,t){return zT(e)||BT(e,t)}function HT(e){return e.status===`pending`?`starting`:e.status===`dead`?`offline`:e.status}function UT({collapsed:e,mainAgent:t,usageSummary:n,systemStats:r,onToggleCollapsed:i,onOpenMainAgent:a,onRestartMainAgent:o}){let s=NT(n),c=VT(n,r),[l,u]=(0,W.useState)(!1);return(0,K.jsxs)(`div`,{className:`code-usage-panel ${e?`collapsed`:``}`,"data-testid":`code-usage-panel`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-header`,"data-testid":`code-usage-toggle`,"aria-expanded":!e,title:`Provider local token usage refreshes periodically.`,onClick:i,children:[(0,K.jsxs)(`span`,{className:`code-usage-title`,children:[(0,K.jsx)(`span`,{className:`code-usage-chevron ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:`Usage`})]}),(0,K.jsx)(`span`,{className:`code-usage-header-meta`,children:(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,children:e?c:`5m`})})]}),!e&&(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-main-agent-block`,children:[(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-main-agent`,title:`${h(t)} · ${t.command} · ${t.cwd}`,"data-testid":`code-main-agent-usage-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-main-agent-open`,"data-testid":`code-main-agent-open`,onClick:a,children:[(0,K.jsx)(`span`,{children:`Main Agent`}),(0,K.jsx)(`strong`,{children:HT(t)})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-usage-main-agent-restart`,"data-testid":`code-main-agent-restart`,"aria-expanded":l,onClick:()=>u(e=>!e),children:`Restart`})]}),l&&(0,K.jsx)(`div`,{className:`code-main-agent-restart-menu`,"data-testid":`code-main-agent-restart-menu`,role:`menu`,children:[[`codex`,`Codex`],[`claude`,`Claude Code`],[`opencode`,`OpenCode`],[`qoder`,`Qoder`],[`bash`,`bash`],[`zsh`,`zsh`]].map(([e,t])=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-main-agent-restart-${e}`,onClick:()=>{u(!1),o(e)},children:t},e))})]}),n?.providers.map(e=>(0,K.jsx)(WT,{provider:e},e.provider)),s!==null&&(0,K.jsxs)(`div`,{className:`code-usage-row`,title:`Sum of local token usage reported by providers.`,children:[(0,K.jsx)(`span`,{children:`Total local tokens`}),(0,K.jsx)(`strong`,{children:jT(s)})]}),r&&(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:`System`}),(0,K.jsxs)(`strong`,{children:[`CPU `,r.cpu,`% / MEM `,r.memory.percentage,`%`]})]})]})]})}function WT({provider:e}){let t=e.quota.primary??null,n=e.quota.secondary??null,r=e.quota.available?e.quota.source:e.quota.reason||e.quota.source;return(0,K.jsxs)(`div`,{className:`code-usage-provider`,children:[(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:e.providerName}),(0,K.jsx)(`strong`,{title:e.auth?.status,children:MT(e)})]}),e.quota.available?(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:kT(r,t),children:[(0,K.jsx)(`span`,{children:wT(t.windowMinutes)}),(0,K.jsx)(`strong`,{children:OT(t)})]}),n&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:kT(r,n),children:[(0,K.jsx)(`span`,{children:wT(n.windowMinutes)}),(0,K.jsx)(`strong`,{children:OT(n)})]})]}):(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow muted`,title:r,children:[(0,K.jsx)(`span`,{children:`Quota`}),(0,K.jsx)(`strong`,{children:`unavailable`})]}),(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:e.tokenUsage.source,children:[(0,K.jsx)(`span`,{children:`Local tokens`}),(0,K.jsx)(`strong`,{children:jT(e.tokenUsage.tokensPerMinute)})]})]})}function GT({items:e,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a,copy:o}){return(0,K.jsx)(`div`,{className:`code-agent-rail`,"data-testid":`code-agent-rail`,"aria-label":o.projectsAndAgents,children:e.map((e,o)=>(0,K.jsx)(KT,{item:e,index:o,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a},fC({kind:`agent`,agent:e.agent})))})}function KT({item:e,index:t,activeTerminalId:n,now:r,onOpenAgent:i,onShowPreview:a,onHidePreview:o}){let s=xC({kind:`agent`,agent:e.agent},r),c=e.agent.id===n,l=[s.title,s.commandTitle,e.projectName].filter(Boolean).join(` · `);return(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-rail-button ${c?`active`:``} ${s.unread?`unread`:``}`,"data-testid":`code-agent-rail-item`,"data-agent-id":e.agent.id,"aria-label":l,onClick:()=>{i(e.agent.id)},onMouseEnter:t=>a(t,eE(e.agent,s,e.projectName),!0),onMouseLeave:o,children:[(0,K.jsx)(`span`,{className:`code-agent-rail-label`,children:t+1}),s.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-rail-status ${s.lifecycleStatus} ${s.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),s.unread&&(0,K.jsx)(`span`,{className:`code-agent-rail-unread`,"aria-hidden":`true`})]})}function qT({agents:e,activeTerminalId:t,selectedSearchAgentId:n,claimedAgentSessionKeyByAgentId:r,now:i,onOpenAgent:a,onOpenAgentContextMenu:o,onOpenAgentKeyboardMenu:s,onShowPreview:c,onHidePreview:l}){return(0,K.jsx)(`div`,{className:`code-project-agent-strip`,"data-testid":`code-project-agent-strip`,"aria-label":`Project agents`,children:e.map((e,u)=>{let d=xC({kind:`agent`,agent:e},i),f=e.id===t,p=e.id===n,m=d.rowTitle||d.title;return(0,K.jsxs)(`button`,{type:`button`,className:`code-project-agent-compact ${f?`active`:``} ${p?`search-selected`:``} ${d.unread?`unread`:``}`,"data-testid":`code-project-agent-compact`,"data-agent-id":e.id,"aria-label":m,onClick:()=>a(e.id),onMouseEnter:t=>c(t,eE(e,d),!0),onMouseLeave:l,onContextMenu:t=>o(t,e.id),onKeyDown:t=>{s(t,e.id),!t.defaultPrevented&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),a(e.id))},children:[(0,K.jsx)(`span`,{className:`code-project-agent-compact-label`,children:u+1}),d.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-status ${d.lifecycleStatus} ${d.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),d.unread&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-unread`,"aria-hidden":`true`})]},fC({kind:`agent`,agent:e,claimedSessionKey:r.get(e.id)}))})})}function JT({items:e,activeTerminalId:t,selectedSearchAgentId:n,selectedSearchSessionHandle:r,claimedAgentSessionKeyByAgentId:i,now:a,onOpenAgent:o,onOpenAgentContextMenu:s,onOpenAgentKeyboardMenu:c,onResumeAgentSession:l,onOpenAgentSessionContextMenu:u,onOpenAgentSessionKeyboardMenu:d,onShowPreview:f,onHidePreview:p}){return(0,K.jsx)(`div`,{className:`code-project-agent-strip code-pinned-agent-strip`,"data-testid":`code-pinned-agent-strip`,"aria-label":`Pinned agents`,children:e.map((e,m)=>{let h=e.kind===`agent`?xC({kind:`agent`,agent:e.agent},a):xC({kind:`history`,session:e.session,fallbackTitle:e.session.providerName||e.session.provider||`Agent`},a),g=e.kind===`agent`?e.agent:null,_=e.kind===`agent`?null:e.session,v=_?Rb(_):null,y=g?g.id===t:!1,b=g?g.id===n:v===r,x=h.rowTitle||h.title;return(0,K.jsxs)(`button`,{type:`button`,className:`code-project-agent-compact ${y?`active`:``} ${b?`search-selected`:``} ${h.unread?`unread`:``}`,"data-testid":`code-pinned-agent-compact`,"data-agent-id":g?.id,"data-session-id":v??void 0,"aria-label":x,onClick:()=>{if(g){o(g.id);return}_&&l(_.provider,_.id,_.providerHomeId)},onMouseEnter:e=>f(e,g?eE(g,h):tE(_,h),!0),onMouseLeave:p,onContextMenu:e=>{if(g){s(e,g.id);return}_&&u(e,_.provider,Rb(_))},onKeyDown:e=>{g?c(e,g.id):_&&d(e,_.provider,Rb(_)),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),g?o(g.id):_&&l(_.provider,_.id,_.providerHomeId))},children:[(0,K.jsx)(`span`,{className:`code-project-agent-compact-label`,children:m+1}),h.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-status ${h.lifecycleStatus} ${h.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),h.unread&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-unread`,"aria-hidden":`true`})]},e.kind===`agent`?fC({kind:`agent`,agent:e.agent,claimedSessionKey:i.get(e.agent.id)}):fC({kind:`history`,session:e.session}))})})}function YT({items:e,collapsed:t,compressed:n,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,agentShortcutKeys:s,keyboardShortcutsEnabled:c,now:l,onOpenAgent:u,onUpdateAgentFlags:d,onReorderAgent:f,onOpenAgentContextMenu:p,onOpenAgentKeyboardMenu:m,onResumeAgentSession:h,onOpenAgentSessionContextMenu:g,onOpenAgentSessionKeyboardMenu:_,onShowAgentPreview:v,onHideAgentPreview:y,onToggleCollapsed:b,copy:x}){let S=e.flatMap(e=>e.kind===`agent`?[e.agent]:[]),[C,w]=(0,W.useState)(null),T=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),y(),w({agentId:t,targetAgentId:``,position:`before`})},E=(e,t)=>{if(!C||C.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?`before`:`after`;C.targetAgentId===t&&C.position===r||w(e=>e?{...e,targetAgentId:t,position:r}:null)},D=()=>w(null),O=(e,t)=>{if(e.preventDefault(),!C||C.agentId===t){D();return}let n=S.filter(e=>e.id!==C.agentId),r=n.findIndex(e=>e.id===t);if(r<0){D();return}let i=C.position===`before`?r:r+1;f(C.agentId,i>0?n[i-1]?.id??``:``,i<n.length?n[i]?.id??``:``),D()};return(0,K.jsxs)(`section`,{className:`code-pinned-section ${t?`collapsed`:``}`,"data-testid":`code-pinned-section`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-pinned-title`,"data-testid":`code-pinned-title`,"aria-expanded":!t,onClick:b,children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:x.pinned})]}),!t&&(0,K.jsx)(`div`,{className:`code-agent-list code-pinned-list`,children:n?(0,K.jsx)(JT,{items:e,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,now:l,onOpenAgent:u,onOpenAgentContextMenu:p,onOpenAgentKeyboardMenu:m,onResumeAgentSession:h,onOpenAgentSessionContextMenu:g,onOpenAgentSessionKeyboardMenu:_,onShowPreview:v,onHidePreview:y}):e.map(e=>{if(e.kind===`agent`){let t=e.agent;return(0,K.jsx)(uE,{agent:t,shortcutHint:c?s.get(t.id):void 0,active:t.id===r,searchSelected:t.id===i,now:l,onOpenAgent:u,onUpdateAgentFlags:d,reorderable:!0,dragging:C?.agentId===t.id,dropPosition:C?.targetAgentId===t.id?C.position:void 0,onAgentDragStart:T,onAgentDragEnd:D,onAgentDragOver:E,onAgentDrop:O,onOpenAgentContextMenu:p,onOpenAgentKeyboardMenu:m,onShowPreview:v,onHidePreview:y,copy:x},fC({kind:`agent`,agent:t,claimedSessionKey:o.get(t.id)}))}return(0,K.jsx)(uE,{session:e.session,searchSelected:Rb(e.session)===a,now:l,onResume:h,onOpenSessionContextMenu:g,onOpenSessionKeyboardMenu:_,onShowPreview:v,onHidePreview:y,copy:x},fC({kind:`history`,session:e.session}))})})]})}function XT({project:e,collapsed:t,compactAgents:n,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,agentShortcutKeys:s,keyboardShortcutsEnabled:c,now:l,openWorkspaceFile:u,openWorkspaceFiles:d,agentLaunchOptions:f,fileRevealRequest:p,fileSearchFocusRequest:h,onToggleProject:g,onToggleProjectSessions:y,onNewAgent:b,onStartAgent:x,onOpenProjectContextMenu:S,onOpenProjectKeyboardMenu:C,onOpenAgent:w,onUpdateAgentFlags:T,onReorderAgent:E,onOpenAgentContextMenu:D,onOpenAgentKeyboardMenu:O,onResumeAgentSession:k,onOpenAgentSessionContextMenu:ee,onOpenAgentSessionKeyboardMenu:te,onShowAgentPreview:A,onHideAgentPreview:j,onOpenProjectFile:M,onSelectOpenWorkspaceFile:N,onCloseOpenWorkspaceFile:P,onMoveWorkspaceEntries:F,onDeleteWorkspaceEntries:ne,copy:I}){let R=(0,W.useRef)(null),z=(0,W.useRef)(null),re=(0,W.useRef)(null),B=(0,W.useRef)(null),ie=(0,W.useRef)(null),[V,ae]=(0,W.useState)(null),[oe,se]=(0,W.useState)(!1),[ce,le]=(0,W.useState)(!1),[ue,de]=(0,W.useState)(null),[pe,me]=(0,W.useState)(()=>uT(null,e.agents)),H=uT(pe,e.agents),he=e.agents.find(e=>!e.isMain&&e.id===H)??null,_e=e.id!==`__farming_main_agent__`&&he!==null,ve=new Set(e.agents.filter(e=>!e.isMain).map(e=>e.id)),ye=(0,W.useCallback)(t=>ve.has(t.agentId)||t.workspaceRoot===e.id,[e.id,ve]),be=u&&ye(u)?u:null,xe=d.filter(ye),Se=new Set(xe.filter(e=>e.dirty).map(e=>e.file.path)),Ce=new Set(xe.filter(e=>e.externalChanged).map(e=>e.file.path)),we=e.agents.filter(e=>!e.pinned),Te=e.agentSessions.filter(e=>!e.pinned),Ee=we.length>0||Te.length>0||(e.hiddenAgentSessionCount??0)>0,De=ce&&L()&&we.length>1,Oe=(n||De)&&we.length>0,ke=Oe||oe?we:QT(we,gT,[r,i]),Ae=Math.max(0,we.length-ke.length);(0,W.useEffect)(()=>{pe!==H&&me(H)},[H,pe]);let U=(0,W.useCallback)(e=>{le(!e)},[]),je=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),j(),de({agentId:t,targetAgentId:``,position:`before`})},Me=(e,t)=>{if(!ue||ue.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?`before`:`after`;ue.targetAgentId===t&&ue.position===r||de(e=>e?{...e,targetAgentId:t,position:r}:null)},Ne=()=>de(null),Pe=(e,t)=>{if(e.preventDefault(),!ue||ue.agentId===t){Ne();return}let n=we.filter(e=>e.id!==ue.agentId),r=n.findIndex(e=>e.id===t);if(r<0){Ne();return}let i=ue.position===`before`?r:r+1;E(ue.agentId,i>0?n[i-1]?.id??``:``,i<n.length?n[i]?.id??``:``),Ne()},Fe=e=>{if(e.preventDefault(),!ue)return;let t=we.filter(e=>e.id!==ue.agentId);E(ue.agentId,t[t.length-1]?.id??``,``),Ne()},G=e=>{ue&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,ue.targetAgentId!==_T&&de(e=>e?{...e,targetAgentId:_T,position:`after`}:null))};(0,W.useEffect)(()=>{we.length<=gT&&oe&&se(!1)},[oe,we.length]),(0,W.useLayoutEffect)(()=>{let e=R.current;if(!e)return;let t=()=>{let t=z.current;e.style.setProperty(`--code-project-sticky-height`,t?`${Math.ceil(t.getBoundingClientRect().height)}px`:``);let n=re.current;e.style.setProperty(`--code-agents-sticky-height`,n?`${Math.ceil(n.getBoundingClientRect().height)}px`:`0px`)};t();let n=z.current,r=re.current,i=typeof ResizeObserver<`u`?new ResizeObserver(t):null;return n&&i?.observe(n),r&&i?.observe(r),window.addEventListener(`resize`,t),()=>{i?.disconnect(),window.removeEventListener(`resize`,t)}},[t,e.id,Ee]),(0,W.useEffect)(()=>{if(!V)return;let e=e=>{let t=e.target;t&&(ie.current?.contains(t)||B.current?.contains(t))||ae(null)},t=e=>{e.key===`Escape`&&(e.preventDefault(),ae(null),B.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t,!0)}},[V]);let Ie=t=>{if(t.preventDefault(),t.stopPropagation(),f.length===0){b(e.workspace,void 0,t.currentTarget);return}let n=t.currentTarget.getBoundingClientRect(),r=Math.min(260,f.length*34+12);ae(L()?Ww(n,r,void 0,160):Uw(n,r,void 0,160))},Le=t=>{ae(null),x(t,e.workspace)};return(0,K.jsxs)(`section`,{ref:R,className:`code-project-group`,"data-testid":`code-project-group`,children:[(0,K.jsxs)(`div`,{ref:z,className:`code-project-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-project-title`,"data-testid":`code-project-title`,"data-project-id":e.id,"aria-expanded":!t,onClick:()=>g(e.id),onContextMenu:t=>S(t,e.id),onKeyDown:t=>C(t,e.id),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:e.name})]}),(0,K.jsxs)(`span`,{className:`code-project-title-actions`,"aria-hidden":!1,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-actions`,"aria-label":I.openOptions,title:I.openOptions,onClick:t=>S(t,e.id),children:(0,K.jsx)($T,{})}),(0,K.jsx)(`button`,{ref:B,type:`button`,className:`code-project-title-action`,"data-testid":`code-project-new-agent`,"aria-label":I.newAgent,title:I.newAgent,"aria-haspopup":`menu`,"aria-expanded":V?!0:void 0,onClick:Ie,children:(0,K.jsx)(ZT,{})})]}),V&&typeof document<`u`&&(0,Nw.createPortal)((0,K.jsx)(`div`,{ref:ie,className:`code-context-menu code-project-launch-menu`,"data-testid":`code-project-new-agent-menu`,role:`menu`,style:{left:V.x,top:V.y},children:f.map(e=>(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-project-agent-launch-${e.name}`,onClick:()=>Le(e.command||e.name),children:[(0,K.jsx)(_,{name:e.name}),(0,K.jsx)(`span`,{children:v(e.name)})]},e.name))}),document.body)]}),!t&&(0,K.jsxs)(`div`,{className:`code-project-expanded`,children:[Ee&&(0,K.jsx)(`div`,{ref:re,className:`code-agents-section`,"data-testid":`code-agents-section`,"data-project-id":e.id,children:(0,K.jsxs)(`div`,{className:`code-agent-list`,children:[Oe?(0,K.jsx)(qT,{agents:we,activeTerminalId:r,selectedSearchAgentId:i,claimedAgentSessionKeyByAgentId:o,now:l,onOpenAgent:w,onOpenAgentContextMenu:D,onOpenAgentKeyboardMenu:O,onShowPreview:A,onHidePreview:j}):ke.map(e=>(0,K.jsx)(uE,{agent:e,shortcutHint:c?s.get(e.id):void 0,active:e.id===r,searchSelected:e.id===i,now:l,onOpenAgent:w,onUpdateAgentFlags:T,reorderable:!0,dragging:ue?.agentId===e.id,dropPosition:ue?.targetAgentId===e.id?ue.position:void 0,onAgentDragStart:je,onAgentDragEnd:Ne,onAgentDragOver:Me,onAgentDrop:Pe,onOpenAgentContextMenu:D,onOpenAgentKeyboardMenu:O,onShowPreview:A,onHidePreview:j,copy:I},fC({kind:`agent`,agent:e,claimedSessionKey:o.get(e.id)}))),!Oe&&Ae>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more ${ue?.targetAgentId===_T?`drop-after`:``}`,"data-testid":`code-agent-show-more`,onClick:()=>se(!0),onDragOver:G,onDrop:Fe,children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:Ae})})]}),!Oe&&oe&&we.length>gT&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-agent-show-less`,onClick:()=>se(!1),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showLess})})}),Te.map(e=>(0,K.jsx)(uE,{session:e,searchSelected:Rb(e)===a,now:l,onResume:k,onOpenSessionContextMenu:ee,onOpenSessionKeyboardMenu:te,onShowPreview:A,onHidePreview:j,copy:I},fC({kind:`history`,session:e}))),(e.hiddenAgentSessionCount??0)>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-more`,onClick:()=>y(e.id),children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:e.hiddenAgentSessionCount})})]}),e.agentSessionsExpanded&&e.agentSessions.length>hT&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-less`,onClick:()=>y(e.id),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showLess})})})]})}),_e&&he&&(0,K.jsx)(W.Suspense,{fallback:null,children:(0,K.jsx)(ST,{projectId:e.id,projectWorkspace:e.workspace,agentId:he.id,agentLaunchOptions:f,activeFilePath:be?.file.path,openFiles:xe.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:m(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:p&&ve.has(p.agentId)?p:void 0,focusSearchRequest:h&&ve.has(h.agentId)?h:void 0,editorDirtyFilePaths:Se,editorExternalChangedFilePaths:Ce,onOpenFile:M,onSelectOpenFile:N,onCloseOpenFile:P,onNewAgent:b,onStartAgent:x,onMoveEntries:F,onDeleteEntries:ne,onFilesCollapsedChange:U,copy:I})})]})]})}function ZT(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M7.5 3C7.77614 3 8 3.22386 8 3.5V7H11.5C11.7761 7 12 7.22386 12 7.5C12 7.77614 11.7761 8 11.5 8H8V11.5C8 11.7761 7.77614 12 7.5 12C7.22386 12 7 11.7761 7 11.5V8H3.5C3.22386 8 3 7.77614 3 7.5C3 7.22386 3.22386 7 3.5 7H7V3.5C7 3.22386 7.22386 3 7.5 3Z`})})}function QT(e,t,n){if(e.length<=t)return e;let r=e.slice(0,t),i=new Set(r.map(e=>e.id)),a=new Set(n.filter(e=>!!e));for(let n of e)if(!(!a.has(n.id)||i.has(n.id))){if(r.length>=t&&r.length>0){let e=r[r.length-1];i.delete(e.id),r[r.length-1]=n}else r.push(n);i.add(n.id)}return r}function $T(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M4 8C4 8.55228 3.55228 9 3 9C2.44772 9 2 8.55228 2 8C2 7.44772 2.44772 7 3 7C3.55228 7 4 7.44772 4 8ZM9 8C9 8.55228 8.55228 9 8 9C7.44772 9 7 8.55228 7 8C7 7.44772 7.44772 7 8 7C8.55228 7 9 7.44772 9 8ZM13 9C13.5523 9 14 8.55228 14 8C14 7.44772 13.5523 7 13 7C12.4477 7 12 7.44772 12 8C12 8.55228 12.4477 9 13 9Z`})})}function eE(e,t,n){return{key:`agent:${e.id}`,title:t.title,project:n||jb(e.projectWorkspace||e.cwd),lastActive:e.lastActivity||e.startedAt||0,provider:yT(e),agentId:e.id}}function tE(e,t){return{key:`session:${Rb(e)}`,title:t.title,project:Ub(e),lastActive:Wb(e),provider:vT(e.provider)}}function nE({preview:e,now:t}){return(0,K.jsxs)(`div`,{className:`code-agent-hover-preview`,"data-testid":`code-agent-hover-preview`,style:{left:e.x,top:e.y,width:e.width},"aria-hidden":`true`,children:[(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-header`,children:[(0,K.jsx)(`strong`,{children:e.title}),(0,K.jsx)(`span`,{children:s(e.lastActive,t)})]}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-icon`,children:(0,K.jsx)(rE,{})}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-project`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-project-name`,children:e.project}),e.provider&&(0,K.jsx)(_,{name:e.provider,variant:`color`,className:`code-agent-hover-preview-provider-icon`})]})]}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-icon`,children:(0,K.jsx)(iE,{})}),(0,K.jsx)(`span`,{children:e.branch||`—`})]})]})}function rE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M1.5 3.75C1.5 2.784 2.284 2 3.25 2h3.104c.464 0 .91.184 1.237.513l.841.842c.14.14.33.22.528.22h3.79c.966 0 1.75.784 1.75 1.75v6.925c0 .966-.784 1.75-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75V3.75Zm1.75-.75a.75.75 0 0 0-.75.75v8.5c0 .414.336.75.75.75h9.5a.75.75 0 0 0 .75-.75V5.325a.75.75 0 0 0-.75-.75H8.96a1.75 1.75 0 0 1-1.235-.512l-.841-.842A.75.75 0 0 0 6.354 3H3.25Z`})})}function iE(){return(0,K.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M21 8.25C21 6.1815 19.3185 4.5 17.25 4.5C15.1815 4.5 13.5 6.1815 13.5 8.25C13.5 10.023 14.739 11.5035 16.395 11.892C16.116 12.819 15.2655 13.5 14.25 13.5H9.75C8.9025 13.5 8.1285 13.7925 7.5 14.268V7.4235C9.21 7.0755 10.5 5.5605 10.5 3.75C10.5 1.6815 8.8185 0 6.75 0C4.6815 0 3 1.6815 3 3.75C3 5.562 4.29 7.0755 6 7.4235V16.575C4.29 16.923 3 18.438 3 20.2485C3 22.317 4.6815 23.9985 6.75 23.9985C8.8185 23.9985 10.5 22.317 10.5 20.2485C10.5 18.4755 9.261 16.995 7.605 16.6065C7.884 15.6795 8.7345 14.9985 9.75 14.9985H14.25C16.0845 14.9985 17.61 13.6725 17.931 11.9295C19.674 11.607 21 10.0845 21 8.25ZM4.5 3.75C4.5 2.5095 5.5095 1.5 6.75 1.5C7.9905 1.5 9 2.5095 9 3.75C9 4.9905 7.9905 6 6.75 6C5.5095 6 4.5 4.9905 4.5 3.75ZM9 20.25C9 21.4905 7.9905 22.5 6.75 22.5C5.5095 22.5 4.5 21.4905 4.5 20.25C4.5 19.0095 5.5095 18 6.75 18C7.9905 18 9 19.0095 9 20.25ZM17.25 10.5C16.0095 10.5 15 9.4905 15 8.25C15 7.0095 16.0095 6 17.25 6C18.4905 6 19.5 7.0095 19.5 8.25C19.5 9.4905 18.4905 10.5 17.25 10.5Z`})})}function aE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M10.0589 2.44511C9.34701 1.73063 8.14697 1.90829 7.67261 2.79839L5.6526 6.58878L2.8419 7.52568C2.6775 7.58048 2.5532 7.71649 2.51339 7.88514C2.47357 8.0538 2.52392 8.23104 2.64646 8.35357L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5265 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L13.1897 8.32423C14.0759 7.84982 14.2538 6.6551 13.5443 5.94305L10.0589 2.44511ZM8.55511 3.2687C8.71323 2.972 9.11324 2.91278 9.35055 3.15094L12.836 6.64889C13.0725 6.88624 13.0131 7.28448 12.7178 7.44262L8.76403 9.55921C8.65137 9.61952 8.56608 9.72068 8.52567 9.84191L7.7815 12.0744L3.92562 8.21853L6.15812 7.47436C6.27966 7.43385 6.38101 7.34823 6.44126 7.23518L8.55511 3.2687Z`})})}function oE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M9.56016 10.2673L14.1464 14.8536C14.3417 15.0488 14.6583 15.0488 14.8536 14.8536C15.0488 14.6583 15.0488 14.3417 14.8536 14.1464L1.85355 1.14645C1.65829 0.951184 1.34171 0.951184 1.14645 1.14645C0.951184 1.34171 0.951184 1.65829 1.14645 1.85355L5.73223 6.43934L5.6526 6.58876L2.8419 7.52566C2.6775 7.58046 2.5532 7.71648 2.51339 7.88513C2.47357 8.05378 2.52392 8.23102 2.64646 8.35356L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5264 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L9.56016 10.2673ZM8.82138 9.52849L8.76403 9.5592C8.65137 9.61951 8.56608 9.72066 8.52567 9.84189L7.7815 12.0744L3.92562 8.21851L6.15812 7.47435C6.27966 7.43383 6.38101 7.34822 6.44126 7.23516L6.47143 7.17854L8.82138 9.52849ZM12.7178 7.4426L10.6636 8.54227L11.4024 9.28105L13.1897 8.32422C14.0759 7.84981 14.2538 6.65509 13.5443 5.94304L10.0589 2.44509C9.34701 1.73062 8.14697 1.90828 7.67261 2.79838L6.71556 4.59421L7.45476 5.33341L8.55511 3.26869C8.71323 2.97199 9.11324 2.91277 9.35055 3.15093L12.836 6.64888C13.0725 6.88623 13.0131 7.28446 12.7178 7.4426Z`})})}function sE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M7.99909 3C10.7605 3 12.9991 5.23858 12.9991 8C12.9991 10.7614 10.7605 13 7.99909 13C5.39117 13 3.2491 11.003 3.0195 8.45512C2.99471 8.1801 2.75167 7.97723 2.47664 8.00202C2.20161 8.0268 1.99875 8.26985 2.02353 8.54488C2.29916 11.6035 4.86898 14 7.99909 14C11.3128 14 13.9991 11.3137 13.9991 8C13.9991 4.68629 11.3128 2 7.99909 2C6.20656 2 4.59815 2.78613 3.49909 4.03138V2.5C3.49909 2.22386 3.27524 2 2.99909 2C2.72295 2 2.49909 2.22386 2.49909 2.5V5.5C2.49909 5.77614 2.72295 6 2.99909 6H3.08812C3.09498 6.00014 3.10184 6.00014 3.10868 6H5.99909C6.27524 6 6.49909 5.77614 6.49909 5.5C6.49909 5.22386 6.27524 5 5.99909 5H3.99863C4.91128 3.78495 6.36382 3 7.99909 3ZM7.99909 5.5C7.99909 5.22386 7.77524 5 7.49909 5C7.22295 5 6.99909 5.22386 6.99909 5.5V8.5C6.99909 8.77614 7.22295 9 7.49909 9H9.49909C9.77524 9 9.99909 8.77614 9.99909 8.5C9.99909 8.22386 9.77524 8 9.49909 8H7.99909V5.5Z`})})}function cE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})})}function lE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M12.854 14.8542L14.854 12.8542C15.049 12.6592 15.049 12.3422 14.854 12.1472L12.854 10.1472C12.659 9.95223 12.342 9.95223 12.147 10.1472C11.952 10.3422 11.952 10.6592 12.147 10.8542L13.293 12.0002H8.5C8.225 12.0002 8 11.7752 8 11.5002V5.50023C8 5.22523 8.225 5.00023 8.5 5.00023H13.293L12.147 6.14623C12.049 6.24423 12.001 6.37223 12.001 6.50023C12.001 6.62823 12.05 6.75623 12.147 6.85423C12.342 7.04923 12.659 7.04923 12.854 6.85423L14.854 4.85423C15.049 4.65923 15.049 4.34223 14.854 4.14723L12.854 2.14723C12.659 1.95223 12.342 1.95223 12.147 2.14723C11.952 2.34223 11.952 2.65923 12.147 2.85423L13.293 4.00023H8.5C7.673 4.00023 7 4.67323 7 5.50023V8.00023H1.5C1.224 8.00023 1 8.22423 1 8.50023C1 8.77623 1.224 9.00023 1.5 9.00023H7V11.5002C7 12.3272 7.673 13.0002 8.5 13.0002H13.293L12.147 14.1462C12.049 14.2442 12.001 14.3722 12.001 14.5002C12.001 14.6282 12.05 14.7562 12.147 14.8542C12.342 15.0492 12.659 15.0492 12.854 14.8542Z`})})}function uE({agent:e,session:t,shortcutHint:n,active:r=!1,searchSelected:i,now:a,onOpenAgent:o,onUpdateAgentFlags:s,reorderable:c=!1,dragging:l=!1,dropPosition:u,onAgentDragStart:d,onAgentDragEnd:f,onAgentDragOver:p,onAgentDrop:m,onOpenAgentContextMenu:h,onOpenAgentKeyboardMenu:g,onResume:v,onOpenSessionContextMenu:y,onOpenSessionKeyboardMenu:b,onShowPreview:x,onHidePreview:S,copy:C}){let w=(0,W.useRef)(!1),T=e?{kind:`agent`,agent:e}:t?{kind:`history`,session:t,fallbackTitle:C.sessionFallbackTitle(t.providerName)}:null;if(!T)return null;let E=xC(T,a),D=E.requiresResume,O=e?.id??``,k=t?.provider??``,ee=t?.id??``,te=D?`code-active-session-row`:`code-agent-row`,A=e?yT(e):vT(t?.provider),j=()=>{if(D){S?.(),k&&ee&&v?.(k,ee,t?.providerHomeId);return}O&&o?.(O)};return(0,K.jsxs)(`div`,{tabIndex:0,className:`code-agent-row ${D?`requires-resume`:``} ${r?`active`:``} ${i?`search-selected`:``} ${E.pinned?`pinned`:``} ${E.unread?`unread`:``} ${l?`dragging`:``} ${u?`drop-${u}`:``}`,draggable:c||void 0,"data-testid":te,"data-agent-id":e?.id,"data-provider":t?.provider,"data-session-id":t?Rb(t):void 0,"aria-label":E.rowTitle||E.title,onDragStart:e=>{!O||!c||(w.current=!0,d?.(e,O))},onDragEnd:()=>{f?.(),window.setTimeout(()=>{w.current=!1},0)},onDragOver:e=>O&&p?.(e,O),onDrop:e=>O&&m?.(e,O),onClick:e=>{if(w.current){e.preventDefault(),e.stopPropagation();return}j()},onMouseEnter:n=>{e?x?.(n,eE(e,E)):t&&x?.(n,tE(t,E))},onMouseLeave:S,onContextMenu:e=>{if(D){S?.(),k&&t&&y?.(e,k,Rb(t));return}O&&h?.(e,O)},onKeyDown:e=>{D?k&&t&&b?.(e,k,Rb(t)):O&&g?.(e,O),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),j())},children:[A&&(0,K.jsx)(`span`,{className:`code-agent-row-provider-icon`,"aria-hidden":`true`,children:(0,K.jsx)(_,{name:A,variant:`color`})}),(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:E.title})}),(0,K.jsxs)(`span`,{className:`code-agent-row-trailing`,children:[E.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${E.lifecycleStatus} ${E.turnActive?`turn-active`:``}`,title:E.commandTitle||E.lifecycleStatus}),E.forkedToNewWorktree&&(0,K.jsx)(`span`,{className:`code-agent-fork-new-worktree`,"data-testid":`code-agent-new-worktree-fork`,title:C.newWorktreeFork,"aria-label":C.newWorktreeFork,role:`img`,children:(0,K.jsx)(lE,{})}),E.scheduled&&(0,K.jsx)(`span`,{className:`code-agent-schedule-clock`,"data-testid":`code-agent-schedule-clock`,title:E.scheduleTitle,"aria-label":E.scheduleTitle||C.scheduledTask}),E.unread&&(0,K.jsx)(`span`,{className:`code-agent-unread`,title:C.unread}),e&&(0,K.jsxs)(`span`,{className:`code-agent-row-actions`,"aria-hidden":!1,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action pin ${E.pinned?`active`:``}`,"data-testid":`code-agent-row-pin`,"aria-label":E.pinned?C.unpinAgent:C.pinAgent,title:E.pinned?C.unpinAgent:C.pinAgent,onClick:t=>{t.preventDefault(),t.stopPropagation(),e&&s?.(e,{pinned:!E.pinned})},children:E.pinned?(0,K.jsx)(oE,{}):(0,K.jsx)(aE,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action archive`,"data-testid":`code-agent-row-archive`,"aria-label":C.archiveAgent,title:C.archiveAgent,onClick:t=>{t.preventDefault(),t.stopPropagation(),e&&s?.(e,{archived:!0})},children:(0,K.jsx)(cE,{})})]}),(e||t)&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-more`,"data-testid":`code-agent-row-more`,"aria-label":C.openOptions,title:C.openOptions,onClick:e=>{if(e.preventDefault(),e.stopPropagation(),D){S?.(),k&&t&&y?.(e,k,Rb(t));return}O&&h?.(e,O)},children:(0,K.jsx)($T,{})}),n&&(0,K.jsx)(`kbd`,{children:n})]})]})}var dE=[`codex`,`claude`,`opencode`,`qoder`],fE=new Set([`bash`,`zsh`]),pE=/^[A-Za-z0-9._-]+$/,mE=[3,5,10,15,30,60,180];function hE(e){let t=e/1e3;return mE.reduce((e,n)=>Math.abs(n-t)<Math.abs(e-t)?n:e)}function gE(e){let t=e===`zh`;return{title:t?`设置`:`Settings`,subtitle:t?`管理 Farming 的本地元数据。`:`Manage local Farming metadata.`,close:t?`关闭`:`Close`,back:t?`返回导航`:`Back to navigation`,general:t?`通用`:`General`,appearance:t?`外观`:`Appearance`,light:t?`浅色`:`Light`,dark:t?`深色`:`Dark`,interface:t?`界面`:`Interface`,interfaceSkin:t?`界面皮肤`:`Interface skin`,farmingCode:`Farming Code`,farmingCrt:`Farming CRT`,language:t?`语言`:`Language`,english:`English`,chinese:`中文`,search:t?`搜索`:`Search`,agentPermissions:t?`Agent 权限`:`Agent Permissions`,dangerousSkipLabel:t?`默认跳过所有 agent 权限检查`:`Skip all agent permission checks by default`,dangerousSkipHint:t?`开启后,新启动的 Codex、Claude、OpenCode、Qoder、Qwen、Aider、GitHub Copilot CLI、Amazon Q 等会使用各自的危险跳过权限 flag。只在可信沙箱中使用。`:`When enabled, new Codex, Claude, OpenCode, Qoder, Qwen, Aider, GitHub Copilot CLI, Amazon Q, and similar agents launch with their provider-specific dangerous skip flags. Use only in trusted sandboxes.`,searchTimeout:t?`搜索超时`:`Search timeout`,searchTimeoutValue:e=>t?e>=60?`${e/60} 分钟`:`${e} 秒`:e>=60?`${e/60} min`:`${e} sec`,updates:t?`更新`:`Updates`,updateHint:t?`更新方式会自动匹配当前安装来源;npm 安装可直接一键升级。`:`Updates follow the current installation source; npm installations support one-click upgrades.`,updateUrl:t?`更新 URL`:`Update URL`,updateUrlPlaceholder:`https://github.com/zhuwenzhuang/farming/releases/latest`,updateUrlEmpty:t?`等待检查更新`:`Waiting for update check`,saveUpdateUrl:t?`保存更新 URL`:`Save Update URL`,refreshUpdates:t?`刷新`:`Refresh`,upgradeNow:t?`立即更新`:`Update Now`,currentVersion:t?`当前版本`:`Current`,latestVersion:t?`最新版本`:`Latest`,targetVersion:t?`升级版本`:`Target`,updateSource:t?`更新源`:`Update source`,updateMethod:t?`安装方式`:`Install method`,updateMethodLabel:e=>({npm:`npm`,"app-bundle":t?`兼容包`:`App bundle`,"source-deploy":t?`源码部署`:`Source deployment`,source:t?`源码检出`:`Source checkout`,"standalone-cli":t?`单文件 CLI`:`Standalone CLI`})[e]||e||`-`,updateRuntime:t?`当前机器`:`This machine`,upToDate:t?`已是最新版本`:`Up to date`,updateAvailable:t?`有新版本可用`:`Update available`,updateNotInstallable:t?`当前更新不可安装`:`Update is not installable`,updateInstalling:t?`升级已开始,服务会自动重启。`:`Upgrade started. The server will restart automatically.`,updateRestarting:t?`新版本已安装,正在重启 Farming。`:`The new version is installed. Restarting Farming.`,updateSucceeded:t?`更新成功。`:`Update completed.`,updateRolledBack:t?`新版本启动失败,已回退到旧版本。`:`The new version failed to start and Farming rolled back.`,agentHomes:`Agent Homes`,agentHomesHint:t?`为不同 Agent 配置独立的主目录。`:`Configure a separate home directory for each agent.`,addHome:e=>t?`添加 ${e} home`:`Add ${e} home`,edit:t?`编辑`:`Edit`,remove:t?`删除`:`Remove`,save:t?`保存`:`Save`,cancel:t?`取消`:`Cancel`,homeName:t?`Home 名称(可选)`:`Home name (optional)`,homePath:t?`Home 路径`:`Home path`,homeNameHint:t?`留空时将根据路径自动生成。允许字母、数字、点、下划线和短横线。`:`Leave empty to generate it from the path. Use letters, numbers, dots, underscores, and hyphens.`,homeNamePlaceholder:t?`例如:work`:`e.g. work`,pathPlaceholder:`~/.codex.local`,loading:t?`加载中…`:`Loading…`,saving:t?`保存中…`:`Saving…`,saved:t?`已保存`:`Saved`,loadFailed:t?`加载设置失败`:`Failed to load settings`,saveFailed:t?`保存失败`:`Failed to save`,invalidId:t?`Home 名称只能包含字母、数字、点、下划线和短横线。`:`Home name can only contain letters, numbers, dots, underscores, and hyphens.`,duplicateId:t?`同一个 provider 下 Home 名称不能重复。`:`Home name must be unique under the same provider.`,missingPath:t?`Home 路径不能为空。`:`Home path is required.`,removeLastHint:t?`至少保留一个 home。`:`Keep at least one home.`,removeDefaultHint:t?`default home 不能删除。`:`The default home cannot be removed.`,editDisabledHint:t?`home 不支持编辑;请删除后重新添加。`:`Homes cannot be edited. Remove and add again.`,confirmRemove:e=>t?`删除 home ${e}?`:`Remove home ${e}?`,empty:t?`还没有配置 home。`:`No homes configured.`,noAgents:t?`当前机器没有识别到可配置的 coding agent。`:`No configurable coding agents were detected on this machine.`,unavailable:t?`未安装`:`Not installed`}}function _E(e){return e.trim().toLowerCase()}function vE(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n={};return Object.entries(t).forEach(([e,t])=>{let r=_E(e);if(!r||!/^[a-z0-9._-]+$/.test(r)||!Array.isArray(t))return;let i=new Set,a=[];t.forEach(e=>{if(!e||typeof e!=`object`)return;let t=e,n=String(t.id??``).trim(),r=String(t.path??``).trim();if(!n||!r||!pE.test(n))return;let o=n.toLowerCase();i.has(o)||(i.add(o),a.push({id:n,path:r}))}),a.length>0&&(n[r]=a)}),n}function yE(e){return e===`codex`?`Codex`:e===`claude`?`Claude`:e===`opencode`?`OpenCode`:e===`qoder`?`Qoder`:e}function bE(e){return{codex:`~/.codex`,claude:`~/.claude`,opencode:`~/.opencode`,qoder:`~/.qoder`}[e]??`~/.${e}`}function xE(e){return!!e?.some(e=>e.id.toLowerCase()!==`default`)}function SE(e){return e.filter(e=>e.supported!==!1&&e.interactive!==!1).filter(e=>!fE.has(e.name)).filter(e=>dE.includes(e.name)).map(e=>_E(e.name)).filter(Boolean)}function CE(e,t){let n=new Set(SE(t)),r=Object.keys(e).filter(t=>xE(e[t])),i=new Set([...n,...r]);return Array.from(i).sort((e,t)=>{let n=dE.indexOf(e),r=dE.indexOf(t),i=n===-1?dE.length:n,a=r===-1?dE.length:r;return i===a?e.localeCompare(t):i-a})}function wE(e,t){let n=e[t]??[];return n.some(e=>e.id.toLowerCase()===`default`)?n:[{id:`default`,path:bE(t)},...n]}function TE(e,t){let n=e.trim().replace(/\/+$/,``).split(`/`).filter(Boolean),r=(n[n.length-1]??``).replace(/^\.+/,``).replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[.-]+|[.-]+$/g,``).slice(0,64)||`home`,i=new Set(t.map(e=>e.id.toLowerCase())),a=1,o=r;for(;i.has(o.toLowerCase());)a+=1,o=`${r}-${a}`;return{id:o}}function EE(e){return{provider:e,id:``,path:``}}function DE({open:e,activeAgentId:t=null,language:r,uiPreferences:i,agentLaunchOptions:a,onClose:o,onUpdateUiPreferences:s}){let c=(0,W.useMemo)(()=>gE(r),[r]),l=(0,W.useRef)(null),u=(0,W.useRef)(null),[d,f]=(0,W.useState)(!1),[p,m]=(0,W.useState)(``),[h,g]=(0,W.useState)(15),[_,v]=(0,W.useState)(null),[y,b]=(0,W.useState)(``),[x,S]=(0,W.useState)(!1),[C,w]=(0,W.useState)(!1),[T,E]=(0,W.useState)(()=>vE({codex:[{id:`default`,path:`~/.codex`}],claude:[{id:`default`,path:`~/.claude`}],opencode:[{id:`default`,path:`~/.opencode`}],qoder:[{id:`default`,path:`~/.qoder`}]})),[D,O]=(0,W.useState)(!1),[k,ee]=(0,W.useState)(!1),[te,A]=(0,W.useState)(``),[j,M]=(0,W.useState)(``),[N,P]=(0,W.useState)(null),F=(0,W.useCallback)(()=>{O(!0),M(``),fetch(n(`/api/settings`)).then(e=>e.json()).then(e=>{E(vE(e.settings?.agentHomes)),f(e.settings?.dangerouslySkipAgentPermissionsByDefault===!0),m(String(e.settings?.updateUrl??``)),g(hE(Number(e.settings?.searchTimeoutMs??15e3)))}).catch(()=>M(c.loadFailed)).finally(()=>O(!1))},[c.loadFailed]);(0,W.useEffect)(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),(0,W.useEffect)(()=>{e&&(F(),window.requestAnimationFrame(()=>l.current?.focus({preventScroll:!0})))},[F,e]),(0,W.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),o())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[o,e]);let ne=(0,W.useCallback)(e=>{ee(!0),M(``),A(``),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentHomes:e})}).then(async t=>{let n=await t.json().catch(()=>null);if(!t.ok)throw Error(n?.error||c.saveFailed);E(vE(n?.settings?.agentHomes??e)),P(null),A(c.saved),window.dispatchEvent(new CustomEvent(`farming-agent-homes-saved`))}).catch(e=>M(e instanceof Error?e.message:c.saveFailed)).finally(()=>ee(!1))},[c.saveFailed,c.saved]),I=(0,W.useCallback)((e=!0,t=!1)=>{t||(S(!0),M(``)),fetch(n(`/api/update${e?`?force=1`:``}`)).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.loadFailed);let n=t?.update??null;v(n);let r=n?.versions??[];b(e=>e&&r.some(t=>t.assetName===e)?e:r[0]?.assetName||``)}).catch(e=>{t||M(e instanceof Error?e.message:c.loadFailed)}).finally(()=>{t||S(!1)})},[c.loadFailed]),L=(0,W.useCallback)(()=>{w(!0),M(``),A(``),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({updateUrl:p})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.saveFailed);m(String(t?.settings?.updateUrl??``)),A(c.saved),I(!0)}).catch(e=>M(e instanceof Error?e.message:c.saveFailed)).finally(()=>w(!1))},[c.saveFailed,c.saved,I,p]),R=(0,W.useCallback)(e=>{g(e),M(``),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({searchTimeoutMs:e*1e3})}).then(async t=>{let n=await t.json().catch(()=>null);if(!t.ok)throw Error(n?.error||c.saveFailed);g(hE(Number(n?.settings?.searchTimeoutMs??e*1e3)))}).catch(e=>M(e instanceof Error?e.message:c.saveFailed))},120)},[c.saveFailed]),z=(0,W.useCallback)(()=>{if(!_?.versions?.find(e=>e.assetName===y)?.available){I(!0);return}S(!0),M(``),fetch(n(`/api/update/install`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({assetName:y})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok){let e=t?.blockingAgents||[],n=e.length?`: ${e.map(e=>e.command).join(`, `)}`:``;throw Error(`${t?.error||c.saveFailed}${n}`)}v(e=>({...e??{},state:t?.update?.state??e?.state,blockingAgents:t?.update?.blockingAgents??e?.blockingAgents})),A(c.updateInstalling)}).catch(e=>M(e instanceof Error?e.message:c.saveFailed)).finally(()=>S(!1))},[c,I,y,_]);(0,W.useEffect)(()=>{e&&I(!1)},[e,I]);let re=(0,W.useCallback)(e=>{f(e),ee(!0),M(``),A(``),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({dangerouslySkipAgentPermissionsByDefault:e})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.saveFailed);f(t?.settings?.dangerouslySkipAgentPermissionsByDefault===!0),A(c.saved)}).catch(t=>{f(!e),M(t instanceof Error?t.message:c.saveFailed)}).finally(()=>ee(!1))},[c.saveFailed,c.saved]),B=(0,W.useCallback)(()=>{if(!N)return;let e=_E(N.provider),t=N.path.trim();if(!t){M(c.missingPath);return}let n=T[e]??[],r=N.id.trim()||TE(t,n).id;if(!pE.test(r)){M(c.invalidId);return}if(n.some(e=>e.id.toLowerCase()===r.toLowerCase())){M(c.duplicateId);return}ne({...T,[e]:[...n,{id:r,path:t}]})},[c.duplicateId,c.invalidId,c.missingPath,N,T,ne]),ie=(0,W.useCallback)((e,t)=>{if(t.toLowerCase()===`default`)return;let n=T[e]??[];window.confirm(c.confirmRemove(t))&&ne({...T,[e]:n.filter(e=>e.id!==t)})},[c,T,ne]),V=_?.state?.phase||``;if((0,W.useEffect)(()=>{if(!e||![`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V))return;let t=window.setInterval(()=>I(!1,!0),1500);return()=>window.clearInterval(t)},[e,I,V]),!e)return null;let ae=CE(T,a),oe=_?.versions??[],se=oe.find(e=>e.assetName===y),de=x||C||[`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V),fe=_?.method||_?.current?.type||``,pe=c.updateMethodLabel(fe),H=fe===`app-bundle`||fe===`source-deploy`,he=_?.current?.releaseVersion||_?.current?.packageVersion||`-`,ge=_?.latest?.version||`-`,_e=V===`rolled-back`?c.updateRolledBack:V===`failed`&&_?.state?.error?_.state.error:V===`restarting`?c.updateRestarting:[`downloading`,`extracting`,`installing`,`rolling-back`].includes(V)?c.updateInstalling:_?.available?c.updateAvailable:V===`succeeded`?c.updateSucceeded:_?.latest?.blockedReason||c.upToDate;return(0,K.jsx)(`div`,{className:`code-settings-panel-overlay`,"data-testid":`code-settings-panel`,onPointerDown:e=>{e.target===e.currentTarget&&o()},children:(0,K.jsxs)(`aside`,{className:`code-settings-panel`,"aria-modal":`true`,role:`dialog`,"aria-labelledby":`code-settings-panel-title`,children:[(0,K.jsxs)(`header`,{className:`code-settings-panel-header`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-settings-panel-back`,onClick:o,"aria-label":c.back,children:(0,K.jsx)(ce,{})}),(0,K.jsx)(`div`,{children:(0,K.jsx)(`h2`,{id:`code-settings-panel-title`,children:c.title})}),(0,K.jsx)(`button`,{ref:l,type:`button`,className:`code-settings-panel-close`,onClick:o,"aria-label":c.close,children:(0,K.jsx)(le,{})})]}),(0,K.jsxs)(`div`,{className:`code-settings-panel-body`,children:[(0,K.jsx)(`section`,{className:`code-settings-section compact`,children:(0,K.jsxs)(`div`,{className:`code-settings-inline-preferences`,children:[(0,K.jsxs)(`div`,{className:`code-settings-inline-choice`,children:[(0,K.jsx)(ue,{"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":c.appearance,children:[(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`light`?`active`:``,onClick:()=>s({appearance:`light`}),children:c.light}),(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`dark`?`active`:``,onClick:()=>s({appearance:`dark`}),children:c.dark})]})]}),(0,K.jsx)(`div`,{className:`code-settings-inline-choice code-settings-language-choice`,children:(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":c.language,children:[(0,K.jsx)(`button`,{type:`button`,className:i.language===`en`?`active`:``,onClick:()=>s({language:`en`}),children:c.english}),(0,K.jsx)(`button`,{type:`button`,className:i.language===`zh`?`active`:``,onClick:()=>s({language:`zh`}),children:c.chinese})]})})]})}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.interface})})}),(0,K.jsx)(`div`,{className:`code-settings-card`,children:(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-runtime-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:c.interfaceSkin})}),(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":c.interfaceSkin,children:[(0,K.jsx)(`button`,{type:`button`,className:`active`,"data-testid":`code-settings-skin-code`,"aria-pressed":`true`,children:c.farmingCode}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-settings-skin-crt`,"aria-pressed":`false`,onClick:()=>window.location.assign(`${n(`/crt/`)}${t?`?agent=${encodeURIComponent(t)}`:``}`),children:c.farmingCrt})]})]})})]}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.search})})}),(0,K.jsx)(`div`,{className:`code-settings-card`,children:(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-search-timeout-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:c.searchTimeout})}),(0,K.jsx)(`input`,{type:`range`,min:`0`,max:String(mE.length-1),step:`1`,value:mE.indexOf(h),"aria-label":c.searchTimeout,onChange:e=>R(mE[Number(e.target.value)]??15)}),(0,K.jsx)(`output`,{children:c.searchTimeoutValue(h)})]})})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsxs)(`div`,{className:`code-settings-section-heading`,children:[(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.updates})}),(x||C)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:x?c.loading:c.saving})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-card`,children:[(0,K.jsxs)(`dl`,{className:`code-settings-update-status`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:c.updateMethod}),(0,K.jsx)(`dd`,{children:pe})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:c.currentVersion}),(0,K.jsx)(`dd`,{children:he})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:c.latestVersion}),(0,K.jsx)(`dd`,{children:ge})]})]}),H&&(0,K.jsxs)(`label`,{className:`code-settings-update-url`,children:[(0,K.jsx)(`span`,{children:c.updateSource}),(0,K.jsx)(`input`,{type:`url`,name:`farming-update-url`,inputMode:`url`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:p,placeholder:c.updateUrlPlaceholder,"aria-label":c.updateUrl,onChange:e=>m(e.target.value),disabled:de})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-actions`,children:[H&&(0,K.jsx)(`button`,{type:`button`,onClick:L,disabled:de,"aria-label":c.saveUpdateUrl,title:c.saveUpdateUrl,children:(0,K.jsx)(me,{})}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>I(!0),disabled:de,"aria-label":c.refreshUpdates,title:c.refreshUpdates,children:`↻`}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,onClick:z,disabled:de||!se?.available,"aria-label":c.upgradeNow,title:c.upgradeNow,children:`↑`})]}),oe.length>0&&(0,K.jsx)(`label`,{className:`code-settings-update-version`,children:(0,K.jsx)(`select`,{value:y,"aria-label":c.targetVersion,onChange:e=>b(e.target.value),disabled:de||oe.length===0,children:oe.map(e=>(0,K.jsxs)(`option`,{value:e.assetName||``,children:[e.version||e.assetName||`-`,e.assetName&&e.assetName!==e.version?` · ${e.assetName}`:``]},e.assetName||e.version))})}),(0,K.jsx)(`div`,{className:`code-settings-update-summary ${_?.available?`available`:``}`,children:_e})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.agentPermissions})})}),(0,K.jsxs)(`div`,{className:`code-settings-choice-row dangerous`,children:[(0,K.jsx)(`span`,{children:c.dangerousSkipLabel}),(0,K.jsx)(`button`,{type:`button`,className:`code-settings-permission-toggle ${d?`active`:``}`,role:`checkbox`,"aria-label":c.dangerousSkipLabel,"aria-pressed":d,disabled:k,onClick:()=>re(!d),children:(0,K.jsx)(me,{})})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsxs)(`div`,{className:`code-settings-section-heading`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:c.agentHomes}),(0,K.jsx)(`p`,{children:c.agentHomesHint})]}),(D||k||te)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:D?c.loading:k?c.saving:te})]}),j&&(0,K.jsx)(`div`,{className:`code-settings-error`,role:`alert`,children:j}),ae.length===0&&(0,K.jsx)(`div`,{className:`code-agent-home-empty`,children:c.noAgents}),(0,K.jsx)(`div`,{className:`code-agent-homes-list`,children:ae.map(e=>{let t=wE(T,e),n=SE(a).includes(e),r=t.find(e=>e.id.toLowerCase()===`default`),i=t.filter(e=>e.id.toLowerCase()!==`default`);return(0,K.jsxs)(`div`,{className:`code-agent-home-provider`,children:[(0,K.jsxs)(`div`,{className:`code-agent-home-provider-header`,children:[(0,K.jsxs)(`div`,{className:`code-agent-home-provider-title`,children:[(0,K.jsxs)(`strong`,{children:[yE(e),n?``:` · ${c.unavailable}`]}),r&&(0,K.jsxs)(`span`,{title:r.path,children:[r.path,` default`]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-agent-home-add`,onClick:()=>{M(``),A(``),P(EE(e))},"aria-label":c.addHome(yE(e)),title:c.addHome(yE(e)),children:(0,K.jsx)(Se,{})})]}),i.map(t=>(0,K.jsxs)(`div`,{className:`code-agent-home-row`,children:[(0,K.jsx)(`div`,{className:`code-agent-home-path`,title:t.path,children:t.path}),(0,K.jsx)(`div`,{className:`code-agent-home-id`,children:t.id}),(0,K.jsx)(`div`,{className:`code-agent-home-actions`,children:(0,K.jsx)(`button`,{type:`button`,onClick:()=>ie(e,t.id),"aria-label":c.remove,title:c.remove,children:(0,K.jsx)(le,{})})})]},t.id)),N&&N.provider===e&&(0,K.jsxs)(`div`,{className:`code-agent-home-form`,children:[(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:c.homePath}),(0,K.jsx)(`input`,{type:`text`,name:`farming-agent-home-${e}-path`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`next`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:N.path,placeholder:c.pathPlaceholder,"aria-label":c.homePath,onChange:e=>P(t=>t&&{...t,path:e.target.value})})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:c.homeName}),(0,K.jsx)(`input`,{type:`text`,name:`farming-agent-home-${e}-name`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:N.id,placeholder:c.homeNamePlaceholder,"aria-label":c.homeName,onChange:e=>P(t=>t&&{...t,id:e.target.value})}),(0,K.jsx)(`span`,{children:c.homeNameHint})]}),(0,K.jsxs)(`div`,{className:`code-agent-home-form-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>P(null),"aria-label":c.cancel,title:c.cancel,children:(0,K.jsx)(le,{})}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,disabled:k,onClick:B,"aria-label":c.save,title:c.save,children:(0,K.jsx)(me,{})})]})]})]},e)})})]})]})]})})}var OE=`\r`;function kE(e){return[{type:`paste`,text:e},OE]}function AE(e){let t=e+1;return t>=1&&t<=9?String(t):`\x1b[H${`\x1B[B`.repeat(Math.max(0,e))}\r`}function jE(e,t){let n=[],r=0;return e.applyModel&&e.modelIndex>=0&&e.reasoningIndex>=0&&(n.push({delayMs:r,input:kE(`/model`),kind:`command`}),r+=220,n.push({delayMs:r,input:AE(e.modelIndex),kind:`selection`}),e.reasoningCount>1&&(r+=220,n.push({delayMs:r,input:AE(e.reasoningIndex),kind:`selection`}))),e.applyFast&&e.fastAvailable&&(r+=n.length>0?220:0,n.push({delayMs:r,input:kE(`/fast`),kind:`command`})),r+=n.length>0?420:0,n.push({delayMs:r,input:kE(t),kind:`message`}),n}var ME={newAgent:`New Agent`,search:`Search`,history:`History`,codex:`Farming Code`,expandSidebar:`Expand sidebar`,collapseSidebar:`Collapse sidebar`,enterFocusMode:`Enter focus mode`,exitFocusMode:`Exit focus mode`,terminalView:`Terminal`,transcriptView:`Chat`,collapseComposer:`Hide input`,restoreComposer:`Show input`,codexTranscriptSyncing:`Syncing chat history...`,codexTranscriptUnavailable:`This session’s Chat history could not be loaded.`,codexTranscriptEmpty:``,codexTranscriptWaiting:`Agent is still working...`,codexTranscriptProcess:`Worked`,codexTranscriptWorking:`Processing`,codexTranscriptThinking:`Thinking`,codexTranscriptRunning:`Running`,codexTranscriptReading:`Reading`,codexTranscriptSearching:`Searching`,codexTranscriptEditing:`Editing`,codexTranscriptPlanActive:`On plan`,codexTranscriptPlanProgress:(e,t)=>`Plan ${e}/${t}`,codexTranscriptFetching:`Fetching`,codexTranscriptUsingTool:`Using tool`,codexTranscriptWorkedFor:e=>`Worked for ${e}`,codexTranscriptProcessCount:e=>`${e} ${e===1?`event`:`events`}`,codexTranscriptCopyDetails:`Copy details`,codexTranscriptCopiedDetails:`Copied`,codexTranscriptCopyAnswer:`Copy answer`,codexTranscriptCopiedAnswer:`Copied answer`,codexTranscriptReviewChanges:`Review`,codexTranscriptShowChanges:`Show file changes`,codexTranscriptLoadingChanges:`Loading exact changes…`,codexTranscriptKeepChange:`Keep`,codexTranscriptRevertChange:`Revert`,codexTranscriptChangeKept:`Kept`,codexTranscriptChangeReverted:`Reverted`,codexTranscriptShowMoreFiles:e=>`Show ${e} more file${e===1?``:`s`}`,codexGoalTitle:`Goal`,codexGoalEmpty:`No active goal`,codexGoalOpen:`Open goal controls`,codexGoalObjective:`Objective`,codexGoalStatus:`Status`,codexGoalTokenBudget:`Token budget`,codexGoalNoBudget:`No budget`,codexGoalUsage:(e,t)=>`${e.toLocaleString()} tokens · ${Math.round(t/60)}m`,codexGoalStatusLabel:e=>({active:`Active`,paused:`Paused`,blocked:`Blocked`,usageLimited:`Usage limited`,budgetLimited:`Budget limited`,complete:`Complete`})[e]??e,codexGoalEdit:`Edit`,codexGoalStart:`Start`,codexGoalStop:`Stop`,codexGoalDelete:`Delete`,codexGoalSave:`Save goal`,codexGoalClear:`Clear`,codexGoalSaving:`Saving...`,codexGoalUnsupported:`Native goal controls require a Codex App Server session.`,searchProjectsOrAgents:`Search projects or agents`,clearSearch:`Clear search`,projectsAndAgents:`Projects and agents`,noAgentsYet:`No agents yet.`,noMatchingProjectsOrAgents:`No matching projects or agents.`,openNavigation:`Open navigation`,closeNavigation:`Close navigation`,openOptions:`Open options`,openSettings:`Settings`,agentActions:`Agent actions`,appearanceLight:`Appearance: Light`,appearanceDark:`Appearance: Dark`,languageEnglish:`Language: English`,languageChinese:`Language: 中文`,pinAgent:`Pin Agent`,unpinAgent:`Unpin Agent`,renameAgent:`Rename Agent`,renameProject:`Rename project`,archiveAgent:`Archive`,reorderAgentFailed:`Failed to reorder Agent`,markAsRead:`Mark as read`,markAsUnread:`Mark as unread`,copyWorkingDirectory:`Copy working directory`,copiedWorkingDirectory:`Copied working directory`,copyFailed:`Copy failed`,sharePage:`Share page`,scanToOpenOnPhone:`Scan to open on phone`,copyFullShareLink:`Copy full link`,copiedShareLink:`Copied full link`,shareLinkFailed:`Share link unavailable`,sharedLocationUnavailable:e=>`Unable to locate shared path: ${e}`,shareLinkExpired:`Expired`,refreshShareLink:`Refresh`,brandStoryOrigin:`Farming Code began with a simple idea: when several coding agents work at once, people should not have to bounce between terminals, editors, and browser tabs.`,brandStoryPurpose:`It brings conversations, terminals, project files, and progress into one calm workspace, so attention stays on what matters.`,brandGithub:`GitHub`,mobileShareTitle:`Share page`,mobileForwardTitle:`Send this page`,mobileForwardHint:`Copy the link to send the current view to someone else.`,mobileShareCopyAction:`Copy link`,mobileShareCopied:`Copied`,mobileInstallTitle:`Add to Home Screen`,mobileInstallChromeHint:`Make sure this page is open in your system browser or Chrome.`,mobileInstallShareStep:`Tap Share in the browser toolbar.`,mobileInstallMoreStep:`If it is hidden, tap •••, then Share.`,mobileInstallAddStep:`Choose “Add to Home Screen”.`,mobileInstallOpenStep:`Open Farming from its Home Screen icon next time.`,mobileShareInstalled:`Farming is already open as a Home Screen app.`,forkSameWorktree:`Fork into same worktree`,forkNewWorktree:`Fork into new worktree`,newWorktreeFork:`Forked to new worktree`,scheduledTask:`Scheduled task`,killAgent:`Kill Agent`,killAgentQuestion:`Kill Agent?`,openSession:`Open Session`,pinChat:`Pin chat`,unpinChat:`Unpin chat`,archiveChat:`Archive`,archiveChats:`Archive chats`,archiveProject:`Archive Project`,deleteWorktree:`Delete Worktree`,deleteWorktreeQuestion:`Delete Worktree?`,deleteWorktreeDirtyDescription:e=>`${e} uncommitted or untracked file${e===1?``:`s`} will be deleted with this worktree.`,forceDelete:`Force Delete`,cancel:`Cancel`,retry:`Retry`,save:`Save`,stopAgentDescription:e=>`Stop ${e} and close its terminal.`,permissionModeLabel:(e,t)=>t,permissionModeDescription:(e,t)=>t,acpModeLabel:(e,t)=>({"read-only":`Read-only`,agent:`Workspace`,"agent-full-access":`Full access`,auto:`Auto`,default:`Manual`,acceptEdits:`Accept edits`,plan:`Plan`,dontAsk:`Don't ask`,bypassPermissions:`Bypass permissions`,build:`Build`})[e]??t,acpModeDescription:(e,t)=>({"read-only":`Read and analyze by default. File writes and commands that need more access require approval. Network access is off.`,agent:`Read and write inside this workspace and run sandboxed commands. Network and out-of-workspace access require approval.`,"agent-full-access":`Access files outside this workspace and use the network without approval prompts. Use only in a trusted environment.`,auto:`Use the model classifier to approve or deny permission requests.`,default:`Prompt before operations that require approval.`,acceptEdits:`Approve file edits automatically; ask about other operations that need permission.`,plan:`Plan and inspect without modifying files.`,dontAsk:`Do not show permission prompts; deny operations that were not already allowed.`,bypassPermissions:`Bypass permission checks. Use only in a trusted environment.`,build:`Run tools according to the permissions configured for this Agent.`})[e]??t,reasoningOptionLabel:(e,t)=>t,serviceTierLabel:(e,t)=>t,serviceTierDescription:(e,t)=>t,messageMode:`Message`,goalMode:`Goal`,planMode:`Plan`,askFollowUpChanges:`Ask for follow-up changes`,shellCommandPlaceholder:`Type a shell command`,describeAgentGoal:`Describe the goal for this agent`,describePlanFirst:`Describe what should be planned first`,openAgentTerminalFirst:`Open an agent terminal first`,queuedMessages:e=>`${e} queued messages`,steerQueuedMessage:`Steer`,discardQueuedMessage:`Discard queued message`,addContext:`Add context`,attachFile:`Attach file`,fileContext:`File context`,setObjective:`Set objective`,planFirst:`Plan first`,clearComposerMode:`Clear composer mode`,agentPermissionMode:`Agent permission mode`,permissionsPrompt:`Launch permission profile`,permissionProfileSavedForNextLaunch:`Saved for new agents. Running sessions keep the permissions they launched with.`,permissionProfileRestarting:`Switching agent permissions…`,permissionProfileApplying:`Applying App Server permissions…`,runtimeModeRestarting:`Restarting Agent…`,agentRestartTimedOut:`Agent restart timed out. The previous Agent remains available; try switching again.`,permissionRestartHint:`The running agent restarts to apply these permissions. If it has no resumable session id yet, a fresh session starts.`,permissionAppServerHint:`Applies to this App Server thread without restarting the Agent. New permissions take effect for subsequent turns.`,modelAndReasoning:`Model and reasoning`,reasoning:`Reasoning`,speed:`Speed`,startDictation:`Start dictation`,stopDictation:`Stop dictation`,speechUnsupported:`Speech recognition is not supported in this browser`,mobileDictationHint:`Use the microphone key on the iOS keyboard to dictate.`,sendMessage:`Send message`,interruptAgent:`Interrupt agent`,startOrSelectAgent:`Start or select an agent`,startOrSelectAgentDescription:`Projects live on the left. Open any agent terminal without closing the rest of the workspace.`,historySummary:(e,t,n,r)=>`${n+r} history agents`,searchHistory:`Search history`,noHistoryYet:`No history yet`,noHistoryDescription:`Agents moved off the main page will appear here.`,historyAgents:`History Agents`,agentSessions:`Agent Sessions`,recentWorkspaces:`Recent Workspaces`,agentsSessionsSummary:(e,t)=>`${e} agents · ${t} sessions`,restore:`Restore`,continueRun:`Continue`,open:`Open`,archived:`Archived`,pinned:`Pinned`,unread:`Unread`,showMore:`Show more`,showLess:`Show less`,latest:`Latest`,upgrade:`UPGRADE`,updating:`UPDATING`,retryUpdate:`RETRY`,checkForUpdates:`Check for updates`,updateFailed:`Update failed`,upgradeToVersion:e=>e?`Upgrade to ${e}`:`Upgrade Farming Code`,sessionFallbackTitle:e=>`${e||`Agent`} session`,resumeSessionAria:e=>`Resume ${e}`,resultsCount:e=>`${e} results`,noMatchingAgents:`No matching agents`,searchHint:`Search by Agent title, session title, or project.`,searchEmptyTitle:`Start a search`,searchEmptyDescription:`Type an Agent title, session title, or project name or path.`,agents:`Agents`,files:`Files`,changes:`Changes`,changedFiles:`Changed files`,trackedChanges:`Tracked`,untrackedChanges:`Untracked`,reviewChanges:`Review`,refreshChanges:`Refresh changes`,searchOrPathLine:`Search or path:line`,searchFilesOrJump:`Search files or jump to path line`,openEditors:`OPEN EDITORS`,loading:`Loading...`,searching:`Searching...`,noMatches:`No matches`,searchIgnoredFolders:`Also search ignored folders`,searchIncomplete:e=>`Search stopped early. Current timeout: ${Math.round(e/1e3)}s.`,terminalSearchPlaceholder:`Find in terminal`,terminalSearchPrevious:`Previous match`,terminalSearchNext:`Next match`,terminalSearchClose:`Close terminal search`,terminalSearchCaseSensitive:`Match case`,terminalSearchWholeWord:`Match whole word`,terminalSearchRegex:`Use regular expression`,terminalSearchNoResults:`No results`,terminalSearchResults:(e,t)=>`${e}/${t}`,terminalSessionUnavailable:`Terminal session unavailable`,appServerWaitingForFirstMessage:`App Server is ready. Send the first Composer message to start the shared Codex CLI terminal.`,appServerRequestTitle:`Codex needs your input`,appServerRequestCommand:`Requested command`,appServerRequestQuestion:`Question`,appServerRequestApprove:`Allow`,appServerRequestDecline:`Decline`,appServerRequestSubmit:`Submit answer`,appServerRequestUnsupported:`This Codex request is not supported in Farming. Declining it will let the turn continue safely.`,appServerApprovalRejectedTitle:`Permission request declined`,appServerApprovalRejectedDescription:`Chat does not approve this permission request. Increase this Agent permission mode, or handle it in Terminal view.`,acpPermissionTitle:`Agent needs permission`,acpPermissionTool:`Requested tool`,file:`File`,folder:`Folder`,go:`Go`,moreMatchesOmitted:`More matches omitted`,stickyFolderPath:`Sticky folder path`,containsUncommittedChanges:`Contains uncommitted changes`,changedOnDisk:`Changed on disk`,unsavedChanges:`Unsaved changes`,gitStatus:e=>`Git status: ${e}`,renameEntry:e=>`Rename ${e}`,newFile:`New File`,newFolder:`New Folder`,refresh:`Refresh`,rename:`Rename`,copyRelativePath:`Copy Relative Path`,copyShareUrl:`Copy Share URL`,delete:`Delete`,deleteFolderContents:e=>`Delete folder and all contents: ${e||``}`,deleteFile:e=>`Delete file: ${e||``}`,saveFile:`Save file`,savingFile:`Saving file`,reloadFile:`Reload file`,overwriteChangedFile:`Overwrite changed file`,openFileDiff:`Open File Diff`,openFileDiffFor:e=>`Open diff for ${e}`,closeDiff:`Close diff`,openFilePreview:`Open preview`,showFileSource:`Show source`,enableWordWrap:`Enable word wrap`,disableWordWrap:`Disable word wrap`,openMarkdownPreview:`Open Markdown preview`,showMarkdownSource:`Show Markdown source`,openMarkdownSplitPreview:`Open Markdown preview to side`,closeMarkdownSplitPreview:`Close Markdown side preview`,markdownPreviewFor:e=>`Markdown preview for ${e}`,markdownFrontMatter:`Front matter`,markdownHeadingAnchor:`Link to heading`,mermaidDiagram:`Mermaid diagram`,mermaidDiagramControls:`Mermaid diagram controls`,mermaidRendering:`Rendering diagram...`,mermaidRenderFailed:`Unable to render Mermaid diagram`,mermaidZoomIn:`Zoom in`,mermaidZoomOut:`Zoom out`,mermaidPanMode:`Toggle pan mode`,mermaidEnterFullscreen:`Open fullscreen diagram`,mermaidExitFullscreen:`Close fullscreen diagram`,mermaidResetView:`Reset view`,mermaidCopySource:`Copy Mermaid source`,mermaidCopiedSource:`Copied Mermaid source`,fileDiff:`File Diff`,loadingDiff:`Loading diff...`,noFileDiff:`No file changes.`,diffUnavailable:`Diff content is unavailable for this file.`,binaryDiffUnavailable:`Binary file diff is unavailable.`,diffTooLarge:`Diff is too large to display.`,deletedFileDiffOnly:`This deleted file is only available as a diff.`,showGitBlame:`Show git blame`,hideGitBlame:`Hide git blame`,gitBlameAnnotations:`Git blame annotations`,gitBlameDetails:`Git blame details`,filePath:`File path`,editorFor:e=>`Editor for ${e}`,revealInExplorer:e=>`Reveal ${e} in Explorer`,previewFor:e=>`Preview for ${e}`,author:`Author`,commit:`Commit`,date:`Date`,line:`Line`,unknown:`Unknown`,uncommitted:`Uncommitted`,closeBlameDetails:`Close blame details`,cut:`Cut`,copy:`Copy`,paste:`Paste`,selectAll:`Select All`,annotateWithBlame:`Annotate with Blame`,hideBlame:`Hide Blame`,openLineChangesWithPreviousRevision:`Open Line Changes with Previous Revision`,openLineChangesWithWorkingFile:`Open Line Changes with Working File`,lineChanges:`Line changes`,loadingLineChanges:`Loading line changes...`,noLineChanges:`No line changes for this line.`,closeLineChanges:`Close line changes`,close:`Close`,closeFile:e=>`Close ${e}`,closeOthers:`Close Others`,closeToRight:`Close to the Right`,closeSaved:`Close Saved`,closeAll:`Close All`,saveBeforeCloseTitle:e=>`Save changes to ${e}?`,saveBeforeCloseDescription:`If you do not save, your changes will be lost.`,dontSave:`Don't Save`,loadingBlame:`Loading blame...`,notGitRepository:`Not a git repository.`,noCommittedLines:`No committed lines.`,cursorPosition:(e,t)=>`Ln ${e}, Col ${t}`,startMainAgent:`Start Main Agent`,startNewAgent:`Start New Agent`,loadingAgents:`Loading agents...`,agentListUnavailable:`Agent list unavailable.`,noSupportedAgentsFound:`No supported agents found.`,resumePreviousMainAgent:`Resume previous Main Agent`,codingAgents:`coding agents`,otherAgents:`Shell`,workspace:`Workspace:`,workspacePathPlaceholder:`/path/to/workspace`,recentWorkspacesLower:`recent workspaces`,start:`Start`,back:`Back`,backToAgent:`Back to Agent`,goBack:`Go Back`,goForward:`Go Forward`,backendConnecting:`Connecting to Farming backend...`,backendConnectionLost:`Farming backend disconnected. Reconnecting...`,backendHeartbeatLost:`No Farming backend heartbeat. Waiting for it to recover...`},NE={newAgent:`新建 Agent`,search:`搜索`,history:`历史`,codex:`Farming Code`,expandSidebar:`展开侧边栏`,collapseSidebar:`收起侧边栏`,enterFocusMode:`进入沉浸模式`,exitFocusMode:`退出沉浸模式`,terminalView:`终端`,transcriptView:`对话`,collapseComposer:`收起输入框`,restoreComposer:`唤出输入框`,codexTranscriptSyncing:`正在同步聊天历史...`,codexTranscriptUnavailable:`无法加载此会话的 Chat 历史。`,codexTranscriptEmpty:``,codexTranscriptWaiting:`Agent 仍在工作...`,codexTranscriptProcess:`执行过程`,codexTranscriptWorking:`处理中`,codexTranscriptThinking:`思考中`,codexTranscriptRunning:`运行命令中`,codexTranscriptReading:`读取文件中`,codexTranscriptSearching:`搜索中`,codexTranscriptEditing:`修改文件中`,codexTranscriptPlanActive:`执行计划中`,codexTranscriptPlanProgress:(e,t)=>`执行计划 ${e}/${t}`,codexTranscriptFetching:`获取信息中`,codexTranscriptUsingTool:`调用工具中`,codexTranscriptWorkedFor:e=>`Worked for ${e}`,codexTranscriptProcessCount:e=>`${e} 个事件`,codexTranscriptCopyDetails:`复制详情`,codexTranscriptCopiedDetails:`已复制`,codexTranscriptCopyAnswer:`复制答复`,codexTranscriptCopiedAnswer:`已复制答复`,codexTranscriptReviewChanges:`Review`,codexTranscriptShowChanges:`展开文件改动`,codexTranscriptLoadingChanges:`正在加载准确改动…`,codexTranscriptKeepChange:`保留`,codexTranscriptRevertChange:`撤销`,codexTranscriptChangeKept:`已保留`,codexTranscriptChangeReverted:`已撤销`,codexTranscriptShowMoreFiles:e=>`显示另外 ${e} 个文件`,codexGoalTitle:`目标`,codexGoalEmpty:`没有活动目标`,codexGoalOpen:`打开目标控制`,codexGoalObjective:`目标内容`,codexGoalStatus:`状态`,codexGoalTokenBudget:`Token 预算`,codexGoalNoBudget:`不限制`,codexGoalUsage:(e,t)=>`${e.toLocaleString()} tokens · ${Math.round(t/60)} 分钟`,codexGoalStatusLabel:e=>({active:`进行中`,paused:`已暂停`,blocked:`已阻塞`,usageLimited:`用量受限`,budgetLimited:`预算受限`,complete:`已完成`})[e]??e,codexGoalEdit:`编辑`,codexGoalStart:`启动`,codexGoalStop:`停止`,codexGoalDelete:`删除`,codexGoalSave:`保存目标`,codexGoalClear:`清除`,codexGoalSaving:`保存中...`,codexGoalUnsupported:`原生目标控制需要 Codex App Server 会话。`,searchProjectsOrAgents:`搜索项目或 Agent`,clearSearch:`清空搜索`,projectsAndAgents:`项目与 Agent`,noAgentsYet:`还没有 Agent。`,noMatchingProjectsOrAgents:`没有匹配的项目或 Agent。`,openNavigation:`打开导航`,closeNavigation:`关闭导航`,openOptions:`打开选项`,openSettings:`设置`,agentActions:`Agent 操作`,appearanceLight:`外观:浅色`,appearanceDark:`外观:深色`,languageEnglish:`语言:English`,languageChinese:`语言:中文`,pinAgent:`置顶 Agent`,unpinAgent:`取消置顶`,renameAgent:`重命名 Agent`,renameProject:`重命名项目`,archiveAgent:`归档`,reorderAgentFailed:`调整 Agent 顺序失败`,markAsRead:`标为已读`,markAsUnread:`标为未读`,copyWorkingDirectory:`复制工作目录`,copiedWorkingDirectory:`已复制工作目录`,copyFailed:`复制失败`,sharePage:`分享页面`,scanToOpenOnPhone:`手机扫码打开`,copyFullShareLink:`复制完整链接`,copiedShareLink:`已复制完整链接`,shareLinkFailed:`分享链接不可用`,sharedLocationUnavailable:e=>`无法定位分享路径:${e}`,shareLinkExpired:`已过期`,refreshShareLink:`刷新`,brandStoryOrigin:`Farming Code 从一个简单的问题出发:当多个 Coding Agent 同时工作,人不该在终端、编辑器和浏览器标签页之间反复切换。`,brandStoryPurpose:`它把对话、终端、项目文件与进展放在一个安静的工作空间里,让注意力留在真正重要的事情上。`,brandGithub:`GitHub`,mobileShareTitle:`分享页面`,mobileForwardTitle:`转发当前页面`,mobileForwardHint:`复制链接,发送给其他人。`,mobileShareCopyAction:`复制链接`,mobileShareCopied:`已复制`,mobileInstallTitle:`添加到主屏幕`,mobileInstallChromeHint:`确认已使用系统浏览器或 Chrome 打开当前页面。`,mobileInstallShareStep:`点浏览器工具栏里的“分享”。`,mobileInstallMoreStep:`没看到时,点 •••,再点“分享”。`,mobileInstallAddStep:`选择“添加到主屏幕”。`,mobileInstallOpenStep:`以后从主屏幕的 Farming 图标进入。`,mobileShareInstalled:`Farming 已经作为主屏幕 App 打开。`,forkSameWorktree:`在同一 worktree 分叉`,forkNewWorktree:`分叉到新 worktree`,newWorktreeFork:`已分叉到新 worktree`,scheduledTask:`周期任务`,killAgent:`停止 Agent`,killAgentQuestion:`停止 Agent?`,openSession:`打开会话`,pinChat:`置顶会话`,unpinChat:`取消置顶会话`,archiveChat:`归档`,archiveChats:`归档会话`,archiveProject:`归档项目`,deleteWorktree:`删除 worktree`,deleteWorktreeQuestion:`删除 worktree?`,deleteWorktreeDirtyDescription:e=>`这个 worktree 里还有 ${e} 个未提交或未跟踪文件,强删会连同目录一起删除。`,forceDelete:`强制删除`,cancel:`取消`,retry:`重试`,save:`保存`,stopAgentDescription:e=>`停止 ${e} 并关闭它的终端。`,permissionModeLabel:(e,t)=>({ask:`请求批准`,approve:`自动批准`,full:`完全访问`,custom:`自定义`,default:`默认`,auto:`自动`,acceptEdits:`接受编辑`,dontAsk:`不询问`,plan:`计划`,bypassPermissions:`绕过权限`})[e]??t,permissionModeDescription:(e,t)=>({ask:`新 Codex 会话以 workspace-write 沙箱启动,并对不可信操作询问`,approve:`新 Codex 会话以 workspace-write 沙箱启动,并在 Codex 请求时询问`,full:`新 Codex 会话绕过批准和沙箱;仅用于可信沙箱`,custom:`新 Codex 会话使用 config.toml 中定义的权限`,default:`新 Claude Code 会话使用默认设置`,auto:`新 Claude Code 会话以 auto 权限模式启动`,acceptEdits:`新 Claude Code 会话允许文件编辑,其他高风险操作仍会询问`,dontAsk:`新 Claude Code 会话在支持时尽量避免交互式批准`,plan:`新 Claude Code 会话以计划权限模式启动`,bypassPermissions:`新 Claude Code 会话绕过权限检查;仅用于可信沙箱`})[e]??t,acpModeLabel:(e,t)=>({"read-only":`只读`,agent:`工作区`,"agent-full-access":`完全访问`,auto:`自动`,default:`手动批准`,acceptEdits:`接受编辑`,plan:`计划`,dontAsk:`不询问`,bypassPermissions:`绕过权限`,build:`执行`})[e]??t,acpModeDescription:(e,t)=>({"read-only":`默认只读和分析;写文件或运行需要更高权限的命令时会请求批准,网络默认关闭`,agent:`可在当前工作区内读写文件并运行沙箱命令;使用网络或访问工作区外内容时会请求批准`,"agent-full-access":`可访问工作区外文件并使用网络,且不再请求批准;仅用于可信环境`,auto:`由模型分类器自动批准或拒绝权限请求`,default:`需要权限的操作会先请求批准`,acceptEdits:`自动批准文件编辑;其他需要权限的操作仍会询问`,plan:`只进行规划和检查,不修改文件`,dontAsk:`不弹出权限询问;未经预先允许的操作会直接拒绝`,bypassPermissions:`绕过权限检查;仅用于可信环境`,build:`按照该 Agent 已配置的权限执行工具`})[e]??t,reasoningOptionLabel:(e,t)=>({config:`使用配置`,low:`低`,medium:`中`,high:`高`,xhigh:`超高`,max:`最高`})[e]??t,serviceTierLabel:(e,t)=>({default:`标准`,priority:`快`,flex:`弹性`})[e]??t,serviceTierDescription:(e,t)=>({default:`默认速度`,priority:`1.5 倍速度,用量增加`})[e]??t,messageMode:`消息`,goalMode:`目标`,planMode:`计划`,askFollowUpChanges:`输入后续修改要求`,shellCommandPlaceholder:`输入 Shell 命令`,describeAgentGoal:`描述这个 Agent 的目标`,describePlanFirst:`描述需要先规划的事情`,openAgentTerminalFirst:`先打开一个 Agent 终端`,queuedMessages:e=>`${e} 条排队消息`,steerQueuedMessage:`引导`,discardQueuedMessage:`丢弃排队消息`,addContext:`添加上下文`,attachFile:`附加文件`,fileContext:`文件上下文`,setObjective:`设置目标`,planFirst:`先做计划`,clearComposerMode:`清除输入模式`,agentPermissionMode:`Agent 权限模式`,permissionsPrompt:`启动权限 profile`,permissionProfileSavedForNextLaunch:`已保存给新 Agent。运行中的会话保留启动时的权限。`,permissionProfileRestarting:`正在切换 Agent 权限…`,permissionProfileApplying:`正在应用 App Server 权限…`,runtimeModeRestarting:`正在重启 Agent…`,agentRestartTimedOut:`Agent 重启超时。原 Agent 仍然可用,请重新切换。`,permissionRestartHint:`运行中的 Agent 会重启以应用权限;如果还没有可 resume 的 Session ID,则启动一个新会话。`,permissionAppServerHint:`直接应用到当前 App Server thread,不重启 Agent;新权限从后续 turn 生效。`,modelAndReasoning:`模型与推理`,reasoning:`推理`,speed:`速度`,startDictation:`开始语音输入`,stopDictation:`停止语音输入`,speechUnsupported:`当前浏览器不支持语音识别`,mobileDictationHint:`请点 iOS 键盘上的麦克风进行听写。`,sendMessage:`发送消息`,interruptAgent:`中止 Agent`,startOrSelectAgent:`启动或选择一个 Agent`,startOrSelectAgentDescription:`项目在左侧。打开任意 Agent 终端时,不会关闭其他工作区。`,historySummary:(e,t,n,r)=>`${n+r} 个 History Agents`,searchHistory:`搜索历史记录`,noHistoryYet:`还没有历史记录`,noHistoryDescription:`从主页面移出的 Agent 会出现在这里。`,historyAgents:`History Agents`,agentSessions:`Agent 会话`,recentWorkspaces:`最近工作区`,agentsSessionsSummary:(e,t)=>`${e} 个 Agent · ${t} 个会话`,restore:`恢复`,continueRun:`继续`,open:`打开`,archived:`已归档`,pinned:`已置顶`,unread:`未读`,showMore:`显示更多`,showLess:`收起`,latest:`最新`,upgrade:`升级`,updating:`更新中`,retryUpdate:`重试`,checkForUpdates:`检查更新`,updateFailed:`更新失败`,upgradeToVersion:e=>e?`升级到 ${e}`:`升级 Farming Code`,sessionFallbackTitle:e=>`${e||`Agent`} 会话`,resumeSessionAria:e=>`恢复 ${e}`,resultsCount:e=>`${e} 个结果`,noMatchingAgents:`没有匹配的 Agent`,searchHint:`可按 Agent 标题、会话标题或项目搜索。`,searchEmptyTitle:`开始搜索`,searchEmptyDescription:`输入 Agent 标题、会话标题,或项目名称、路径。`,agents:`Agent`,files:`文件`,changes:`变更`,changedFiles:`变更文件`,trackedChanges:`已跟踪`,untrackedChanges:`未跟踪`,reviewChanges:`Review`,refreshChanges:`刷新变更`,searchOrPathLine:`搜索或路径:行号`,searchFilesOrJump:`搜索文件或跳转到路径行号`,openEditors:`打开的编辑器`,loading:`加载中...`,searching:`搜索中...`,noMatches:`无匹配`,searchIgnoredFolders:`同时在已忽略目录中搜索`,searchIncomplete:e=>`搜索提前停止(当前超时:${Math.round(e/1e3)} 秒)`,terminalSearchPlaceholder:`在终端中查找`,terminalSearchPrevious:`上一个匹配`,terminalSearchNext:`下一个匹配`,terminalSearchClose:`关闭终端搜索`,terminalSearchCaseSensitive:`区分大小写`,terminalSearchWholeWord:`全词匹配`,terminalSearchRegex:`使用正则表达式`,terminalSearchNoResults:`无结果`,terminalSearchResults:(e,t)=>`${e}/${t}`,terminalSessionUnavailable:`终端会话不可用`,appServerWaitingForFirstMessage:`App Server 已就绪。发送第一条 Composer 消息后,会启动加入同一条 thread 的 Codex CLI 终端。`,appServerRequestTitle:`Codex 需要你的输入`,appServerRequestCommand:`请求执行的命令`,appServerRequestQuestion:`问题`,appServerRequestApprove:`允许`,appServerRequestDecline:`拒绝`,appServerRequestSubmit:`提交回答`,appServerRequestUnsupported:`Farming 目前不支持这类 Codex 请求。拒绝后,当前 turn 会安全地继续。`,appServerApprovalRejectedTitle:`已拒绝权限申请`,appServerApprovalRejectedDescription:`Chat 界面不会批准这类权限申请。请调高这个 Agent 的权限,或切到 Terminal 界面处理。`,acpPermissionTitle:`Agent 需要权限`,acpPermissionTool:`请求使用工具`,file:`文件`,folder:`文件夹`,go:`跳转`,moreMatchesOmitted:`更多匹配已省略`,stickyFolderPath:`固定文件夹路径`,containsUncommittedChanges:`包含未提交改动`,changedOnDisk:`磁盘上已变更`,unsavedChanges:`未保存改动`,gitStatus:e=>`Git 状态:${e}`,renameEntry:e=>`重命名 ${e}`,newFile:`新建文件`,newFolder:`新建文件夹`,refresh:`刷新`,rename:`重命名`,copyRelativePath:`复制相对路径`,copyShareUrl:`拷贝分享 URL`,delete:`删除`,deleteFolderContents:e=>`删除文件夹及其所有内容:${e||``}`,deleteFile:e=>`删除文件:${e||``}`,saveFile:`保存文件`,savingFile:`正在保存文件`,reloadFile:`重新加载文件`,overwriteChangedFile:`覆盖已变更文件`,openFileDiff:`打开文件 Diff`,openFileDiffFor:e=>`打开 ${e} 的 Diff`,closeDiff:`关闭 Diff`,openFilePreview:`打开预览`,showFileSource:`显示源码`,enableWordWrap:`开启折行`,disableWordWrap:`关闭折行`,openMarkdownPreview:`打开 Markdown 预览`,showMarkdownSource:`显示 Markdown 源码`,openMarkdownSplitPreview:`打开 Markdown 侧边预览`,closeMarkdownSplitPreview:`关闭 Markdown 侧边预览`,markdownPreviewFor:e=>`${e} 的 Markdown 预览`,markdownFrontMatter:`Front matter`,markdownHeadingAnchor:`跳转到这个标题`,mermaidDiagram:`Mermaid 图表`,mermaidDiagramControls:`Mermaid 图表控制`,mermaidRendering:`正在渲染图表...`,mermaidRenderFailed:`无法渲染 Mermaid 图表`,mermaidZoomIn:`放大`,mermaidZoomOut:`缩小`,mermaidPanMode:`切换平移模式`,mermaidEnterFullscreen:`全屏查看图表`,mermaidExitFullscreen:`退出全屏查看`,mermaidResetView:`重置视图`,mermaidCopySource:`复制 Mermaid 源码`,mermaidCopiedSource:`已复制 Mermaid 源码`,fileDiff:`文件 Diff`,loadingDiff:`正在加载 Diff...`,noFileDiff:`文件没有变化。`,diffUnavailable:`这个文件没有可显示的 Diff 内容。`,binaryDiffUnavailable:`二进制文件不能显示 Diff。`,diffTooLarge:`Diff 过大,无法显示。`,deletedFileDiffOnly:`这个已删除文件只支持以 Diff 查看。`,showGitBlame:`显示 Git Blame`,hideGitBlame:`隐藏 Git Blame`,gitBlameAnnotations:`Git Blame 标注`,gitBlameDetails:`Git Blame 详情`,filePath:`文件路径`,editorFor:e=>`${e} 的编辑器`,revealInExplorer:e=>`在文件树中显示 ${e}`,previewFor:e=>`${e} 的预览`,author:`作者`,commit:`提交`,date:`日期`,line:`行`,unknown:`未知`,uncommitted:`未提交`,closeBlameDetails:`关闭 Blame 详情`,cut:`剪切`,copy:`复制`,paste:`粘贴`,selectAll:`全选`,annotateWithBlame:`用 Blame 标注`,hideBlame:`隐藏 Blame`,openLineChangesWithPreviousRevision:`打开与上一版的行变化`,openLineChangesWithWorkingFile:`打开与工作区文件的行变化`,lineChanges:`行变化`,loadingLineChanges:`正在加载行变化...`,noLineChanges:`这一行没有可显示的变化。`,closeLineChanges:`关闭行变化`,close:`关闭`,closeFile:e=>`关闭 ${e}`,closeOthers:`关闭其他`,closeToRight:`关闭右侧`,closeSaved:`关闭已保存`,closeAll:`全部关闭`,saveBeforeCloseTitle:e=>`是否保存对 ${e} 的更改?`,saveBeforeCloseDescription:`如果不保存,你的更改将丢失。`,dontSave:`不保存`,loadingBlame:`正在加载 Blame...`,notGitRepository:`不是 Git 仓库。`,noCommittedLines:`没有已提交行。`,cursorPosition:(e,t)=>`第 ${e} 行,第 ${t} 列`,startMainAgent:`启动 Main Agent`,startNewAgent:`启动新 Agent`,loadingAgents:`正在加载 Agent...`,agentListUnavailable:`Agent 列表不可用。`,noSupportedAgentsFound:`没有找到支持的 Agent。`,resumePreviousMainAgent:`恢复上一个 Main Agent`,codingAgents:`Coding Agent`,otherAgents:`Shell`,workspace:`工作区:`,workspacePathPlaceholder:`/工作区/路径`,recentWorkspacesLower:`最近工作区`,start:`启动`,back:`返回`,backToAgent:`返回 Agent`,goBack:`后退`,goForward:`前进`,backendConnecting:`正在连接 Farming 后端...`,backendConnectionLost:`Farming 后端连接已断开,正在重连...`,backendHeartbeatLost:`没有收到 Farming 后端心跳,正在等待恢复...`};function PE(e){return e===`zh`?NE:ME}function FE(){return window}function IE(e,t={},n=FE()){let r=t.delays??[],i=[],a=t.animationFrame!==!1,o;return t.runNow!==!1&&e(),a&&(o=n.requestAnimationFrame(e)),r.forEach(t=>{i.push(n.setTimeout(e,t))}),()=>{o!==void 0&&n.cancelAnimationFrame(o),i.forEach(e=>n.clearTimeout(e))}}var LE={ask:`Ask for approval`,approve:`Approve for me`,full:`Full access`,custom:`Custom`},RE={ask:`Launch Codex with workspace-write sandbox and ask for untrusted actions`,approve:`Launch Codex with workspace-write sandbox and ask when Codex requests approval`,full:`Launch Codex with approvals and sandbox bypassed; use only in trusted sandboxes`,custom:`Launch Codex with permissions defined in config.toml`},zE=[`ask`,`approve`,`full`,`custom`].map(e=>({value:e,label:LE[e],description:RE[e],color:e===`approve`?`blue`:e===`full`?`orange`:`muted`})),BE={default:`Default`,auto:`Auto`,acceptEdits:`Accept edits`,dontAsk:`Don't ask`,plan:`Plan`,bypassPermissions:`Bypass permissions`},VE={default:`Launch Claude Code with its default settings`,auto:`Launch Claude Code in auto permission mode`,acceptEdits:`Launch Claude Code allowing file edits while still asking for other risky actions`,dontAsk:`Launch Claude Code avoiding interactive approval prompts where supported`,plan:`Launch Claude Code in plan permission mode`,bypassPermissions:`Launch Claude Code with permission checks bypassed; use only in trusted sandboxes`},HE=[`default`,`auto`,`acceptEdits`,`dontAsk`,`plan`,`bypassPermissions`].map(e=>({value:e,label:BE[e],description:VE[e],color:e===`bypassPermissions`?`orange`:[`auto`,`acceptEdits`,`plan`].includes(e)?`blue`:`muted`})),UE=[{value:`low`,effort:`low`,label:`Low`},{value:`medium`,effort:`medium`,label:`Medium`},{value:`high`,effort:`high`,label:`High`},{value:`xhigh`,effort:`xhigh`,label:`Extra High`},{value:`max`,effort:`max`,label:`Max`}],WE=`Claude settings`,GE={value:`config`,effort:`config`,label:WE},KE=[{value:`config`,label:WE,displayName:WE,defaultEffort:`config`,reasoningLevels:[GE,...UE],source:`settings`}],qE={available:!1,effectiveModel:``,effectiveEffort:``,modelOptions:[],effortOptions:UE};function JE(e){return!!(e&&e in LE)}function YE(e){return!!(e&&e in BE)}function XE(e,t,n){return e?JE(t)?t:`custom`:n}function ZE(e,t,n){return e?YE(t)?t:`default`:n}function QE(e){if(typeof e!=`string`)return``;let t=e.trim();return!t||/[\s\x00-\x1f\x7f]/.test(t)||t.startsWith(`-`)?``:t}function $E(e){return e===`config`?e:QE(e)||`config`}function eD(e){return e&&UE.some(t=>t.value===e)?e:``}function tD(e){return e===`config`?e:eD(e)||`config`}function nD(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{let n=eD(e?.value);n&&t.push({value:n,effort:n,label:e.label||Nb(n),description:e.description})}),t.length>0?t:UE}function rD(e){let t=nD(e?.effortOptions),n=QE(e?.effectiveModel),r=eD(e?.effectiveEffort),i=[];return Array.isArray(e?.modelOptions)&&e.modelOptions.forEach(e=>{let n=QE(e?.value);n&&i.push({...e,value:n,label:e.label||n,displayName:e.displayName||n,defaultEffort:eD(e.defaultEffort)||r||`medium`,reasoningLevels:t,source:e.source||`settings`})}),n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,displayName:n,defaultEffort:r||`medium`,reasoningLevels:t,source:`settings`}),{available:e?.available===!0,effectiveModel:n,effectiveEffort:r,modelOptions:i,effortOptions:t}}function iD(e,t){let n=t.effortOptions?.length?t.effortOptions:UE,r=t.modelOptions?.length?t.modelOptions:KE.map(e=>({...e})),i=$E(e);return!i||i===`config`||r.some(e=>e.value===i)?r.map(e=>({...e,reasoningLevels:e.reasoningLevels?.length?e.reasoningLevels:n})):[...r.map(e=>({...e,reasoningLevels:e.reasoningLevels?.length?e.reasoningLevels:n})),{value:i,label:i,displayName:i,defaultEffort:t.effectiveEffort||`medium`,reasoningLevels:n,source:`settings`}]}function aD(e,t){return e===`config`?t.effectiveModel||t.modelOptions?.[0]?.value||`config`:$E(e)}function oD(e,t){return e===`config`?t.effectiveEffort||`config`:tD(e)}function sD(e,t){let n=t.effortOptions?.length?t.effortOptions:UE;return e===`config`?[GE,...n]:n.some(t=>t.value===e)?n:[...n,{value:e,effort:e,label:Nb(e)}]}function cD(e,t,n,r){if(!e||r.some(t=>t.value===e))return r;let i=[{value:`default`,label:`Standard`,description:`Default speed`}];return n&&n!==`default`&&i.push({value:n,label:n===`priority`?`Fast`:n}),[...r,{value:e,label:Fb(void 0,e),displayName:Fb(void 0,e),defaultEffort:t,reasoningLevels:[{value:t,effort:t,label:Nb(t)}],serviceTiers:i,source:`pending-catalog`}]}function lD(e){let t=e.agentLaunchProfiles?.codex??{},n=t.approvalMode??e.codexApprovalMode,r=Pb(t.modelPreset??e.codexModelPreset),i=t.model||e.codexModel||r.model,a=t.reasoningEffort||e.codexReasoningEffort||r.effort,o=e.agentLaunchProfiles?.claude??{};return{codexApprovalMode:JE(n)?n:`approve`,codexModel:i,codexReasoningEffort:a,codexServiceTier:t.serviceTier||e.codexServiceTier||`default`,codexModelPreset:`${i}:${a}`,claudePermissionMode:YE(o.permissionMode)?o.permissionMode:`default`,claudeModel:$E(o.model),claudeEffort:tD(o.effort)}}function uD({agentKind:e,codexModel:t,codexReasoningEffort:n,codexServiceTier:r,codexModelPreset:i,codexModelOptions:a,codexApprovalMode:o,claudeModel:s,claudeEffort:c,claudeSettings:l,claudePermissionMode:u}){let d=aD(s,l),f=oD(c,l),p=e===`claude`?iD(s,l):e===`codex`?cD(t,n,r,a):a,m=e===`claude`?d:t,h=e===`claude`?f:n,g=e===`claude`?``:r,_=e===`claude`?`${m}:${h}`:i,v=p.find(e=>e.value===m)??p[0],y=e===`claude`?sD(h,l):v?.reasoningLevels?.length?v.reasoningLevels:Db[0]?.reasoningLevels??[],b=e===`claude`?[]:v?.serviceTiers?.length?v.serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],x=y.find(e=>e.value===h)??y[0],S=b.find(e=>e.value===g)??b[0],C=e===`claude`?HE:zE,w=e===`claude`?u:o,T=C.find(e=>e.value===w)??C[0];return{agentModelOptions:p,agentModel:m,agentReasoningEffort:h,agentServiceTier:g,agentModelPreset:_,currentModelOption:v,currentReasoningOptions:y,currentServiceTierOptions:b,currentReasoningOption:x,currentServiceTierOption:S,currentModelLabel:Fb(v,m),currentReasoningLabel:x?.label??Nb(h),currentSpeedLabel:S?.label??``,permissionModeOptions:C,currentPermissionMode:w,currentPermissionOption:T,currentPermissionLabel:T?.label??w,currentPermissionColor:T?.color??`muted`}}function dD(e){return!e.isMain&&e.archived!==!0&&e.status!==`dead`&&e.status!==`stopped`}function fD(e){return!e.isMain&&e.archived===!0}function pD(e,t=[]){let n=new Map;return e.forEach(e=>{if(!dD(e))return;let t=e.providerSessionKey||NS(e.source);t&&n.set(e.id,t)}),n}function mD(e,t){return t.get(e.id)||`agent:${e.id}`}function hD(e){return e.providerSessionKey&&e.providerSessionTemporary!==!0?120:NS(e.source)?100:e.providerSessionKey?40:0}function gD(e){return e.status===`running`?30:e.status===`pending`?20:0}function _D(e,t){return hD(e)+(t.has(e.id)?50:0)+gD(e)}function vD(e,t){let n=new Map;return e.forEach(e=>{let r=mD(e,t),i=n.get(r);if(!i){n.set(r,e);return}let a=_D(e,t),o=_D(i,t),s=Number(e.startedAt)||0,c=Number(i.startedAt)||0;(a>o||a===o&&s>c)&&n.set(r,e)}),e.filter(e=>n.get(mD(e,t))===e)}function yD(e,t){return e.filter(e=>!t.has(Rb(e)))}function bD(e,t,n){return e.filter(e=>{let r=Rb(e);return(e.archived||!t.has(r))&&!n.has(r)})}function xD({allAgents:e,liveAgents:t,sessions:n,mainPageSessionKeys:r}){let i=t.filter(dD),a=pD(i,n),o=new Set(a.values()),s=vD(i,a),c=n.filter(e=>!e.archived&&r.has(Rb(e))).sort(Gb),l=yD(c,o),u=yD(n,o).sort(Gb),d=bD(n,r,o).sort(Gb);return{liveAgents:s,archivedAgents:e.filter(fD).sort((e,t)=>(t.archivedAt??0)-(e.archivedAt??0)),mainPageAgentSessions:c,sidebarAgentSessions:l,searchableAgentSessions:u,historyAgentSessions:d,claimedAgentSessionKeys:o,claimedAgentSessionKeyByAgentId:a}}function SD(){return{activeFile:null,files:[],closedFileCache:new Map}}function CD(e){return{activeFile:e.activeFile,files:e.files,closedFileCache:e.closedFileCache}}function wD(){let[e,t]=(0,W.useState)(()=>SD()),n=(0,W.useRef)(e),r=(0,W.useCallback)(e=>(n.current=CD(e),t(n.current),n.current),[]),i=(0,W.useCallback)((e,t,i)=>r(x(n.current,e,t,i)),[r]),a=(0,W.useCallback)((e,t,i)=>{let a=c(n.current,e,t,i);return a?r(a):null},[r]),o=(0,W.useCallback)(e=>{let t=T(n.current,e);return t.closedFiles.length>0&&r(t),t},[r]),s=(0,W.useCallback)(e=>{let t=N(n.current,{canReopen:e});return t?r(t):null},[r]),u=(0,W.useCallback)(e=>r(l(n.current,e)),[r]),d=(0,W.useCallback)(e=>{let t=n.current.activeFile;if(!t)return null;let i=p(t,e);return r({...n.current,activeFile:i,files:g(n.current.files,i)})},[r]),f=(0,W.useCallback)((e,t)=>{let i=P(n.current,e,t);return i!==n.current&&r(i),i},[r]),m=(0,W.useCallback)((e,t)=>{let i=y(n.current,e,t);return t.length>0&&r(i),i},[r]),h=(0,W.useMemo)(()=>Array.from(e.closedFileCache.values()),[e.closedFileCache]);return(0,W.useMemo)(()=>({activeFile:e.activeFile,files:e.files,closedFiles:h,openFromRead:i,select:a,close:o,reopenLastClosed:s,update:u,updateDraft:d,move:f,deleteEntries:m}),[h,o,m,f,i,s,a,e.activeFile,e.files,u,d])}function TD(){let[e,t]=(0,W.useState)(()=>mt()),n=(0,W.useRef)(e),r=(0,W.useRef)(!1),i=(0,W.useRef)(null),a=(0,W.useCallback)(e=>(n.current=e,t(e),e),[]),o=(0,W.useCallback)(e=>{r.current||a(yt(n.current,e))},[a]),s=(0,W.useCallback)(e=>{o(ht(e))},[o]),c=(0,W.useCallback)(e=>{o(gt(e))},[o]),l=(0,W.useCallback)(e=>{r.current||(i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,o(gt({...e,reason:`cursor`}))},650))},[o]),u=(0,W.useCallback)(e=>{let t=n.current,i=t.index+e,o=t.entries[i];return o?(r.current=!0,a({entries:t.entries,index:i}),o):null},[a]),d=(0,W.useCallback)(()=>{window.setTimeout(()=>{r.current=!1},120)},[]),f=(0,W.useCallback)(e=>{let t=n.current,r=t.entries.filter(e);if(r.length===t.entries.length)return;let i=t.entries[t.index],o=i?r.indexOf(i):-1;a({entries:r,index:o>=0?o:Math.min(t.index,r.length-1)})},[a]);return(0,W.useEffect)(()=>()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),(0,W.useMemo)(()=>({canGoBack:e.index>0,canGoForward:e.index>=0&&e.index<e.entries.length-1,recordAgent:s,recordFile:c,recordFileCursor:l,beginNavigation:u,finishNavigation:d,pruneEntries:f}),[u,d,f,s,c,l,e.entries.length,e.index])}function ED({agents:e,permissionSwitchReplacement:t,onDiscardAttachment:n}){let[r,i]=(0,W.useState)({});(0,W.useLayoutEffect)(()=>{let r=new Set(e.filter(e=>!e.archived&&e.status!==`dead`&&e.status!==`stopped`).flatMap(e=>[KC(e),bw(e)]).filter(Boolean));i(i=>{let a=i,o=!1,s=()=>(a===i&&(a={...i}),o=!0,a);if(t){let e=(e,t)=>{let n=a[e];if(!n)return;let r=s(),i=r[t];r[t]=i?WC(i,n):n,delete r[e]};e(t.originalAgentId,t.replacementAgentId),e(`acp:${t.originalAgentId}`,`acp:${t.replacementAgentId}`)}return e.forEach(e=>{let t=KC(e);if(!t)return;qC(e).forEach(e=>{if(e===t)return;let n=a[e];if(!n)return;let r=s();r[t]=r[t]?WC(r[t],n):n,delete r[e]});let n=bw(e);xw(e).forEach(e=>{if(e===n)return;let t=a[e];if(!t)return;let r=s();r[n]=r[n]?WC(r[n],t):t,delete r[e]})}),Object.entries(a).forEach(([e,t])=>{if(r.has(e))return;let i=s();t.attachments.forEach(n),delete i[e]}),o?a:i})},[e,n,t]);let a=(0,W.useCallback)(t=>{if(!t)return``;for(let n of e){let e=Sw(t),r=e?bw(n):KC(n);if(!r)continue;let i=e?xw(n):qC(n);if(t===r||i.includes(t))return r}return t},[e]);return{composerByAgentKey:r,updateComposerStateForKey:(0,W.useCallback)((e,t)=>{i(n=>{let r=a(e);if(!r)return n;let i=n[r]??zC(),o=t(i);return o===i?n:{...n,[r]:o}})},[a]),updateExistingComposerStateForKey:(0,W.useCallback)((e,t)=>{i(n=>{let r=a(e);if(!r)return n;let i=n[r];if(!i)return n;let o=t(i);return o===i?n:{...n,[r]:o}})},[a])}}function DD(){if(typeof window>`u`)return``;let e=window.location.hostname;return e?e===`localhost`||e===`127.0.0.1`||e===`::1`?`Local server`:`Remote server`:``}function OD(e){return e.replace(/^Language:\s*/i,``).replace(/^语言[::]\s*/,``)}function kD(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.trim(),i=String(n??``).trim();!r||!i||(t[r]=i.slice(0,80))}),t}function AD(e){return e.replace(/^Appearance:\s*/i,``).replace(/^外观[::]\s*/,``)}function jD(e,t){return e.size===t.length?t.every(t=>e.has(t)):!1}function MD(e){return(e.ctrlKey||e.metaKey)&&e.shiftKey&&!e.altKey&&e.key.toLowerCase()===`t`}var ND=296,PD=220,FD=520,ID=52,LD=172,RD=900,zD=12,BD=214,VD=86,HD=60,UD=1e3,WD=150;function GD(){return typeof window>`u`?!1:L()&&F()}function KD(e){let t=(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop()||``;return t===`qoder`||t===`qodercli`||t===`opencode`}function qD(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function JD(e){return MS(e)}function YD(e){return e.kind===`agent-session`?Rb(e):Ob(e)}function XD(){return L()}function ZD(e){return!XD()&&e>0&&e<RD}function QD(){return XD()?!0:typeof window<`u`&&ZD(window.innerWidth)}function $D(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}function eO(e){let t=(e||``).replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`workspace`}function tO(e){if(e.lineNumber)return{lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn}}function nO(e){let t=new Map;for(let n of e)n.kind!==`path`||t.has(n.path)||t.set(n.path,n);return Array.from(t.values())}function rO(e){let t=new Map;for(let n of e)t.has(n.path)||t.set(n.path,n);return Array.from(t.values())}async function iO(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,`true`),t.setAttribute(`autocomplete`,`off`),t.setAttribute(`autocorrect`,`off`),t.setAttribute(`autocapitalize`,`none`),t.setAttribute(`spellcheck`,`false`),t.setAttribute(`data-lpignore`,`true`),t.setAttribute(`data-1p-ignore`,`true`),t.setAttribute(`data-bwignore`,`true`),t.setAttribute(`data-form-type`,`other`),t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`0`,document.body.appendChild(t),t.select();try{return document.execCommand(`copy`)}finally{t.remove()}}function aO({agents:e,taskHistory:t,mainPageSessionKeys:r,activeView:i,dialogOpen:a,systemStats:o,usageSummary:s,contextWindowByAgentId:c={},activeTerminalId:l,permissionSwitchingAgentId:p,agentSwitchingKind:g,permissionSwitchReplacement:_,openTerminalIds:v,terminalFocusRequest:y,keyMap:b,keyboardShortcutsEnabled:x,uiPreferences:T,onOpenTerminal:E,onOpenTerminalWhenReady:te,onNewAgent:j,onStartAgent:N,onRenameAgent:P,onUpdateAgentFlags:F,onOpenArchivedAgent:R,onForkAgent:re,onDeleteForkWorktreeProject:B,onRestartMainAgent:ie,onWorkspaceViewChange:V,onKill:ae,onInterruptAgent:oe,sendInput:se,sendComposerInput:ce,respondToAppServerRequest:le,resizeAgent:ue,onSessionOutput:de,onUpdateUiPreferences:fe}){let pe=Pe(),{composerByAgentKey:me,updateComposerStateForKey:H,updateExistingComposerStateForKey:he}=ED({agents:e,permissionSwitchReplacement:_,onDiscardAttachment:aw}),ge=(0,W.useRef)({}),[_e,ve]=(0,W.useState)({}),[ye,be]=(0,W.useState)(`terminal`),[xe]=(0,W.useState)(()=>ee().surface),Se=(0,W.useRef)(!1),Ce=(0,W.useRef)(!xe),we=wD(),{canGoBack:Te,canGoForward:Ee,recordAgent:De,recordFile:U,recordFileCursor:je,beginNavigation:Me,finishNavigation:Ne,pruneEntries:Fe}=TD(),G=we.activeFile,Ie=we.files,[Le,Be]=(0,W.useState)(!1),[Ve,Ue]=(0,W.useState)(``),[We,Ge]=(0,W.useState)(0),[,Ke]=(0,W.useState)([]),[qe,Ye]=(0,W.useState)({}),[Xe,Ze]=(0,W.useState)([]),[Qe,$e]=(0,W.useState)(()=>new Set),[et,nt]=(0,W.useState)(`approve`),[rt,it]=(0,W.useState)(`gpt-5.5:xhigh`),[at,ot]=(0,W.useState)(`gpt-5.5`),[st,ct]=(0,W.useState)(`xhigh`),[lt,ut]=(0,W.useState)(`default`),[dt,ft]=(0,W.useState)(Db),[pt,mt]=(0,W.useState)(`default`),[ht,gt]=(0,W.useState)(`config`),[_t,vt]=(0,W.useState)(`config`),[yt,xt]=(0,W.useState)(qE),[St,Ct]=(0,W.useState)([]),[wt,Tt]=(0,W.useState)([]),[Et,Dt]=(0,W.useState)(``),[Ot,kt]=(0,W.useState)(!1),[At,q]=(0,W.useState)([]),[jt,Mt]=(0,W.useState)(!1),Nt=(0,W.useRef)(!1),Pt=(0,W.useRef)(HD),[Ft,It]=(0,W.useState)(()=>DS().pinnedOverrides),[Lt,Rt]=(0,W.useState)(!1),[zt,Bt]=(0,W.useState)(!1),[Vt,Ht]=(0,W.useState)(()=>new Set),[Ut,Wt]=(0,W.useState)(()=>new Set),[Gt,Kt]=(0,W.useState)(ND),[qt,Jt]=(0,W.useState)(()=>QD()),[Yt,Xt]=(0,W.useState)(()=>typeof window>`u`?null:k(window.location.search)),[Zt,Qt]=(0,W.useState)(0),[$t,en]=(0,W.useState)(void 0),[tn,nn]=(0,W.useState)(null),[rn,an]=(0,W.useState)(null),[on,sn]=(0,W.useState)(null),[cn,ln]=(0,W.useState)(null),[un,dn]=(0,W.useState)(!1),[fn,pn]=(0,W.useState)(``),[mn,hn]=(0,W.useState)(null),[gn,_n]=(0,W.useState)(null),[vn,yn]=(0,W.useState)(null),[bn,xn]=(0,W.useState)(null),[Sn,Cn]=(0,W.useState)(null),[wn,Tn]=(0,W.useState)(null),En=mn?mn.kind===`agent`?`agent:${mn.agentId}`:`project:${mn.projectId}`:``,[Dn,On]=(0,W.useState)(Date.now()),kn=(0,W.useRef)(null),An=(0,W.useRef)(null),jn=(0,W.useRef)([]),Mn=(0,W.useRef)({}),Nn=(0,W.useRef)([]),Pn=(0,W.useRef)(null),Fn=(0,W.useRef)(null),In=(0,W.useRef)(null),Ln=(0,W.useRef)(null),Rn=(0,W.useRef)(null),zn=(0,W.useRef)(null),Bn=(0,W.useRef)(null),Vn=(0,W.useRef)(null),Hn=(0,W.useRef)(null),Un=(0,W.useRef)(null),Wn=(0,W.useRef)(null),Gn=(0,W.useRef)(null),Kn=(0,W.useRef)(null),qn=(0,W.useRef)(!1),Jn=(0,W.useRef)(0),Yn=(0,W.useRef)(null),Xn=(0,W.useRef)(!1),Zn=(0,W.useRef)(!1),Qn=(0,W.useRef)(()=>{}),$n=(0,W.useRef)(l),er=(0,W.useRef)(0),tr=(0,W.useRef)(0),nr=(0,W.useRef)(0),rr=(0,W.useRef)(0),ir=(0,W.useRef)(0),ar=(0,W.useRef)(0),or=(0,W.useRef)(null),sr=(0,W.useRef)(null),cr=(0,W.useRef)(null),lr=(0,W.useRef)(0),ur=(0,W.useRef)(new Set),dr=(0,W.useRef)(!1),fr=(0,W.useRef)(qt),pr=(0,W.useRef)(XD()),mr=(0,W.useCallback)(()=>{fr.current=!1,Jt(!0)},[]),hr=(0,W.useCallback)(()=>{Jt(e=>(e||(fr.current=!0),!0))},[]),gr=(0,W.useCallback)(()=>{fr.current=!1,Jt(!1)},[]),_r=(0,W.useCallback)(()=>{fr.current=!1,Jt(e=>!e)},[]);$n.current=l;let J=(0,W.useMemo)(()=>PE(T.language),[T.language]);(0,W.useEffect)(()=>()=>{Nn.current.forEach(e=>window.clearTimeout(e)),Nn.current=[]},[]),(0,W.useEffect)(()=>{OS({promotedKeys:[],pinnedOverrides:Ft,archivedOverrides:{}})},[Ft]);let vr=(0,W.useMemo)(()=>e.filter(e=>!e.isMain),[e]),yr=(0,W.useMemo)(()=>e.find(e=>e.isMain)??null,[e]),Y=(0,W.useMemo)(()=>vr.filter(dD),[vr]),br=(0,W.useMemo)(()=>{let e=new Set(Y.map(e=>e.id));return yr&&e.add(yr.id),e},[Y,yr]);(0,W.useEffect)(()=>{Fe(e=>br.has(e.agentId))},[Fe,br]);let xr=(0,W.useMemo)(()=>AS(wt,Ft,{}),[Ft,wt]),Sr=(0,W.useMemo)(()=>xD({allAgents:vr,liveAgents:Y,sessions:xr,mainPageSessionKeys:Qe}),[Y,xr,Qe,vr]),Cr=Sr.mainPageAgentSessions,wr=Sr.sidebarAgentSessions,Tr=Sr.searchableAgentSessions,X=Sr.historyAgentSessions,Er=Sr.liveAgents,Dr=Sr.archivedAgents,Or=t,kr=X,Ar=(0,W.useMemo)(()=>new Set(At.map(Rb)),[At]),jr=(0,W.useMemo)(()=>new Set(Array.from(Sr.claimedAgentSessionKeyByAgentId.entries()).filter(([,e])=>Ar.has(e)).map(([e])=>e)),[Sr.claimedAgentSessionKeyByAgentId,Ar]),Mr=(0,W.useMemo)(()=>{let e=new Map(Tr.map(e=>[Rb(e),e]));return At.forEach(t=>e.set(Rb(t),t)),yD(Array.from(e.values()),Sr.claimedAgentSessionKeys)},[Sr.claimedAgentSessionKeys,At,Tr]),Nr=(0,W.useMemo)(()=>fT(Er,wr,qe),[qe,wr,Er]),Pr=(0,W.useMemo)(()=>PS(Nr,Ut,!1),[Ut,Nr]),Fr=(0,W.useMemo)(()=>fT(Er,Mr,qe),[qe,Mr,Er]),Ir=Ve.trim().toLowerCase(),Lr=Ir.length>0,Rr=(0,W.useMemo)(()=>pT((i===`search`||Le)&&Lr?Fr:Pr,Ir,Ut,Ar,jr),[i,Ut,Lr,Ir,Pr,Fr,jr,Ar,Le]),zr=Pr.some(e=>e.agents.length>0||e.agentSessions.length>0),Br=(0,W.useMemo)(()=>Lr?Rr:[],[Rr,Lr]),Vr=(0,W.useMemo)(()=>mT(Rr,Vt,Ir),[Vt,Rr,Ir]),Hr=(0,W.useMemo)(()=>Lr?Vr:[],[Lr,Vr]),Ur=(0,W.useMemo)(()=>{let e=new Map;return x&&b.forEach((t,n)=>{e.set(t,n)}),e},[b,x]),Wr=(0,W.useMemo)(()=>v.map(e=>Y.find(t=>t.id===e)??(yr?.id===e?yr:null)).filter(e=>!!e),[Y,yr,v]),Gr=(0,W.useMemo)(()=>Wr.find(e=>e.id===l)??Wr[0]??null,[l,Wr]),Kr=Gr?[Gr]:[],Z=(0,W.useMemo)(()=>Y.find(e=>e.id===l)??(yr?.id===l?yr:null),[Y,l,yr]),qr=!!(Z&&Z.id===p),Jr=Z?c[Z.id]??null:null,Yr=Z?.agentRuntimeMode===`acp`?bw(Z):Z?KC(Z):``,Xr=(0,W.useMemo)(()=>lC(Z),[Z]),Zr=Yr?me[Yr]??(Z?(Z.agentRuntimeMode===`acp`?xw(Z):qC(Z)).map(e=>me[e]).find(Boolean):void 0)??RC:RC,Qr=Zr.draft,$r=Zr.attachments,ei=Zr.mode,{plusMenuOpen:ti,approvalMenuOpen:ni,modelMenuOpen:ri,modelPickerPane:ii}=Zr.ui,ai=(0,W.useMemo)(()=>Sb(Z),[Z]),oi=(0,W.useMemo)(()=>bb(Z),[Z]),si=Xr.kind,ci=(0,W.useMemo)(()=>XE(!!(Z&&si===`codex`),Z?.launchPermissionMode,et),[Z,et,si]),li=(0,W.useMemo)(()=>ZE(!!(Z&&si===`claude`),Z?.launchPermissionMode,pt),[Z,pt,si]),ui=(0,W.useMemo)(()=>ai||!!Z&&Z?.status===`running`&&si===`shell`&&oi.terminalBusy,[Z,oi.terminalBusy,ai,si]),di=(0,W.useMemo)(()=>cC([...sC(si),...St]),[si,St]),fi=Zr.pendingFollowUp;(0,W.useEffect)(()=>{!l||ye!==`terminal`||i!==`projects`||De(l)},[l,i,ye,De]),(0,W.useEffect)(()=>{!G||ye!==`editor`||i!==`projects`||U({agentId:G.agentId,filePath:G.file.path,view:G.diffRequestId?`diff`:`editor`,lineNumber:G.cursor?.lineNumber,column:G.cursor?.column,endColumn:G.cursor?.endColumn})},[i,ye,G?.agentId,G?.cursor?.column,G?.cursor?.endColumn,G?.cursor?.lineNumber,G?.cursor?.requestId,G?.diffRequestId,G?.file.path,U]);let pi=ow($r).length>0,mi=$r.some(e=>e.status===`uploading`),hi=Z&&!mi&&(Qr.trim()||pi)?`send`:ui?`interrupt`:`disabled`,gi=Z?.agentRuntimeMode===`acp`?hi:`disabled`,_i=(0,W.useCallback)(e=>{Yr&&H(Yr,e)},[Yr,H]),vi=(0,W.useCallback)(()=>{_i(HC)},[_i]),yi=(0,W.useMemo)(()=>Y.find(e=>e.id===tn?.agentId)??null,[Y,tn?.agentId]),bi=(0,W.useMemo)(()=>Nr.find(e=>e.id===rn?.projectId)??null,[Nr,rn?.projectId]),xi=(0,W.useMemo)(()=>Rr.flatMap(e=>e.agentSessions).find(e=>e.provider===on?.provider&&Rb(e)===on?.sessionId)??null,[on?.provider,on?.sessionId,Rr]),Si=Le?Hr[We]??null:null,Ci=Si?.kind===`agent`?Si.id:null,wi=Si?.kind===`agent-session`?Rb(Si):null,Ti=Z?Ab(Z):void 0,Ei=(0,W.useMemo)(()=>{if(G)return Y.find(e=>e.id===G.agentId&&!e.isMain)??null;if(Z&&!Z.isMain)return Z;if(Ti){let e=Y.find(e=>!e.isMain&&Ab(e)===Ti);if(e)return e}return Y.find(e=>!e.isMain)??null},[Z,Y,Ti,G]),Di=(0,W.useCallback)(e=>{if(!(e instanceof Element))return null;let t=e.closest(`[data-testid="code-agent-row"][data-agent-id], [data-testid="code-project-agent-compact"][data-agent-id], [data-testid="code-pinned-agent-compact"][data-agent-id], [data-testid="code-agent-rail-item"][data-agent-id]`)?.dataset.agentId;if(t){let e=Y.find(e=>e.id===t&&!e.isMain);if(e)return e}let n=e.closest(`[data-testid="code-project-group"]`)?.querySelector(`[data-testid="code-project-title"][data-project-id]`)?.dataset.projectId;return n?Y.find(e=>!e.isMain&&Ab(e)===n)??null:null},[Y]),Oi=Z?.isMain?$t??Pr[0]?.workspace:Ti??$t??Pr[0]?.workspace,ki=ye===`editor`&&!!G,Ai=(0,W.useMemo)(()=>{if(ki&&G){let e=G.workspaceRoot??Y.find(e=>e.id===G.agentId)?.projectWorkspace??Y.find(e=>e.id===G.agentId)?.cwd??``;return{kind:`file`,agentId:G.agentId,filePath:G.file.path,...e?{absolutePath:w(e,G.file.path)}:{},...e?{projectLabel:A(e)}:{},view:G.diffRequestId?`diff`:`editor`,lineNumber:G.cursor?.lineNumber,column:G.cursor?.column,endColumn:G.cursor?.endColumn}}return l&&br.has(l)?{kind:`agent`,agentId:l}:null},[l,G?.agentId,G?.cursor?.column,G?.cursor?.endColumn,G?.cursor?.lineNumber,G?.diffRequestId,G?.file.path,G?.workspaceRoot,ki,Y,br]),{agentModelOptions:ji,agentModel:Mi,agentReasoningEffort:Ni,agentServiceTier:Pi,agentModelPreset:Fi,currentReasoningOptions:Ii,currentServiceTierOptions:Li,currentPermissionMode:Ri,currentPermissionLabel:zi,currentPermissionColor:Bi,currentModelLabel:Vi,currentReasoningLabel:Hi,currentSpeedLabel:Ui,permissionModeOptions:Wi}=(0,W.useMemo)(()=>uD({agentKind:si,codexModel:at,codexReasoningEffort:st,codexServiceTier:lt,codexModelPreset:rt,codexModelOptions:dt,codexApprovalMode:ci,claudeModel:ht,claudeEffort:_t,claudeSettings:yt,claudePermissionMode:li}),[_t,ht,yt,li,ci,at,dt,rt,st,lt,si]),Gi=DD(),Ki=Le||i===`search`?J.search:i===`history`?J.history:ki&&G?kb(G.file.path):Z?h(Z):J.codex,qi=Z?.isMain?`farming`:eO(Z?Ab(Z):void 0),Ji=Z?`${qi} · ${Gi}`:Gi,Yi=ki&&G?G.sourceAgentId??G.agentId:null,Xi=!!Yi,Zi=(0,W.useCallback)(()=>{let e=An.current;if(!e)return;e.style.height=`auto`;let t=Math.min(e.scrollHeight,132);e.style.height=`${t}px`,e.style.overflowY=e.scrollHeight>132?`auto`:`hidden`},[]),Qi=(0,W.useCallback)(()=>{IE(()=>{document.querySelector(`.code-composer-menu`)||(An.current??document.querySelector(`[data-testid="code-composer-input"]`))?.focus({preventScroll:!0})},{delays:[60]})},[]),$i=(0,W.useCallback)(e=>{let t=lD(e);nt(t.codexApprovalMode),ot(t.codexModel),ct(t.codexReasoningEffort),ut(t.codexServiceTier),it(t.codexModelPreset),mt(t.claudePermissionMode),gt(t.claudeModel),vt(t.claudeEffort)},[]),ea=(0,W.useCallback)(()=>{let e=!1,t=lr.current;return fetch(n(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};t===lr.current&&$e(new Set(kS(r.mainPageSessionKeys??[]))),Ye(kD(r.projectNames)),$i(r)}).catch(()=>{}),()=>{e=!0}},[$i]),ta=(0,W.useCallback)(()=>{if(Xn.current||Zn.current)return()=>{};let e=!1;return Zn.current=!0,fetch(n(`/api/codex/models`)).then(e=>e.json()).then(t=>{if(e)return;let n=Lb(t);Xn.current=!0,n.length>0&&ft(n)}).catch(()=>{}).finally(()=>{Zn.current=!1}),()=>{e=!0}},[]),na=(0,W.useCallback)(()=>{let e=!1;return fetch(n(`/api/claude/settings`)).then(e=>e.json()).then(t=>{e||xt(rD(t.settings))}).catch(()=>{e||xt(qE)}),()=>{e=!0}},[]),ra=(0,W.useCallback)(async(e,t)=>{let r=new URLSearchParams({q:e,limit:String(UD),fresh:`1`}),i=await fetch(n(`/api/agent-sessions/search?${r.toString()}`),{signal:t,cache:`no-store`});if(!i.ok)throw Error(`Failed to search Agent sessions: ${i.status}`);let a=await i.json();return Array.isArray(a.sessions)?a.sessions:[]},[]),ia=(0,W.useCallback)(async(e,t)=>bD(AS(await ra(e,t),Ft,{}),Qe,Sr.claimedAgentSessionKeys),[Sr.claimedAgentSessionKeys,Ft,ra,Qe]),aa=(0,W.useCallback)(async(e={})=>{let t=new URLSearchParams({limit:String(e.limit||HD)});e.cursor&&t.set(`cursor`,e.cursor),e.fresh&&t.set(`fresh`,`1`);let r=await(await fetch(n(`/api/agent-sessions?${t.toString()}`),{cache:e.fresh?`no-store`:`default`})).json();return{sessions:Array.isArray(r.sessions)?r.sessions:[],nextCursor:typeof r.nextCursor==`string`?r.nextCursor:``,hasMore:r.hasMore===!0}},[]),oa=(0,W.useCallback)((e=!1)=>{let t=!1;return aa({fresh:e}).then(e=>{t||(Tt(e.sessions),Dt(e.nextCursor),kt(e.hasMore),Pt.current=Math.max(HD,e.sessions.length))}).catch(()=>{t||(Tt([]),Dt(``),kt(!1))}),()=>{t=!0}},[aa]),sa=(0,W.useCallback)(()=>{aa({limit:Pt.current,fresh:!0}).then(e=>{Tt(e.sessions),Dt(e.nextCursor),kt(e.hasMore)}).catch(()=>Tt([]))},[aa]),ca=(0,W.useCallback)(()=>{!Ot||!Et||Nt.current||(Nt.current=!0,aa({cursor:Et}).then(e=>{Tt(t=>{let n=new Set(t.map(Rb)),r=[...t];return e.sessions.forEach(e=>{let t=Rb(e);n.has(t)||(n.add(t),r.push(e))}),Pt.current=Math.max(HD,r.length),r}),Dt(e.nextCursor),kt(e.hasMore)}).catch(()=>{}).finally(()=>{Nt.current=!1}))},[Et,Ot,aa]);(0,W.useEffect)(()=>{if(!((i===`search`||Le)&&Lr)){q([]),Mt(!1);return}let e=new AbortController;q([]),Mt(!0);let t=window.setTimeout(()=>{ra(Ir,e.signal).then(q).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||q([])}).finally(()=>{e.signal.aborted||Mt(!1)})},WD);return()=>{window.clearTimeout(t),e.abort()}},[i,ra,Lr,Ir,Le]);let la=(0,W.useCallback)((e,t)=>{if(e!==`codex`&&e!==`claude`)return Ct([]),()=>{};let r=!1,i=new URLSearchParams({provider:e});return t&&i.set(`workspace`,t),fetch(n(`/api/slash-commands?${i.toString()}`)).then(e=>e.json()).then(e=>{r||Ct(Array.isArray(e.commands)?e.commands:[])}).catch(()=>{r||Ct([])}),()=>{r=!0}},[]),ua=(0,W.useCallback)(()=>{Yr&&(_i(e=>({...e,ui:{...e.ui,plusMenuOpen:!1}})),Pn.current?.click())},[Yr,_i]),da=(0,W.useCallback)((e,t)=>{let n=rw(t),r=$C(t,`pasted image`),i=iw(t),a={id:n,kind:`image`,name:r,type:t.type||`image/png`,size:t.size,status:`uploading`,previewUrl:i};H(e,e=>({...e,attachments:[...e.attachments,a]})),dw(t).then(t=>{he(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,name:r,type:t.type||e.type,size:t.size||e.size,status:`ready`,path:t.path,messageBlock:nw({...t,name:r}),error:void 0}:e)}))}).catch(()=>{he(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,status:`error`,messageBlock:pw(t),error:`Upload failed`}:e)}))})},[H,he]),fa=(0,W.useCallback)(async e=>{if(!Yr||e.length===0)return;e.filter(ew).forEach(e=>da(Yr,e));let t=e.filter(e=>!ew(e));if(t.length===0){Qi();return}let n=[];for(let e of t)try{n.push(await fw(e))}catch{n.push(pw(e))}H(Yr,e=>({...e,draft:QC(e.draft,n.join(`
122
+ `)).trimEnd()}function lw(e){return e.flatMap(e=>e.status===`ready`&&e.path?[{kind:`image`,path:e.path,name:e.name,type:e.type,size:e.size}]:[])}function uw(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>n(r.error??Error(`File read failed`)),r.onload=()=>t(typeof r.result==`string`?r.result:``),r.readAsText(e)})}async function dw(e){let t=await fetch(ZC(`/api/attachments/image`),{method:`POST`,headers:{"Content-Type":e.type||`image/png`},body:e});if(!t.ok)throw Error(`Image upload failed: ${t.status}`);return t.json()}async function fw(e){if(ew(e))return nw(await dw(e));try{return tw(e,await uw(e))}catch{return`Attached file: ${$C(e)}\n\n[Unable to read this file as text]`}}function pw(e){return ew(e)?`Attached image: ${$C(e,`pasted image`)}\n\n[Unable to upload this image]`:`Attached file: ${$C(e)}\n\n[Unable to read this file as text]`}function mw(e){if(!e)return[];let t=Array.from(e.files??[]).filter(ew);return t.length>0?t:Array.from(e.items??[]).filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(e=>!!(e&&ew(e)))}function hw(e,t){return e===`default`?t:`${YC[e]}\n\n${t}`}function gw({agent:e,composerKey:t,draft:n,attachments:r,composerMode:i,turnActive:a,sendMessage:o,updateComposerState:s}){let c=lw(r),l=hw(i,cw(n,r).trim());return!l&&c.length===0||!e||e.agentRuntimeMode!==`acp`||!t||!a&&!o(e,l,c)?!1:(s(t,e=>({...e,draft:``,attachments:[],mode:`default`,history:PC(e.history,n),...a?{pendingFollowUp:{messages:[...e.pendingFollowUp?.messages||[],BC(l,c)],createdAt:e.pendingFollowUp?.createdAt||Date.now()}}:{}})),r.forEach(aw),!0)}function _w(e,t,r,i=!1){return fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-permission`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,optionId:r,cancelled:i})})}function vw(e,t,r,i){return fetch(n(`/api/agents/${encodeURIComponent(e)}/acp-elicitation`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t,action:r,content:i})})}var yw=`acp:`;function bw(e){let t=KC(e);return t?`${yw}${t}`:``}function xw(e){return qC(e).map(e=>`${yw}${e}`)}function Sw(e){return e.startsWith(yw)}function Cw(){return typeof window>`u`?!1:navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches}function ww(){return(0,K.jsx)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M10 13V3m0 0L6.5 6.5M10 3l3.5 3.5M4 9v6.5A1.5 1.5 0 0 0 5.5 17h9a1.5 1.5 0 0 0 1.5-1.5V9`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`,strokeLinejoin:`round`})})}function Tw(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`rect`,{x:`3`,y:`3`,width:`14`,height:`14`,rx:`3`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`}),(0,K.jsx)(`path`,{d:`M10 6.5v7M6.5 10h7`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinecap:`round`})]})}function Ew(){return(0,K.jsxs)(`svg`,{viewBox:`0 0 20 20`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`rect`,{x:`6.5`,y:`6.5`,width:`9`,height:`9`,rx:`2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`}),(0,K.jsx)(`path`,{d:`M13.5 6.5v-2A1.5 1.5 0 0 0 12 3H4.5A1.5 1.5 0 0 0 3 4.5V12A1.5 1.5 0 0 0 4.5 13.5h2`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.5`,strokeLinecap:`round`})]})}function Dw({copy:e,title:t,url:n,onClose:r}){let i=Cw(),[a,o]=(0,W.useState)(!1),[s,c]=(0,W.useState)(!1);(0,W.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[r]),(0,W.useEffect)(()=>{if(!a&&!s)return;let e=window.setTimeout(()=>{o(!1),c(!1)},1800);return()=>window.clearTimeout(e)},[a,s]);let l=(0,W.useCallback)(async()=>{let e=await M(n);o(e),c(!e)},[n]);return(0,K.jsx)(`div`,{className:`code-mobile-share-backdrop`,"data-testid":`code-mobile-share-sheet`,role:`presentation`,onPointerDown:r,children:(0,K.jsxs)(`section`,{className:`code-mobile-share-sheet`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-mobile-share-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsxs)(`header`,{className:`code-mobile-share-header`,children:[(0,K.jsx)(`h2`,{id:`code-mobile-share-title`,children:e.mobileShareTitle}),(0,K.jsx)(`button`,{type:`button`,"aria-label":e.cancel,onClick:r,children:`×`})]}),(0,K.jsxs)(`section`,{className:`code-mobile-share-choice code-mobile-share-forward`,children:[(0,K.jsxs)(`div`,{className:`code-mobile-share-choice-copy`,children:[(0,K.jsx)(`h3`,{children:e.mobileForwardTitle}),(0,K.jsx)(`p`,{children:e.mobileForwardHint})]}),(0,K.jsxs)(`div`,{className:`code-mobile-share-link-row`,children:[(0,K.jsx)(`span`,{className:`code-mobile-share-link`,title:t,children:n}),(0,K.jsxs)(`button`,{type:`button`,"data-testid":`code-mobile-share-copy-action`,onClick:()=>void l(),children:[(0,K.jsx)(Ew,{}),(0,K.jsx)(`span`,{children:a?e.mobileShareCopied:e.mobileShareCopyAction})]})]}),s&&(0,K.jsx)(`span`,{className:`code-mobile-share-status`,role:`status`,children:e.copyFailed})]}),(0,K.jsxs)(`section`,{className:`code-mobile-share-choice code-mobile-share-install-guide`,children:[(0,K.jsx)(`h3`,{children:e.mobileInstallTitle}),i?(0,K.jsx)(`p`,{className:`code-mobile-install-complete`,children:e.mobileShareInstalled}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`p`,{className:`code-mobile-install-hint`,children:e.mobileInstallChromeHint}),(0,K.jsxs)(`div`,{className:`code-mobile-install-steps`,children:[(0,K.jsxs)(`div`,{className:`code-mobile-install-step`,children:[(0,K.jsxs)(`span`,{className:`code-mobile-install-controls`,"aria-hidden":`true`,children:[(0,K.jsx)(`span`,{className:`code-mobile-install-control`,children:(0,K.jsx)(ww,{})}),(0,K.jsx)(`span`,{className:`code-mobile-install-or`,children:`/`}),(0,K.jsx)(`span`,{className:`code-mobile-install-control code-mobile-install-more`,children:`•••`})]}),(0,K.jsxs)(`span`,{children:[e.mobileInstallShareStep,(0,K.jsx)(`small`,{children:e.mobileInstallMoreStep})]})]}),(0,K.jsxs)(`div`,{className:`code-mobile-install-step`,children:[(0,K.jsx)(`span`,{className:`code-mobile-install-controls`,"aria-hidden":`true`,children:(0,K.jsx)(`span`,{className:`code-mobile-install-control`,children:(0,K.jsx)(Tw,{})})}),(0,K.jsxs)(`span`,{children:[e.mobileInstallAddStep,(0,K.jsx)(`small`,{children:e.mobileInstallOpenStep})]})]})]})]})]})]})})}function Ow(e){let t=e.filter(e=>!e.hidden),n=[];for(t.forEach(e=>{e.type===`separator`&&(n.length===0||n[n.length-1]?.type===`separator`)||n.push(e)});n[n.length-1]?.type===`separator`;)n.pop();return n}function kw({contextMenuAgent:e,contextMenuAgentSession:t,contextMenuProject:n,agentMenu:r,projectMenu:i,agentSessionMenu:a,renameDialog:o,killDialog:s,deleteWorktreeDialog:c,copyNotice:l,contextMenuRef:u,renameDialogRef:d,renameInputRef:f,killDialogRef:p,killCancelButtonRef:m,deleteWorktreeDialogRef:h,deleteWorktreeCancelButtonRef:g,onContextMenuKeyDown:_,onUpdateAgentFlags:v,onRenameAgent:y,onRenameProject:b,onCopyAgentWorkingDirectory:x,onForkAgent:S,onKillAgent:C,onOpenSession:w,onToggleSessionPinned:T,onArchiveSession:E,onCopySessionWorkingDirectory:D,onArchiveProject:O,onCloseRenameDialog:k,onRenameDialogTitleChange:A,onSubmitRenameDialog:ee,onCloseKillDialog:j,onSubmitKillDialog:M,onCloseDeleteWorktreeDialog:N,onSubmitDeleteWorktreeDialog:te,copy:P}){let F=lC(e),ne=uC(n),I=Ow([{type:`item`,id:`pin-agent`,label:e?.pinned?P.unpinAgent:P.pinAgent,hidden:!F.actions.pin,onSelect:()=>v({pinned:!e?.pinned})},{type:`item`,id:`rename-agent`,label:P.renameAgent,hidden:!F.actions.rename,onSelect:y},{type:`item`,id:`archive-agent`,label:P.archiveAgent,hidden:!F.actions.archive,onSelect:()=>v({archived:!0})},{type:`item`,id:`toggle-agent-unread`,label:e?.unread?P.markAsRead:P.markAsUnread,hidden:!F.actions.markUnread,onSelect:()=>v({unread:!e?.unread})},{type:`separator`,id:`agent-copy-separator`},{type:`item`,id:`copy-agent-working-directory`,label:P.copyWorkingDirectory,hidden:!F.actions.copyWorkingDirectory,onSelect:x},{type:`separator`,id:`agent-fork-separator`},{type:`item`,id:`fork-same-worktree`,label:P.forkSameWorktree,hidden:!F.actions.forkSameWorktree,onSelect:()=>S(`same-worktree`)},{type:`item`,id:`fork-new-worktree`,label:P.forkNewWorktree,hidden:!F.actions.forkNewWorktree,onSelect:()=>S(`new-worktree`)},{type:`item`,id:`kill-agent`,label:P.killAgent,danger:!0,hidden:!F.actions.kill,onSelect:C}]),L=Ow([{type:`item`,id:`open-session`,label:P.openSession,onSelect:()=>{t&&w(t.provider,t.id)}},{type:`item`,id:`toggle-session-pinned`,label:t?.pinned?P.unpinChat:P.pinChat,onSelect:T},{type:`item`,id:`archive-session`,label:P.archiveChat,onSelect:E},{type:`item`,id:`copy-session-working-directory`,label:P.copyWorkingDirectory,onSelect:D}]),re=Ow([{type:`item`,id:`rename-project`,label:P.renameProject,icon:`rename`,hidden:!n?.workspace,onSelect:b},{type:`item`,id:`archive-project`,label:P.archiveChats,icon:`archive`,disabled:!ne,onSelect:O}]);return(0,K.jsxs)(K.Fragment,{children:[e&&(0,K.jsx)(`div`,{className:`code-context-menu`,"data-testid":`code-agent-context-menu`,style:{left:r?.x??0,top:r?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(Aw,{entries:I})}),t&&(0,K.jsx)(`div`,{className:`code-context-menu`,"data-testid":`code-session-context-menu`,style:{left:a?.x??0,top:a?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(Aw,{entries:L})}),n&&(0,K.jsx)(`div`,{className:`code-context-menu code-project-context-menu`,"data-testid":`code-project-context-menu`,style:{left:i?.x??0,top:i?.y??0},role:`menu`,ref:u,onKeyDownCapture:_,onKeyDown:_,children:(0,K.jsx)(Aw,{entries:re})}),o&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-rename-backdrop`,onMouseDown:k,children:(0,K.jsxs)(`form`,{className:`code-rename-dialog`,"data-testid":`code-rename-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-rename-title`,ref:d,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>Mw(e,d.current),onKeyDown:e=>Mw(e,d.current),onSubmit:e=>{e.preventDefault(),ee()},children:[(0,K.jsx)(`label`,{id:`code-rename-title`,htmlFor:`code-rename-input`,children:o.kind===`project`?P.renameProject:P.renameAgent}),(0,K.jsx)(`input`,{id:`code-rename-input`,ref:f,"data-testid":`code-rename-input`,type:`text`,name:`farming-rename-title`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:o.title,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),k())}}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:k,children:P.cancel}),(0,K.jsx)(`button`,{type:`submit`,className:`primary`,disabled:!o.title.trim(),children:P.save})]})]})}),s&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-kill-backdrop`,onMouseDown:j,children:(0,K.jsxs)(`div`,{className:`code-rename-dialog code-kill-dialog`,"data-testid":`code-kill-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-kill-title`,ref:p,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>Mw(e,p.current),onKeyDown:e=>Mw(e,p.current),children:[(0,K.jsx)(`h2`,{id:`code-kill-title`,children:P.killAgentQuestion}),(0,K.jsx)(`p`,{children:P.stopAgentDescription(s.title)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:m,onClick:j,autoFocus:!0,children:P.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:M,children:P.killAgent})]})]})}),c&&(0,K.jsx)(`div`,{className:`code-rename-backdrop`,"data-testid":`code-delete-worktree-backdrop`,onMouseDown:N,children:(0,K.jsxs)(`div`,{className:`code-rename-dialog code-kill-dialog`,"data-testid":`code-delete-worktree-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-delete-worktree-title`,ref:h,onMouseDown:e=>e.stopPropagation(),onKeyDownCapture:e=>Mw(e,h.current),onKeyDown:e=>Mw(e,h.current),children:[(0,K.jsx)(`h2`,{id:`code-delete-worktree-title`,children:P.deleteWorktreeQuestion}),(0,K.jsx)(`p`,{children:P.deleteWorktreeDirtyDescription(c.dirtyEntries.length)}),(0,K.jsxs)(`div`,{className:`code-rename-actions`,children:[(0,K.jsx)(`button`,{type:`button`,ref:g,onClick:N,autoFocus:!0,children:P.cancel}),(0,K.jsx)(`button`,{type:`button`,className:`danger`,onClick:te,children:P.forceDelete})]})]})}),l&&(0,K.jsx)(`div`,{className:`code-copy-toast ${l.kind}`,"data-testid":`code-copy-toast`,role:`status`,children:l.message})]})}function Aw({entries:e}){return(0,K.jsx)(K.Fragment,{children:e.map(e=>e.type===`separator`?(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`},e.id):(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,className:e.danger?`danger`:void 0,disabled:e.disabled,onClick:e.onSelect,children:[e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(jw,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}function jw({kind:e}){return e===`archive`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})}):(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M11.3536 1.64645C10.963 1.25592 10.3299 1.25592 9.93934 1.64645L3.14645 8.43934C3.05268 8.53311 2.99999 8.66029 2.99999 8.79289V11.5C2.99999 11.7761 3.22385 12 3.49999 12H6.2071C6.33971 12 6.46689 11.9473 6.56066 11.8536L13.3536 5.06066C13.7441 4.67014 13.7441 4.037 13.3536 3.64645L11.3536 1.64645ZM3.99999 9L8.99999 4L11 6L6 11H3.99999V9ZM9.7071 3.29289L10.6464 2.35355L12.6464 4.35355L11.7071 5.29289L9.7071 3.29289ZM2.5 14C2.22386 14 2 14.2239 2 14.5C2 14.7761 2.22386 15 2.5 15H13.5C13.7761 15 14 14.7761 14 14.5C14 14.2239 13.7761 14 13.5 14H2.5Z`})})}function Mw(e,t){if(e.key!==`Tab`||!t)return;let n=Array.from(t.querySelectorAll(`button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [href], [tabindex]:not([tabindex="-1"])`)).filter(e=>e.offsetParent!==null);if(n.length===0){e.preventDefault();return}let r=n[0],i=n[n.length-1];!r||!i||(e.shiftKey&&document.activeElement===r?(e.preventDefault(),i.focus()):!e.shiftKey&&document.activeElement===i&&(e.preventDefault(),r.focus()))}var Nw=a(),Pw=`https://github.com/zhuwenzhuang/farming`;function Fw({copy:e,version:t,onClose:r}){let i=(0,W.useRef)(null);return(0,W.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;i.current?.focus({preventScroll:!0});let t=e=>{e.key===`Escape`&&r()};return document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`keydown`,t),e?.focus({preventScroll:!0})}},[r]),(0,Nw.createPortal)((0,K.jsx)(`div`,{className:`code-brand-backdrop`,"data-testid":`code-brand-dialog`,role:`presentation`,onPointerDown:r,children:(0,K.jsxs)(`section`,{className:`code-brand-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`code-brand-title`,onPointerDown:e=>e.stopPropagation(),children:[(0,K.jsx)(`button`,{ref:i,type:`button`,className:`code-brand-close`,"aria-label":e.cancel,onClick:r,children:`×`}),(0,K.jsx)(`img`,{className:`code-brand-logo`,src:n(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-brand-heading`,children:[(0,K.jsx)(`h2`,{id:`code-brand-title`,children:`Farming Code`}),t&&(0,K.jsx)(`span`,{children:t})]}),(0,K.jsxs)(`div`,{className:`code-brand-story`,children:[(0,K.jsx)(`p`,{children:e.brandStoryOrigin}),(0,K.jsx)(`p`,{children:e.brandStoryPurpose})]}),(0,K.jsx)(`a`,{className:`code-brand-github`,href:Pw,target:`_blank`,rel:`noreferrer`,children:e.brandGithub})]})}),document.body)}var Iw=8,Lw=26,Rw=11,zw=10;function Bw(){return typeof window>`u`?{width:220+Iw*2,height:zw+Iw*2}:{width:window.innerWidth,height:window.innerHeight}}function Vw(e,t=0){return zw+e*Lw+t*Rw}function Hw(e,t,n,r=Bw(),i=220){let a=Math.max(Iw,r.width-i-Iw),o=Math.max(Iw,r.height-n-Iw);return{x:Math.max(Iw,Math.min(e,a)),y:Math.max(Iw,Math.min(t,o))}}function Uw(e,t,n=Bw(),r=220){let i=e.right+Iw,a=e.left-r-Iw,o=i+r<=n.width-Iw?i:a>=Iw?a:Hw(i,e.top,t,n,r).x;return{x:o,y:Hw(o,e.top,t,n,r).y}}function Ww(e,t,n=Bw(),r=220){let i=Math.max(Iw,n.width-r-Iw),a=Math.max(Iw,Math.min(e.right-r,i)),o=e.bottom+6,s=Math.max(Iw,n.height-t-Iw),c=e.top-t-6;return{x:a,y:o<=s?o:Math.max(Iw,Math.min(c,s))}}function Gw(e){let t=dC(e);return Vw(t.itemCount,t.separatorCount)}var Kw=140,qw=264,Jw=340,Yw=4,Xw=null;function Zw(e){if(typeof e==`function`)return e;if(typeof e.default==`function`)return e.default;if(typeof e.qrcode==`function`)return e.qrcode;throw Error(`QR renderer failed to load`)}function Qw(){return Xw||=o(()=>import(`./qrcode-DV-_rjU8.js`).then(e=>Zw(e)),[]),Xw}function $w(e){let t=Math.max(0,Math.ceil(e/1e3)),n=Math.floor(t/60),r=t%60;return`${n}:${String(r).padStart(2,`0`)}`}function eT(e,t){return!!(e&&e.expiresAt>t+1e3)}function tT(e){return e.split(`-`).map(e=>e.trim()).filter(Boolean)}async function nT(e){e?.code&&await fetch(n(`/api/share/qr-ticket/${encodeURIComponent(e.code)}`),{method:`DELETE`}).catch(()=>{})}function rT(e,t,n){let r=e<7,i=t<7,a=t>=n-7,o=e>=n-7;return r&&i||r&&a||o&&i}function iT(e,t,n,r){let i=Math.floor((n-r)/2),a=i+r;return e>=i&&e<a&&t>=i&&t<a}function aT(e,t){return(e+t)%11==0?`#6d8a63`:(e*3+t)%17==0?`#9b7a35`:`#263327`}function oT(e,t,n){return(0,K.jsxs)(`g`,{children:[(0,K.jsx)(`rect`,{x:e,y:t,width:`7`,height:`7`,rx:`1.45`,fill:`#263327`}),(0,K.jsx)(`rect`,{x:e+1,y:t+1,width:`5`,height:`5`,rx:`1`,fill:`#fbfaf2`}),(0,K.jsx)(`rect`,{x:e+2,y:t+2,width:`3`,height:`3`,rx:`0.72`,fill:`#263327`}),(0,K.jsx)(`rect`,{x:e+3.05,y:t+3.05,width:`0.9`,height:`0.9`,rx:`0.32`,fill:`#d9a735`})]},n)}function sT({value:e,badgeUrl:t,qrCodeFactory:n}){let r=(0,W.useId)().replace(/:/g,``),i=(0,W.useMemo)(()=>{let t=n(0,`H`);return t.addData(e),t.make(),t},[n,e]),a=i.getModuleCount(),o=a+Yw*2,s=Math.max(7,Math.min(11,Math.floor(a*.26)|1)),c=s+1.4,l=Yw+(a-c)/2,u=Yw+(a-c)/2,d=`farming-qr-badge-${r}`,f=[];for(let e=0;e<a;e+=1)for(let t=0;t<a;t+=1)i.isDark(e,t)&&(rT(e,t,a)||iT(e,t,a,s)||f.push((0,K.jsx)(`rect`,{x:Yw+t+.14,y:Yw+e+.14,width:`0.72`,height:`0.72`,rx:`0.24`,fill:aT(e,t)},`${e}-${t}`)));return(0,K.jsxs)(`svg`,{className:`code-share-qr-svg`,viewBox:`0 0 ${o} ${o}`,role:`img`,"aria-label":`QR code`,shapeRendering:`geometricPrecision`,children:[(0,K.jsx)(`defs`,{children:(0,K.jsx)(`clipPath`,{id:d,children:(0,K.jsx)(`rect`,{x:l+.55,y:u+.55,width:c-1.1,height:c-1.1,rx:`2.1`})})}),(0,K.jsx)(`rect`,{x:`0`,y:`0`,width:o,height:o,rx:`4`,fill:`#fbfaf2`}),f,oT(Yw,Yw,`top-left`),oT(Yw+a-7,Yw,`top-right`),oT(Yw,Yw+a-7,`bottom-left`),(0,K.jsx)(`rect`,{x:l,y:u,width:c,height:c,rx:`2.6`,fill:`#fbfaf2`}),(0,K.jsx)(`rect`,{x:l+.35,y:u+.35,width:c-.7,height:c-.7,rx:`2.25`,fill:`#ffffff`}),(0,K.jsx)(`image`,{href:t,x:l+.55,y:u+.55,width:c-1.1,height:c-1.1,preserveAspectRatio:`xMidYMid slice`,clipPath:`url(#${d})`})]})}function cT(){return(0,K.jsxs)(`svg`,{className:`code-share-icon`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:[(0,K.jsx)(`path`,{d:`M2.5 2.5h4v4h-4zM9.5 2.5h4v4h-4zM2.5 9.5h4v4h-4z`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.4`,strokeLinejoin:`round`}),(0,K.jsx)(`path`,{d:`M4 4h1v1H4zM11 4h1v1h-1zM4 11h1v1H4zM9.5 9.5h1.4v1.4H9.5zM12.1 9.5h1.4v1.4h-1.4zM9.5 12.1h1.4v1.4H9.5zM12.1 12.1h1.4v1.4h-1.4z`,fill:`currentColor`})]})}function lT({copy:e,sidebarCollapsed:t,shareTarget:r}){let[i,a]=(0,W.useState)(!1),[o,s]=(0,W.useState)(!1),[c,l]=(0,W.useState)(null),[u,d]=(0,W.useState)(!1),[f,p]=(0,W.useState)(``),[m,h]=(0,W.useState)(!1),[g,_]=(0,W.useState)(()=>Date.now()),[v,y]=(0,W.useState)({x:0,y:0}),b=(0,W.useRef)(null),x=(0,W.useRef)(null),S=(0,W.useRef)(null),C=(0,W.useRef)(null),w=(0,W.useRef)(null),T=(0,W.useRef)(0),D=(0,W.useRef)(null),O=(0,W.useRef)(null),[k,A]=(0,W.useState)(!0),[ee,j]=(0,W.useState)(null),N=n(`/farming-2/app-icon-v2-180.png`),te=E(r);(0,W.useEffect)(()=>{D.current=c},[c]);let P=(0,W.useCallback)(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]),F=(0,W.useCallback)(()=>{let e=x.current?.getBoundingClientRect();if(!e)return;let t=e.right+8,n=e.left-qw-8;y({x:t+qw+10<=window.innerWidth?t:Math.max(8,n),y:Math.max(8,Math.min(e.top-4,window.innerHeight-Jw-8))})},[]),ne=(0,W.useCallback)(()=>{t||Qw().then(e=>j(()=>e)).catch(()=>p(e.shareLinkFailed))},[e.shareLinkFailed,t]),I=(0,W.useCallback)(async(t=!1)=>{let i=D.current;if(!t&&eT(i,Date.now()))return i;let a=T.current+1;T.current=a,d(!0),p(``);try{let t=await fetch(n(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r?{target:r}:{})}),i=await t.json();if(!t.ok||!(`shortUrl`in i))throw Error(`error`in i&&i.error?i.error:e.shareLinkFailed);return a===T.current?(l(i),_(Date.now()),h(!1),i):(await nT(i),null)}catch(t){return a===T.current&&p(t instanceof Error?t.message:e.shareLinkFailed),null}finally{a===T.current&&d(!1)}},[e.shareLinkFailed,r,te]),L=(0,W.useCallback)(()=>{P(),T.current+=1,a(!1),s(!1),p(``),h(!1),d(!1);let e=D.current;D.current=null,l(null),nT(e)},[P]),re=(0,W.useCallback)((e,t=!1)=>{P(),F(),a(!0),s(e),ne(),I(t)},[P,I,ne,F]),R=(0,W.useCallback)(()=>{!i||o||(P(),w.current=window.setTimeout(()=>{w.current=null,L()},Kw))},[P,L,i,o]),z=(0,W.useCallback)(()=>{if(i&&o){L();return}re(!0,!0)},[L,i,re,o]),B=(0,W.useCallback)(async()=>{let t=eT(D.current,Date.now())?D.current:await I(!0);if(t){if(!await M(t.longUrl)){p(e.copyFailed);return}h(!0),O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{h(!1),O.current=null},1800)}},[e.copyFailed,I]);(0,W.useLayoutEffect)(()=>{if(i)return F(),window.addEventListener(`resize`,F),()=>window.removeEventListener(`resize`,F)},[i,F]),(0,W.useEffect)(()=>{if(!i)return;let e=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(e)},[i]),(0,W.useEffect)(()=>{let e=D.current;e&&(D.current=null,l(null),h(!1),nT(e))},[te]),(0,W.useLayoutEffect)(()=>{if(!i)return;let e=()=>{let e=S.current,t=C.current;!e||!t||A(t.scrollWidth<=e.clientWidth+1)};e();let t=typeof ResizeObserver<`u`?new ResizeObserver(e):null;return t&&S.current&&t.observe(S.current),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[i,c?.tokenLabel,c?.shortPath]),(0,W.useEffect)(()=>{if(!i)return;let e=e=>{let t=e.target;t instanceof Node&&b.current?.contains(t)||L()},t=e=>{e.key===`Escape`&&L()};return document.addEventListener(`pointerdown`,e,!0),document.addEventListener(`keydown`,t,!0),()=>{document.removeEventListener(`pointerdown`,e,!0),document.removeEventListener(`keydown`,t,!0)}},[L,i]),(0,W.useEffect)(()=>()=>{P(),O.current!==null&&window.clearTimeout(O.current),T.current+=1,nT(D.current)},[P]);let ie=!!(c&&c.expiresAt<=g),V=c?$w(c.expiresAt-g):``,ae=c?.tokenLabel||c?.shortPath||e.copyFullShareLink,oe=tT(ae),se=k||oe.length<=1?[ae]:oe;return(0,K.jsxs)(`div`,{ref:b,className:`code-share-root`,onMouseEnter:ne,onMouseLeave:R,onFocus:()=>{P(),ne()},onBlur:e=>{!e.currentTarget.contains(e.relatedTarget)&&!o&&L()},children:[(0,K.jsx)(`button`,{ref:x,type:`button`,className:`code-share-button`,"data-testid":`code-share-button`,"aria-label":e.sharePage,title:e.sharePage,"aria-haspopup":`dialog`,"aria-expanded":i,onClick:z,children:(0,K.jsx)(cT,{})}),i&&(0,K.jsxs)(`div`,{className:`code-share-popover`,"data-testid":`code-share-popover`,role:`dialog`,"aria-label":e.scanToOpenOnPhone,style:{left:v.x,top:v.y},onMouseEnter:()=>{P()},onMouseLeave:R,onKeyDown:e=>{e.key===`Escape`&&(L(),x.current?.focus())},children:[(0,K.jsxs)(`div`,{className:`code-share-qr-frame`,"data-expired":ie?`true`:`false`,children:[(0,K.jsx)(`div`,{className:`code-share-qr-canvas`,children:c&&!u&&ee?(0,K.jsx)(sT,{value:c.shortUrl,badgeUrl:N,qrCodeFactory:ee}):(0,K.jsx)(`div`,{className:`code-share-qr-loading`,children:u?e.loading:e.shareLinkFailed})}),c&&(0,K.jsx)(`div`,{className:`code-share-countdown`,children:ie?e.shareLinkExpired:V}),ie&&(0,K.jsx)(`button`,{type:`button`,className:`code-share-refresh`,onClick:()=>void I(!0),children:e.refreshShareLink})]}),(0,K.jsxs)(`button`,{type:`button`,className:`code-share-copy-token`,"data-testid":`code-share-copy-link`,disabled:!c&&u,onClick:()=>void B(),children:[(0,K.jsxs)(`span`,{ref:S,className:`code-share-token ${k?`single-line`:``}`,"aria-label":ae,children:[(0,K.jsx)(`span`,{ref:C,className:`code-share-token-measure`,"aria-hidden":`true`,children:ae}),se.map((e,t)=>(0,K.jsx)(`span`,{className:`code-share-token-line`,children:e},`${t}-${e}`))]}),(0,K.jsx)(`span`,{className:`code-share-copy-action`,children:m?e.copiedShareLink:e.copyFullShareLink})]}),f&&(0,K.jsx)(`div`,{className:`code-share-error`,role:`status`,children:f})]})]})}function uT(e,t){return e&&t.some(t=>!t.isMain&&t.id===e)?e:t.find(e=>!e.isMain)?.id??null}function dT(e){return e&&(e.projectWorkspace||e.cwd)||``}function fT(e,t,n={}){return Kb(e,t).map(e=>{let t=e.workspace?n[e.workspace]?.trim():``;return t&&!e.hasMain?{...e,name:t}:e})}function pT(e,t,n,r=new Set,i=new Set){return t?PS(e.map(e=>{let n=[e.name,e.workspace].some(e=>e.toLowerCase().includes(t)),a=n?e.agents:e.agents.filter(e=>i.has(e.id)||h(e).toLowerCase().includes(t)),o=n?e.agentSessions:e.agentSessions.filter(e=>r.has(Rb(e))||e.title.toLowerCase().includes(t));return a.length>0||o.length>0?{...e,agents:a,agentSessions:o}:null}).filter(e=>!!e),n,!0):e}function mT(e,t,n){return e.flatMap(e=>t.has(e.id)&&!n?[]:[...e.agents.map(e=>({kind:`agent`,id:e.id})),...e.agentSessions.map(e=>({kind:`agent-session`,provider:e.provider,id:e.id,...e.providerHomeId?{providerHomeId:e.providerHomeId}:{}}))])}var hT=5,gT=5,_T=`__project_agent_drop_end__`;function vT(e){let t=e?.trim().toLowerCase()||``;if(t===`claude-code`)return`claude`;if([`codex`,`claude`,`opencode`,`qoder`,`bash`,`zsh`].includes(t))return t}function yT(e){return vT(e.providerSessionProvider)||vT(e.command.trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop())}function bT(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M3.75 3C3.33579 3 3 3.33579 3 3.75V5.5C3 5.77614 2.77614 6 2.5 6C2.22386 6 2 5.77614 2 5.5V3.75C2 2.7835 2.7835 2 3.75 2H5.5C5.77614 2 6 2.22386 6 2.5C6 2.77614 5.77614 3 5.5 3H3.75ZM10 2.5C10 2.22386 10.2239 2 10.5 2H12.25C13.2165 2 14 2.7835 14 3.75V5.5C14 5.77614 13.7761 6 13.5 6C13.2239 6 13 5.77614 13 5.5V3.75C13 3.33579 12.6642 3 12.25 3H10.5C10.2239 3 10 2.77614 10 2.5ZM2.5 10C2.77614 10 3 10.2239 3 10.5V12.25C3 12.6642 3.33579 13 3.75 13H5.5C5.77614 13 6 13.2239 6 13.5C6 13.7761 5.77614 14 5.5 14H3.75C2.7835 14 2 13.2165 2 12.25V10.5C2 10.2239 2.22386 10 2.5 10ZM13.5 10C13.7761 10 14 10.2239 14 10.5V12.25C14 13.2165 13.2165 14 12.25 14H10.5C10.2239 14 10 13.7761 10 13.5C10 13.2239 10.2239 13 10.5 13H12.25C12.6642 13 13 12.6642 13 12.25V10.5C13 10.2239 13.2239 10 13.5 10Z`})})}function xT(e){let t=e.trim().replace(/^v/i,``);if(!t)return``;let n=/^(\d+\.\d+\.\d+)-(\d+)-g[0-9a-f]+(?:-dirty)?$/i.exec(t);if(n)return`${n[1]}-${n[2]}`;let r=/^(\d+\.\d+\.\d+)-dirty$/i.exec(t);return r?`${r[1]}-1`:t.replace(/-dirty$/i,``)}var ST=(0,W.lazy)(()=>o(()=>import(`./ProjectFilesSection-Q4PDsWmM.js`).then(e=>({default:e.ProjectFilesSection})),__vite__mapDeps([14,1,5,6,15,12,13])));function CT({sidebarCollapsed:e,activeView:t,searchOpen:r,displayedProjects:i,collapsedProjectIds:a,normalizedSearch:o,hasProjectListItems:s,hasDisplayedProjectListItems:c,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:d,claimedAgentSessionKeyByAgentId:f,agentShortcutKeys:p,keyboardShortcutsEnabled:h,now:g,mainAgent:_,systemStats:v,usageSummary:y,shareTarget:b,agentLaunchOptions:x,agentCreationWorkspace:S,openWorkspaceFile:C,openWorkspaceFiles:w,fileRevealRequest:T,fileSearchFocusRequest:E,projectListRef:D,canLoadMoreAgentSessions:O,onLoadMoreAgentSessions:k,onNewAgent:A,onStartAgent:ee,onToggleSidebar:j,onOpenSearch:M,onOpenWorkspaceView:N,onOpenMainAgent:te,onRestartMainAgent:P,onProjectListKeyDown:F,onToggleProject:ne,onToggleProjectSessions:I,onOpenProjectContextMenu:L,onOpenProjectKeyboardMenu:re,onOpenAgent:R,onUpdateAgentFlags:B,onReorderAgent:V,onOpenAgentContextMenu:ae,onOpenAgentKeyboardMenu:oe,onResumeAgentSession:se,onOpenAgentSessionContextMenu:le,onOpenAgentSessionKeyboardMenu:ue,onOpenProjectFile:de,onSelectOpenWorkspaceFile:pe,onCloseOpenWorkspaceFile:me,onMoveWorkspaceEntries:H,onDeleteWorkspaceEntries:he,onOpenOptionsMenu:_e,copy:ve}){let[ye,be]=(0,W.useState)(null),xe=(0,W.useRef)(null),Se=(0,W.useRef)(!1),Ce=(0,W.useRef)(new Map),[we,Te]=(0,W.useState)(!0),[Ee,De]=(0,W.useState)(!1),[Ae,U]=(0,W.useState)(!1),je=(0,W.useCallback)(()=>U(!1),[]),[Me,Ne]=(0,W.useState)(!1),[Pe,G]=(0,W.useState)(!1),[Fe,Ie]=(0,W.useState)(!1),Le=(0,W.useCallback)(e=>{O&&e.scrollHeight-e.scrollTop-e.clientHeight<=240&&k()},[O,k]),Re=(0,W.useCallback)(()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),ze=(0,W.useCallback)(()=>{Re(),be(null)},[Re]),Be=(0,W.useCallback)(()=>{Se.current=!1,ze()},[ze]),Ve=(0,W.useCallback)((e,t,r=!1)=>{Re();let i=e.currentTarget,a=Se.current?0:r?450:1500;xe.current=window.setTimeout(()=>{if(xe.current=null,!i.matches(`:hover`))return;let e=i.getBoundingClientRect(),r=e.right+10,a=Math.min(320,window.innerWidth-r-12);if(a<200)return;let o=Math.max(8,Math.min(e.top-4,window.innerHeight-152)),s=t.agentId?Ce.current.get(t.agentId):void 0,c=s&&s.expiresAt>Date.now()?s.branch:``;Se.current=!0,be({...t,x:r,y:o,width:a,branch:c}),!(!t.agentId||c)&&fetch(n(`/api/files/branch?agentId=${encodeURIComponent(t.agentId)}`)).then(e=>e.ok?e.json():null).then(e=>{let n=typeof e?.branch==`string`?e.branch.trim():``;Ce.current.set(t.agentId,{branch:n,expiresAt:Date.now()+3e4}),be(e=>e?.key===t.key?{...e,branch:n}:e)}).catch(()=>{Ce.current.set(t.agentId,{branch:``,expiresAt:Date.now()+3e4})})},a)},[Re]);(0,W.useEffect)(()=>()=>Re(),[Re]),(0,W.useEffect)(()=>{G(!!(document.fullscreenEnabled&&document.documentElement.requestFullscreen));let e=()=>{Ne(!!document.fullscreenElement)};return document.addEventListener(`fullscreenchange`,e),e(),()=>{document.removeEventListener(`fullscreenchange`,e)}},[]);let He=(0,W.useCallback)(()=>{if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>{})},[]),Ue=i.flatMap(e=>[...e.agents.filter(e=>e.pinned).map(e=>({kind:`agent`,agent:e})),...e.agentSessions.filter(e=>e.pinned).map(e=>({kind:`agent-session`,session:e}))]).sort((e,t)=>e.kind===`agent`&&t.kind===`agent`?(e.agent.pinnedOrder??0)-(t.agent.pinnedOrder??0)||(e.agent.startedAt??0)-(t.agent.startedAt??0):e.kind===t.kind?e.kind===`agent-session`&&t.kind===`agent-session`?Wb(t.session)-Wb(e.session):0:e.kind===`agent`?-1:1),We=i.filter(e=>e.agents.some(e=>!e.pinned||!e.isMain)||e.agentSessions.some(e=>!e.pinned)||(e.hiddenAgentSessionCount??0)>0),Ge=i.flatMap(e=>[...e.agents.filter(e=>!e.isMain).map(t=>({agent:t,projectName:e.name}))]),Ke=w.filter(e=>Oe(e.agentId)),qe=C&&Oe(C.agentId)?C:null,Je=T?.agentId===ke,Ye=Ke.length>0||Je;(0,W.useEffect)(()=>{Ye||Ie(!1)},[Ye]),(0,W.useEffect)(()=>{Je&&Ie(!1)},[Je]);let Xe=xT(`2.2.8`),Ze=Xe?`v${Xe}`:``,Qe=e;return(0,K.jsxs)(`aside`,{className:`code-sidebar ${e?`collapsed`:``}`,"data-testid":`code-sidebar`,onMouseLeave:Be,children:[(0,K.jsx)(`div`,{className:`code-nav`,children:(0,K.jsxs)(`div`,{className:`code-nav-top-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-nav-item primary`,"data-testid":`code-new-agent`,onClick:e=>A(S,void 0,e.currentTarget),children:[(0,K.jsx)(`span`,{className:`code-nav-icon`,children:(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,children:(0,K.jsx)(`path`,{d:`M14.452 1.548C14.087 1.183 13.608 1 13.13 1C12.652 1 12.173 1.183 11.808 1.548L6.979 6.377C6.697 6.659 6.498 7.011 6.401 7.398L6.027 8.896C5.883 9.473 6.329 10.002 6.886 10.002C6.958 10.002 7.031 9.993 7.106 9.975L8.604 9.601C8.99 9.504 9.343 9.305 9.625 9.023L14.454 4.194C15.184 3.464 15.184 2.28 14.454 1.549L14.452 1.548ZM13.745 3.485L8.916 8.314C8.763 8.467 8.57 8.576 8.36 8.629L7.04 8.962L7.371 7.64C7.424 7.43 7.532 7.237 7.686 7.084L12.516 2.255C12.68 2.091 12.899 2 13.131 2C13.363 2 13.582 2.091 13.746 2.255C14.085 2.594 14.085 3.146 13.746 3.486L13.745 3.485ZM13 7.768L14 6.768V11.5C14 12.878 12.879 14 11.5 14H4.5C3.121 14 2 12.878 2 11.5V4.5C2 3.122 3.121 2 4.5 2H9.236L8.236 3H4.5C3.673 3 3 3.673 3 4.5V11.5C3 12.327 3.673 13 4.5 13H11.5C12.327 13 13 12.327 13 11.5V7.768Z`})})}),(0,K.jsx)(`span`,{children:ve.newAgent}),h&&(0,K.jsx)(`kbd`,{children:`N`})]}),(0,K.jsx)(lT,{copy:ve,sidebarCollapsed:e,shareTarget:b}),Pe&&!e&&(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-focus-toggle ${Me?`active`:``}`,"data-testid":`code-sidebar-focus-toggle`,"aria-label":Me?ve.exitFocusMode:ve.enterFocusMode,title:Me?ve.exitFocusMode:ve.enterFocusMode,"aria-pressed":Me,onClick:He,children:(0,K.jsx)(`span`,{className:`code-sidebar-focus-icon`,children:(0,K.jsx)(bT,{})})}),!e&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-search-toggle ${t===`search`||r?`active`:``}`,"data-testid":`code-nav-search`,"aria-label":ve.search,title:ve.search,"aria-pressed":t===`search`||r,onClick:M,children:(0,K.jsx)(`span`,{className:`code-sidebar-search-icon`,"aria-hidden":`true`,children:(0,K.jsx)(ie,{})})}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-history-toggle ${t===`history`?`active`:``}`,"data-testid":`code-nav-history`,"aria-label":ve.history,title:ve.history,"aria-pressed":t===`history`,onClick:()=>N(`history`),children:(0,K.jsx)(`span`,{className:`code-sidebar-history-icon`,"aria-hidden":`true`,children:(0,K.jsx)(sE,{})})})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-toggle`,"data-testid":`code-sidebar-toggle`,"aria-label":e?ve.expandSidebar:ve.collapseSidebar,title:e?ve.expandSidebar:ve.collapseSidebar,onClick:j,children:(0,K.jsx)(`span`,{className:`code-sidebar-toggle-icon ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(fe,{}):(0,K.jsx)(ce,{})})})]})}),e&&Ge.length>0&&(0,K.jsx)(GT,{items:Ge,activeTerminalId:l,now:g,onOpenAgent:R,onShowPreview:Ve,onHidePreview:ze,copy:ve}),(0,K.jsxs)(`div`,{className:`code-project-list`,"data-testid":`code-project-list`,ref:D,tabIndex:0,onKeyDown:F,onScroll:e=>Le(e.currentTarget),"aria-label":ve.projectsAndAgents,children:[!s&&(0,K.jsx)(`div`,{className:`code-empty-project`,children:ve.noAgentsYet}),s&&!c&&(0,K.jsx)(`div`,{className:`code-empty-project`,"data-testid":`code-empty-search`,children:ve.noMatchingProjectsOrAgents}),Ue.length>0&&(0,K.jsx)(YT,{items:Ue,collapsed:Ee,compressed:Qe,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:d,claimedAgentSessionKeyByAgentId:f,agentShortcutKeys:p,keyboardShortcutsEnabled:h,now:g,onOpenAgent:R,onUpdateAgentFlags:B,onReorderAgent:V,onOpenAgentContextMenu:ae,onOpenAgentKeyboardMenu:oe,onResumeAgentSession:se,onOpenAgentSessionContextMenu:le,onOpenAgentSessionKeyboardMenu:ue,onShowAgentPreview:Ve,onHideAgentPreview:ze,onToggleCollapsed:()=>De(e=>!e),copy:ve}),Ye&&(0,K.jsxs)(`section`,{className:`code-project-group code-root-files-group`,"data-testid":`code-root-files-group`,children:[(0,K.jsx)(`div`,{className:`code-project-row code-root-files-row`,children:(0,K.jsxs)(`button`,{type:`button`,className:`code-project-title`,"data-testid":`code-root-files-title`,"aria-expanded":!Fe,onClick:()=>Ie(e=>!e),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${Fe?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:Fe?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:`/`})]})}),!Fe&&(0,K.jsx)(`div`,{className:`code-project-expanded`,children:(0,K.jsx)(W.Suspense,{fallback:null,children:(0,K.jsx)(ST,{projectId:`__farming_global_files_project__`,projectWorkspace:`/`,agentId:`__farming_global_files__`,agentLaunchOptions:[],activeFilePath:qe?.file.path,openFiles:Ke.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:m(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:T?.agentId===`__farming_global_files__`?T:void 0,focusSearchRequest:E?.agentId===`__farming_global_files__`?E:void 0,onOpenFile:de,onSelectOpenFile:pe,onCloseOpenFile:me,onMoveEntries:H,onDeleteEntries:he,readOnly:!0,copy:ve})})})]}),We.map(e=>(0,K.jsx)(XT,{project:e,collapsed:a.has(e.id)&&!o,compactAgents:Qe,activeTerminalId:l,selectedSearchAgentId:u,selectedSearchSessionHandle:d,claimedAgentSessionKeyByAgentId:f,agentShortcutKeys:p,keyboardShortcutsEnabled:h,now:g,openWorkspaceFile:C,openWorkspaceFiles:w,agentLaunchOptions:x,fileRevealRequest:T,fileSearchFocusRequest:E,onToggleProject:ne,onToggleProjectSessions:I,onNewAgent:A,onStartAgent:ee,onOpenProjectContextMenu:L,onOpenProjectKeyboardMenu:re,onOpenAgent:R,onUpdateAgentFlags:B,onReorderAgent:V,onOpenAgentContextMenu:ae,onOpenAgentKeyboardMenu:oe,onResumeAgentSession:se,onOpenAgentSessionContextMenu:le,onOpenAgentSessionKeyboardMenu:ue,onShowAgentPreview:Ve,onHideAgentPreview:ze,onOpenProjectFile:de,onSelectOpenWorkspaceFile:pe,onCloseOpenWorkspaceFile:me,onMoveWorkspaceEntries:H,onDeleteWorkspaceEntries:he,copy:ve},e.id))]}),(0,K.jsxs)(`div`,{className:`code-sidebar-footer`,children:[(0,K.jsxs)(`div`,{className:`code-product-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-product-mark`,"data-testid":`code-product-mark`,title:`Farming Code`,"aria-label":`Farming Code`,onClick:()=>U(!0),children:[(0,K.jsx)(`img`,{className:`code-product-logo`,src:n(`/farming-2/app-icon-v2-180.png`),alt:``,"aria-hidden":`true`}),(0,K.jsxs)(`span`,{className:`code-product-mark-copy`,children:[(0,K.jsxs)(`span`,{className:`code-product-mark-main-slot`,children:[(0,K.jsx)(`span`,{className:`code-product-mark-main code-product-mark-main-full`,children:`Farming Code`}),(0,K.jsx)(`span`,{className:`code-product-mark-main code-product-mark-main-short`,"aria-hidden":`true`,children:`Farming`})]}),Ze&&(0,K.jsx)(`span`,{className:`code-product-mark-badge`,children:Ze})]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-sidebar-options`,"data-testid":`code-sidebar-options`,"aria-label":ve.openSettings,title:ve.openSettings,onClick:_e,children:(0,K.jsx)(z,{})})]}),(y||v||_)&&(0,K.jsx)(K.Fragment,{children:!e&&(y||v||_)&&(0,K.jsx)(UT,{collapsed:we,mainAgent:_,usageSummary:y,systemStats:v,onToggleCollapsed:()=>Te(e=>!e),onOpenMainAgent:te,onRestartMainAgent:P})})]}),ye&&(0,K.jsx)(nE,{preview:ye,now:g}),Ae&&(0,K.jsx)(Fw,{copy:ve,version:Ze,onClose:je})]})}function wT(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`Window`:t===10080?`Weekly`:t%1440==0?`${t/1440}d`:t%60==0?`${t/60}h`:`${t}m`}function TT(e){let t=Number(e);return Number.isFinite(t)?`${Math.round(t)}%`:`--`}function ET(e){let t=Number(e);if(!Number.isFinite(t))return`-- left`;let n=Math.max(0,Math.min(100,100-t));return`${Math.round(n)}% left`}function DT(e){let t=e.forecast?.remainingTokens,n=t==null?null:Number(t);return typeof n==`number`&&Number.isFinite(n)&&n>=0?`${AT(Math.round(n))} tok left`:ET(e.usedPercent)}function OT(e){return DT(e)}function kT(e,t){let n=[e],r=TT(t.usedPercent),i=DT(t);return r!==`--`&&n.push(`${r} used`),i!==`-- left`&&n.push(i),n.filter(Boolean).join(` / `)}function AT(e){if(e>=1e6){let t=e/1e6;return`${t>=10?Math.round(t):Math.round(t*10)/10}M`}if(e>=1e3){let t=e/1e3;return`${t>=10?Math.round(t):Math.round(t*10)/10}k`}return`${e}`}function jT(e,t=!1){let n=Number(e);if(!Number.isFinite(n))return`-- tok/min`;let r=n<10?Math.round(n*10)/10:Math.round(n);return`${t?`~`:``}${AT(r)} tok/min`}function MT(e){let t=e.auth?.status||``;return e.auth?.available?/logged in/i.test(t)?`logged in`:t||`available`:`offline`}function NT(e){return e?.providers.length?e.providers.reduce((e,t)=>{let n=Number(t.tokenUsage.tokensPerMinute);return e+(Number.isFinite(n)?n:0)},0):null}function PT(e){let t=e.forecast?.remainingPercent;if(typeof t==`number`&&Number.isFinite(t))return Math.max(0,Math.min(100,t));let n=Number(e.usedPercent);return Number.isFinite(n)?Math.max(0,Math.min(100,100-n)):null}function FT(e){let t=Number(e.windowMinutes);return Number.isFinite(t)&&t>=10020?0:Number.isFinite(t)&&t>=285&&t<=315?1:2}function IT(e){return[e.quota.primary,e.quota.secondary].filter(e=>!!e).map(e=>({label:wT(e.windowMinutes),limit:e,remaining:PT(e),exhaustedAt:typeof e.forecast?.projectedExhaustedAt==`number`&&Number.isFinite(e.forecast.projectedExhaustedAt)?e.forecast.projectedExhaustedAt:null})).filter(e=>e.remaining!==null).sort((e,t)=>FT(e.limit)-FT(t.limit))}function LT(e){let t=Number(e.tokenUsage.tokensPerMinute);return Number.isFinite(t)&&t>0}function RT(e){return e?.providers.length?e.providers.filter(e=>LT(e)&&e.quota.available).map(e=>{let t=IT(e),n=t.filter(e=>e.remaining!==null&&e.remaining<50);return n.length?{provider:e,limits:t,earliestExhaustedAt:n.reduce((e,t)=>t.exhaustedAt===null?e:e===null?t.exhaustedAt:Math.min(e,t.exhaustedAt),null),lowestRemaining:n.reduce((e,t)=>Math.min(e,t.remaining??100),100)}:null}).filter(e=>!!e).sort((e,t)=>e.earliestExhaustedAt!==null&&t.earliestExhaustedAt!==null?e.earliestExhaustedAt-t.earliestExhaustedAt:e.earliestExhaustedAt===null?t.earliestExhaustedAt===null?e.lowestRemaining-t.lowestRemaining:1:-1)[0]??null:null}function zT(e){let t=RT(e);return t?[t.provider.providerName,...t.limits.map(e=>`${e.label} ${Math.round(e.remaining??0)}%`)].join(` · `):null}function BT(e,t){let n=[],r=NT(e);return r!==null&&n.push(jT(r)),t&&n.push(`CPU ${t.cpu}% / MEM ${t.memory.percentage}%`),n.join(` · `)||`5m`}function VT(e,t){return zT(e)||BT(e,t)}function HT(e){return e.status===`pending`?`starting`:e.status===`dead`?`offline`:e.status}function UT({collapsed:e,mainAgent:t,usageSummary:n,systemStats:r,onToggleCollapsed:i,onOpenMainAgent:a,onRestartMainAgent:o}){let s=NT(n),c=VT(n,r),[l,u]=(0,W.useState)(!1);return(0,K.jsxs)(`div`,{className:`code-usage-panel ${e?`collapsed`:``}`,"data-testid":`code-usage-panel`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-header`,"data-testid":`code-usage-toggle`,"aria-expanded":!e,title:`Provider local token usage refreshes periodically.`,onClick:i,children:[(0,K.jsxs)(`span`,{className:`code-usage-title`,children:[(0,K.jsx)(`span`,{className:`code-usage-chevron ${e?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:e?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:`Usage`})]}),(0,K.jsx)(`span`,{className:`code-usage-header-meta`,children:(0,K.jsx)(`span`,{className:`code-usage-summary`,"data-testid":`code-usage-summary`,children:e?c:`5m`})})]}),!e&&(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-main-agent-block`,children:[(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-main-agent`,title:`${h(t)} · ${t.command} · ${t.cwd}`,"data-testid":`code-main-agent-usage-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-usage-main-agent-open`,"data-testid":`code-main-agent-open`,onClick:a,children:[(0,K.jsx)(`span`,{children:`Main Agent`}),(0,K.jsx)(`strong`,{children:HT(t)})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-usage-main-agent-restart`,"data-testid":`code-main-agent-restart`,"aria-expanded":l,onClick:()=>u(e=>!e),children:`Restart`})]}),l&&(0,K.jsx)(`div`,{className:`code-main-agent-restart-menu`,"data-testid":`code-main-agent-restart-menu`,role:`menu`,children:[[`codex`,`Codex`],[`claude`,`Claude Code`],[`opencode`,`OpenCode`],[`qoder`,`Qoder`],[`bash`,`bash`],[`zsh`,`zsh`]].map(([e,t])=>(0,K.jsx)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-main-agent-restart-${e}`,onClick:()=>{u(!1),o(e)},children:t},e))})]}),n?.providers.map(e=>(0,K.jsx)(WT,{provider:e},e.provider)),s!==null&&(0,K.jsxs)(`div`,{className:`code-usage-row`,title:`Sum of local token usage reported by providers.`,children:[(0,K.jsx)(`span`,{children:`Total local tokens`}),(0,K.jsx)(`strong`,{children:jT(s)})]}),r&&(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:`System`}),(0,K.jsxs)(`strong`,{children:[`CPU `,r.cpu,`% / MEM `,r.memory.percentage,`%`]})]})]})]})}function WT({provider:e}){let t=e.quota.primary??null,n=e.quota.secondary??null,r=e.quota.available?e.quota.source:e.quota.reason||e.quota.source;return(0,K.jsxs)(`div`,{className:`code-usage-provider`,children:[(0,K.jsxs)(`div`,{className:`code-usage-row`,children:[(0,K.jsx)(`span`,{children:e.providerName}),(0,K.jsx)(`strong`,{title:e.auth?.status,children:MT(e)})]}),e.quota.available?(0,K.jsxs)(K.Fragment,{children:[t&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:kT(r,t),children:[(0,K.jsx)(`span`,{children:wT(t.windowMinutes)}),(0,K.jsx)(`strong`,{children:OT(t)})]}),n&&(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:kT(r,n),children:[(0,K.jsx)(`span`,{children:wT(n.windowMinutes)}),(0,K.jsx)(`strong`,{children:OT(n)})]})]}):(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow muted`,title:r,children:[(0,K.jsx)(`span`,{children:`Quota`}),(0,K.jsx)(`strong`,{children:`unavailable`})]}),(0,K.jsxs)(`div`,{className:`code-usage-row code-usage-subrow`,title:e.tokenUsage.source,children:[(0,K.jsx)(`span`,{children:`Local tokens`}),(0,K.jsx)(`strong`,{children:jT(e.tokenUsage.tokensPerMinute)})]})]})}function GT({items:e,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a,copy:o}){return(0,K.jsx)(`div`,{className:`code-agent-rail`,"data-testid":`code-agent-rail`,"aria-label":o.projectsAndAgents,children:e.map((e,o)=>(0,K.jsx)(KT,{item:e,index:o,activeTerminalId:t,now:n,onOpenAgent:r,onShowPreview:i,onHidePreview:a},fC({kind:`agent`,agent:e.agent})))})}function KT({item:e,index:t,activeTerminalId:n,now:r,onOpenAgent:i,onShowPreview:a,onHidePreview:o}){let s=xC({kind:`agent`,agent:e.agent},r),c=e.agent.id===n,l=[s.title,s.commandTitle,e.projectName].filter(Boolean).join(` · `);return(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-rail-button ${c?`active`:``} ${s.unread?`unread`:``}`,"data-testid":`code-agent-rail-item`,"data-agent-id":e.agent.id,"aria-label":l,onClick:()=>{i(e.agent.id)},onMouseEnter:t=>a(t,eE(e.agent,s,e.projectName),!0),onMouseLeave:o,children:[(0,K.jsx)(`span`,{className:`code-agent-rail-label`,children:t+1}),s.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-rail-status ${s.lifecycleStatus} ${s.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),s.unread&&(0,K.jsx)(`span`,{className:`code-agent-rail-unread`,"aria-hidden":`true`})]})}function qT({agents:e,activeTerminalId:t,selectedSearchAgentId:n,claimedAgentSessionKeyByAgentId:r,now:i,onOpenAgent:a,onOpenAgentContextMenu:o,onOpenAgentKeyboardMenu:s,onShowPreview:c,onHidePreview:l}){return(0,K.jsx)(`div`,{className:`code-project-agent-strip`,"data-testid":`code-project-agent-strip`,"aria-label":`Project agents`,children:e.map((e,u)=>{let d=xC({kind:`agent`,agent:e},i),f=e.id===t,p=e.id===n,m=d.rowTitle||d.title;return(0,K.jsxs)(`button`,{type:`button`,className:`code-project-agent-compact ${f?`active`:``} ${p?`search-selected`:``} ${d.unread?`unread`:``}`,"data-testid":`code-project-agent-compact`,"data-agent-id":e.id,"aria-label":m,onClick:()=>a(e.id),onMouseEnter:t=>c(t,eE(e,d),!0),onMouseLeave:l,onContextMenu:t=>o(t,e.id),onKeyDown:t=>{s(t,e.id),!t.defaultPrevented&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),a(e.id))},children:[(0,K.jsx)(`span`,{className:`code-project-agent-compact-label`,children:u+1}),d.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-status ${d.lifecycleStatus} ${d.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),d.unread&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-unread`,"aria-hidden":`true`})]},fC({kind:`agent`,agent:e,claimedSessionKey:r.get(e.id)}))})})}function JT({items:e,activeTerminalId:t,selectedSearchAgentId:n,selectedSearchSessionHandle:r,claimedAgentSessionKeyByAgentId:i,now:a,onOpenAgent:o,onOpenAgentContextMenu:s,onOpenAgentKeyboardMenu:c,onResumeAgentSession:l,onOpenAgentSessionContextMenu:u,onOpenAgentSessionKeyboardMenu:d,onShowPreview:f,onHidePreview:p}){return(0,K.jsx)(`div`,{className:`code-project-agent-strip code-pinned-agent-strip`,"data-testid":`code-pinned-agent-strip`,"aria-label":`Pinned agents`,children:e.map((e,m)=>{let h=e.kind===`agent`?xC({kind:`agent`,agent:e.agent},a):xC({kind:`history`,session:e.session,fallbackTitle:e.session.providerName||e.session.provider||`Agent`},a),g=e.kind===`agent`?e.agent:null,_=e.kind===`agent`?null:e.session,v=_?Rb(_):null,y=g?g.id===t:!1,b=g?g.id===n:v===r,x=h.rowTitle||h.title;return(0,K.jsxs)(`button`,{type:`button`,className:`code-project-agent-compact ${y?`active`:``} ${b?`search-selected`:``} ${h.unread?`unread`:``}`,"data-testid":`code-pinned-agent-compact`,"data-agent-id":g?.id,"data-session-id":v??void 0,"aria-label":x,onClick:()=>{if(g){o(g.id);return}_&&l(_.provider,_.id,_.providerHomeId)},onMouseEnter:e=>f(e,g?eE(g,h):tE(_,h),!0),onMouseLeave:p,onContextMenu:e=>{if(g){s(e,g.id);return}_&&u(e,_.provider,Rb(_))},onKeyDown:e=>{g?c(e,g.id):_&&d(e,_.provider,Rb(_)),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),g?o(g.id):_&&l(_.provider,_.id,_.providerHomeId))},children:[(0,K.jsx)(`span`,{className:`code-project-agent-compact-label`,children:m+1}),h.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-status ${h.lifecycleStatus} ${h.turnActive?`turn-active`:``}`,"aria-hidden":`true`}),h.unread&&(0,K.jsx)(`span`,{className:`code-project-agent-compact-unread`,"aria-hidden":`true`})]},e.kind===`agent`?fC({kind:`agent`,agent:e.agent,claimedSessionKey:i.get(e.agent.id)}):fC({kind:`history`,session:e.session}))})})}function YT({items:e,collapsed:t,compressed:n,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,agentShortcutKeys:s,keyboardShortcutsEnabled:c,now:l,onOpenAgent:u,onUpdateAgentFlags:d,onReorderAgent:f,onOpenAgentContextMenu:p,onOpenAgentKeyboardMenu:m,onResumeAgentSession:h,onOpenAgentSessionContextMenu:g,onOpenAgentSessionKeyboardMenu:_,onShowAgentPreview:v,onHideAgentPreview:y,onToggleCollapsed:b,copy:x}){let S=e.flatMap(e=>e.kind===`agent`?[e.agent]:[]),[C,w]=(0,W.useState)(null),T=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),y(),w({agentId:t,targetAgentId:``,position:`before`})},E=(e,t)=>{if(!C||C.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?`before`:`after`;C.targetAgentId===t&&C.position===r||w(e=>e?{...e,targetAgentId:t,position:r}:null)},D=()=>w(null),O=(e,t)=>{if(e.preventDefault(),!C||C.agentId===t){D();return}let n=S.filter(e=>e.id!==C.agentId),r=n.findIndex(e=>e.id===t);if(r<0){D();return}let i=C.position===`before`?r:r+1;f(C.agentId,i>0?n[i-1]?.id??``:``,i<n.length?n[i]?.id??``:``),D()};return(0,K.jsxs)(`section`,{className:`code-pinned-section ${t?`collapsed`:``}`,"data-testid":`code-pinned-section`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-pinned-title`,"data-testid":`code-pinned-title`,"aria-expanded":!t,onClick:b,children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:x.pinned})]}),!t&&(0,K.jsx)(`div`,{className:`code-agent-list code-pinned-list`,children:n?(0,K.jsx)(JT,{items:e,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,now:l,onOpenAgent:u,onOpenAgentContextMenu:p,onOpenAgentKeyboardMenu:m,onResumeAgentSession:h,onOpenAgentSessionContextMenu:g,onOpenAgentSessionKeyboardMenu:_,onShowPreview:v,onHidePreview:y}):e.map(e=>{if(e.kind===`agent`){let t=e.agent;return(0,K.jsx)(uE,{agent:t,shortcutHint:c?s.get(t.id):void 0,active:t.id===r,searchSelected:t.id===i,now:l,onOpenAgent:u,onUpdateAgentFlags:d,reorderable:!0,dragging:C?.agentId===t.id,dropPosition:C?.targetAgentId===t.id?C.position:void 0,onAgentDragStart:T,onAgentDragEnd:D,onAgentDragOver:E,onAgentDrop:O,onOpenAgentContextMenu:p,onOpenAgentKeyboardMenu:m,onShowPreview:v,onHidePreview:y,copy:x},fC({kind:`agent`,agent:t,claimedSessionKey:o.get(t.id)}))}return(0,K.jsx)(uE,{session:e.session,searchSelected:Rb(e.session)===a,now:l,onResume:h,onOpenSessionContextMenu:g,onOpenSessionKeyboardMenu:_,onShowPreview:v,onHidePreview:y,copy:x},fC({kind:`history`,session:e.session}))})})]})}function XT({project:e,collapsed:t,compactAgents:n,activeTerminalId:r,selectedSearchAgentId:i,selectedSearchSessionHandle:a,claimedAgentSessionKeyByAgentId:o,agentShortcutKeys:s,keyboardShortcutsEnabled:c,now:l,openWorkspaceFile:u,openWorkspaceFiles:d,agentLaunchOptions:f,fileRevealRequest:p,fileSearchFocusRequest:h,onToggleProject:g,onToggleProjectSessions:y,onNewAgent:b,onStartAgent:x,onOpenProjectContextMenu:S,onOpenProjectKeyboardMenu:C,onOpenAgent:w,onUpdateAgentFlags:T,onReorderAgent:E,onOpenAgentContextMenu:D,onOpenAgentKeyboardMenu:O,onResumeAgentSession:k,onOpenAgentSessionContextMenu:A,onOpenAgentSessionKeyboardMenu:ee,onShowAgentPreview:j,onHideAgentPreview:M,onOpenProjectFile:N,onSelectOpenWorkspaceFile:te,onCloseOpenWorkspaceFile:P,onMoveWorkspaceEntries:F,onDeleteWorkspaceEntries:ne,copy:I}){let re=(0,W.useRef)(null),R=(0,W.useRef)(null),z=(0,W.useRef)(null),B=(0,W.useRef)(null),ie=(0,W.useRef)(null),[V,ae]=(0,W.useState)(null),[oe,se]=(0,W.useState)(!1),[ce,le]=(0,W.useState)(!1),[ue,de]=(0,W.useState)(null),[pe,me]=(0,W.useState)(()=>uT(null,e.agents)),H=uT(pe,e.agents),he=e.agents.find(e=>!e.isMain&&e.id===H)??null,_e=e.id!==`__farming_main_agent__`&&he!==null,ve=new Set(e.agents.filter(e=>!e.isMain).map(e=>e.id)),ye=(0,W.useCallback)(t=>ve.has(t.agentId)||t.workspaceRoot===e.id,[e.id,ve]),be=u&&ye(u)?u:null,xe=d.filter(ye),Se=new Set(xe.filter(e=>e.dirty).map(e=>e.file.path)),Ce=new Set(xe.filter(e=>e.externalChanged).map(e=>e.file.path)),we=e.agents.filter(e=>!e.pinned),Te=e.agentSessions.filter(e=>!e.pinned),Ee=we.length>0||Te.length>0||(e.hiddenAgentSessionCount??0)>0,De=ce&&L()&&we.length>1,Oe=(n||De)&&we.length>0,ke=Oe||oe?we:QT(we,gT,[r,i]),Ae=Math.max(0,we.length-ke.length);(0,W.useEffect)(()=>{pe!==H&&me(H)},[H,pe]);let U=(0,W.useCallback)(e=>{le(!e)},[]),je=(e,t)=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),M(),de({agentId:t,targetAgentId:``,position:`before`})},Me=(e,t)=>{if(!ue||ue.agentId===t)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?`before`:`after`;ue.targetAgentId===t&&ue.position===r||de(e=>e?{...e,targetAgentId:t,position:r}:null)},Ne=()=>de(null),Pe=(e,t)=>{if(e.preventDefault(),!ue||ue.agentId===t){Ne();return}let n=we.filter(e=>e.id!==ue.agentId),r=n.findIndex(e=>e.id===t);if(r<0){Ne();return}let i=ue.position===`before`?r:r+1;E(ue.agentId,i>0?n[i-1]?.id??``:``,i<n.length?n[i]?.id??``:``),Ne()},G=e=>{if(e.preventDefault(),!ue)return;let t=we.filter(e=>e.id!==ue.agentId);E(ue.agentId,t[t.length-1]?.id??``,``),Ne()},Fe=e=>{ue&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,ue.targetAgentId!==_T&&de(e=>e?{...e,targetAgentId:_T,position:`after`}:null))};(0,W.useEffect)(()=>{we.length<=gT&&oe&&se(!1)},[oe,we.length]),(0,W.useLayoutEffect)(()=>{let e=re.current;if(!e)return;let t=()=>{let t=R.current;e.style.setProperty(`--code-project-sticky-height`,t?`${Math.ceil(t.getBoundingClientRect().height)}px`:``);let n=z.current;e.style.setProperty(`--code-agents-sticky-height`,n?`${Math.ceil(n.getBoundingClientRect().height)}px`:`0px`)};t();let n=R.current,r=z.current,i=typeof ResizeObserver<`u`?new ResizeObserver(t):null;return n&&i?.observe(n),r&&i?.observe(r),window.addEventListener(`resize`,t),()=>{i?.disconnect(),window.removeEventListener(`resize`,t)}},[t,e.id,Ee]),(0,W.useEffect)(()=>{if(!V)return;let e=e=>{let t=e.target;t&&(ie.current?.contains(t)||B.current?.contains(t))||ae(null)},t=e=>{e.key===`Escape`&&(e.preventDefault(),ae(null),B.current?.focus())};return window.addEventListener(`pointerdown`,e,!0),window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`pointerdown`,e,!0),window.removeEventListener(`keydown`,t,!0)}},[V]);let Ie=t=>{if(t.preventDefault(),t.stopPropagation(),f.length===0){b(e.workspace,void 0,t.currentTarget);return}let n=t.currentTarget.getBoundingClientRect(),r=Math.min(260,f.length*34+12);ae(L()?Ww(n,r,void 0,160):Uw(n,r,void 0,160))},Le=t=>{ae(null),x(t,e.workspace)};return(0,K.jsxs)(`section`,{ref:re,className:`code-project-group`,"data-testid":`code-project-group`,children:[(0,K.jsxs)(`div`,{ref:R,className:`code-project-row`,children:[(0,K.jsxs)(`button`,{type:`button`,className:`code-project-title`,"data-testid":`code-project-title`,"data-project-id":e.id,"aria-expanded":!t,onClick:()=>g(e.id),onContextMenu:t=>S(t,e.id),onKeyDown:t=>C(t,e.id),children:[(0,K.jsx)(`span`,{className:`code-folder-icon ${t?`collapsed`:`expanded`}`,"aria-hidden":`true`,children:t?(0,K.jsx)(fe,{}):(0,K.jsx)(ge,{})}),(0,K.jsx)(`span`,{children:e.name})]}),(0,K.jsxs)(`span`,{className:`code-project-title-actions`,"aria-hidden":!1,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-project-title-action`,"data-testid":`code-project-actions`,"aria-label":I.openOptions,title:I.openOptions,onClick:t=>S(t,e.id),children:(0,K.jsx)($T,{})}),(0,K.jsx)(`button`,{ref:B,type:`button`,className:`code-project-title-action`,"data-testid":`code-project-new-agent`,"aria-label":I.newAgent,title:I.newAgent,"aria-haspopup":`menu`,"aria-expanded":V?!0:void 0,onClick:Ie,children:(0,K.jsx)(ZT,{})})]}),V&&typeof document<`u`&&(0,Nw.createPortal)((0,K.jsx)(`div`,{ref:ie,className:`code-context-menu code-project-launch-menu`,"data-testid":`code-project-new-agent-menu`,role:`menu`,style:{left:V.x,top:V.y},children:f.map(e=>(0,K.jsxs)(`button`,{type:`button`,role:`menuitem`,"data-testid":`code-project-agent-launch-${e.name}`,onClick:()=>Le(e.command||e.name),children:[(0,K.jsx)(_,{name:e.name}),(0,K.jsx)(`span`,{children:v(e.name)})]},e.name))}),document.body)]}),!t&&(0,K.jsxs)(`div`,{className:`code-project-expanded`,children:[Ee&&(0,K.jsx)(`div`,{ref:z,className:`code-agents-section`,"data-testid":`code-agents-section`,"data-project-id":e.id,children:(0,K.jsxs)(`div`,{className:`code-agent-list`,children:[Oe?(0,K.jsx)(qT,{agents:we,activeTerminalId:r,selectedSearchAgentId:i,claimedAgentSessionKeyByAgentId:o,now:l,onOpenAgent:w,onOpenAgentContextMenu:D,onOpenAgentKeyboardMenu:O,onShowPreview:j,onHidePreview:M}):ke.map(e=>(0,K.jsx)(uE,{agent:e,shortcutHint:c?s.get(e.id):void 0,active:e.id===r,searchSelected:e.id===i,now:l,onOpenAgent:w,onUpdateAgentFlags:T,reorderable:!0,dragging:ue?.agentId===e.id,dropPosition:ue?.targetAgentId===e.id?ue.position:void 0,onAgentDragStart:je,onAgentDragEnd:Ne,onAgentDragOver:Me,onAgentDrop:Pe,onOpenAgentContextMenu:D,onOpenAgentKeyboardMenu:O,onShowPreview:j,onHidePreview:M,copy:I},fC({kind:`agent`,agent:e,claimedSessionKey:o.get(e.id)}))),!Oe&&Ae>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more ${ue?.targetAgentId===_T?`drop-after`:``}`,"data-testid":`code-agent-show-more`,onClick:()=>se(!0),onDragOver:Fe,onDrop:G,children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:Ae})})]}),!Oe&&oe&&we.length>gT&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-agent-show-less`,onClick:()=>se(!1),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showLess})})}),Te.map(e=>(0,K.jsx)(uE,{session:e,searchSelected:Rb(e)===a,now:l,onResume:k,onOpenSessionContextMenu:A,onOpenSessionKeyboardMenu:ee,onShowPreview:j,onHidePreview:M,copy:I},fC({kind:`history`,session:e}))),(e.hiddenAgentSessionCount??0)>0&&(0,K.jsxs)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-more`,onClick:()=>y(e.id),children:[(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showMore})}),(0,K.jsx)(`span`,{className:`code-agent-row-trailing`,children:(0,K.jsx)(`span`,{className:`code-agent-age`,children:e.hiddenAgentSessionCount})})]}),e.agentSessionsExpanded&&e.agentSessions.length>hT&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row code-session-show-more`,"data-testid":`code-session-show-less`,onClick:()=>y(e.id),children:(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:I.showLess})})})]})}),_e&&he&&(0,K.jsx)(W.Suspense,{fallback:null,children:(0,K.jsx)(ST,{projectId:e.id,projectWorkspace:e.workspace,agentId:he.id,agentLaunchOptions:f,activeFilePath:be?.file.path,openFiles:xe.map(e=>({agentId:e.agentId,workspaceRoot:e.workspaceRoot,key:m(e),path:e.file.path,dirty:e.dirty,externalChanged:e.externalChanged})),revealRequest:p&&ve.has(p.agentId)?p:void 0,focusSearchRequest:h&&ve.has(h.agentId)?h:void 0,editorDirtyFilePaths:Se,editorExternalChangedFilePaths:Ce,onOpenFile:N,onSelectOpenFile:te,onCloseOpenFile:P,onNewAgent:b,onStartAgent:x,onMoveEntries:F,onDeleteEntries:ne,onFilesCollapsedChange:U,copy:I})})]})]})}function ZT(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M7.5 3C7.77614 3 8 3.22386 8 3.5V7H11.5C11.7761 7 12 7.22386 12 7.5C12 7.77614 11.7761 8 11.5 8H8V11.5C8 11.7761 7.77614 12 7.5 12C7.22386 12 7 11.7761 7 11.5V8H3.5C3.22386 8 3 7.77614 3 7.5C3 7.22386 3.22386 7 3.5 7H7V3.5C7 3.22386 7.22386 3 7.5 3Z`})})}function QT(e,t,n){if(e.length<=t)return e;let r=e.slice(0,t),i=new Set(r.map(e=>e.id)),a=new Set(n.filter(e=>!!e));for(let n of e)if(!(!a.has(n.id)||i.has(n.id))){if(r.length>=t&&r.length>0){let e=r[r.length-1];i.delete(e.id),r[r.length-1]=n}else r.push(n);i.add(n.id)}return r}function $T(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M4 8C4 8.55228 3.55228 9 3 9C2.44772 9 2 8.55228 2 8C2 7.44772 2.44772 7 3 7C3.55228 7 4 7.44772 4 8ZM9 8C9 8.55228 8.55228 9 8 9C7.44772 9 7 8.55228 7 8C7 7.44772 7.44772 7 8 7C8.55228 7 9 7.44772 9 8ZM13 9C13.5523 9 14 8.55228 14 8C14 7.44772 13.5523 7 13 7C12.4477 7 12 7.44772 12 8C12 8.55228 12.4477 9 13 9Z`})})}function eE(e,t,n){return{key:`agent:${e.id}`,title:t.title,project:n||jb(e.projectWorkspace||e.cwd),lastActive:e.lastActivity||e.startedAt||0,provider:yT(e),agentId:e.id}}function tE(e,t){return{key:`session:${Rb(e)}`,title:t.title,project:Ub(e),lastActive:Wb(e),provider:vT(e.provider)}}function nE({preview:e,now:t}){return(0,K.jsxs)(`div`,{className:`code-agent-hover-preview`,"data-testid":`code-agent-hover-preview`,style:{left:e.x,top:e.y,width:e.width},"aria-hidden":`true`,children:[(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-header`,children:[(0,K.jsx)(`strong`,{children:e.title}),(0,K.jsx)(`span`,{children:s(e.lastActive,t)})]}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-icon`,children:(0,K.jsx)(rE,{})}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-project`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-project-name`,children:e.project}),e.provider&&(0,K.jsx)(_,{name:e.provider,variant:`color`,className:`code-agent-hover-preview-provider-icon`})]})]}),(0,K.jsxs)(`div`,{className:`code-agent-hover-preview-line`,children:[(0,K.jsx)(`span`,{className:`code-agent-hover-preview-icon`,children:(0,K.jsx)(iE,{})}),(0,K.jsx)(`span`,{children:e.branch||`—`})]})]})}function rE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M1.5 3.75C1.5 2.784 2.284 2 3.25 2h3.104c.464 0 .91.184 1.237.513l.841.842c.14.14.33.22.528.22h3.79c.966 0 1.75.784 1.75 1.75v6.925c0 .966-.784 1.75-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75V3.75Zm1.75-.75a.75.75 0 0 0-.75.75v8.5c0 .414.336.75.75.75h9.5a.75.75 0 0 0 .75-.75V5.325a.75.75 0 0 0-.75-.75H8.96a1.75 1.75 0 0 1-1.235-.512l-.841-.842A.75.75 0 0 0 6.354 3H3.25Z`})})}function iE(){return(0,K.jsx)(`svg`,{width:`24`,height:`24`,viewBox:`0 0 24 24`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M21 8.25C21 6.1815 19.3185 4.5 17.25 4.5C15.1815 4.5 13.5 6.1815 13.5 8.25C13.5 10.023 14.739 11.5035 16.395 11.892C16.116 12.819 15.2655 13.5 14.25 13.5H9.75C8.9025 13.5 8.1285 13.7925 7.5 14.268V7.4235C9.21 7.0755 10.5 5.5605 10.5 3.75C10.5 1.6815 8.8185 0 6.75 0C4.6815 0 3 1.6815 3 3.75C3 5.562 4.29 7.0755 6 7.4235V16.575C4.29 16.923 3 18.438 3 20.2485C3 22.317 4.6815 23.9985 6.75 23.9985C8.8185 23.9985 10.5 22.317 10.5 20.2485C10.5 18.4755 9.261 16.995 7.605 16.6065C7.884 15.6795 8.7345 14.9985 9.75 14.9985H14.25C16.0845 14.9985 17.61 13.6725 17.931 11.9295C19.674 11.607 21 10.0845 21 8.25ZM4.5 3.75C4.5 2.5095 5.5095 1.5 6.75 1.5C7.9905 1.5 9 2.5095 9 3.75C9 4.9905 7.9905 6 6.75 6C5.5095 6 4.5 4.9905 4.5 3.75ZM9 20.25C9 21.4905 7.9905 22.5 6.75 22.5C5.5095 22.5 4.5 21.4905 4.5 20.25C4.5 19.0095 5.5095 18 6.75 18C7.9905 18 9 19.0095 9 20.25ZM17.25 10.5C16.0095 10.5 15 9.4905 15 8.25C15 7.0095 16.0095 6 17.25 6C18.4905 6 19.5 7.0095 19.5 8.25C19.5 9.4905 18.4905 10.5 17.25 10.5Z`})})}function aE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M10.0589 2.44511C9.34701 1.73063 8.14697 1.90829 7.67261 2.79839L5.6526 6.58878L2.8419 7.52568C2.6775 7.58048 2.5532 7.71649 2.51339 7.88514C2.47357 8.0538 2.52392 8.23104 2.64646 8.35357L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5265 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L13.1897 8.32423C14.0759 7.84982 14.2538 6.6551 13.5443 5.94305L10.0589 2.44511ZM8.55511 3.2687C8.71323 2.972 9.11324 2.91278 9.35055 3.15094L12.836 6.64889C13.0725 6.88624 13.0131 7.28448 12.7178 7.44262L8.76403 9.55921C8.65137 9.61952 8.56608 9.72068 8.52567 9.84191L7.7815 12.0744L3.92562 8.21853L6.15812 7.47436C6.27966 7.43385 6.38101 7.34823 6.44126 7.23518L8.55511 3.2687Z`})})}function oE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,xmlns:`http://www.w3.org/2000/svg`,fill:`currentColor`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{d:`M9.56016 10.2673L14.1464 14.8536C14.3417 15.0488 14.6583 15.0488 14.8536 14.8536C15.0488 14.6583 15.0488 14.3417 14.8536 14.1464L1.85355 1.14645C1.65829 0.951184 1.34171 0.951184 1.14645 1.14645C0.951184 1.34171 0.951184 1.65829 1.14645 1.85355L5.73223 6.43934L5.6526 6.58876L2.8419 7.52566C2.6775 7.58046 2.5532 7.71648 2.51339 7.88513C2.47357 8.05378 2.52392 8.23102 2.64646 8.35356L4.79291 10.5L2.14645 13.1465L2 14L2.85356 13.8536L5.50002 11.2071L7.64646 13.3536C7.76899 13.4761 7.94623 13.5264 8.11489 13.4866C8.28354 13.4468 8.41955 13.3225 8.47435 13.1581L9.41143 10.3469L9.56016 10.2673ZM8.82138 9.52849L8.76403 9.5592C8.65137 9.61951 8.56608 9.72066 8.52567 9.84189L7.7815 12.0744L3.92562 8.21851L6.15812 7.47435C6.27966 7.43383 6.38101 7.34822 6.44126 7.23516L6.47143 7.17854L8.82138 9.52849ZM12.7178 7.4426L10.6636 8.54227L11.4024 9.28105L13.1897 8.32422C14.0759 7.84981 14.2538 6.65509 13.5443 5.94304L10.0589 2.44509C9.34701 1.73062 8.14697 1.90828 7.67261 2.79838L6.71556 4.59421L7.45476 5.33341L8.55511 3.26869C8.71323 2.97199 9.11324 2.91277 9.35055 3.15093L12.836 6.64888C13.0725 6.88623 13.0131 7.28446 12.7178 7.4426Z`})})}function sE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M7.99909 3C10.7605 3 12.9991 5.23858 12.9991 8C12.9991 10.7614 10.7605 13 7.99909 13C5.39117 13 3.2491 11.003 3.0195 8.45512C2.99471 8.1801 2.75167 7.97723 2.47664 8.00202C2.20161 8.0268 1.99875 8.26985 2.02353 8.54488C2.29916 11.6035 4.86898 14 7.99909 14C11.3128 14 13.9991 11.3137 13.9991 8C13.9991 4.68629 11.3128 2 7.99909 2C6.20656 2 4.59815 2.78613 3.49909 4.03138V2.5C3.49909 2.22386 3.27524 2 2.99909 2C2.72295 2 2.49909 2.22386 2.49909 2.5V5.5C2.49909 5.77614 2.72295 6 2.99909 6H3.08812C3.09498 6.00014 3.10184 6.00014 3.10868 6H5.99909C6.27524 6 6.49909 5.77614 6.49909 5.5C6.49909 5.22386 6.27524 5 5.99909 5H3.99863C4.91128 3.78495 6.36382 3 7.99909 3ZM7.99909 5.5C7.99909 5.22386 7.77524 5 7.49909 5C7.22295 5 6.99909 5.22386 6.99909 5.5V8.5C6.99909 8.77614 7.22295 9 7.49909 9H9.49909C9.77524 9 9.99909 8.77614 9.99909 8.5C9.99909 8.22386 9.77524 8 9.49909 8H7.99909V5.5Z`})})}function cE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})})}function lE(){return(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M12.854 14.8542L14.854 12.8542C15.049 12.6592 15.049 12.3422 14.854 12.1472L12.854 10.1472C12.659 9.95223 12.342 9.95223 12.147 10.1472C11.952 10.3422 11.952 10.6592 12.147 10.8542L13.293 12.0002H8.5C8.225 12.0002 8 11.7752 8 11.5002V5.50023C8 5.22523 8.225 5.00023 8.5 5.00023H13.293L12.147 6.14623C12.049 6.24423 12.001 6.37223 12.001 6.50023C12.001 6.62823 12.05 6.75623 12.147 6.85423C12.342 7.04923 12.659 7.04923 12.854 6.85423L14.854 4.85423C15.049 4.65923 15.049 4.34223 14.854 4.14723L12.854 2.14723C12.659 1.95223 12.342 1.95223 12.147 2.14723C11.952 2.34223 11.952 2.65923 12.147 2.85423L13.293 4.00023H8.5C7.673 4.00023 7 4.67323 7 5.50023V8.00023H1.5C1.224 8.00023 1 8.22423 1 8.50023C1 8.77623 1.224 9.00023 1.5 9.00023H7V11.5002C7 12.3272 7.673 13.0002 8.5 13.0002H13.293L12.147 14.1462C12.049 14.2442 12.001 14.3722 12.001 14.5002C12.001 14.6282 12.05 14.7562 12.147 14.8542C12.342 15.0492 12.659 15.0492 12.854 14.8542Z`})})}function uE({agent:e,session:t,shortcutHint:n,active:r=!1,searchSelected:i,now:a,onOpenAgent:o,onUpdateAgentFlags:s,reorderable:c=!1,dragging:l=!1,dropPosition:u,onAgentDragStart:d,onAgentDragEnd:f,onAgentDragOver:p,onAgentDrop:m,onOpenAgentContextMenu:h,onOpenAgentKeyboardMenu:g,onResume:v,onOpenSessionContextMenu:y,onOpenSessionKeyboardMenu:b,onShowPreview:x,onHidePreview:S,copy:C}){let w=(0,W.useRef)(!1),T=e?{kind:`agent`,agent:e}:t?{kind:`history`,session:t,fallbackTitle:C.sessionFallbackTitle(t.providerName)}:null;if(!T)return null;let E=xC(T,a),D=E.requiresResume,O=e?.id??``,k=t?.provider??``,A=t?.id??``,ee=D?`code-active-session-row`:`code-agent-row`,j=e?yT(e):vT(t?.provider),M=()=>{if(D){S?.(),k&&A&&v?.(k,A,t?.providerHomeId);return}O&&o?.(O)};return(0,K.jsxs)(`div`,{tabIndex:0,className:`code-agent-row ${D?`requires-resume`:``} ${r?`active`:``} ${i?`search-selected`:``} ${E.pinned?`pinned`:``} ${E.unread?`unread`:``} ${l?`dragging`:``} ${u?`drop-${u}`:``}`,draggable:c||void 0,"data-testid":ee,"data-agent-id":e?.id,"data-provider":t?.provider,"data-session-id":t?Rb(t):void 0,"aria-label":E.rowTitle||E.title,onDragStart:e=>{!O||!c||(w.current=!0,d?.(e,O))},onDragEnd:()=>{f?.(),window.setTimeout(()=>{w.current=!1},0)},onDragOver:e=>O&&p?.(e,O),onDrop:e=>O&&m?.(e,O),onClick:e=>{if(w.current){e.preventDefault(),e.stopPropagation();return}M()},onMouseEnter:n=>{e?x?.(n,eE(e,E)):t&&x?.(n,tE(t,E))},onMouseLeave:S,onContextMenu:e=>{if(D){S?.(),k&&t&&y?.(e,k,Rb(t));return}O&&h?.(e,O)},onKeyDown:e=>{D?k&&t&&b?.(e,k,Rb(t)):O&&g?.(e,O),!e.defaultPrevented&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),M())},children:[j&&(0,K.jsx)(`span`,{className:`code-agent-row-provider-icon`,"aria-hidden":`true`,children:(0,K.jsx)(_,{name:j,variant:`color`})}),(0,K.jsx)(`span`,{className:`code-agent-row-copy`,children:(0,K.jsx)(`span`,{className:`code-agent-name`,children:E.title})}),(0,K.jsxs)(`span`,{className:`code-agent-row-trailing`,children:[E.statusIndicatorVisible&&(0,K.jsx)(`span`,{className:`code-agent-dot ${E.lifecycleStatus} ${E.turnActive?`turn-active`:``}`,title:E.commandTitle||E.lifecycleStatus}),E.forkedToNewWorktree&&(0,K.jsx)(`span`,{className:`code-agent-fork-new-worktree`,"data-testid":`code-agent-new-worktree-fork`,title:C.newWorktreeFork,"aria-label":C.newWorktreeFork,role:`img`,children:(0,K.jsx)(lE,{})}),E.scheduled&&(0,K.jsx)(`span`,{className:`code-agent-schedule-clock`,"data-testid":`code-agent-schedule-clock`,title:E.scheduleTitle,"aria-label":E.scheduleTitle||C.scheduledTask}),E.unread&&(0,K.jsx)(`span`,{className:`code-agent-unread`,title:C.unread}),e&&(0,K.jsxs)(`span`,{className:`code-agent-row-actions`,"aria-hidden":!1,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action pin ${E.pinned?`active`:``}`,"data-testid":`code-agent-row-pin`,"aria-label":E.pinned?C.unpinAgent:C.pinAgent,title:E.pinned?C.unpinAgent:C.pinAgent,onClick:t=>{t.preventDefault(),t.stopPropagation(),e&&s?.(e,{pinned:!E.pinned})},children:E.pinned?(0,K.jsx)(oE,{}):(0,K.jsx)(aE,{})}),(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-action archive`,"data-testid":`code-agent-row-archive`,"aria-label":C.archiveAgent,title:C.archiveAgent,onClick:t=>{t.preventDefault(),t.stopPropagation(),e&&s?.(e,{archived:!0})},children:(0,K.jsx)(cE,{})})]}),(e||t)&&(0,K.jsx)(`button`,{type:`button`,className:`code-agent-row-more`,"data-testid":`code-agent-row-more`,"aria-label":C.openOptions,title:C.openOptions,onClick:e=>{if(e.preventDefault(),e.stopPropagation(),D){S?.(),k&&t&&y?.(e,k,Rb(t));return}O&&h?.(e,O)},children:(0,K.jsx)($T,{})}),n&&(0,K.jsx)(`kbd`,{children:n})]})]})}var dE=[`codex`,`claude`,`opencode`,`qoder`],fE=new Set([`bash`,`zsh`]),pE=/^[A-Za-z0-9._-]+$/,mE=[3,5,10,15,30,60,180];function hE(e){let t=e/1e3;return mE.reduce((e,n)=>Math.abs(n-t)<Math.abs(e-t)?n:e)}function gE(e){let t=e===`zh`;return{title:t?`设置`:`Settings`,subtitle:t?`管理 Farming 的本地元数据。`:`Manage local Farming metadata.`,close:t?`关闭`:`Close`,back:t?`返回导航`:`Back to navigation`,general:t?`通用`:`General`,appearance:t?`外观`:`Appearance`,light:t?`浅色`:`Light`,dark:t?`深色`:`Dark`,interface:t?`界面`:`Interface`,interfaceSkin:t?`界面皮肤`:`Interface skin`,farmingCode:`Farming Code`,farmingCrt:`Farming CRT`,language:t?`语言`:`Language`,english:`English`,chinese:`中文`,search:t?`搜索`:`Search`,agentPermissions:t?`Agent 权限`:`Agent Permissions`,dangerousSkipLabel:t?`默认跳过所有 agent 权限检查`:`Skip all agent permission checks by default`,dangerousSkipHint:t?`开启后,新启动的 Codex、Claude、OpenCode、Qoder、Qwen、Aider、GitHub Copilot CLI、Amazon Q 等会使用各自的危险跳过权限 flag。只在可信沙箱中使用。`:`When enabled, new Codex, Claude, OpenCode, Qoder, Qwen, Aider, GitHub Copilot CLI, Amazon Q, and similar agents launch with their provider-specific dangerous skip flags. Use only in trusted sandboxes.`,searchTimeout:t?`搜索超时`:`Search timeout`,searchTimeoutValue:e=>t?e>=60?`${e/60} 分钟`:`${e} 秒`:e>=60?`${e/60} min`:`${e} sec`,updates:t?`更新`:`Updates`,updateHint:t?`更新方式会自动匹配当前安装来源;npm 安装可直接一键升级。`:`Updates follow the current installation source; npm installations support one-click upgrades.`,updateUrl:t?`更新 URL`:`Update URL`,updateUrlPlaceholder:`https://github.com/zhuwenzhuang/farming/releases/latest`,updateUrlEmpty:t?`等待检查更新`:`Waiting for update check`,saveUpdateUrl:t?`保存更新 URL`:`Save Update URL`,refreshUpdates:t?`刷新`:`Refresh`,upgradeNow:t?`立即更新`:`Update Now`,currentVersion:t?`当前版本`:`Current`,latestVersion:t?`最新版本`:`Latest`,targetVersion:t?`升级版本`:`Target`,updateSource:t?`更新源`:`Update source`,updateMethod:t?`安装方式`:`Install method`,updateMethodLabel:e=>({npm:`npm`,"app-bundle":t?`兼容包`:`App bundle`,"source-deploy":t?`源码部署`:`Source deployment`,source:t?`源码检出`:`Source checkout`,"standalone-cli":t?`单文件 CLI`:`Standalone CLI`})[e]||e||`-`,updateRuntime:t?`当前机器`:`This machine`,upToDate:t?`已是最新版本`:`Up to date`,updateAvailable:t?`有新版本可用`:`Update available`,updateNotInstallable:t?`当前更新不可安装`:`Update is not installable`,updateInstalling:t?`升级已开始,服务会自动重启。`:`Upgrade started. The server will restart automatically.`,updateRestarting:t?`新版本已安装,正在重启 Farming。`:`The new version is installed. Restarting Farming.`,updateSucceeded:t?`更新成功。`:`Update completed.`,updateRolledBack:t?`新版本启动失败,已回退到旧版本。`:`The new version failed to start and Farming rolled back.`,agentHomes:`Agent Homes`,agentHomesHint:t?`为不同 Agent 配置独立的主目录。`:`Configure a separate home directory for each agent.`,addHome:e=>t?`添加 ${e} home`:`Add ${e} home`,edit:t?`编辑`:`Edit`,remove:t?`删除`:`Remove`,save:t?`保存`:`Save`,cancel:t?`取消`:`Cancel`,homeName:t?`Home 名称(可选)`:`Home name (optional)`,homePath:t?`Home 路径`:`Home path`,homeNameHint:t?`留空时将根据路径自动生成。允许字母、数字、点、下划线和短横线。`:`Leave empty to generate it from the path. Use letters, numbers, dots, underscores, and hyphens.`,homeNamePlaceholder:t?`例如:work`:`e.g. work`,pathPlaceholder:`~/.codex.local`,loading:t?`加载中…`:`Loading…`,saving:t?`保存中…`:`Saving…`,saved:t?`已保存`:`Saved`,loadFailed:t?`加载设置失败`:`Failed to load settings`,saveFailed:t?`保存失败`:`Failed to save`,invalidId:t?`Home 名称只能包含字母、数字、点、下划线和短横线。`:`Home name can only contain letters, numbers, dots, underscores, and hyphens.`,duplicateId:t?`同一个 provider 下 Home 名称不能重复。`:`Home name must be unique under the same provider.`,missingPath:t?`Home 路径不能为空。`:`Home path is required.`,removeLastHint:t?`至少保留一个 home。`:`Keep at least one home.`,removeDefaultHint:t?`default home 不能删除。`:`The default home cannot be removed.`,editDisabledHint:t?`home 不支持编辑;请删除后重新添加。`:`Homes cannot be edited. Remove and add again.`,confirmRemove:e=>t?`删除 home ${e}?`:`Remove home ${e}?`,empty:t?`还没有配置 home。`:`No homes configured.`,noAgents:t?`当前机器没有识别到可配置的 coding agent。`:`No configurable coding agents were detected on this machine.`,unavailable:t?`未安装`:`Not installed`}}function _E(e){return e.trim().toLowerCase()}function vE(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n={};return Object.entries(t).forEach(([e,t])=>{let r=_E(e);if(!r||!/^[a-z0-9._-]+$/.test(r)||!Array.isArray(t))return;let i=new Set,a=[];t.forEach(e=>{if(!e||typeof e!=`object`)return;let t=e,n=String(t.id??``).trim(),r=String(t.path??``).trim();if(!n||!r||!pE.test(n))return;let o=n.toLowerCase();i.has(o)||(i.add(o),a.push({id:n,path:r}))}),a.length>0&&(n[r]=a)}),n}function yE(e){return e===`codex`?`Codex`:e===`claude`?`Claude`:e===`opencode`?`OpenCode`:e===`qoder`?`Qoder`:e}function bE(e){return{codex:`~/.codex`,claude:`~/.claude`,opencode:`~/.opencode`,qoder:`~/.qoder`}[e]??`~/.${e}`}function xE(e){return!!e?.some(e=>e.id.toLowerCase()!==`default`)}function SE(e){return e.filter(e=>e.supported!==!1&&e.interactive!==!1).filter(e=>!fE.has(e.name)).filter(e=>dE.includes(e.name)).map(e=>_E(e.name)).filter(Boolean)}function CE(e,t){let n=new Set(SE(t)),r=Object.keys(e).filter(t=>xE(e[t])),i=new Set([...n,...r]);return Array.from(i).sort((e,t)=>{let n=dE.indexOf(e),r=dE.indexOf(t),i=n===-1?dE.length:n,a=r===-1?dE.length:r;return i===a?e.localeCompare(t):i-a})}function wE(e,t){let n=e[t]??[];return n.some(e=>e.id.toLowerCase()===`default`)?n:[{id:`default`,path:bE(t)},...n]}function TE(e,t){let n=e.trim().replace(/\/+$/,``).split(`/`).filter(Boolean),r=(n[n.length-1]??``).replace(/^\.+/,``).replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/^[.-]+|[.-]+$/g,``).slice(0,64)||`home`,i=new Set(t.map(e=>e.id.toLowerCase())),a=1,o=r;for(;i.has(o.toLowerCase());)a+=1,o=`${r}-${a}`;return{id:o}}function EE(e){return{provider:e,id:``,path:``}}function DE({open:e,activeAgentId:t=null,language:r,uiPreferences:i,agentLaunchOptions:a,onClose:o,onUpdateUiPreferences:s}){let c=(0,W.useMemo)(()=>gE(r),[r]),l=(0,W.useRef)(null),u=(0,W.useRef)(null),[d,f]=(0,W.useState)(!1),[p,m]=(0,W.useState)(``),[h,g]=(0,W.useState)(15),[_,v]=(0,W.useState)(null),[y,b]=(0,W.useState)(``),[x,S]=(0,W.useState)(!1),[C,w]=(0,W.useState)(!1),[T,E]=(0,W.useState)(()=>vE({codex:[{id:`default`,path:`~/.codex`}],claude:[{id:`default`,path:`~/.claude`}],opencode:[{id:`default`,path:`~/.opencode`}],qoder:[{id:`default`,path:`~/.qoder`}]})),[D,O]=(0,W.useState)(!1),[k,A]=(0,W.useState)(!1),[ee,j]=(0,W.useState)(``),[M,N]=(0,W.useState)(``),[te,P]=(0,W.useState)(null),F=(0,W.useCallback)(()=>{O(!0),N(``),fetch(n(`/api/settings`)).then(e=>e.json()).then(e=>{E(vE(e.settings?.agentHomes)),f(e.settings?.dangerouslySkipAgentPermissionsByDefault===!0),m(String(e.settings?.updateUrl??``)),g(hE(Number(e.settings?.searchTimeoutMs??15e3)))}).catch(()=>N(c.loadFailed)).finally(()=>O(!1))},[c.loadFailed]);(0,W.useEffect)(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),(0,W.useEffect)(()=>{e&&(F(),window.requestAnimationFrame(()=>l.current?.focus({preventScroll:!0})))},[F,e]),(0,W.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),o())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[o,e]);let ne=(0,W.useCallback)(e=>{A(!0),N(``),j(``),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentHomes:e})}).then(async t=>{let n=await t.json().catch(()=>null);if(!t.ok)throw Error(n?.error||c.saveFailed);E(vE(n?.settings?.agentHomes??e)),P(null),j(c.saved),window.dispatchEvent(new CustomEvent(`farming-agent-homes-saved`))}).catch(e=>N(e instanceof Error?e.message:c.saveFailed)).finally(()=>A(!1))},[c.saveFailed,c.saved]),I=(0,W.useCallback)((e=!0,t=!1)=>{t||(S(!0),N(``)),fetch(n(`/api/update${e?`?force=1`:``}`)).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.loadFailed);let n=t?.update??null;v(n);let r=n?.versions??[];b(e=>e&&r.some(t=>t.assetName===e)?e:r[0]?.assetName||``)}).catch(e=>{t||N(e instanceof Error?e.message:c.loadFailed)}).finally(()=>{t||S(!1)})},[c.loadFailed]),L=(0,W.useCallback)(()=>{w(!0),N(``),j(``),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({updateUrl:p})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.saveFailed);m(String(t?.settings?.updateUrl??``)),j(c.saved),I(!0)}).catch(e=>N(e instanceof Error?e.message:c.saveFailed)).finally(()=>w(!1))},[c.saveFailed,c.saved,I,p]),re=(0,W.useCallback)(e=>{g(e),N(``),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({searchTimeoutMs:e*1e3})}).then(async t=>{let n=await t.json().catch(()=>null);if(!t.ok)throw Error(n?.error||c.saveFailed);g(hE(Number(n?.settings?.searchTimeoutMs??e*1e3)))}).catch(e=>N(e instanceof Error?e.message:c.saveFailed))},120)},[c.saveFailed]),R=(0,W.useCallback)(()=>{if(!_?.versions?.find(e=>e.assetName===y)?.available){I(!0);return}S(!0),N(``),fetch(n(`/api/update/install`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({assetName:y})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok){let e=t?.blockingAgents||[],n=e.length?`: ${e.map(e=>e.command).join(`, `)}`:``;throw Error(`${t?.error||c.saveFailed}${n}`)}v(e=>({...e??{},state:t?.update?.state??e?.state,blockingAgents:t?.update?.blockingAgents??e?.blockingAgents})),j(c.updateInstalling)}).catch(e=>N(e instanceof Error?e.message:c.saveFailed)).finally(()=>S(!1))},[c,I,y,_]);(0,W.useEffect)(()=>{e&&I(!1)},[e,I]);let z=(0,W.useCallback)(e=>{f(e),A(!0),N(``),j(``),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({dangerouslySkipAgentPermissionsByDefault:e})}).then(async e=>{let t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||c.saveFailed);f(t?.settings?.dangerouslySkipAgentPermissionsByDefault===!0),j(c.saved)}).catch(t=>{f(!e),N(t instanceof Error?t.message:c.saveFailed)}).finally(()=>A(!1))},[c.saveFailed,c.saved]),B=(0,W.useCallback)(()=>{if(!te)return;let e=_E(te.provider),t=te.path.trim();if(!t){N(c.missingPath);return}let n=T[e]??[],r=te.id.trim()||TE(t,n).id;if(!pE.test(r)){N(c.invalidId);return}if(n.some(e=>e.id.toLowerCase()===r.toLowerCase())){N(c.duplicateId);return}ne({...T,[e]:[...n,{id:r,path:t}]})},[c.duplicateId,c.invalidId,c.missingPath,te,T,ne]),ie=(0,W.useCallback)((e,t)=>{if(t.toLowerCase()===`default`)return;let n=T[e]??[];window.confirm(c.confirmRemove(t))&&ne({...T,[e]:n.filter(e=>e.id!==t)})},[c,T,ne]),V=_?.state?.phase||``;if((0,W.useEffect)(()=>{if(!e||![`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V))return;let t=window.setInterval(()=>I(!1,!0),1500);return()=>window.clearInterval(t)},[e,I,V]),!e)return null;let ae=CE(T,a),oe=_?.versions??[],se=oe.find(e=>e.assetName===y),de=x||C||[`downloading`,`extracting`,`installing`,`restarting`,`rolling-back`].includes(V),fe=_?.method||_?.current?.type||``,pe=c.updateMethodLabel(fe),H=fe===`app-bundle`||fe===`source-deploy`,he=_?.current?.releaseVersion||_?.current?.packageVersion||`-`,ge=_?.latest?.version||`-`,_e=V===`rolled-back`?c.updateRolledBack:V===`failed`&&_?.state?.error?_.state.error:V===`restarting`?c.updateRestarting:[`downloading`,`extracting`,`installing`,`rolling-back`].includes(V)?c.updateInstalling:_?.available?c.updateAvailable:V===`succeeded`?c.updateSucceeded:_?.latest?.blockedReason||c.upToDate;return(0,K.jsx)(`div`,{className:`code-settings-panel-overlay`,"data-testid":`code-settings-panel`,onPointerDown:e=>{e.target===e.currentTarget&&o()},children:(0,K.jsxs)(`aside`,{className:`code-settings-panel`,"aria-modal":`true`,role:`dialog`,"aria-labelledby":`code-settings-panel-title`,children:[(0,K.jsxs)(`header`,{className:`code-settings-panel-header`,children:[(0,K.jsx)(`button`,{type:`button`,className:`code-settings-panel-back`,onClick:o,"aria-label":c.back,children:(0,K.jsx)(ce,{})}),(0,K.jsx)(`div`,{children:(0,K.jsx)(`h2`,{id:`code-settings-panel-title`,children:c.title})}),(0,K.jsx)(`button`,{ref:l,type:`button`,className:`code-settings-panel-close`,onClick:o,"aria-label":c.close,children:(0,K.jsx)(le,{})})]}),(0,K.jsxs)(`div`,{className:`code-settings-panel-body`,children:[(0,K.jsx)(`section`,{className:`code-settings-section compact`,children:(0,K.jsxs)(`div`,{className:`code-settings-inline-preferences`,children:[(0,K.jsxs)(`div`,{className:`code-settings-inline-choice`,children:[(0,K.jsx)(ue,{"aria-hidden":`true`}),(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":c.appearance,children:[(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`light`?`active`:``,onClick:()=>s({appearance:`light`}),children:c.light}),(0,K.jsx)(`button`,{type:`button`,className:i.appearance===`dark`?`active`:``,onClick:()=>s({appearance:`dark`}),children:c.dark})]})]}),(0,K.jsx)(`div`,{className:`code-settings-inline-choice code-settings-language-choice`,children:(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":c.language,children:[(0,K.jsx)(`button`,{type:`button`,className:i.language===`en`?`active`:``,onClick:()=>s({language:`en`}),children:c.english}),(0,K.jsx)(`button`,{type:`button`,className:i.language===`zh`?`active`:``,onClick:()=>s({language:`zh`}),children:c.chinese})]})})]})}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.interface})})}),(0,K.jsx)(`div`,{className:`code-settings-card`,children:(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-runtime-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:c.interfaceSkin})}),(0,K.jsxs)(`div`,{className:`code-settings-segmented`,role:`group`,"aria-label":c.interfaceSkin,children:[(0,K.jsx)(`button`,{type:`button`,className:`active`,"data-testid":`code-settings-skin-code`,"aria-pressed":`true`,children:c.farmingCode}),(0,K.jsx)(`button`,{type:`button`,"data-testid":`code-settings-skin-crt`,"aria-pressed":`false`,onClick:()=>window.location.assign(`${n(`/crt/`)}${t?`?agent=${encodeURIComponent(t)}`:``}`),children:c.farmingCrt})]})]})})]}),(0,K.jsxs)(`section`,{className:`code-settings-section code-settings-group`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.search})})}),(0,K.jsx)(`div`,{className:`code-settings-card`,children:(0,K.jsxs)(`div`,{className:`code-settings-choice-row code-settings-search-timeout-row`,children:[(0,K.jsx)(`div`,{className:`code-settings-row-copy`,children:(0,K.jsx)(`strong`,{children:c.searchTimeout})}),(0,K.jsx)(`input`,{type:`range`,min:`0`,max:String(mE.length-1),step:`1`,value:mE.indexOf(h),"aria-label":c.searchTimeout,onChange:e=>re(mE[Number(e.target.value)]??15)}),(0,K.jsx)(`output`,{children:c.searchTimeoutValue(h)})]})})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsxs)(`div`,{className:`code-settings-section-heading`,children:[(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.updates})}),(x||C)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:x?c.loading:c.saving})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-card`,children:[(0,K.jsxs)(`dl`,{className:`code-settings-update-status`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:c.updateMethod}),(0,K.jsx)(`dd`,{children:pe})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:c.currentVersion}),(0,K.jsx)(`dd`,{children:he})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:c.latestVersion}),(0,K.jsx)(`dd`,{children:ge})]})]}),H&&(0,K.jsxs)(`label`,{className:`code-settings-update-url`,children:[(0,K.jsx)(`span`,{children:c.updateSource}),(0,K.jsx)(`input`,{type:`url`,name:`farming-update-url`,inputMode:`url`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:p,placeholder:c.updateUrlPlaceholder,"aria-label":c.updateUrl,onChange:e=>m(e.target.value),disabled:de})]}),(0,K.jsxs)(`div`,{className:`code-settings-update-actions`,children:[H&&(0,K.jsx)(`button`,{type:`button`,onClick:L,disabled:de,"aria-label":c.saveUpdateUrl,title:c.saveUpdateUrl,children:(0,K.jsx)(me,{})}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>I(!0),disabled:de,"aria-label":c.refreshUpdates,title:c.refreshUpdates,children:`↻`}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,onClick:R,disabled:de||!se?.available,"aria-label":c.upgradeNow,title:c.upgradeNow,children:`↑`})]}),oe.length>0&&(0,K.jsx)(`label`,{className:`code-settings-update-version`,children:(0,K.jsx)(`select`,{value:y,"aria-label":c.targetVersion,onChange:e=>b(e.target.value),disabled:de||oe.length===0,children:oe.map(e=>(0,K.jsxs)(`option`,{value:e.assetName||``,children:[e.version||e.assetName||`-`,e.assetName&&e.assetName!==e.version?` · ${e.assetName}`:``]},e.assetName||e.version))})}),(0,K.jsx)(`div`,{className:`code-settings-update-summary ${_?.available?`available`:``}`,children:_e})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsx)(`div`,{className:`code-settings-section-heading`,children:(0,K.jsx)(`div`,{children:(0,K.jsx)(`h3`,{children:c.agentPermissions})})}),(0,K.jsxs)(`div`,{className:`code-settings-choice-row dangerous`,children:[(0,K.jsx)(`span`,{children:c.dangerousSkipLabel}),(0,K.jsx)(`button`,{type:`button`,className:`code-settings-permission-toggle ${d?`active`:``}`,role:`checkbox`,"aria-label":c.dangerousSkipLabel,"aria-pressed":d,disabled:k,onClick:()=>z(!d),children:(0,K.jsx)(me,{})})]})]}),(0,K.jsxs)(`section`,{className:`code-settings-section`,children:[(0,K.jsxs)(`div`,{className:`code-settings-section-heading`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:c.agentHomes}),(0,K.jsx)(`p`,{children:c.agentHomesHint})]}),(D||k||ee)&&(0,K.jsx)(`span`,{className:`code-settings-status`,children:D?c.loading:k?c.saving:ee})]}),M&&(0,K.jsx)(`div`,{className:`code-settings-error`,role:`alert`,children:M}),ae.length===0&&(0,K.jsx)(`div`,{className:`code-agent-home-empty`,children:c.noAgents}),(0,K.jsx)(`div`,{className:`code-agent-homes-list`,children:ae.map(e=>{let t=wE(T,e),n=SE(a).includes(e),r=t.find(e=>e.id.toLowerCase()===`default`),i=t.filter(e=>e.id.toLowerCase()!==`default`);return(0,K.jsxs)(`div`,{className:`code-agent-home-provider`,children:[(0,K.jsxs)(`div`,{className:`code-agent-home-provider-header`,children:[(0,K.jsxs)(`div`,{className:`code-agent-home-provider-title`,children:[(0,K.jsxs)(`strong`,{children:[yE(e),n?``:` · ${c.unavailable}`]}),r&&(0,K.jsxs)(`span`,{title:r.path,children:[r.path,` default`]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-agent-home-add`,onClick:()=>{N(``),j(``),P(EE(e))},"aria-label":c.addHome(yE(e)),title:c.addHome(yE(e)),children:(0,K.jsx)(Se,{})})]}),i.map(t=>(0,K.jsxs)(`div`,{className:`code-agent-home-row`,children:[(0,K.jsx)(`div`,{className:`code-agent-home-path`,title:t.path,children:t.path}),(0,K.jsx)(`div`,{className:`code-agent-home-id`,children:t.id}),(0,K.jsx)(`div`,{className:`code-agent-home-actions`,children:(0,K.jsx)(`button`,{type:`button`,onClick:()=>ie(e,t.id),"aria-label":c.remove,title:c.remove,children:(0,K.jsx)(le,{})})})]},t.id)),te&&te.provider===e&&(0,K.jsxs)(`div`,{className:`code-agent-home-form`,children:[(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:c.homePath}),(0,K.jsx)(`input`,{type:`text`,name:`farming-agent-home-${e}-path`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`next`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:te.path,placeholder:c.pathPlaceholder,"aria-label":c.homePath,onChange:e=>P(t=>t&&{...t,path:e.target.value})})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:c.homeName}),(0,K.jsx)(`input`,{type:`text`,name:`farming-agent-home-${e}-name`,inputMode:`text`,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`none`,spellCheck:!1,enterKeyHint:`done`,"data-lpignore":`true`,"data-1p-ignore":`true`,"data-bwignore":`true`,"data-form-type":`other`,value:te.id,placeholder:c.homeNamePlaceholder,"aria-label":c.homeName,onChange:e=>P(t=>t&&{...t,id:e.target.value})}),(0,K.jsx)(`span`,{children:c.homeNameHint})]}),(0,K.jsxs)(`div`,{className:`code-agent-home-form-actions`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>P(null),"aria-label":c.cancel,title:c.cancel,children:(0,K.jsx)(le,{})}),(0,K.jsx)(`button`,{type:`button`,className:`primary`,disabled:k,onClick:B,"aria-label":c.save,title:c.save,children:(0,K.jsx)(me,{})})]})]})]},e)})})]})]})]})})}var OE=`\r`;function kE(e){return[{type:`paste`,text:e},OE]}function AE(e){let t=e+1;return t>=1&&t<=9?String(t):`\x1b[H${`\x1B[B`.repeat(Math.max(0,e))}\r`}function jE(e,t){let n=[],r=0;return e.applyModel&&e.modelIndex>=0&&e.reasoningIndex>=0&&(n.push({delayMs:r,input:kE(`/model`),kind:`command`}),r+=220,n.push({delayMs:r,input:AE(e.modelIndex),kind:`selection`}),e.reasoningCount>1&&(r+=220,n.push({delayMs:r,input:AE(e.reasoningIndex),kind:`selection`}))),e.applyFast&&e.fastAvailable&&(r+=n.length>0?220:0,n.push({delayMs:r,input:kE(`/fast`),kind:`command`})),r+=n.length>0?420:0,n.push({delayMs:r,input:kE(t),kind:`message`}),n}var ME={newAgent:`New Agent`,search:`Search`,history:`History`,codex:`Farming Code`,expandSidebar:`Expand sidebar`,collapseSidebar:`Collapse sidebar`,enterFocusMode:`Enter focus mode`,exitFocusMode:`Exit focus mode`,terminalView:`Terminal`,transcriptView:`Chat`,collapseComposer:`Hide input`,restoreComposer:`Show input`,codexTranscriptSyncing:`Syncing chat history...`,codexTranscriptUnavailable:`This session’s Chat history could not be loaded.`,codexTranscriptEmpty:``,codexTranscriptWaiting:`Agent is still working...`,codexTranscriptProcess:`Worked`,codexTranscriptWorking:`Processing`,codexTranscriptThinking:`Thinking`,codexTranscriptRunning:`Running`,codexTranscriptReading:`Reading`,codexTranscriptSearching:`Searching`,codexTranscriptEditing:`Editing`,codexTranscriptPlanActive:`On plan`,codexTranscriptPlanProgress:(e,t)=>`Plan ${e}/${t}`,codexTranscriptFetching:`Fetching`,codexTranscriptUsingTool:`Using tool`,codexTranscriptWorkedFor:e=>`Worked for ${e}`,codexTranscriptProcessCount:e=>`${e} ${e===1?`event`:`events`}`,codexTranscriptCopyDetails:`Copy details`,codexTranscriptCopiedDetails:`Copied`,codexTranscriptCopyAnswer:`Copy answer`,codexTranscriptCopiedAnswer:`Copied answer`,codexTranscriptReviewChanges:`Review`,codexTranscriptShowChanges:`Show file changes`,codexTranscriptLoadingChanges:`Loading exact changes…`,codexTranscriptKeepChange:`Keep`,codexTranscriptRevertChange:`Revert`,codexTranscriptChangeKept:`Kept`,codexTranscriptChangeReverted:`Reverted`,codexTranscriptShowMoreFiles:e=>`Show ${e} more file${e===1?``:`s`}`,codexGoalTitle:`Goal`,codexGoalEmpty:`No active goal`,codexGoalOpen:`Open goal controls`,codexGoalObjective:`Objective`,codexGoalStatus:`Status`,codexGoalTokenBudget:`Token budget`,codexGoalNoBudget:`No budget`,codexGoalUsage:(e,t)=>`${e.toLocaleString()} tokens · ${Math.round(t/60)}m`,codexGoalStatusLabel:e=>({active:`Active`,paused:`Paused`,blocked:`Blocked`,usageLimited:`Usage limited`,budgetLimited:`Budget limited`,complete:`Complete`})[e]??e,codexGoalEdit:`Edit`,codexGoalStart:`Start`,codexGoalStop:`Stop`,codexGoalDelete:`Delete`,codexGoalSave:`Save goal`,codexGoalClear:`Clear`,codexGoalSaving:`Saving...`,codexGoalUnsupported:`Native goal controls require a Codex App Server session.`,searchProjectsOrAgents:`Search projects or agents`,clearSearch:`Clear search`,projectsAndAgents:`Projects and agents`,noAgentsYet:`No agents yet.`,noMatchingProjectsOrAgents:`No matching projects or agents.`,openNavigation:`Open navigation`,closeNavigation:`Close navigation`,openOptions:`Open options`,openSettings:`Settings`,agentActions:`Agent actions`,appearanceLight:`Appearance: Light`,appearanceDark:`Appearance: Dark`,languageEnglish:`Language: English`,languageChinese:`Language: 中文`,pinAgent:`Pin Agent`,unpinAgent:`Unpin Agent`,renameAgent:`Rename Agent`,renameProject:`Rename project`,archiveAgent:`Archive`,reorderAgentFailed:`Failed to reorder Agent`,markAsRead:`Mark as read`,markAsUnread:`Mark as unread`,copyWorkingDirectory:`Copy working directory`,copiedWorkingDirectory:`Copied working directory`,copyFailed:`Copy failed`,sharePage:`Share page`,scanToOpenOnPhone:`Scan to open on phone`,copyFullShareLink:`Copy full link`,copiedShareLink:`Copied full link`,shareLinkFailed:`Share link unavailable`,sharedLocationUnavailable:e=>`Unable to locate shared path: ${e}`,shareLinkExpired:`Expired`,refreshShareLink:`Refresh`,brandStoryOrigin:`Farming Code began with a simple idea: when several coding agents work at once, people should not have to bounce between terminals, editors, and browser tabs.`,brandStoryPurpose:`It brings conversations, terminals, project files, and progress into one calm workspace, so attention stays on what matters.`,brandGithub:`GitHub`,mobileShareTitle:`Share page`,mobileForwardTitle:`Send this page`,mobileForwardHint:`Copy the link to send the current view to someone else.`,mobileShareCopyAction:`Copy link`,mobileShareCopied:`Copied`,mobileInstallTitle:`Add to Home Screen`,mobileInstallChromeHint:`Make sure this page is open in your system browser or Chrome.`,mobileInstallShareStep:`Tap Share in the browser toolbar.`,mobileInstallMoreStep:`If it is hidden, tap •••, then Share.`,mobileInstallAddStep:`Choose “Add to Home Screen”.`,mobileInstallOpenStep:`Open Farming from its Home Screen icon next time.`,mobileShareInstalled:`Farming is already open as a Home Screen app.`,forkSameWorktree:`Fork into same worktree`,forkNewWorktree:`Fork into new worktree`,newWorktreeFork:`Forked to new worktree`,scheduledTask:`Scheduled task`,killAgent:`Kill Agent`,killAgentQuestion:`Kill Agent?`,openSession:`Open Session`,pinChat:`Pin chat`,unpinChat:`Unpin chat`,archiveChat:`Archive`,archiveChats:`Archive chats`,archiveProject:`Archive Project`,deleteWorktree:`Delete Worktree`,deleteWorktreeQuestion:`Delete Worktree?`,deleteWorktreeDirtyDescription:e=>`${e} uncommitted or untracked file${e===1?``:`s`} will be deleted with this worktree.`,forceDelete:`Force Delete`,cancel:`Cancel`,retry:`Retry`,save:`Save`,stopAgentDescription:e=>`Stop ${e} and close its terminal.`,permissionModeLabel:(e,t)=>t,permissionModeDescription:(e,t)=>t,acpModeLabel:(e,t)=>({"read-only":`Read-only`,agent:`Workspace`,"agent-full-access":`Full access`,auto:`Auto`,default:`Manual`,acceptEdits:`Accept edits`,plan:`Plan`,dontAsk:`Don't ask`,bypassPermissions:`Bypass permissions`,build:`Build`})[e]??t,acpModeDescription:(e,t)=>({"read-only":`Read and analyze by default. File writes and commands that need more access require approval. Network access is off.`,agent:`Read and write inside this workspace and run sandboxed commands. Network and out-of-workspace access require approval.`,"agent-full-access":`Access files outside this workspace and use the network without approval prompts. Use only in a trusted environment.`,auto:`Use the model classifier to approve or deny permission requests.`,default:`Prompt before operations that require approval.`,acceptEdits:`Approve file edits automatically; ask about other operations that need permission.`,plan:`Plan and inspect without modifying files.`,dontAsk:`Do not show permission prompts; deny operations that were not already allowed.`,bypassPermissions:`Bypass permission checks. Use only in a trusted environment.`,build:`Run tools according to the permissions configured for this Agent.`})[e]??t,reasoningOptionLabel:(e,t)=>t,serviceTierLabel:(e,t)=>t,serviceTierDescription:(e,t)=>t,messageMode:`Message`,goalMode:`Goal`,planMode:`Plan`,askFollowUpChanges:`Ask for follow-up changes`,shellCommandPlaceholder:`Type a shell command`,describeAgentGoal:`Describe the goal for this agent`,describePlanFirst:`Describe what should be planned first`,openAgentTerminalFirst:`Open an agent terminal first`,queuedMessages:e=>`${e} queued messages`,steerQueuedMessage:`Steer`,discardQueuedMessage:`Discard queued message`,addContext:`Add context`,attachFile:`Attach file`,fileContext:`File context`,setObjective:`Set objective`,planFirst:`Plan first`,clearComposerMode:`Clear composer mode`,agentPermissionMode:`Agent permission mode`,permissionsPrompt:`Launch permission profile`,permissionProfileSavedForNextLaunch:`Saved for new agents. Running sessions keep the permissions they launched with.`,permissionProfileRestarting:`Switching agent permissions…`,permissionProfileApplying:`Applying App Server permissions…`,runtimeModeRestarting:`Restarting Agent…`,agentRestartTimedOut:`Agent restart timed out. The previous Agent remains available; try switching again.`,permissionRestartHint:`The running agent restarts to apply these permissions. If it has no resumable session id yet, a fresh session starts.`,permissionAppServerHint:`Applies to this App Server thread without restarting the Agent. New permissions take effect for subsequent turns.`,modelAndReasoning:`Model and reasoning`,reasoning:`Reasoning`,speed:`Speed`,startDictation:`Start dictation`,stopDictation:`Stop dictation`,speechUnsupported:`Speech recognition is not supported in this browser`,mobileDictationHint:`Use the microphone key on the iOS keyboard to dictate.`,sendMessage:`Send message`,interruptAgent:`Interrupt agent`,startOrSelectAgent:`Start or select an agent`,startOrSelectAgentDescription:`Projects live on the left. Open any agent terminal without closing the rest of the workspace.`,historySummary:(e,t,n,r)=>`${n+r} history agents`,searchHistory:`Search history`,noHistoryYet:`No history yet`,noHistoryDescription:`Agents moved off the main page will appear here.`,historyAgents:`History Agents`,agentSessions:`Agent Sessions`,recentWorkspaces:`Recent Workspaces`,agentsSessionsSummary:(e,t)=>`${e} agents · ${t} sessions`,restore:`Restore`,continueRun:`Continue`,open:`Open`,archived:`Archived`,pinned:`Pinned`,unread:`Unread`,showMore:`Show more`,showLess:`Show less`,latest:`Latest`,upgrade:`UPGRADE`,updating:`UPDATING`,retryUpdate:`RETRY`,checkForUpdates:`Check for updates`,updateFailed:`Update failed`,upgradeToVersion:e=>e?`Upgrade to ${e}`:`Upgrade Farming Code`,sessionFallbackTitle:e=>`${e||`Agent`} session`,resumeSessionAria:e=>`Resume ${e}`,resultsCount:e=>`${e} results`,noMatchingAgents:`No matching agents`,searchHint:`Search by Agent title, session title, or project.`,searchEmptyTitle:`Start a search`,searchEmptyDescription:`Type an Agent title, session title, or project name or path.`,agents:`Agents`,files:`Files`,changes:`Changes`,changedFiles:`Changed files`,trackedChanges:`Tracked`,untrackedChanges:`Untracked`,reviewChanges:`Review`,refreshChanges:`Refresh changes`,searchOrPathLine:`Search or path:line`,searchFilesOrJump:`Search files or jump to path line`,openEditors:`OPEN EDITORS`,loading:`Loading...`,searching:`Searching...`,noMatches:`No matches`,searchIgnoredFolders:`Also search ignored folders`,searchIncomplete:e=>`Search stopped early. Current timeout: ${Math.round(e/1e3)}s.`,terminalSearchPlaceholder:`Find in terminal`,terminalSearchPrevious:`Previous match`,terminalSearchNext:`Next match`,terminalSearchClose:`Close terminal search`,terminalSearchCaseSensitive:`Match case`,terminalSearchWholeWord:`Match whole word`,terminalSearchRegex:`Use regular expression`,terminalSearchNoResults:`No results`,terminalSearchResults:(e,t)=>`${e}/${t}`,terminalSessionUnavailable:`Terminal session unavailable`,appServerWaitingForFirstMessage:`App Server is ready. Send the first Composer message to start the shared Codex CLI terminal.`,appServerRequestTitle:`Codex needs your input`,appServerRequestCommand:`Requested command`,appServerRequestQuestion:`Question`,appServerRequestApprove:`Allow`,appServerRequestDecline:`Decline`,appServerRequestSubmit:`Submit answer`,appServerRequestUnsupported:`This Codex request is not supported in Farming. Declining it will let the turn continue safely.`,appServerApprovalRejectedTitle:`Permission request declined`,appServerApprovalRejectedDescription:`Chat does not approve this permission request. Increase this Agent permission mode, or handle it in Terminal view.`,acpPermissionTitle:`Agent needs permission`,acpPermissionTool:`Requested tool`,file:`File`,folder:`Folder`,go:`Go`,moreMatchesOmitted:`More matches omitted`,stickyFolderPath:`Sticky folder path`,containsUncommittedChanges:`Contains uncommitted changes`,changedOnDisk:`Changed on disk`,unsavedChanges:`Unsaved changes`,gitStatus:e=>`Git status: ${e}`,renameEntry:e=>`Rename ${e}`,newFile:`New File`,newFolder:`New Folder`,refresh:`Refresh`,rename:`Rename`,copyRelativePath:`Copy Relative Path`,copyShareUrl:`Copy Share URL`,delete:`Delete`,deleteFolderContents:e=>`Delete folder and all contents: ${e||``}`,deleteFile:e=>`Delete file: ${e||``}`,saveFile:`Save file`,savingFile:`Saving file`,reloadFile:`Reload file`,overwriteChangedFile:`Overwrite changed file`,openFileDiff:`Open File Diff`,openFileDiffFor:e=>`Open diff for ${e}`,closeDiff:`Close diff`,openFilePreview:`Open preview`,showFileSource:`Show source`,enableWordWrap:`Enable word wrap`,disableWordWrap:`Disable word wrap`,openMarkdownPreview:`Open Markdown preview`,showMarkdownSource:`Show Markdown source`,openMarkdownSplitPreview:`Open Markdown preview to side`,closeMarkdownSplitPreview:`Close Markdown side preview`,markdownPreviewFor:e=>`Markdown preview for ${e}`,markdownFrontMatter:`Front matter`,markdownHeadingAnchor:`Link to heading`,mermaidDiagram:`Mermaid diagram`,mermaidDiagramControls:`Mermaid diagram controls`,mermaidRendering:`Rendering diagram...`,mermaidRenderFailed:`Unable to render Mermaid diagram`,mermaidZoomIn:`Zoom in`,mermaidZoomOut:`Zoom out`,mermaidPanMode:`Toggle pan mode`,mermaidEnterFullscreen:`Open fullscreen diagram`,mermaidExitFullscreen:`Close fullscreen diagram`,mermaidResetView:`Reset view`,mermaidCopySource:`Copy Mermaid source`,mermaidCopiedSource:`Copied Mermaid source`,fileDiff:`File Diff`,loadingDiff:`Loading diff...`,noFileDiff:`No file changes.`,diffUnavailable:`Diff content is unavailable for this file.`,binaryDiffUnavailable:`Binary file diff is unavailable.`,diffTooLarge:`Diff is too large to display.`,deletedFileDiffOnly:`This deleted file is only available as a diff.`,showGitBlame:`Show git blame`,hideGitBlame:`Hide git blame`,gitBlameAnnotations:`Git blame annotations`,gitBlameDetails:`Git blame details`,filePath:`File path`,editorFor:e=>`Editor for ${e}`,revealInExplorer:e=>`Reveal ${e} in Explorer`,previewFor:e=>`Preview for ${e}`,author:`Author`,commit:`Commit`,date:`Date`,line:`Line`,unknown:`Unknown`,uncommitted:`Uncommitted`,closeBlameDetails:`Close blame details`,cut:`Cut`,copy:`Copy`,paste:`Paste`,selectAll:`Select All`,annotateWithBlame:`Annotate with Blame`,hideBlame:`Hide Blame`,openLineChangesWithPreviousRevision:`Open Line Changes with Previous Revision`,openLineChangesWithWorkingFile:`Open Line Changes with Working File`,lineChanges:`Line changes`,loadingLineChanges:`Loading line changes...`,noLineChanges:`No line changes for this line.`,closeLineChanges:`Close line changes`,close:`Close`,closeFile:e=>`Close ${e}`,closeOthers:`Close Others`,closeToRight:`Close to the Right`,closeSaved:`Close Saved`,closeAll:`Close All`,saveBeforeCloseTitle:e=>`Save changes to ${e}?`,saveBeforeCloseDescription:`If you do not save, your changes will be lost.`,dontSave:`Don't Save`,loadingBlame:`Loading blame...`,notGitRepository:`Not a git repository.`,noCommittedLines:`No committed lines.`,cursorPosition:(e,t)=>`Ln ${e}, Col ${t}`,startMainAgent:`Start Main Agent`,startNewAgent:`Start New Agent`,loadingAgents:`Loading agents...`,agentListUnavailable:`Agent list unavailable.`,noSupportedAgentsFound:`No supported agents found.`,resumePreviousMainAgent:`Resume previous Main Agent`,codingAgents:`coding agents`,otherAgents:`Shell`,workspace:`Workspace:`,workspacePathPlaceholder:`/path/to/workspace`,recentWorkspacesLower:`recent workspaces`,start:`Start`,back:`Back`,backToAgent:`Back to Agent`,goBack:`Go Back`,goForward:`Go Forward`,backendConnecting:`Connecting to Farming backend...`,backendConnectionLost:`Farming backend disconnected. Reconnecting...`,backendHeartbeatLost:`No Farming backend heartbeat. Waiting for it to recover...`},NE={newAgent:`新建 Agent`,search:`搜索`,history:`历史`,codex:`Farming Code`,expandSidebar:`展开侧边栏`,collapseSidebar:`收起侧边栏`,enterFocusMode:`进入沉浸模式`,exitFocusMode:`退出沉浸模式`,terminalView:`终端`,transcriptView:`对话`,collapseComposer:`收起输入框`,restoreComposer:`唤出输入框`,codexTranscriptSyncing:`正在同步聊天历史...`,codexTranscriptUnavailable:`无法加载此会话的 Chat 历史。`,codexTranscriptEmpty:``,codexTranscriptWaiting:`Agent 仍在工作...`,codexTranscriptProcess:`执行过程`,codexTranscriptWorking:`处理中`,codexTranscriptThinking:`思考中`,codexTranscriptRunning:`运行命令中`,codexTranscriptReading:`读取文件中`,codexTranscriptSearching:`搜索中`,codexTranscriptEditing:`修改文件中`,codexTranscriptPlanActive:`执行计划中`,codexTranscriptPlanProgress:(e,t)=>`执行计划 ${e}/${t}`,codexTranscriptFetching:`获取信息中`,codexTranscriptUsingTool:`调用工具中`,codexTranscriptWorkedFor:e=>`Worked for ${e}`,codexTranscriptProcessCount:e=>`${e} 个事件`,codexTranscriptCopyDetails:`复制详情`,codexTranscriptCopiedDetails:`已复制`,codexTranscriptCopyAnswer:`复制答复`,codexTranscriptCopiedAnswer:`已复制答复`,codexTranscriptReviewChanges:`Review`,codexTranscriptShowChanges:`展开文件改动`,codexTranscriptLoadingChanges:`正在加载准确改动…`,codexTranscriptKeepChange:`保留`,codexTranscriptRevertChange:`撤销`,codexTranscriptChangeKept:`已保留`,codexTranscriptChangeReverted:`已撤销`,codexTranscriptShowMoreFiles:e=>`显示另外 ${e} 个文件`,codexGoalTitle:`目标`,codexGoalEmpty:`没有活动目标`,codexGoalOpen:`打开目标控制`,codexGoalObjective:`目标内容`,codexGoalStatus:`状态`,codexGoalTokenBudget:`Token 预算`,codexGoalNoBudget:`不限制`,codexGoalUsage:(e,t)=>`${e.toLocaleString()} tokens · ${Math.round(t/60)} 分钟`,codexGoalStatusLabel:e=>({active:`进行中`,paused:`已暂停`,blocked:`已阻塞`,usageLimited:`用量受限`,budgetLimited:`预算受限`,complete:`已完成`})[e]??e,codexGoalEdit:`编辑`,codexGoalStart:`启动`,codexGoalStop:`停止`,codexGoalDelete:`删除`,codexGoalSave:`保存目标`,codexGoalClear:`清除`,codexGoalSaving:`保存中...`,codexGoalUnsupported:`原生目标控制需要 Codex App Server 会话。`,searchProjectsOrAgents:`搜索项目或 Agent`,clearSearch:`清空搜索`,projectsAndAgents:`项目与 Agent`,noAgentsYet:`还没有 Agent。`,noMatchingProjectsOrAgents:`没有匹配的项目或 Agent。`,openNavigation:`打开导航`,closeNavigation:`关闭导航`,openOptions:`打开选项`,openSettings:`设置`,agentActions:`Agent 操作`,appearanceLight:`外观:浅色`,appearanceDark:`外观:深色`,languageEnglish:`语言:English`,languageChinese:`语言:中文`,pinAgent:`置顶 Agent`,unpinAgent:`取消置顶`,renameAgent:`重命名 Agent`,renameProject:`重命名项目`,archiveAgent:`归档`,reorderAgentFailed:`调整 Agent 顺序失败`,markAsRead:`标为已读`,markAsUnread:`标为未读`,copyWorkingDirectory:`复制工作目录`,copiedWorkingDirectory:`已复制工作目录`,copyFailed:`复制失败`,sharePage:`分享页面`,scanToOpenOnPhone:`手机扫码打开`,copyFullShareLink:`复制完整链接`,copiedShareLink:`已复制完整链接`,shareLinkFailed:`分享链接不可用`,sharedLocationUnavailable:e=>`无法定位分享路径:${e}`,shareLinkExpired:`已过期`,refreshShareLink:`刷新`,brandStoryOrigin:`Farming Code 从一个简单的问题出发:当多个 Coding Agent 同时工作,人不该在终端、编辑器和浏览器标签页之间反复切换。`,brandStoryPurpose:`它把对话、终端、项目文件与进展放在一个安静的工作空间里,让注意力留在真正重要的事情上。`,brandGithub:`GitHub`,mobileShareTitle:`分享页面`,mobileForwardTitle:`转发当前页面`,mobileForwardHint:`复制链接,发送给其他人。`,mobileShareCopyAction:`复制链接`,mobileShareCopied:`已复制`,mobileInstallTitle:`添加到主屏幕`,mobileInstallChromeHint:`确认已使用系统浏览器或 Chrome 打开当前页面。`,mobileInstallShareStep:`点浏览器工具栏里的“分享”。`,mobileInstallMoreStep:`没看到时,点 •••,再点“分享”。`,mobileInstallAddStep:`选择“添加到主屏幕”。`,mobileInstallOpenStep:`以后从主屏幕的 Farming 图标进入。`,mobileShareInstalled:`Farming 已经作为主屏幕 App 打开。`,forkSameWorktree:`在同一 worktree 分叉`,forkNewWorktree:`分叉到新 worktree`,newWorktreeFork:`已分叉到新 worktree`,scheduledTask:`周期任务`,killAgent:`停止 Agent`,killAgentQuestion:`停止 Agent?`,openSession:`打开会话`,pinChat:`置顶会话`,unpinChat:`取消置顶会话`,archiveChat:`归档`,archiveChats:`归档会话`,archiveProject:`归档项目`,deleteWorktree:`删除 worktree`,deleteWorktreeQuestion:`删除 worktree?`,deleteWorktreeDirtyDescription:e=>`这个 worktree 里还有 ${e} 个未提交或未跟踪文件,强删会连同目录一起删除。`,forceDelete:`强制删除`,cancel:`取消`,retry:`重试`,save:`保存`,stopAgentDescription:e=>`停止 ${e} 并关闭它的终端。`,permissionModeLabel:(e,t)=>({ask:`请求批准`,approve:`自动批准`,full:`完全访问`,custom:`自定义`,default:`默认`,auto:`自动`,acceptEdits:`接受编辑`,dontAsk:`不询问`,plan:`计划`,bypassPermissions:`绕过权限`})[e]??t,permissionModeDescription:(e,t)=>({ask:`新 Codex 会话以 workspace-write 沙箱启动,并对不可信操作询问`,approve:`新 Codex 会话以 workspace-write 沙箱启动,并在 Codex 请求时询问`,full:`新 Codex 会话绕过批准和沙箱;仅用于可信沙箱`,custom:`新 Codex 会话使用 config.toml 中定义的权限`,default:`新 Claude Code 会话使用默认设置`,auto:`新 Claude Code 会话以 auto 权限模式启动`,acceptEdits:`新 Claude Code 会话允许文件编辑,其他高风险操作仍会询问`,dontAsk:`新 Claude Code 会话在支持时尽量避免交互式批准`,plan:`新 Claude Code 会话以计划权限模式启动`,bypassPermissions:`新 Claude Code 会话绕过权限检查;仅用于可信沙箱`})[e]??t,acpModeLabel:(e,t)=>({"read-only":`只读`,agent:`工作区`,"agent-full-access":`完全访问`,auto:`自动`,default:`手动批准`,acceptEdits:`接受编辑`,plan:`计划`,dontAsk:`不询问`,bypassPermissions:`绕过权限`,build:`执行`})[e]??t,acpModeDescription:(e,t)=>({"read-only":`默认只读和分析;写文件或运行需要更高权限的命令时会请求批准,网络默认关闭`,agent:`可在当前工作区内读写文件并运行沙箱命令;使用网络或访问工作区外内容时会请求批准`,"agent-full-access":`可访问工作区外文件并使用网络,且不再请求批准;仅用于可信环境`,auto:`由模型分类器自动批准或拒绝权限请求`,default:`需要权限的操作会先请求批准`,acceptEdits:`自动批准文件编辑;其他需要权限的操作仍会询问`,plan:`只进行规划和检查,不修改文件`,dontAsk:`不弹出权限询问;未经预先允许的操作会直接拒绝`,bypassPermissions:`绕过权限检查;仅用于可信环境`,build:`按照该 Agent 已配置的权限执行工具`})[e]??t,reasoningOptionLabel:(e,t)=>({config:`使用配置`,low:`低`,medium:`中`,high:`高`,xhigh:`超高`,max:`最高`})[e]??t,serviceTierLabel:(e,t)=>({default:`标准`,priority:`快`,flex:`弹性`})[e]??t,serviceTierDescription:(e,t)=>({default:`默认速度`,priority:`1.5 倍速度,用量增加`})[e]??t,messageMode:`消息`,goalMode:`目标`,planMode:`计划`,askFollowUpChanges:`输入后续修改要求`,shellCommandPlaceholder:`输入 Shell 命令`,describeAgentGoal:`描述这个 Agent 的目标`,describePlanFirst:`描述需要先规划的事情`,openAgentTerminalFirst:`先打开一个 Agent 终端`,queuedMessages:e=>`${e} 条排队消息`,steerQueuedMessage:`引导`,discardQueuedMessage:`丢弃排队消息`,addContext:`添加上下文`,attachFile:`附加文件`,fileContext:`文件上下文`,setObjective:`设置目标`,planFirst:`先做计划`,clearComposerMode:`清除输入模式`,agentPermissionMode:`Agent 权限模式`,permissionsPrompt:`启动权限 profile`,permissionProfileSavedForNextLaunch:`已保存给新 Agent。运行中的会话保留启动时的权限。`,permissionProfileRestarting:`正在切换 Agent 权限…`,permissionProfileApplying:`正在应用 App Server 权限…`,runtimeModeRestarting:`正在重启 Agent…`,agentRestartTimedOut:`Agent 重启超时。原 Agent 仍然可用,请重新切换。`,permissionRestartHint:`运行中的 Agent 会重启以应用权限;如果还没有可 resume 的 Session ID,则启动一个新会话。`,permissionAppServerHint:`直接应用到当前 App Server thread,不重启 Agent;新权限从后续 turn 生效。`,modelAndReasoning:`模型与推理`,reasoning:`推理`,speed:`速度`,startDictation:`开始语音输入`,stopDictation:`停止语音输入`,speechUnsupported:`当前浏览器不支持语音识别`,mobileDictationHint:`请点 iOS 键盘上的麦克风进行听写。`,sendMessage:`发送消息`,interruptAgent:`中止 Agent`,startOrSelectAgent:`启动或选择一个 Agent`,startOrSelectAgentDescription:`项目在左侧。打开任意 Agent 终端时,不会关闭其他工作区。`,historySummary:(e,t,n,r)=>`${n+r} 个 History Agents`,searchHistory:`搜索历史记录`,noHistoryYet:`还没有历史记录`,noHistoryDescription:`从主页面移出的 Agent 会出现在这里。`,historyAgents:`History Agents`,agentSessions:`Agent 会话`,recentWorkspaces:`最近工作区`,agentsSessionsSummary:(e,t)=>`${e} 个 Agent · ${t} 个会话`,restore:`恢复`,continueRun:`继续`,open:`打开`,archived:`已归档`,pinned:`已置顶`,unread:`未读`,showMore:`显示更多`,showLess:`收起`,latest:`最新`,upgrade:`升级`,updating:`更新中`,retryUpdate:`重试`,checkForUpdates:`检查更新`,updateFailed:`更新失败`,upgradeToVersion:e=>e?`升级到 ${e}`:`升级 Farming Code`,sessionFallbackTitle:e=>`${e||`Agent`} 会话`,resumeSessionAria:e=>`恢复 ${e}`,resultsCount:e=>`${e} 个结果`,noMatchingAgents:`没有匹配的 Agent`,searchHint:`可按 Agent 标题、会话标题或项目搜索。`,searchEmptyTitle:`开始搜索`,searchEmptyDescription:`输入 Agent 标题、会话标题,或项目名称、路径。`,agents:`Agent`,files:`文件`,changes:`变更`,changedFiles:`变更文件`,trackedChanges:`已跟踪`,untrackedChanges:`未跟踪`,reviewChanges:`Review`,refreshChanges:`刷新变更`,searchOrPathLine:`搜索或路径:行号`,searchFilesOrJump:`搜索文件或跳转到路径行号`,openEditors:`打开的编辑器`,loading:`加载中...`,searching:`搜索中...`,noMatches:`无匹配`,searchIgnoredFolders:`同时在已忽略目录中搜索`,searchIncomplete:e=>`搜索提前停止(当前超时:${Math.round(e/1e3)} 秒)`,terminalSearchPlaceholder:`在终端中查找`,terminalSearchPrevious:`上一个匹配`,terminalSearchNext:`下一个匹配`,terminalSearchClose:`关闭终端搜索`,terminalSearchCaseSensitive:`区分大小写`,terminalSearchWholeWord:`全词匹配`,terminalSearchRegex:`使用正则表达式`,terminalSearchNoResults:`无结果`,terminalSearchResults:(e,t)=>`${e}/${t}`,terminalSessionUnavailable:`终端会话不可用`,appServerWaitingForFirstMessage:`App Server 已就绪。发送第一条 Composer 消息后,会启动加入同一条 thread 的 Codex CLI 终端。`,appServerRequestTitle:`Codex 需要你的输入`,appServerRequestCommand:`请求执行的命令`,appServerRequestQuestion:`问题`,appServerRequestApprove:`允许`,appServerRequestDecline:`拒绝`,appServerRequestSubmit:`提交回答`,appServerRequestUnsupported:`Farming 目前不支持这类 Codex 请求。拒绝后,当前 turn 会安全地继续。`,appServerApprovalRejectedTitle:`已拒绝权限申请`,appServerApprovalRejectedDescription:`Chat 界面不会批准这类权限申请。请调高这个 Agent 的权限,或切到 Terminal 界面处理。`,acpPermissionTitle:`Agent 需要权限`,acpPermissionTool:`请求使用工具`,file:`文件`,folder:`文件夹`,go:`跳转`,moreMatchesOmitted:`更多匹配已省略`,stickyFolderPath:`固定文件夹路径`,containsUncommittedChanges:`包含未提交改动`,changedOnDisk:`磁盘上已变更`,unsavedChanges:`未保存改动`,gitStatus:e=>`Git 状态:${e}`,renameEntry:e=>`重命名 ${e}`,newFile:`新建文件`,newFolder:`新建文件夹`,refresh:`刷新`,rename:`重命名`,copyRelativePath:`复制相对路径`,copyShareUrl:`拷贝分享 URL`,delete:`删除`,deleteFolderContents:e=>`删除文件夹及其所有内容:${e||``}`,deleteFile:e=>`删除文件:${e||``}`,saveFile:`保存文件`,savingFile:`正在保存文件`,reloadFile:`重新加载文件`,overwriteChangedFile:`覆盖已变更文件`,openFileDiff:`打开文件 Diff`,openFileDiffFor:e=>`打开 ${e} 的 Diff`,closeDiff:`关闭 Diff`,openFilePreview:`打开预览`,showFileSource:`显示源码`,enableWordWrap:`开启折行`,disableWordWrap:`关闭折行`,openMarkdownPreview:`打开 Markdown 预览`,showMarkdownSource:`显示 Markdown 源码`,openMarkdownSplitPreview:`打开 Markdown 侧边预览`,closeMarkdownSplitPreview:`关闭 Markdown 侧边预览`,markdownPreviewFor:e=>`${e} 的 Markdown 预览`,markdownFrontMatter:`Front matter`,markdownHeadingAnchor:`跳转到这个标题`,mermaidDiagram:`Mermaid 图表`,mermaidDiagramControls:`Mermaid 图表控制`,mermaidRendering:`正在渲染图表...`,mermaidRenderFailed:`无法渲染 Mermaid 图表`,mermaidZoomIn:`放大`,mermaidZoomOut:`缩小`,mermaidPanMode:`切换平移模式`,mermaidEnterFullscreen:`全屏查看图表`,mermaidExitFullscreen:`退出全屏查看`,mermaidResetView:`重置视图`,mermaidCopySource:`复制 Mermaid 源码`,mermaidCopiedSource:`已复制 Mermaid 源码`,fileDiff:`文件 Diff`,loadingDiff:`正在加载 Diff...`,noFileDiff:`文件没有变化。`,diffUnavailable:`这个文件没有可显示的 Diff 内容。`,binaryDiffUnavailable:`二进制文件不能显示 Diff。`,diffTooLarge:`Diff 过大,无法显示。`,deletedFileDiffOnly:`这个已删除文件只支持以 Diff 查看。`,showGitBlame:`显示 Git Blame`,hideGitBlame:`隐藏 Git Blame`,gitBlameAnnotations:`Git Blame 标注`,gitBlameDetails:`Git Blame 详情`,filePath:`文件路径`,editorFor:e=>`${e} 的编辑器`,revealInExplorer:e=>`在文件树中显示 ${e}`,previewFor:e=>`${e} 的预览`,author:`作者`,commit:`提交`,date:`日期`,line:`行`,unknown:`未知`,uncommitted:`未提交`,closeBlameDetails:`关闭 Blame 详情`,cut:`剪切`,copy:`复制`,paste:`粘贴`,selectAll:`全选`,annotateWithBlame:`用 Blame 标注`,hideBlame:`隐藏 Blame`,openLineChangesWithPreviousRevision:`打开与上一版的行变化`,openLineChangesWithWorkingFile:`打开与工作区文件的行变化`,lineChanges:`行变化`,loadingLineChanges:`正在加载行变化...`,noLineChanges:`这一行没有可显示的变化。`,closeLineChanges:`关闭行变化`,close:`关闭`,closeFile:e=>`关闭 ${e}`,closeOthers:`关闭其他`,closeToRight:`关闭右侧`,closeSaved:`关闭已保存`,closeAll:`全部关闭`,saveBeforeCloseTitle:e=>`是否保存对 ${e} 的更改?`,saveBeforeCloseDescription:`如果不保存,你的更改将丢失。`,dontSave:`不保存`,loadingBlame:`正在加载 Blame...`,notGitRepository:`不是 Git 仓库。`,noCommittedLines:`没有已提交行。`,cursorPosition:(e,t)=>`第 ${e} 行,第 ${t} 列`,startMainAgent:`启动 Main Agent`,startNewAgent:`启动新 Agent`,loadingAgents:`正在加载 Agent...`,agentListUnavailable:`Agent 列表不可用。`,noSupportedAgentsFound:`没有找到支持的 Agent。`,resumePreviousMainAgent:`恢复上一个 Main Agent`,codingAgents:`Coding Agent`,otherAgents:`Shell`,workspace:`工作区:`,workspacePathPlaceholder:`/工作区/路径`,recentWorkspacesLower:`最近工作区`,start:`启动`,back:`返回`,backToAgent:`返回 Agent`,goBack:`后退`,goForward:`前进`,backendConnecting:`正在连接 Farming 后端...`,backendConnectionLost:`Farming 后端连接已断开,正在重连...`,backendHeartbeatLost:`没有收到 Farming 后端心跳,正在等待恢复...`};function PE(e){return e===`zh`?NE:ME}function FE(){return window}function IE(e,t={},n=FE()){let r=t.delays??[],i=[],a=t.animationFrame!==!1,o;return t.runNow!==!1&&e(),a&&(o=n.requestAnimationFrame(e)),r.forEach(t=>{i.push(n.setTimeout(e,t))}),()=>{o!==void 0&&n.cancelAnimationFrame(o),i.forEach(e=>n.clearTimeout(e))}}var LE={ask:`Ask for approval`,approve:`Approve for me`,full:`Full access`,custom:`Custom`},RE={ask:`Launch Codex with workspace-write sandbox and ask for untrusted actions`,approve:`Launch Codex with workspace-write sandbox and ask when Codex requests approval`,full:`Launch Codex with approvals and sandbox bypassed; use only in trusted sandboxes`,custom:`Launch Codex with permissions defined in config.toml`},zE=[`ask`,`approve`,`full`,`custom`].map(e=>({value:e,label:LE[e],description:RE[e],color:e===`approve`?`blue`:e===`full`?`orange`:`muted`})),BE={default:`Default`,auto:`Auto`,acceptEdits:`Accept edits`,dontAsk:`Don't ask`,plan:`Plan`,bypassPermissions:`Bypass permissions`},VE={default:`Launch Claude Code with its default settings`,auto:`Launch Claude Code in auto permission mode`,acceptEdits:`Launch Claude Code allowing file edits while still asking for other risky actions`,dontAsk:`Launch Claude Code avoiding interactive approval prompts where supported`,plan:`Launch Claude Code in plan permission mode`,bypassPermissions:`Launch Claude Code with permission checks bypassed; use only in trusted sandboxes`},HE=[`default`,`auto`,`acceptEdits`,`dontAsk`,`plan`,`bypassPermissions`].map(e=>({value:e,label:BE[e],description:VE[e],color:e===`bypassPermissions`?`orange`:[`auto`,`acceptEdits`,`plan`].includes(e)?`blue`:`muted`})),UE=[{value:`low`,effort:`low`,label:`Low`},{value:`medium`,effort:`medium`,label:`Medium`},{value:`high`,effort:`high`,label:`High`},{value:`xhigh`,effort:`xhigh`,label:`Extra High`},{value:`max`,effort:`max`,label:`Max`}],WE=`Claude settings`,GE={value:`config`,effort:`config`,label:WE},KE=[{value:`config`,label:WE,displayName:WE,defaultEffort:`config`,reasoningLevels:[GE,...UE],source:`settings`}],qE={available:!1,effectiveModel:``,effectiveEffort:``,modelOptions:[],effortOptions:UE};function JE(e){return!!(e&&e in LE)}function YE(e){return!!(e&&e in BE)}function XE(e,t,n){return e?JE(t)?t:`custom`:n}function ZE(e,t,n){return e?YE(t)?t:`default`:n}function QE(e){if(typeof e!=`string`)return``;let t=e.trim();return!t||/[\s\x00-\x1f\x7f]/.test(t)||t.startsWith(`-`)?``:t}function $E(e){return e===`config`?e:QE(e)||`config`}function eD(e){return e&&UE.some(t=>t.value===e)?e:``}function tD(e){return e===`config`?e:eD(e)||`config`}function nD(e){let t=[];return Array.isArray(e)&&e.forEach(e=>{let n=eD(e?.value);n&&t.push({value:n,effort:n,label:e.label||Nb(n),description:e.description})}),t.length>0?t:UE}function rD(e){let t=nD(e?.effortOptions),n=QE(e?.effectiveModel),r=eD(e?.effectiveEffort),i=[];return Array.isArray(e?.modelOptions)&&e.modelOptions.forEach(e=>{let n=QE(e?.value);n&&i.push({...e,value:n,label:e.label||n,displayName:e.displayName||n,defaultEffort:eD(e.defaultEffort)||r||`medium`,reasoningLevels:t,source:e.source||`settings`})}),n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,displayName:n,defaultEffort:r||`medium`,reasoningLevels:t,source:`settings`}),{available:e?.available===!0,effectiveModel:n,effectiveEffort:r,modelOptions:i,effortOptions:t}}function iD(e,t){let n=t.effortOptions?.length?t.effortOptions:UE,r=t.modelOptions?.length?t.modelOptions:KE.map(e=>({...e})),i=$E(e);return!i||i===`config`||r.some(e=>e.value===i)?r.map(e=>({...e,reasoningLevels:e.reasoningLevels?.length?e.reasoningLevels:n})):[...r.map(e=>({...e,reasoningLevels:e.reasoningLevels?.length?e.reasoningLevels:n})),{value:i,label:i,displayName:i,defaultEffort:t.effectiveEffort||`medium`,reasoningLevels:n,source:`settings`}]}function aD(e,t){return e===`config`?t.effectiveModel||t.modelOptions?.[0]?.value||`config`:$E(e)}function oD(e,t){return e===`config`?t.effectiveEffort||`config`:tD(e)}function sD(e,t){let n=t.effortOptions?.length?t.effortOptions:UE;return e===`config`?[GE,...n]:n.some(t=>t.value===e)?n:[...n,{value:e,effort:e,label:Nb(e)}]}function cD(e,t,n,r){if(!e||r.some(t=>t.value===e))return r;let i=[{value:`default`,label:`Standard`,description:`Default speed`}];return n&&n!==`default`&&i.push({value:n,label:n===`priority`?`Fast`:n}),[...r,{value:e,label:Fb(void 0,e),displayName:Fb(void 0,e),defaultEffort:t,reasoningLevels:[{value:t,effort:t,label:Nb(t)}],serviceTiers:i,source:`pending-catalog`}]}function lD(e){let t=e.agentLaunchProfiles?.codex??{},n=t.approvalMode??e.codexApprovalMode,r=Pb(t.modelPreset??e.codexModelPreset),i=t.model||e.codexModel||r.model,a=t.reasoningEffort||e.codexReasoningEffort||r.effort,o=e.agentLaunchProfiles?.claude??{};return{codexApprovalMode:JE(n)?n:`approve`,codexModel:i,codexReasoningEffort:a,codexServiceTier:t.serviceTier||e.codexServiceTier||`default`,codexModelPreset:`${i}:${a}`,claudePermissionMode:YE(o.permissionMode)?o.permissionMode:`default`,claudeModel:$E(o.model),claudeEffort:tD(o.effort)}}function uD({agentKind:e,codexModel:t,codexReasoningEffort:n,codexServiceTier:r,codexModelPreset:i,codexModelOptions:a,codexApprovalMode:o,claudeModel:s,claudeEffort:c,claudeSettings:l,claudePermissionMode:u}){let d=aD(s,l),f=oD(c,l),p=e===`claude`?iD(s,l):e===`codex`?cD(t,n,r,a):a,m=e===`claude`?d:t,h=e===`claude`?f:n,g=e===`claude`?``:r,_=e===`claude`?`${m}:${h}`:i,v=p.find(e=>e.value===m)??p[0],y=e===`claude`?sD(h,l):v?.reasoningLevels?.length?v.reasoningLevels:Db[0]?.reasoningLevels??[],b=e===`claude`?[]:v?.serviceTiers?.length?v.serviceTiers:[{value:`default`,label:`Standard`,description:`Default speed`}],x=y.find(e=>e.value===h)??y[0],S=b.find(e=>e.value===g)??b[0],C=e===`claude`?HE:zE,w=e===`claude`?u:o,T=C.find(e=>e.value===w)??C[0];return{agentModelOptions:p,agentModel:m,agentReasoningEffort:h,agentServiceTier:g,agentModelPreset:_,currentModelOption:v,currentReasoningOptions:y,currentServiceTierOptions:b,currentReasoningOption:x,currentServiceTierOption:S,currentModelLabel:Fb(v,m),currentReasoningLabel:x?.label??Nb(h),currentSpeedLabel:S?.label??``,permissionModeOptions:C,currentPermissionMode:w,currentPermissionOption:T,currentPermissionLabel:T?.label??w,currentPermissionColor:T?.color??`muted`}}function dD(e){return!e.isMain&&e.archived!==!0&&e.status!==`dead`&&e.status!==`stopped`}function fD(e){return!e.isMain&&e.archived===!0}function pD(e,t=[]){let n=new Map;return e.forEach(e=>{if(!dD(e))return;let t=e.providerSessionKey||NS(e.source);t&&n.set(e.id,t)}),n}function mD(e,t){return t.get(e.id)||`agent:${e.id}`}function hD(e){return e.providerSessionKey&&e.providerSessionTemporary!==!0?120:NS(e.source)?100:e.providerSessionKey?40:0}function gD(e){return e.status===`running`?30:e.status===`pending`?20:0}function _D(e,t){return hD(e)+(t.has(e.id)?50:0)+gD(e)}function vD(e,t){let n=new Map;return e.forEach(e=>{let r=mD(e,t),i=n.get(r);if(!i){n.set(r,e);return}let a=_D(e,t),o=_D(i,t),s=Number(e.startedAt)||0,c=Number(i.startedAt)||0;(a>o||a===o&&s>c)&&n.set(r,e)}),e.filter(e=>n.get(mD(e,t))===e)}function yD(e,t){return e.filter(e=>!t.has(Rb(e)))}function bD(e,t,n){return e.filter(e=>{let r=Rb(e);return(e.archived||!t.has(r))&&!n.has(r)})}function xD({allAgents:e,liveAgents:t,sessions:n,mainPageSessionKeys:r}){let i=t.filter(dD),a=pD(i,n),o=new Set(a.values()),s=vD(i,a),c=n.filter(e=>!e.archived&&r.has(Rb(e))).sort(Gb),l=yD(c,o),u=yD(n,o).sort(Gb),d=bD(n,r,o).sort(Gb);return{liveAgents:s,archivedAgents:e.filter(fD).sort((e,t)=>(t.archivedAt??0)-(e.archivedAt??0)),mainPageAgentSessions:c,sidebarAgentSessions:l,searchableAgentSessions:u,historyAgentSessions:d,claimedAgentSessionKeys:o,claimedAgentSessionKeyByAgentId:a}}function SD(){return{activeFile:null,files:[],closedFileCache:new Map}}function CD(e){return{activeFile:e.activeFile,files:e.files,closedFileCache:e.closedFileCache}}function wD(){let[e,t]=(0,W.useState)(()=>SD()),n=(0,W.useRef)(e),r=(0,W.useCallback)(e=>(n.current=CD(e),t(n.current),n.current),[]),i=(0,W.useCallback)((e,t,i)=>r(x(n.current,e,t,i)),[r]),a=(0,W.useCallback)((e,t,i)=>{let a=c(n.current,e,t,i);return a?r(a):null},[r]),o=(0,W.useCallback)(e=>{let t=T(n.current,e);return t.closedFiles.length>0&&r(t),t},[r]),s=(0,W.useCallback)(e=>{let t=te(n.current,{canReopen:e});return t?r(t):null},[r]),u=(0,W.useCallback)(e=>r(l(n.current,e)),[r]),d=(0,W.useCallback)(e=>{let t=n.current.activeFile;if(!t)return null;let i=p(t,e);return r({...n.current,activeFile:i,files:g(n.current.files,i)})},[r]),f=(0,W.useCallback)((e,t)=>{let i=P(n.current,e,t);return i!==n.current&&r(i),i},[r]),m=(0,W.useCallback)((e,t)=>{let i=y(n.current,e,t);return t.length>0&&r(i),i},[r]),h=(0,W.useMemo)(()=>Array.from(e.closedFileCache.values()),[e.closedFileCache]);return(0,W.useMemo)(()=>({activeFile:e.activeFile,files:e.files,closedFiles:h,openFromRead:i,select:a,close:o,reopenLastClosed:s,update:u,updateDraft:d,move:f,deleteEntries:m}),[h,o,m,f,i,s,a,e.activeFile,e.files,u,d])}function TD(){let[e,t]=(0,W.useState)(()=>mt()),n=(0,W.useRef)(e),r=(0,W.useRef)(!1),i=(0,W.useRef)(null),a=(0,W.useCallback)(e=>(n.current=e,t(e),e),[]),o=(0,W.useCallback)(e=>{r.current||a(yt(n.current,e))},[a]),s=(0,W.useCallback)(e=>{o(ht(e))},[o]),c=(0,W.useCallback)(e=>{o(gt(e))},[o]),l=(0,W.useCallback)(e=>{r.current||(i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,o(gt({...e,reason:`cursor`}))},650))},[o]),u=(0,W.useCallback)(e=>{let t=n.current,i=t.index+e,o=t.entries[i];return o?(r.current=!0,a({entries:t.entries,index:i}),o):null},[a]),d=(0,W.useCallback)(()=>{window.setTimeout(()=>{r.current=!1},120)},[]),f=(0,W.useCallback)(e=>{let t=n.current,r=t.entries.filter(e);if(r.length===t.entries.length)return;let i=t.entries[t.index],o=i?r.indexOf(i):-1;a({entries:r,index:o>=0?o:Math.min(t.index,r.length-1)})},[a]);return(0,W.useEffect)(()=>()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]),(0,W.useMemo)(()=>({canGoBack:e.index>0,canGoForward:e.index>=0&&e.index<e.entries.length-1,recordAgent:s,recordFile:c,recordFileCursor:l,beginNavigation:u,finishNavigation:d,pruneEntries:f}),[u,d,f,s,c,l,e.entries.length,e.index])}function ED({agents:e,permissionSwitchReplacement:t,onDiscardAttachment:n}){let[r,i]=(0,W.useState)({});(0,W.useLayoutEffect)(()=>{let r=new Set(e.filter(e=>!e.archived&&e.status!==`dead`&&e.status!==`stopped`).flatMap(e=>[KC(e),bw(e)]).filter(Boolean));i(i=>{let a=i,o=!1,s=()=>(a===i&&(a={...i}),o=!0,a);if(t){let e=(e,t)=>{let n=a[e];if(!n)return;let r=s(),i=r[t];r[t]=i?WC(i,n):n,delete r[e]};e(t.originalAgentId,t.replacementAgentId),e(`acp:${t.originalAgentId}`,`acp:${t.replacementAgentId}`)}return e.forEach(e=>{let t=KC(e);if(!t)return;qC(e).forEach(e=>{if(e===t)return;let n=a[e];if(!n)return;let r=s();r[t]=r[t]?WC(r[t],n):n,delete r[e]});let n=bw(e);xw(e).forEach(e=>{if(e===n)return;let t=a[e];if(!t)return;let r=s();r[n]=r[n]?WC(r[n],t):t,delete r[e]})}),Object.entries(a).forEach(([e,t])=>{if(r.has(e))return;let i=s();t.attachments.forEach(n),delete i[e]}),o?a:i})},[e,n,t]);let a=(0,W.useCallback)(t=>{if(!t)return``;for(let n of e){let e=Sw(t),r=e?bw(n):KC(n);if(!r)continue;let i=e?xw(n):qC(n);if(t===r||i.includes(t))return r}return t},[e]);return{composerByAgentKey:r,updateComposerStateForKey:(0,W.useCallback)((e,t)=>{i(n=>{let r=a(e);if(!r)return n;let i=n[r]??zC(),o=t(i);return o===i?n:{...n,[r]:o}})},[a]),updateExistingComposerStateForKey:(0,W.useCallback)((e,t)=>{i(n=>{let r=a(e);if(!r)return n;let i=n[r];if(!i)return n;let o=t(i);return o===i?n:{...n,[r]:o}})},[a])}}function DD(){if(typeof window>`u`)return``;let e=window.location.hostname;return e?e===`localhost`||e===`127.0.0.1`||e===`::1`?`Local server`:`Remote server`:``}function OD(e){return e.replace(/^Language:\s*/i,``).replace(/^语言[::]\s*/,``)}function kD(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.trim(),i=String(n??``).trim();!r||!i||(t[r]=i.slice(0,80))}),t}function AD(e){return e.replace(/^Appearance:\s*/i,``).replace(/^外观[::]\s*/,``)}function jD(e,t){return e.size===t.length?t.every(t=>e.has(t)):!1}function MD(e){return(e.ctrlKey||e.metaKey)&&e.shiftKey&&!e.altKey&&e.key.toLowerCase()===`t`}var ND=296,PD=220,FD=520,ID=52,LD=172,RD=900,zD=12,BD=214,VD=86,HD=60,UD=1e3,WD=150;function GD(){return typeof window>`u`?!1:L()&&F()}function KD(e){let t=(e||``).trim().split(/\s+/).find(e=>e!==`env`&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(e))?.split(`/`).pop()||``;return t===`qoder`||t===`qodercli`||t===`opencode`}function qD(e){return e instanceof HTMLElement?e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable:!1}function JD(e){return MS(e)}function YD(e){return e.kind===`agent-session`?Rb(e):Ob(e)}function XD(){return L()}function ZD(e){return!XD()&&e>0&&e<RD}function QD(){return XD()?!0:typeof window<`u`&&ZD(window.innerWidth)}function $D(e){e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation()}function eO(e){let t=(e||``).replace(/\/+$/,``);return t.split(`/`).filter(Boolean).pop()||t||`workspace`}function tO(e){if(e.lineNumber)return{lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn}}function nO(e){let t=new Map;for(let n of e)n.kind!==`path`||t.has(n.path)||t.set(n.path,n);return Array.from(t.values())}function rO(e){let t=new Map;for(let n of e)t.has(n.path)||t.set(n.path,n);return Array.from(t.values())}async function iO(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,`true`),t.setAttribute(`autocomplete`,`off`),t.setAttribute(`autocorrect`,`off`),t.setAttribute(`autocapitalize`,`none`),t.setAttribute(`spellcheck`,`false`),t.setAttribute(`data-lpignore`,`true`),t.setAttribute(`data-1p-ignore`,`true`),t.setAttribute(`data-bwignore`,`true`),t.setAttribute(`data-form-type`,`other`),t.style.position=`fixed`,t.style.left=`-9999px`,t.style.top=`0`,document.body.appendChild(t),t.select();try{return document.execCommand(`copy`)}finally{t.remove()}}function aO({agents:e,taskHistory:t,mainPageSessionKeys:r,activeView:i,dialogOpen:a,systemStats:o,usageSummary:s,contextWindowByAgentId:c={},activeTerminalId:l,permissionSwitchingAgentId:p,agentSwitchingKind:g,permissionSwitchReplacement:_,openTerminalIds:v,terminalFocusRequest:y,keyMap:b,keyboardShortcutsEnabled:x,uiPreferences:T,onOpenTerminal:E,onOpenTerminalWhenReady:ee,onNewAgent:M,onStartAgent:te,onRenameAgent:P,onUpdateAgentFlags:F,onOpenArchivedAgent:re,onForkAgent:z,onDeleteForkWorktreeProject:B,onRestartMainAgent:ie,onWorkspaceViewChange:V,onKill:ae,onInterruptAgent:oe,sendInput:se,sendComposerInput:ce,respondToAppServerRequest:le,resizeAgent:ue,onSessionOutput:de,onUpdateUiPreferences:fe}){let pe=Ie(),{composerByAgentKey:me,updateComposerStateForKey:H,updateExistingComposerStateForKey:he}=ED({agents:e,permissionSwitchReplacement:_,onDiscardAttachment:aw}),ge=(0,W.useRef)({}),[_e,ve]=(0,W.useState)({}),[ye,be]=(0,W.useState)(`terminal`),[xe]=(0,W.useState)(()=>A().surface),Se=(0,W.useRef)(!1),Ce=(0,W.useRef)(!xe),we=wD(),{canGoBack:Te,canGoForward:Ee,recordAgent:De,recordFile:U,recordFileCursor:je,beginNavigation:Me,finishNavigation:Ne,pruneEntries:Pe}=TD(),G=we.activeFile,Fe=we.files,[Le,Be]=(0,W.useState)(!1),[Ve,Ue]=(0,W.useState)(``),[We,Ge]=(0,W.useState)(0),[,Ke]=(0,W.useState)([]),[qe,Ye]=(0,W.useState)({}),[Xe,Ze]=(0,W.useState)([]),[Qe,$e]=(0,W.useState)(()=>new Set),[et,nt]=(0,W.useState)(`approve`),[rt,it]=(0,W.useState)(`gpt-5.5:xhigh`),[at,ot]=(0,W.useState)(`gpt-5.5`),[st,ct]=(0,W.useState)(`xhigh`),[lt,ut]=(0,W.useState)(`default`),[dt,ft]=(0,W.useState)(Db),[pt,mt]=(0,W.useState)(`default`),[ht,gt]=(0,W.useState)(`config`),[_t,vt]=(0,W.useState)(`config`),[yt,xt]=(0,W.useState)(qE),[St,Ct]=(0,W.useState)([]),[wt,Tt]=(0,W.useState)([]),[Et,Dt]=(0,W.useState)(``),[Ot,kt]=(0,W.useState)(!1),[At,q]=(0,W.useState)([]),[jt,Mt]=(0,W.useState)(!1),Nt=(0,W.useRef)(!1),Pt=(0,W.useRef)(HD),[Ft,It]=(0,W.useState)(()=>DS().pinnedOverrides),[Lt,Rt]=(0,W.useState)(!1),[zt,Bt]=(0,W.useState)(!1),[Vt,Ht]=(0,W.useState)(()=>new Set),[Ut,Wt]=(0,W.useState)(()=>new Set),[Gt,Kt]=(0,W.useState)(ND),[qt,Jt]=(0,W.useState)(()=>QD()),[Yt,Xt]=(0,W.useState)(()=>typeof window>`u`?null:k(window.location.search)),[Zt,Qt]=(0,W.useState)(0),[$t,en]=(0,W.useState)(void 0),[tn,nn]=(0,W.useState)(null),[rn,an]=(0,W.useState)(null),[on,sn]=(0,W.useState)(null),[cn,ln]=(0,W.useState)(null),[un,dn]=(0,W.useState)(!1),[fn,pn]=(0,W.useState)(``),[mn,hn]=(0,W.useState)(null),[gn,_n]=(0,W.useState)(null),[vn,yn]=(0,W.useState)(null),[bn,xn]=(0,W.useState)(null),[Sn,Cn]=(0,W.useState)(null),[wn,Tn]=(0,W.useState)(null),En=mn?mn.kind===`agent`?`agent:${mn.agentId}`:`project:${mn.projectId}`:``,[Dn,On]=(0,W.useState)(Date.now()),kn=(0,W.useRef)(null),An=(0,W.useRef)(null),jn=(0,W.useRef)([]),Mn=(0,W.useRef)({}),Nn=(0,W.useRef)([]),Pn=(0,W.useRef)(null),Fn=(0,W.useRef)(null),In=(0,W.useRef)(null),Ln=(0,W.useRef)(null),Rn=(0,W.useRef)(null),zn=(0,W.useRef)(null),Bn=(0,W.useRef)(null),Vn=(0,W.useRef)(null),Hn=(0,W.useRef)(null),Un=(0,W.useRef)(null),Wn=(0,W.useRef)(null),Gn=(0,W.useRef)(null),Kn=(0,W.useRef)(null),qn=(0,W.useRef)(!1),Jn=(0,W.useRef)(0),Yn=(0,W.useRef)(null),Xn=(0,W.useRef)(!1),Zn=(0,W.useRef)(!1),Qn=(0,W.useRef)(()=>{}),$n=(0,W.useRef)(l),er=(0,W.useRef)(0),tr=(0,W.useRef)(0),nr=(0,W.useRef)(0),rr=(0,W.useRef)(0),ir=(0,W.useRef)(0),ar=(0,W.useRef)(0),or=(0,W.useRef)(null),sr=(0,W.useRef)(null),cr=(0,W.useRef)(null),lr=(0,W.useRef)(0),ur=(0,W.useRef)(new Set),dr=(0,W.useRef)(!1),fr=(0,W.useRef)(qt),pr=(0,W.useRef)(XD()),mr=(0,W.useCallback)(()=>{fr.current=!1,Jt(!0)},[]),hr=(0,W.useCallback)(()=>{Jt(e=>(e||(fr.current=!0),!0))},[]),gr=(0,W.useCallback)(()=>{fr.current=!1,Jt(!1)},[]),_r=(0,W.useCallback)(()=>{fr.current=!1,Jt(e=>!e)},[]);$n.current=l;let J=(0,W.useMemo)(()=>PE(T.language),[T.language]);(0,W.useEffect)(()=>()=>{Nn.current.forEach(e=>window.clearTimeout(e)),Nn.current=[]},[]),(0,W.useEffect)(()=>{OS({promotedKeys:[],pinnedOverrides:Ft,archivedOverrides:{}})},[Ft]);let vr=(0,W.useMemo)(()=>e.filter(e=>!e.isMain),[e]),yr=(0,W.useMemo)(()=>e.find(e=>e.isMain)??null,[e]),Y=(0,W.useMemo)(()=>vr.filter(dD),[vr]),br=(0,W.useMemo)(()=>{let e=new Set(Y.map(e=>e.id));return yr&&e.add(yr.id),e},[Y,yr]);(0,W.useEffect)(()=>{Pe(e=>br.has(e.agentId))},[Pe,br]);let xr=(0,W.useMemo)(()=>AS(wt,Ft,{}),[Ft,wt]),Sr=(0,W.useMemo)(()=>xD({allAgents:vr,liveAgents:Y,sessions:xr,mainPageSessionKeys:Qe}),[Y,xr,Qe,vr]),Cr=Sr.mainPageAgentSessions,wr=Sr.sidebarAgentSessions,Tr=Sr.searchableAgentSessions,X=Sr.historyAgentSessions,Er=Sr.liveAgents,Dr=Sr.archivedAgents,Or=t,kr=X,Ar=(0,W.useMemo)(()=>new Set(At.map(Rb)),[At]),jr=(0,W.useMemo)(()=>new Set(Array.from(Sr.claimedAgentSessionKeyByAgentId.entries()).filter(([,e])=>Ar.has(e)).map(([e])=>e)),[Sr.claimedAgentSessionKeyByAgentId,Ar]),Mr=(0,W.useMemo)(()=>{let e=new Map(Tr.map(e=>[Rb(e),e]));return At.forEach(t=>e.set(Rb(t),t)),yD(Array.from(e.values()),Sr.claimedAgentSessionKeys)},[Sr.claimedAgentSessionKeys,At,Tr]),Nr=(0,W.useMemo)(()=>fT(Er,wr,qe),[qe,wr,Er]),Pr=(0,W.useMemo)(()=>PS(Nr,Ut,!1),[Ut,Nr]),Fr=(0,W.useMemo)(()=>fT(Er,Mr,qe),[qe,Mr,Er]),Ir=Ve.trim().toLowerCase(),Lr=Ir.length>0,Rr=(0,W.useMemo)(()=>pT((i===`search`||Le)&&Lr?Fr:Pr,Ir,Ut,Ar,jr),[i,Ut,Lr,Ir,Pr,Fr,jr,Ar,Le]),zr=Pr.some(e=>e.agents.length>0||e.agentSessions.length>0),Br=(0,W.useMemo)(()=>Lr?Rr:[],[Rr,Lr]),Vr=(0,W.useMemo)(()=>mT(Rr,Vt,Ir),[Vt,Rr,Ir]),Hr=(0,W.useMemo)(()=>Lr?Vr:[],[Lr,Vr]),Ur=(0,W.useMemo)(()=>{let e=new Map;return x&&b.forEach((t,n)=>{e.set(t,n)}),e},[b,x]),Wr=(0,W.useMemo)(()=>v.map(e=>Y.find(t=>t.id===e)??(yr?.id===e?yr:null)).filter(e=>!!e),[Y,yr,v]),Gr=(0,W.useMemo)(()=>Wr.find(e=>e.id===l)??Wr[0]??null,[l,Wr]),Kr=Gr?[Gr]:[],Z=(0,W.useMemo)(()=>Y.find(e=>e.id===l)??(yr?.id===l?yr:null),[Y,l,yr]),qr=!!(Z&&Z.id===p),Jr=Z?c[Z.id]??null:null,Yr=Z?.agentRuntimeMode===`acp`?bw(Z):Z?KC(Z):``,Xr=(0,W.useMemo)(()=>lC(Z),[Z]),Zr=Yr?me[Yr]??(Z?(Z.agentRuntimeMode===`acp`?xw(Z):qC(Z)).map(e=>me[e]).find(Boolean):void 0)??RC:RC,Qr=Zr.draft,$r=Zr.attachments,ei=Zr.mode,{plusMenuOpen:ti,approvalMenuOpen:ni,modelMenuOpen:ri,modelPickerPane:ii}=Zr.ui,ai=(0,W.useMemo)(()=>Sb(Z),[Z]),oi=(0,W.useMemo)(()=>bb(Z),[Z]),si=Xr.kind,ci=(0,W.useMemo)(()=>XE(!!(Z&&si===`codex`),Z?.launchPermissionMode,et),[Z,et,si]),li=(0,W.useMemo)(()=>ZE(!!(Z&&si===`claude`),Z?.launchPermissionMode,pt),[Z,pt,si]),ui=(0,W.useMemo)(()=>ai||!!Z&&Z?.status===`running`&&si===`shell`&&oi.terminalBusy,[Z,oi.terminalBusy,ai,si]),di=(0,W.useMemo)(()=>cC([...sC(si),...St]),[si,St]),fi=Zr.pendingFollowUp;(0,W.useEffect)(()=>{!l||ye!==`terminal`||i!==`projects`||De(l)},[l,i,ye,De]),(0,W.useEffect)(()=>{!G||ye!==`editor`||i!==`projects`||U({agentId:G.agentId,filePath:G.file.path,view:G.diffRequestId?`diff`:`editor`,lineNumber:G.cursor?.lineNumber,column:G.cursor?.column,endColumn:G.cursor?.endColumn})},[i,ye,G?.agentId,G?.cursor?.column,G?.cursor?.endColumn,G?.cursor?.lineNumber,G?.cursor?.requestId,G?.diffRequestId,G?.file.path,U]);let pi=ow($r).length>0,mi=$r.some(e=>e.status===`uploading`),hi=Z&&!mi&&(Qr.trim()||pi)?`send`:ui?`interrupt`:`disabled`,gi=Z?.agentRuntimeMode===`acp`?hi:`disabled`,_i=(0,W.useCallback)(e=>{Yr&&H(Yr,e)},[Yr,H]),vi=(0,W.useCallback)(()=>{_i(HC)},[_i]),yi=(0,W.useMemo)(()=>Y.find(e=>e.id===tn?.agentId)??null,[Y,tn?.agentId]),bi=(0,W.useMemo)(()=>Nr.find(e=>e.id===rn?.projectId)??null,[Nr,rn?.projectId]),xi=(0,W.useMemo)(()=>Rr.flatMap(e=>e.agentSessions).find(e=>e.provider===on?.provider&&Rb(e)===on?.sessionId)??null,[on?.provider,on?.sessionId,Rr]),Si=Le?Hr[We]??null:null,Ci=Si?.kind===`agent`?Si.id:null,wi=Si?.kind===`agent-session`?Rb(Si):null,Ti=Z?Ab(Z):void 0,Ei=(0,W.useMemo)(()=>{if(G)return Y.find(e=>e.id===G.agentId&&!e.isMain)??null;if(Z&&!Z.isMain)return Z;if(Ti){let e=Y.find(e=>!e.isMain&&Ab(e)===Ti);if(e)return e}return Y.find(e=>!e.isMain)??null},[Z,Y,Ti,G]),Di=(0,W.useCallback)(e=>{if(!(e instanceof Element))return null;let t=e.closest(`[data-testid="code-agent-row"][data-agent-id], [data-testid="code-project-agent-compact"][data-agent-id], [data-testid="code-pinned-agent-compact"][data-agent-id], [data-testid="code-agent-rail-item"][data-agent-id]`)?.dataset.agentId;if(t){let e=Y.find(e=>e.id===t&&!e.isMain);if(e)return e}let n=e.closest(`[data-testid="code-project-group"]`)?.querySelector(`[data-testid="code-project-title"][data-project-id]`)?.dataset.projectId;return n?Y.find(e=>!e.isMain&&Ab(e)===n)??null:null},[Y]),Oi=Z?.isMain?$t??Pr[0]?.workspace:Ti??$t??Pr[0]?.workspace,ki=ye===`editor`&&!!G,Ai=(0,W.useMemo)(()=>{if(ki&&G){let e=G.workspaceRoot??Y.find(e=>e.id===G.agentId)?.projectWorkspace??Y.find(e=>e.id===G.agentId)?.cwd??``;return{kind:`file`,agentId:G.agentId,filePath:G.file.path,...e?{absolutePath:w(e,G.file.path)}:{},...e?{projectLabel:j(e)}:{},view:G.diffRequestId?`diff`:`editor`,lineNumber:G.cursor?.lineNumber,column:G.cursor?.column,endColumn:G.cursor?.endColumn}}return l&&br.has(l)?{kind:`agent`,agentId:l}:null},[l,G?.agentId,G?.cursor?.column,G?.cursor?.endColumn,G?.cursor?.lineNumber,G?.diffRequestId,G?.file.path,G?.workspaceRoot,ki,Y,br]),{agentModelOptions:ji,agentModel:Mi,agentReasoningEffort:Ni,agentServiceTier:Pi,agentModelPreset:Fi,currentReasoningOptions:Ii,currentServiceTierOptions:Li,currentPermissionMode:Ri,currentPermissionLabel:zi,currentPermissionColor:Bi,currentModelLabel:Vi,currentReasoningLabel:Hi,currentSpeedLabel:Ui,permissionModeOptions:Wi}=(0,W.useMemo)(()=>uD({agentKind:si,codexModel:at,codexReasoningEffort:st,codexServiceTier:lt,codexModelPreset:rt,codexModelOptions:dt,codexApprovalMode:ci,claudeModel:ht,claudeEffort:_t,claudeSettings:yt,claudePermissionMode:li}),[_t,ht,yt,li,ci,at,dt,rt,st,lt,si]),Gi=DD(),Ki=Le||i===`search`?J.search:i===`history`?J.history:ki&&G?kb(G.file.path):Z?h(Z):J.codex,qi=Z?.isMain?`farming`:eO(Z?Ab(Z):void 0),Ji=Z?`${qi} · ${Gi}`:Gi,Yi=ki&&G?G.sourceAgentId??G.agentId:null,Xi=!!Yi,Zi=(0,W.useCallback)(()=>{let e=An.current;if(!e)return;e.style.height=`auto`;let t=Math.min(e.scrollHeight,132);e.style.height=`${t}px`,e.style.overflowY=e.scrollHeight>132?`auto`:`hidden`},[]),Qi=(0,W.useCallback)(()=>{IE(()=>{document.querySelector(`.code-composer-menu`)||(An.current??document.querySelector(`[data-testid="code-composer-input"]`))?.focus({preventScroll:!0})},{delays:[60]})},[]),$i=(0,W.useCallback)(e=>{let t=lD(e);nt(t.codexApprovalMode),ot(t.codexModel),ct(t.codexReasoningEffort),ut(t.codexServiceTier),it(t.codexModelPreset),mt(t.claudePermissionMode),gt(t.claudeModel),vt(t.claudeEffort)},[]),ea=(0,W.useCallback)(()=>{let e=!1,t=lr.current;return fetch(n(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};t===lr.current&&$e(new Set(kS(r.mainPageSessionKeys??[]))),Ye(kD(r.projectNames)),$i(r)}).catch(()=>{}),()=>{e=!0}},[$i]),ta=(0,W.useCallback)(()=>{if(Xn.current||Zn.current)return()=>{};let e=!1;return Zn.current=!0,fetch(n(`/api/codex/models`)).then(e=>e.json()).then(t=>{if(e)return;let n=Lb(t);Xn.current=!0,n.length>0&&ft(n)}).catch(()=>{}).finally(()=>{Zn.current=!1}),()=>{e=!0}},[]),na=(0,W.useCallback)(()=>{let e=!1;return fetch(n(`/api/claude/settings`)).then(e=>e.json()).then(t=>{e||xt(rD(t.settings))}).catch(()=>{e||xt(qE)}),()=>{e=!0}},[]),ra=(0,W.useCallback)(async(e,t)=>{let r=new URLSearchParams({q:e,limit:String(UD),fresh:`1`}),i=await fetch(n(`/api/agent-sessions/search?${r.toString()}`),{signal:t,cache:`no-store`});if(!i.ok)throw Error(`Failed to search Agent sessions: ${i.status}`);let a=await i.json();return Array.isArray(a.sessions)?a.sessions:[]},[]),ia=(0,W.useCallback)(async(e,t)=>bD(AS(await ra(e,t),Ft,{}),Qe,Sr.claimedAgentSessionKeys),[Sr.claimedAgentSessionKeys,Ft,ra,Qe]),aa=(0,W.useCallback)(async(e={})=>{let t=new URLSearchParams({limit:String(e.limit||HD)});e.cursor&&t.set(`cursor`,e.cursor),e.fresh&&t.set(`fresh`,`1`);let r=await(await fetch(n(`/api/agent-sessions?${t.toString()}`),{cache:e.fresh?`no-store`:`default`})).json();return{sessions:Array.isArray(r.sessions)?r.sessions:[],nextCursor:typeof r.nextCursor==`string`?r.nextCursor:``,hasMore:r.hasMore===!0}},[]),oa=(0,W.useCallback)((e=!1)=>{let t=!1;return aa({fresh:e}).then(e=>{t||(Tt(e.sessions),Dt(e.nextCursor),kt(e.hasMore),Pt.current=Math.max(HD,e.sessions.length))}).catch(()=>{t||(Tt([]),Dt(``),kt(!1))}),()=>{t=!0}},[aa]),sa=(0,W.useCallback)(()=>{aa({limit:Pt.current,fresh:!0}).then(e=>{Tt(e.sessions),Dt(e.nextCursor),kt(e.hasMore)}).catch(()=>Tt([]))},[aa]),ca=(0,W.useCallback)(()=>{!Ot||!Et||Nt.current||(Nt.current=!0,aa({cursor:Et}).then(e=>{Tt(t=>{let n=new Set(t.map(Rb)),r=[...t];return e.sessions.forEach(e=>{let t=Rb(e);n.has(t)||(n.add(t),r.push(e))}),Pt.current=Math.max(HD,r.length),r}),Dt(e.nextCursor),kt(e.hasMore)}).catch(()=>{}).finally(()=>{Nt.current=!1}))},[Et,Ot,aa]);(0,W.useEffect)(()=>{if(!((i===`search`||Le)&&Lr)){q([]),Mt(!1);return}let e=new AbortController;q([]),Mt(!0);let t=window.setTimeout(()=>{ra(Ir,e.signal).then(q).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||q([])}).finally(()=>{e.signal.aborted||Mt(!1)})},WD);return()=>{window.clearTimeout(t),e.abort()}},[i,ra,Lr,Ir,Le]);let la=(0,W.useCallback)((e,t)=>{if(e!==`codex`&&e!==`claude`)return Ct([]),()=>{};let r=!1,i=new URLSearchParams({provider:e});return t&&i.set(`workspace`,t),fetch(n(`/api/slash-commands?${i.toString()}`)).then(e=>e.json()).then(e=>{r||Ct(Array.isArray(e.commands)?e.commands:[])}).catch(()=>{r||Ct([])}),()=>{r=!0}},[]),ua=(0,W.useCallback)(()=>{Yr&&(_i(e=>({...e,ui:{...e.ui,plusMenuOpen:!1}})),Pn.current?.click())},[Yr,_i]),da=(0,W.useCallback)((e,t)=>{let n=rw(t),r=$C(t,`pasted image`),i=iw(t),a={id:n,kind:`image`,name:r,type:t.type||`image/png`,size:t.size,status:`uploading`,previewUrl:i};H(e,e=>({...e,attachments:[...e.attachments,a]})),dw(t).then(t=>{he(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,name:r,type:t.type||e.type,size:t.size||e.size,status:`ready`,path:t.path,messageBlock:nw({...t,name:r}),error:void 0}:e)}))}).catch(()=>{he(e,e=>({...e,attachments:e.attachments.map(e=>e.id===n?{...e,status:`error`,messageBlock:pw(t),error:`Upload failed`}:e)}))})},[H,he]),fa=(0,W.useCallback)(async e=>{if(!Yr||e.length===0)return;e.filter(ew).forEach(e=>da(Yr,e));let t=e.filter(e=>!ew(e));if(t.length===0){Qi();return}let n=[];for(let e of t)try{n.push(await fw(e))}catch{n.push(pw(e))}H(Yr,e=>({...e,draft:QC(e.draft,n.join(`
123
123
 
124
- `))})),Qi()},[Yr,da,Qi,H]),pa=(0,W.useCallback)(e=>{_i(t=>{let n=t.attachments.find(t=>t.id===e);return n&&aw(n),{...t,attachments:t.attachments.filter(t=>t.id!==e)}}),Qi()},[Qi,_i]),ma=(0,W.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value=``,fa(t)},[fa]),ha=(0,W.useCallback)(e=>{let t=mw(e.clipboardData);t.length!==0&&(e.preventDefault(),fa(t))},[fa]);(0,W.useEffect)(()=>{let e=Pn.current;if(e)return e.addEventListener(`cancel`,Qi),()=>e.removeEventListener(`cancel`,Qi)},[Qi]),(0,W.useEffect)(()=>{jn.current=Object.values(me).flatMap(e=>e.attachments)},[me]),(0,W.useEffect)(()=>()=>{jn.current.forEach(aw)},[]);let ga=(0,W.useCallback)(e=>{_i(t=>({...t,mode:e,ui:{...t.ui,plusMenuOpen:!1}})),Qi()},[Qi,_i]),_a=(0,W.useCallback)(e=>{let t=Y.find(t=>t.id===e);if(!t)return;let n=Number.isFinite(t.attentionSeq)?Math.max(0,Number(t.attentionSeq)):0;n>(Number.isFinite(t.readAttentionSeq)?Math.max(0,Number(t.readAttentionSeq)):0)?F(e,{readAttentionSeq:n}):t.unread&&F(e,{unread:!1})},[Y,F]),va=(0,W.useCallback)((e,t)=>{ve(n=>{let r=n[e];return r?.following===t.following&&r?.hasUnreadOutput===t.hasUnreadOutput?n:{...n,[e]:t}}),e===l&&i===`projects`&&ye===`terminal`&&t.following&&!t.hasUnreadOutput&&_a(e)},[l,i,ye,_a]);(0,W.useEffect)(()=>{if(!l||i!==`projects`||ye!==`terminal`)return;let e=_e[l];e&&e.following&&!e.hasUnreadOutput&&_a(l)},[l,i,ye,_a,_e]);let ya=(0,W.useCallback)(e=>{_i(t=>({...t,draft:e,history:{...t.history,cursor:null}}))},[_i]),ba=(0,W.useCallback)((e,t)=>{if(!Z||!Yr||!FC(t))return null;let n=IC(Zr.history,e,t.value);return n.changed?(H(Yr,e=>({...e,draft:n.value,history:n.history})),n.value):null},[Z,Yr,Zr.history,H]),xa=(0,W.useCallback)((e,t,n,r)=>{if(!Z||si!==`codex`||[`acp`,`json`].includes(Z.agentRuntimeMode||``)||Z.codexRuntimeMode===`app-server`)return;let i=dt.findIndex(t=>t.value===e),a=dt[i],o=a?.reasoningLevels||[],s=o.findIndex(e=>e.value===t);if(i<0||s<0)return;let c=Mn.current[Z.id],l=!!a?.serviceTiers?.some(e=>e.value===`priority`);Mn.current[Z.id]={model:e,effort:t,modelIndex:i,reasoningIndex:s,reasoningCount:o.length,fast:n===`priority`,fastAvailable:l,applyModel:!!(r.applyModel||c?.applyModel),applyFast:!!(r.applyFast||c?.applyFast)}},[Z,dt,si]),Sa=(0,W.useCallback)((e,t,n)=>{let r=jE(t,n),i=t=>{let n=r[t];if(!n||!se(n.input,e.id))return!1;let a=r[t+1];if(a){let e=window.setTimeout(()=>{Nn.current=Nn.current.filter(t=>t!==e),i(t+1)},a.delayMs-n.delayMs);Nn.current.push(e)}return!0};return i(0)?(delete Mn.current[e.id],!0):!1},[se]),Ca=(0,W.useCallback)((e,t,n=[])=>{if([`acp`,`json`].includes(e.agentRuntimeMode||``)||e.providerSessionProvider===`codex`&&e.codexRuntimeMode===`app-server`)return ce(t,e.id,e.agentRuntimeMode===`acp`?n:[]);if(rb(e.command)===`codex`){let n=Mn.current[e.id];if(n)return Sa(e,n,t)}return rb(e.command)===`shell`||lC(e).kind===`shell`||KD(e.command)?se(`${t}\r`,e.id):se(kE(t),e.id)},[Sa,ce,se]),wa=(0,W.useCallback)(async(e,t)=>(await fetch(n(`/api/agents/${encodeURIComponent(e.id)}/codex-goal`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({objective:t,status:`active`,tokenBudget:null})})).ok,[]),Ta=(0,W.useCallback)(e=>{let t=e??An.current?.value??Qr,n=sw(t,$r);if(!n||!Z||!Yr||$r.some(e=>e.status===`uploading`))return;if(ei===`goal`&&Z.providerSessionProvider===`codex`&&Z.codexRuntimeMode===`app-server`){(async()=>{await wa(Z,n)&&Ca(Z,n)&&(H(Yr,e=>(e.attachments.forEach(aw),{...e,draft:``,attachments:[],mode:`default`,history:PC(e.history,t)})),Qi())})();return}let r=hw(ei,n),i=!0;xb(Z)&&Z.codexRuntimeMode!==`app-server`&&![`acp`,`json`].includes(Z.agentRuntimeMode||``)?H(Yr,e=>{let t=e.pendingFollowUp;return{...e,pendingFollowUp:{messages:[...t?.messages||[],BC(r)],createdAt:t?.createdAt||Date.now()}}}):i=Ca(Z,r),i&&(H(Yr,e=>(e.attachments.forEach(aw),{...e,draft:``,attachments:[],mode:`default`,history:PC(e.history,t)})),Qi())},[Z,Yr,$r,ei,Qr,Qi,Ca,wa,H]),Ea=(0,W.useCallback)(e=>{gw({agent:Z,composerKey:Yr,draft:e??An.current?.value??Qr,attachments:$r,composerMode:ei,turnActive:ai,sendMessage:Ca,updateComposerState:H})&&Qi()},[Z,ai,Yr,$r,ei,Qr,Qi,Ca,H]),Da=(0,W.useCallback)(()=>{!Z||!ui||(oe(Z.id),Qi())},[Z,ui,Qi,oe]),Oa=(0,W.useCallback)((e,t)=>{Z&&le(Z.id,e,t)},[Z,le]),ka=(0,W.useCallback)(e=>{Z&&le(Z.id,e,void 0,{reject:!0,reason:`Declined in Farming`})},[Z,le]),Aa=(0,W.useCallback)((e,t,n)=>{Z&&_w(Z.id,e,t,n===!0)},[Z]),ja=(0,W.useCallback)((e,t,n)=>{Z&&vw(Z.id,e,t,n)},[Z]),Ma=(0,W.useCallback)(e=>{if(!Z||!Yr)return;let t=me[Yr]?.pendingFollowUp;if(!t||t.messages.length===0)return;let n=t.messages.find(t=>t.id===e);n&&Ca(Z,n.text,n.attachments)&&(ge.current[Yr]=n.id,H(Yr,t=>t.pendingFollowUp?{...t,pendingFollowUp:VC(t.pendingFollowUp,e)}:t),Qi())},[Z,Yr,me,Qi,Ca,H]),Na=(0,W.useCallback)(e=>{!Z||!Yr||(H(Yr,t=>t.pendingFollowUp?{...t,pendingFollowUp:VC(t.pendingFollowUp,e)}:t),Qi())},[Z,Yr,Qi,H]);(0,W.useEffect)(()=>{let e=[];Y.forEach(t=>{let n=t.agentRuntimeMode===`acp`?bw(t):KC(t);if(!n)return;let r=me[n]?.pendingFollowUp;if(!r||r.messages.length===0){delete ge.current[n];return}if(t.archived||t.status===`dead`||t.status===`stopped`)return;if(t.agentRuntimeMode===`acp`?Sb(t):xb(t)){delete ge.current[n];return}if(ge.current[n])return;let i=r.messages[0];i&&e.push({agent:t,composerKey:n,message:i})}),e.length!==0&&e.forEach(({agent:e,composerKey:t,message:n})=>{Ca(e,n.text,n.attachments)&&(ge.current[t]=n.id,he(t,e=>e.pendingFollowUp?{...e,pendingFollowUp:VC(e.pendingFollowUp,n.id)}:e))})},[Y,me,Ca,he]);let Pa=(0,W.useCallback)(()=>{nn(null),an(null),sn(null),ln(null),vi(),gr(),V(`search`),Be(!0),requestAnimationFrame(()=>Rn.current?.focus())},[vi,gr,V]),Fa=(0,W.useCallback)(()=>{XD()&&hr()},[hr]),Ia=(0,W.useCallback)(()=>{gr()},[gr]),La=(0,W.useCallback)((e,t,n)=>{j(e,t,n),Fa()},[Fa,j]),Ra=(0,W.useCallback)((e,t,n)=>{if(Ue(``),Be(!1),Ge(0),be(`terminal`),V(`projects`),rb(e)!==`codex`){N(e,t,n);return}let r=n?.codexApprovalMode||et;N(e,t,{...n,codexApprovalMode:r,...r===`full`?{dangerouslySkipPermissions:!0}:{}})},[et,N,V]);(0,W.useEffect)(()=>{let e=!1;return fetch(n(`/api/executables`)).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(t=>{e||Ze(Je(Array.isArray(t)?t:t.agents??[]))}).catch(()=>{e||Ze([])}),()=>{e=!0}},[]);let za=(0,W.useCallback)(e=>{fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mainPageSessionKeys:kS(e)})}).catch(()=>{})},[]),Ba=(0,W.useCallback)(e=>{$e(t=>{let n=kS(e(t));return jD(t,n)?t:(lr.current+=1,za(n),new Set(n))})},[za]);(0,W.useEffect)(()=>{let e=kS(r);$e(t=>jD(t,e)?t:new Set(e))},[r]);let Va=(0,W.useCallback)((e,t,n=``)=>{let r=Rb({provider:e,id:t,providerHomeId:n});Ba(e=>[...e,r])},[Ba]),Ha=(0,W.useCallback)(e=>{Ba(t=>Array.from(t).filter(t=>t!==e))},[Ba]),Ua=(0,W.useCallback)(e=>{let t=new Set(e);Ba(e=>Array.from(e).filter(e=>!t.has(e)))},[Ba]),Wa=(0,W.useCallback)(e=>{Promise.resolve(e).then(e=>{if(!e||typeof e!=`object`)return;let t=Array.isArray(e.removedMainPageSessionKeys)?e.removedMainPageSessionKeys:[];t.length>0&&Ua(t)}).catch(()=>{})},[Ua]);(0,W.useEffect)(()=>{Y.forEach(e=>{if(e.providerSessionTemporary===!0)return;let t=e.providerSessionKey||NS(e.source);if(!t)return;let n=`${e.id}:${t}`;ur.current.has(n)||(ur.current.add(n),Ba(e=>[...e,t]),sa())})},[Y,sa,Ba]),(0,W.useEffect)(()=>{if(!pe||!Y.some(e=>e.providerSessionTemporary===!0))return;sa();let e=window.setInterval(sa,5e3);return()=>window.clearInterval(e)},[Y,pe,sa]);let Ga=(0,W.useCallback)(()=>{let e=$n.current,t=Array.from(kn.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`)??[]),n=(e?t.find(t=>t.dataset.agentId===e):null)??t[0]??Gn.current;return n?(n.focus({preventScroll:!0}),document.activeElement===n):!1},[]),Ka=(0,W.useCallback)(e=>{let t=Array.from(kn.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`)??[]).find(t=>e.kind===`agent`?t.dataset.agentId===e.id:t.dataset.provider===e.provider&&t.dataset.sessionId===YD(e));return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),qa=(0,W.useCallback)(()=>{if(a||document.querySelector(`.code-context-menu`)||document.querySelector(`.code-composer.menu-open, .code-composer-menu`))return!0;let e=document.activeElement;return e instanceof HTMLElement?e.closest(`.code-context-menu`)?!0:e===document.body||e===document.documentElement||Gn.current?.contains(e)||e.closest(`.code-sidebar`)?!1:!!e.closest(`.code-composer`):!1},[a]),Ja=(0,W.useCallback)(e=>{window.requestAnimationFrame(()=>{e?.skipIfFocusMoved&&qa()||Ga()})},[Ga,qa]),Ya=(0,W.useCallback)(()=>{Ue(``),Be(!1),Ge(0)},[]),Xa=(0,W.useCallback)(()=>{Ya(),V(`projects`),or.current=`active-force`},[Ya,V]);(0,W.useEffect)(()=>{if(!Le||i!==`search`)return;let e=e=>{let t=e.target;t instanceof Element&&(t.closest(`.code-search-panel, [data-testid="code-nav-search"], [data-testid="code-mobile-menu"]`)||Xa())};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[i,Xa,Le]);let Za=(0,W.useCallback)(e=>{nn(null),an(null),sn(null),ln(null),e===`projects`?(gr(),Ya()):e!==`search`&&Ya(),V(e)},[Ya,gr,V]),Qa=(0,W.useCallback)(()=>{Pa(),Fa()},[Fa,Pa]),$a=(0,W.useCallback)(e=>{Za(e),Fa()},[Fa,Za]),eo=(0,W.useCallback)(e=>{Ht(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),to=(0,W.useCallback)(e=>{Wt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),no=(0,W.useCallback)((e,t)=>{be(`terminal`),V(`projects`),e.kind===`agent`?E(e.id,{focusTerminal:t?.focusTerminal}):Qn.current(e.provider,e.id,e.providerHomeId)},[E,V]),Q=(0,W.useCallback)(()=>{let e=document.activeElement;if(e instanceof HTMLElement){let t=e.closest(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`);if(t?.dataset.agentId)return Ob({kind:`agent`,id:t.dataset.agentId});if(t?.dataset.sessionId&&t.dataset.provider)return t.dataset.sessionId}let t=$n.current;return t?Ob({kind:`agent`,id:t}):``},[]),ro=(0,W.useCallback)(e=>{if(Vr.length===0)return;let t=Q(),n=Vr.findIndex(e=>YD(e)===t),r=Vr[((n===-1?e>0?-1:0:n)+e+Vr.length)%Vr.length];r&&(no(r,{focusTerminal:!1}),r.kind===`agent`&&(qa()||Ka(r),window.requestAnimationFrame(()=>{qa()||Ka(r)})),or.current=`active`)},[Q,Ka,no,qa,Vr]),io=(0,W.useCallback)(e=>{if(!(e.ctrlKey||e.metaKey||e.altKey)){if(e.key===`/`&&!e.shiftKey){e.preventDefault(),Pa();return}if(e.key===`ArrowDown`){e.preventDefault(),ro(1);return}e.key===`ArrowUp`&&(e.preventDefault(),ro(-1))}},[ro,Pa]),ao=(0,W.useCallback)(e=>{Hr.length!==0&&Ge(t=>(t+e+Hr.length)%Hr.length)},[Hr.length]),oo=(0,W.useCallback)(()=>{Si&&(no(Si),Ya())},[Ya,no,Si]),so=(0,W.useCallback)(e=>{if(e.key===`Escape`){e.preventDefault(),Xa();return}if(e.key===`ArrowDown`){e.preventDefault(),ao(1);return}if(e.key===`ArrowUp`){e.preventDefault(),ao(-1);return}e.key===`Enter`&&(e.preventDefault(),oo())},[Xa,ao,oo]),co=(0,W.useCallback)(e=>{let t=e-(kn.current?.getBoundingClientRect().left??0);if(t<=LD){mr();return}let n=Math.max(PD,Math.min(FD,t));gr(),Kt(n)},[mr,gr]),lo=(0,W.useCallback)(e=>{let t=Array.from(kn.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"]`)??[]).find(t=>t.dataset.agentId===e);return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),uo=(0,W.useCallback)(e=>{IE(()=>{lo(e)},{delays:[80,180]})},[lo]),fo=(0,W.useCallback)((e,t)=>{window.requestAnimationFrame(()=>{Array.from(kn.current?.querySelectorAll(`[data-testid="code-active-session-row"]`)??[]).find(n=>n.dataset.provider===e&&n.dataset.sessionId===t)?.focus({preventScroll:!0})})},[]),po=(0,W.useCallback)(e=>{window.requestAnimationFrame(()=>{Array.from(kn.current?.querySelectorAll(`[data-testid="code-project-title"]`)??[]).find(t=>t.dataset.projectId===e)?.focus()})},[]),mo=(0,W.useCallback)(async()=>{if(!xi)return;let e=Rb(xi),t=xi.pinned!==!0;It(n=>({...n,[e]:t})),sn(null),ln(null),Qe.has(e)?fo(xi.provider,e):window.requestAnimationFrame(()=>Gn.current?.focus({preventScroll:!0}));try{if(!(await fetch(n(`/api/agent-sessions/${encodeURIComponent(xi.provider)}/${encodeURIComponent(xi.id)}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t,providerHomeId:xi.providerHomeId||`default`})})).ok)throw Error(J.updateFailed);let r=await aa({limit:Pt.current});Tt(r.sessions),Dt(r.nextCursor),kt(r.hasMore),It(t=>{let n={...t};return delete n[e],n})}catch(n){It(n=>({...n,[e]:!t})),xn({id:Date.now(),kind:`error`,message:n instanceof Error?n.message:J.updateFailed})}},[xi,J.updateFailed,aa,fo,Qe]),ho=(0,W.useCallback)(()=>{if(!xi)return;let e=Rb(xi);It(t=>({...t,[e]:!1})),Ha(e),sn(null),ln(null),window.requestAnimationFrame(()=>Gn.current?.focus({preventScroll:!0}))},[xi,Ha]),go=(0,W.useCallback)(e=>{e.preventDefault(),gr(),dr.current=!0,document.body.classList.add(`code-resizing-sidebar`),co(e.clientX)},[gr,co]),_o=(0,W.useCallback)((e,t)=>{nn(null),an(null),sn(null),ln(null),Ya(),be(`terminal`),V(`projects`),E(e,t)},[Ya,E,V]),vo=(0,W.useCallback)(e=>{_o(e),Fa()},[Fa,_o]),yo=(0,W.useCallback)(e=>d(e,{cursorRequestId:e?.lineNumber?er.current+=1:er.current,diffRequestId:e?.view===`diff`?tr.current+=1:tr.current}),[]),bo=(0,W.useCallback)((e,t,n)=>{let r=Oe(e),i=n?.sourceAgentId??(r?$n.current??void 0:e),a=Y.find(t=>t.id===(r?i:e)),o=r?`/`:a&&!a.isMain?Ab(a):void 0;if(!r&&a){let e=a.isMain?Tb:Ab(a);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`editor`);let s={...yo(n),workspaceRoot:o,sourceAgentId:i};we.openFromRead(e,t,s),u(n)&&Cn({agentId:e,path:t.path,kind:`file`,requestId:nr.current+=1}),a&&i&&E(i,{focusTerminal:!1}),Fa()},[Y,Ya,Fa,yo,E,V,we]);(0,W.useEffect)(()=>{if(Ce.current||Se.current||Y.length===0)return;Se.current=!0;let e=xe;if(!e){Ce.current=!0;return}if(e.kind===`agent`){let t=Y.find(t=>t.id===e.agentId)??Y.find(t=>!!e.providerSessionKey&&t.providerSessionKey===e.providerSessionKey)??Y.find(t=>!!e.workspace&&Ab(t)===e.workspace);t?_o(t.id,{focusTerminal:!1}):D({surface:void 0}),Ce.current=!0;return}let t=e.workspace===`/`?ke:Y.find(t=>Ab(t)===e.workspace)?.id;if(!t){D({surface:void 0}),Ce.current=!0;return}z(t,e.filePath).then(n=>{bo(t,n,{view:e.view??`editor`,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,revealInTree:!0,sourceAgentId:e.sourceAgentId})}).catch(()=>{D({surface:void 0})}).finally(()=>{Ce.current=!0})},[Y,xe,bo,_o]),(0,W.useEffect)(()=>{if(!Ce.current||i!==`projects`)return;if(ye===`terminal`){let e=Y.find(e=>e.id===l);if(!e)return;D({surface:{kind:`agent`,agentId:e.id,providerSessionKey:e.providerSessionKey||void 0,workspace:Ab(e)}});return}if(!G)return;let e=G.workspaceRoot??Y.find(e=>e.id===G.agentId)?.projectWorkspace??Y.find(e=>e.id===G.agentId)?.cwd??``;e&&D({surface:{kind:`file`,workspace:e,filePath:G.file.path,view:G.diffRequestId?`diff`:`editor`,lineNumber:G.cursor?.lineNumber,column:G.cursor?.column,endColumn:G.cursor?.endColumn,sourceAgentId:G.sourceAgentId}})},[Y,l,i,ye,G]);let xo=(0,W.useCallback)((e,t)=>{let n=Y.find(t=>t.id===e);if(!Oe(e)&&n){let e=n.isMain?Tb:Ab(n);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}nn(null),an(null),sn(null),ln(null),Ya(),gr(),V(`projects`),Tn({agentId:e,...t?{query:t}:{},requestId:rr.current+=1})},[Y,Ya,gr,V]),So=(0,W.useCallback)((e,t,n)=>{let r=Y.find(t=>t.id===e);if(!Oe(e)&&r){let e=r.isMain?Tb:Ab(r);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}nn(null),an(null),sn(null),ln(null),Ya(),gr(),V(`projects`),Cn({agentId:e,path:t,kind:n,requestId:nr.current+=1})},[Y,Ya,gr,V]),Co=(0,W.useCallback)(async(e,t)=>{let n=Y.find(t=>t.id===e),r=gv(t.path,n?Ab(n):``);if(!r)return null;try{let n=nO((await I(e,r,{limit:zD})).matches),i=n.find(e=>e.path===r)?.path??(n.length===1?n[0]?.path:``);return i?{...t,path:i}:null}catch{return null}},[Y]),wo=(0,W.useCallback)((e,t)=>{let n=Y.find(t=>t.id===e),r=gv(t.path,n?Ab(n):``);if(!r)return;let i=ir.current+1;ir.current=i;let a=tO(t),o=async(t,n=a)=>{let r=await z(e,t);ir.current===i&&bo(e,r,n)},s=t=>{ir.current===i&&So(e,t,`directory`)},c=async e=>{if(e.entryType===`directory`){s(e.path);return}await o(e.path)},l=()=>{ir.current===i&&xo(e,r)};(async()=>{try{await ne(e,r),s(r);return}catch{}try{await o(r);return}catch{}try{let t=await I(e,r,{limit:zD});if(ir.current!==i)return;let n=nO(t.matches);if(n.length===1){let e=n[0];if(!e)return;await c(e);return}let s=rO(t.matches);if(n.length===0&&s.length===1){let e=s[0];if(!e)return;await o(e.path,a??(e.kind===`content`?{lineNumber:e.lineNumber,column:e.ranges[0]?e.ranges[0].start+1:void 0,endColumn:e.ranges[0]?Math.max(e.ranges[0].start+1,e.ranges[0].end+1):void 0}:void 0));return}}catch{}l()})()},[Y,xo,bo,So]),To=(0,W.useCallback)((e,t,n)=>{let r=Oe(e),i=n?.sourceAgentId??(r?$n.current??void 0:e),a=Y.find(t=>t.id===(r?i:e)),o=r?`/`:a&&!a.isMain?Ab(a):void 0;if(!r&&a){let e=a.isMain?Tb:Ab(a);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}let s=f({agentId:e,workspaceRoot:o,filePath:t});if(!Ie.some(e=>m(e)===s))return!1;let c={...yo(n),workspaceRoot:o,sourceAgentId:i};return we.select(e,t,c)?(nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`editor`),u(n)&&Cn({agentId:e,path:t,kind:`file`,requestId:nr.current+=1}),a&&i&&E(i,{focusTerminal:!1}),Fa(),!0):!1},[Y,Ya,Fa,yo,E,V,Ie,we]),Eo=(0,W.useCallback)(async(e,t,n)=>{let r=n?.globalRoot?ke:e,i=n?.globalRoot?Ae(t):t,a=n?.globalRoot?{...n,sourceAgentId:n.sourceAgentId??e}:n;if(To(r,i,a))return;let o=async(e,t=a)=>{bo(r,await z(r,e),t)};try{await o(i,a)}catch{try{await ne(r,i),So(r,i,`directory`)}catch{try{let e=await I(r,i,{limit:zD}),t=nO(e.matches),n=rO(e.matches);if(t.length===1){let e=t[0];if(e?.entryType===`directory`){So(r,e.path,`directory`);return}if(e?.path){await o(e.path,a);return}}if(t.length===0&&n.length===1){let e=n[0];if(e?.path){await o(e.path,a??(e.kind===`content`?{lineNumber:e.lineNumber,column:e.ranges[0]?e.ranges[0].start+1:void 0,endColumn:e.ranges[0]?Math.max(e.ranges[0].start+1,e.ranges[0].end+1):void 0}:void 0));return}}}catch{}a?.suppressSearchOnMiss||xo(r,i)}}},[xo,bo,So,To]),Do=(0,W.useCallback)(async e=>{if(e.kind===`agent`)return br.has(e.agentId)?(nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`terminal`),E(e.agentId,{focusTerminal:!1}),Fa(),!0):!1;let t=O(e,Y.filter(e=>!e.isMain).map(e=>({agentId:e.id,workspace:Ab(e)})),ke);if(!t)return!1;if(e.kind===`folder`)try{let e=C((await ne(t.agentId,t.filePath)).items);if(e){let n=await z(t.agentId,e);return bo(t.agentId,n),!0}return So(t.agentId,t.filePath,`directory`),!0}catch{return!1}let n=M(e);if(To(t.agentId,t.filePath,n))return!0;try{let e=await z(t.agentId,t.filePath);return bo(t.agentId,e,n),!0}catch{return!1}},[Y,Ya,Fa,E,V,bo,So,To,br]),Oo=(0,W.useRef)(Do);Oo.current=Do;let ko=(0,W.useCallback)(()=>{if(typeof window>`u`)return;let e=S(window.location.search);window.history.replaceState(window.history.state,``,`${window.location.pathname}${e}${window.location.hash}`)},[]);(0,W.useEffect)(()=>{if(!Yt)return;let e=!1,t=null,n=Yt.kind===`agent`?Yt.agentId:Yt.absolutePath||(Yt.kind===`folder`?Yt.folderPath:Yt.filePath);return Oo.current(Yt).then(r=>{if(!e){if(r){Xt(null),ko();return}if(ar.current+=1,ar.current>=20){xn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),Xt(null),ko();return}t=window.setTimeout(()=>{Qt(e=>e+1)},250)}}).catch(()=>{e||(xn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),Xt(null),ko())}),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[ko,J.sharedLocationUnavailable,Yt,Zt]);let Ao=(0,W.useCallback)(async e=>{if(!br.has(e.agentId))return!1;if(nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),e.kind===`agent`)return be(`terminal`),E(e.agentId),Fa(),!0;let t={view:e.view,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn};if(To(e.agentId,e.filePath,t))return!0;try{let n=await z(e.agentId,e.filePath);return bo(e.agentId,n,t),!0}catch{return!1}},[Ya,Fa,E,V,bo,To,br]),jo=(0,W.useCallback)(e=>{let t=Me(e);return t?((async()=>{let n=t;for(;n;){if(await Ao(n))return;n=Me(e)}})().finally(()=>{Ne()}),!0):!1},[Me,Ne,Ao]),Mo=(0,W.useCallback)(e=>{be(`terminal`),V(`projects`),E(e,{focusTerminal:!L()}),Fa()},[Fa,E,V]),No=(0,W.useCallback)(e=>{let t=we.close(e);t.closedFiles.length!==0&&t.activeFileClosed&&be(t.activeFile?`editor`:`terminal`)},[we]),Po=(0,W.useCallback)((e,t,n)=>{No([{agentId:e,filePath:t,workspaceRoot:n}])},[No]),Fo=(0,W.useCallback)(()=>{let e=we.reopenLastClosed(e=>Y.some(t=>t.id===e.agentId&&!t.isMain)||Oe(e.agentId))?.activeFile;if(!e)return!1;nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`editor`);let t=Oe(e.agentId)?e.sourceAgentId:e.agentId;return t&&Y.some(e=>e.id===t)&&E(t,{focusTerminal:!1}),Fa(),!0},[Y,Ya,Fa,E,V,we]),Io=(0,W.useCallback)(e=>{we.update(e)},[we]),Lo=(0,W.useCallback)(e=>{we.updateDraft(e)},[we]),Ro=(0,W.useCallback)((e,t)=>{t.length!==0&&we.move(e,t)},[we]),zo=(0,W.useCallback)((e,t)=>{if(t.length===0)return;let n=we.deleteEntries(e,t);n.activeFileDeleted&&(n.activeFile||be(`terminal`))},[we]),Bo=(0,W.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=Y.find(e=>e.id===t),r=Hw(e.clientX,e.clientY,Gw(n));an(null),sn(null),ln(null),nn({agentId:t,x:r.x,y:r.y})},[Y]),Vo=(0,W.useCallback)((e,t)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=Y.find(e=>e.id===t),i=Hw(n.left+24,n.top+n.height,Gw(r));an(null),sn(null),ln(null),nn({agentId:t,x:i.x,y:i.y})},[Y]),Ho=(0,W.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=L()?VD:Vw(2),i=L()?Ww(n,r,void 0,BD):Uw(n,r);nn(null),sn(null),ln(null),an({projectId:t,x:i.x,y:i.y})},[]),Uo=(0,W.useCallback)((e,t)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=L()?VD:Vw(2),i=L()?Ww(n,r,void 0,BD):Uw(n,r);nn(null),sn(null),ln(null),an({projectId:t,x:i.x,y:i.y})},[]),Wo=(0,W.useCallback)((e,t,n)=>{e.preventDefault(),e.stopPropagation();let r=Hw(e.clientX,e.clientY,Vw(3));nn(null),an(null),ln(null),sn({provider:t,sessionId:n,x:r.x,y:r.y})},[]),Go=(0,W.useCallback)((e,t,n)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let r=e.currentTarget.getBoundingClientRect(),i=Hw(r.left+24,r.top+r.height,Vw(3));nn(null),an(null),ln(null),sn({provider:t,sessionId:n,x:i.x,y:i.y})},[]),Ko=(0,W.useCallback)(()=>{if(!yi)return;let e=h(yi);nn(null),ln(null),hn({kind:`agent`,agentId:yi.id,title:e})},[yi]),qo=(0,W.useCallback)(()=>{bi&&(an(null),ln(null),hn({kind:`project`,projectId:bi.id,workspace:bi.workspace,title:bi.name}))},[bi]),Jo=(0,W.useCallback)(()=>{let e=mn;hn(null),e&&(e.kind===`agent`&&uo(e.agentId),e.kind===`project`&&po(e.projectId))},[uo,po,mn]),Yo=(0,W.useCallback)(()=>{if(!mn)return;let e=mn.title.trim();if(mn.kind===`agent`){if(!e)return;P(mn.agentId,e),hn(null),uo(mn.agentId);return}if(!e)return;let t={...qe,[mn.workspace]:e};Ye(t),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectNames:t})}).then(e=>e.json()).then(e=>{Ye(kD((e.settings??{}).projectNames))}).catch(()=>{xn({id:Date.now(),kind:`error`,message:J.copyFailed})}),hn(null),po(mn.projectId)},[J.copyFailed,uo,po,P,qe,mn]),Xo=(0,W.useCallback)(async(e,t)=>{nn(null),an(null),sn(null),ln(null);let n=await iO(e);xn({id:Date.now(),kind:n?`success`:`error`,message:n?J.copiedWorkingDirectory:J.copyFailed}),t?.kind===`agent`&&uo(t.id),t?.kind===`agent-session`&&fo(t.provider,Rb(t))},[J.copiedWorkingDirectory,J.copyFailed,uo,fo]),Zo=(0,W.useCallback)(()=>{yi&&(nn(null),ln(null),_n({agentId:yi.id,title:h(yi)}))},[yi]),Qo=(0,W.useCallback)(()=>{let e=gn?.agentId;_n(null),e&&uo(e)},[uo,gn?.agentId]),$o=(0,W.useCallback)(()=>{gn&&(ae(gn.agentId),_n(null))},[gn,ae]),es=(0,W.useCallback)(e=>{yi&&(nn(null),ln(null),re(yi.id,e))},[yi,re]),ts=(0,W.useCallback)(e=>{if(!yi)return;let t=yi.id;if(nn(null),ln(null),e.archived===!0){let e=yi.providerSessionKey||NS(yi.source);e&&Ha(e),sr.current=t,window.setTimeout(()=>Ga(),120),window.setTimeout(()=>Ga(),360),window.setTimeout(()=>Ga(),720)}let n=F(t,e);e.archived===!0&&Wa(n),e.archived!==!0&&uo(t)},[yi,Ga,uo,F,Ha,Wa]),ns=(0,W.useCallback)((e,t)=>{let n=e.id;if(nn(null),ln(null),t.archived===!0){let t=e.providerSessionKey||NS(e.source);t&&Ha(t),sr.current=n,window.setTimeout(()=>Ga(),120),window.setTimeout(()=>Ga(),360),window.setTimeout(()=>Ga(),720)}let r=F(n,t);t.archived===!0&&Wa(r),t.archived!==!0&&uo(n)},[Ga,uo,F,Ha,Wa]),rs=(0,W.useCallback)(async(e,t,r)=>{try{let i=await fetch(n(`/api/agents/${encodeURIComponent(e)}/reorder`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({beforeAgentId:t,afterAgentId:r})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error||J.reorderAgentFailed)}}catch(e){xn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.reorderAgentFailed})}},[J.reorderAgentFailed]),is=(0,W.useCallback)(e=>{sr.current=null,cr.current=e,F(e,{archived:!1}),Ya(),V(`projects`),[120,360,720,1200,1800].forEach(t=>{window.setTimeout(()=>{qa()||lo(e)},t)})},[Ya,lo,F,V,qa]),as=(0,W.useCallback)(e=>{R(e)},[R]),os=(0,W.useCallback)(async(e,t,r=``,i=``)=>{let a=Rb({provider:e,id:t,providerHomeId:r}),o=()=>{Tt(n=>n.map(n=>n.provider===e&&n.id===t&&(n.providerHomeId||`default`)===(r||`default`)?{...n,archived:!1}:n))},s=Y.find(n=>(n.providerSessionKey===a||n.source===jS(e,t,r))&&n.archived!==!0&&n.status!==`dead`&&n.status!==`stopped`);if(s){o(),Va(e,t,r),E(s.id),Fa();return}try{let a=await fetch(n(`/api/agent-sessions/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resume`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unarchiveArchived:!0,providerHomeId:r,...[`codex`,`claude`,`opencode`,`qoder`].includes(e)?{agentRuntimeMode:`acp`,acpHistoryMode:`load`}:{},...i?{customTitle:i}:{}})}),s=await a.json().catch(()=>null);if(!a.ok||!s?.agentId){xn({id:Date.now(),kind:`error`,message:s?.error||`Failed to resume agent session (${a.status})`});return}o(),Va(e,t,r),te(s.agentId),Fa()}catch(e){xn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to resume agent session`})}},[Y,Va,Fa,E,te]);Qn.current=os;let ss=(0,W.useCallback)(e=>{let t=JD(e.source);if(t){os(t.provider,t.sessionId,t.providerHomeId,e.customTitle||``),V(`projects`);return}j(dT(e),e.command||void 0,null,e.customTitle||void 0)},[j,V,os]),cs=(0,W.useCallback)(e=>{if(e.preventDefault(),e.stopPropagation(),nn(null),an(null),sn(null),!L()){ln(null),dn(!0);return}let t=e.currentTarget.getBoundingClientRect();ln({x:Math.max(8,t.right-164),y:Math.min(window.innerHeight-12,t.bottom+6),returnFocusTarget:e.currentTarget})},[]),ls=(0,W.useCallback)(async()=>{ln(null);try{let e=await fetch(n(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ai?{target:Ai}:{})}),t=await e.json().catch(()=>null);if(!e.ok||!t?.longUrl&&!t?.shortUrl)throw Error(t?.error||J.shareLinkFailed);pn(t.longUrl||t.shortUrl||``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;xn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.shareLinkFailed})}},[J.shareLinkFailed,Ai]),us=(0,W.useCallback)(e=>{ln(null),fe({language:e})},[fe]),ds=(0,W.useCallback)(e=>{ln(null),fe({appearance:e})},[fe]),fs=(0,W.useCallback)(()=>{ln(null),dn(!0)},[]),ps=(0,W.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),ln(null),dn(!0)},[]),ms=(0,W.useMemo)(()=>L()?Ow([{type:`separator`,id:`options-mobile-share-separator`},{type:`item`,id:`options-mobile-share`,label:J.sharePage,ariaLabel:J.sharePage,onSelect:ls}]):Ow([{type:`item`,id:`options-appearance-light`,label:AD(J.appearanceLight),ariaLabel:J.appearanceLight,checked:T.appearance===`light`,onSelect:()=>ds(`light`)},{type:`item`,id:`options-appearance-dark`,label:AD(J.appearanceDark),ariaLabel:J.appearanceDark,checked:T.appearance===`dark`,onSelect:()=>ds(`dark`)},{type:`separator`,id:`options-appearance-language-separator`},{type:`item`,id:`options-language-en`,label:OD(J.languageEnglish),ariaLabel:J.languageEnglish,checked:T.language===`en`,onSelect:()=>us(`en`)},{type:`item`,id:`options-language-zh`,label:OD(J.languageChinese),ariaLabel:J.languageChinese,checked:T.language===`zh`,onSelect:()=>us(`zh`)},{type:`separator`,id:`options-settings-separator`},{type:`item`,id:`options-open-settings`,label:J.openSettings,ariaLabel:J.openSettings,onSelect:fs}]),[J.appearanceDark,J.appearanceLight,J.languageChinese,J.languageEnglish,J.openSettings,J.sharePage,fs,ls,T.appearance,T.language,ds,us]),hs=(0,W.useCallback)((e,t)=>{fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentLaunchProfiles:{[e]:t}})}).catch(()=>{})},[]),gs=(0,W.useCallback)(e=>{if(p)return;if(si===`claude`){let t=YE(e)?e:`default`;mt(t),hs(`claude`,{permissionMode:t}),Z&&(xn({id:Date.now(),kind:`success`,message:J.permissionProfileRestarting}),F(Z.id,{launchPermissionMode:t})),vi(),Qi();return}let t=JE(e)?e:`approve`;nt(t),hs(`codex`,{approvalMode:t}),Z&&si===`codex`&&(xn({id:Date.now(),kind:`success`,message:Z.codexRuntimeMode===`app-server`?J.permissionProfileApplying:J.permissionProfileRestarting}),F(Z.id,{launchPermissionMode:t})),vi(),Qi()},[Z,vi,si,J.permissionProfileApplying,J.permissionProfileRestarting,Qi,F,p,hs]),_s=(0,W.useCallback)((e,t)=>{p||(xn({id:Date.now(),kind:`success`,message:J.runtimeModeRestarting}),F(e,{agentRuntimeMode:t}))},[J.runtimeModeRestarting,F,p]),vs=(0,W.useCallback)(e=>{if(si===`claude`){let t=$E(e);gt(t),vi(),Qi(),hs(`claude`,{model:t,effort:_t});return}let t=dt.find(t=>t.value===e),n=t?.reasoningLevels??[],r=t?.serviceTiers??[],i=n.some(e=>e.value===st)?st:t?.defaultEffort||n[0]?.value||st,a=r.some(e=>e.value===lt)?lt:`default`;ot(e),ct(i),ut(a),it(`${e}:${i}`),vi(),Qi(),hs(`codex`,{model:e,reasoningEffort:i,serviceTier:a}),xa(e,i,a,{applyModel:!0})},[_t,vi,dt,st,lt,si,Qi,hs,xa]),ys=(0,W.useCallback)((e,t)=>{if(si!==`codex`)return;let n=dt.find(t=>t.value===e);if(!n)return;let r=n.reasoningLevels?.some(e=>e.value===t)?t:n.defaultEffort||n.reasoningLevels?.[0]?.value||t,i=n.serviceTiers?.some(e=>e.value===lt)?lt:`default`;ot(e),ct(r),ut(i),it(`${e}:${r}`),hs(`codex`,{model:e,reasoningEffort:r,serviceTier:i}),xa(e,r,i,{applyModel:!0})},[dt,lt,si,hs,xa]),bs=(0,W.useCallback)(e=>{if(si===`claude`){let t=tD(e);vt(t),vi(),Qi(),hs(`claude`,{model:ht,effort:t});return}ct(e),it(`${at}:${e}`),vi(),Qi(),hs(`codex`,{model:at,reasoningEffort:e,serviceTier:lt}),xa(at,e,lt,{applyModel:!0})},[ht,vi,at,lt,si,Qi,hs,xa]),xs=(0,W.useCallback)(e=>{si!==`claude`&&(ut(e),vi(),Qi(),hs(`codex`,{model:at,reasoningEffort:st,serviceTier:e}),xa(at,st,e,{applyFast:!0}))},[vi,at,st,si,Qi,hs,xa]),Ss=(0,W.useCallback)(e=>{si===`codex`&&(ut(e),hs(`codex`,{model:at,reasoningEffort:st,serviceTier:e}),xa(at,st,e,{applyFast:!0}))},[at,st,si,hs,xa]),Cs=(0,W.useCallback)(()=>{if(zt){Yn.current?.stop(),Yn.current=null,Bt(!1);return}let e=Yr;if(!e)return;let t=L(),n=GD(),r=Lt&&!n?window.SpeechRecognition||window.webkitSpeechRecognition:null;if(!r){(GD()||t)&&Qi(),Bt(!1);return}let i=new r,a=null,o=()=>{a!==null&&(window.clearTimeout(a),a=null)},s=()=>{if(Yn.current===i)try{i.stop()}catch{Bt(!1),Yn.current=null}};i.continuous=!1,i.interimResults=!1,i.lang=T.language===`zh`?`zh-CN`:navigator.language||`en-US`,i.onresult=t=>{let n=``;for(let e=t.resultIndex;e<t.results.length;e+=1)n+=t.results[e]?.[0]?.transcript??``;n.trim()&&(H(e,e=>{let t=e.draft&&!/\s$/.test(e.draft)?` `:``;return{...e,draft:`${e.draft}${t}${n.trim()}`}}),Qi())},i.onerror=()=>{o(),Bt(!1)},i.onspeechend=s,i.onaudioend=s,i.onend=()=>{o(),Bt(!1),Yn.current=null},Yn.current=i,Bt(!0);try{i.start(),a=window.setTimeout(s,6e4)}catch{o(),Yn.current=null,Bt(!1),t&&Qi()}},[Yr,Qi,zt,Lt,T.language,H]),ws=(0,W.useCallback)(()=>{if(!bi)return;let e=bi.workspace,t=bi.agents.filter(e=>!e.isMain),n=Cr.filter(t=>Bb(t)===e);if(t.length===0&&n.length===0){an(null),ln(null),or.current=`list`;return}t.forEach(e=>{F(e.id,{archived:!0})}),Ua(n.map(Rb)),an(null),ln(null),or.current=`list`},[Cr,bi,F,Ua]),Ts=(0,W.useCallback)(()=>{let e=vn?.projectId;yn(null),e&&po(e)},[vn?.projectId,po]),Es=(0,W.useCallback)(async()=>{if(!vn)return;let e=vn,t=await B(e.workspace,{force:!0});t.deleted&&(Ua([...e.sessionHandles,...t.removedMainPageSessionKeys??[]]),or.current=`list`,yn(null))},[vn,B,Ua]),Ds=(0,W.useCallback)(()=>{let e=tn?.agentId,t=rn?.projectId,n=on?.provider,r=on?.sessionId,i=cn?.returnFocusTarget??null;nn(null),an(null),sn(null),ln(null),e?uo(e):t?po(t):n&&r?fo(n,r):i&&window.requestAnimationFrame(()=>i.focus({preventScroll:!0}))},[tn?.agentId,on?.provider,on?.sessionId,uo,fo,po,cn?.returnFocusTarget,rn?.projectId]),Os=(0,W.useCallback)((e,t)=>{if(!t)return!1;if(e.key===`Escape`)return e.preventDefault(),e.stopPropagation(),Ds(),!0;let n=Array.from(t.querySelectorAll(`button:not(:disabled)`));if(n.length===0)return;let r=n.findIndex(e=>e===document.activeElement),i=Math.min(Jn.current,n.length-1),a=r===-1?i:r,o=e=>{Jn.current=e,n[e]?.focus()};if(e.key===`Tab`){qn.current=!0,e.preventDefault(),e.stopPropagation();let t=a+(e.shiftKey?-1:1);if(t<0||t>=n.length){Ds();return}return o(t),!0}if(e.key===`ArrowDown`||e.key===`ArrowUp`){qn.current=!0,e.preventDefault(),e.stopPropagation();let t=e.key===`ArrowDown`?1:-1;return o(a===-1?t>0?0:n.length-1:(a+t+n.length)%n.length),!0}return e.key===`Home`?(qn.current=!0,e.preventDefault(),e.stopPropagation(),o(0),!0):e.key===`End`?(qn.current=!0,e.preventDefault(),e.stopPropagation(),o(n.length-1),!0):!1},[Ds]),ks=(0,W.useCallback)(e=>{e.defaultPrevented||Os(e.nativeEvent,e.currentTarget)},[Os]);(0,W.useLayoutEffect)(()=>{if(!tn&&!rn&&!on&&!cn)return;let e=e=>{Os(e,document.querySelector(`.code-context-menu`))&&e.stopImmediatePropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[tn,on,Os,cn,rn]);let As=(0,W.useCallback)(e=>{let t=Array.from(e.currentTarget.querySelectorAll(`button:not(:disabled)`)),n=e.target instanceof Element?e.target.closest(`button`):null,r=t.findIndex(e=>e===n||e===document.activeElement);if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),vi(),Qi();return}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=ni?`[data-testid="code-composer-model-picker"]`:ri?XD()?`[data-testid="code-composer-send"]`:`[data-testid="code-composer-mic"]`:`[data-testid="code-composer-approval"]`;vi(),window.requestAnimationFrame(()=>{document.querySelector(t)?.focus({preventScroll:!0})});return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let n=e.key===`ArrowDown`?1:-1;t[r===-1?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus();return}if(e.key===`Home`){e.preventDefault(),e.stopPropagation(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),e.stopPropagation(),t[t.length-1]?.focus())},[ni,vi,Qi,ri]),js=(0,W.useCallback)(e=>{let t=e.relatedTarget;t&&(t instanceof Node&&e.currentTarget.contains(t)||t instanceof Element&&t.closest(`.code-composer`)||vi())},[vi]);(0,W.useEffect)(()=>{function e(e){if(a)return;let t=e.target;if(tn||rn||on||cn){if(Os(e,Kn.current))return;if(e.key.length===1||e.key===`Tab`||e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`Home`||e.key===`End`){e.preventDefault(),e.stopPropagation();return}}if(e.key===`Escape`&&mn){e.preventDefault(),Jo();return}if(e.key===`Escape`&&gn){e.preventDefault(),Qo();return}if(e.key===`Escape`&&vn){e.preventDefault(),Ts();return}if(mn||gn||vn){He(t)||(e.preventDefault(),e.stopPropagation());return}let n=x?bt(e):null;if(n){$D(e),jo(n);return}if(MD(e)&&!He(t)){e.preventDefault(),e.stopPropagation(),Fo();return}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&!e.altKey&&!e.shiftKey&&!mn&&!gn&&!vn&&!He(t)&&!qD(t)&&!Re(t)){let n=Di(t)??Ei;if(!n)return;e.preventDefault(),xo(n.id);return}if(!(ze(t)||Re(t))&&!(He(t)&&e.key!==`Escape`)){if(e.key===`Escape`&&(ti||ni||ri)){e.preventDefault(),vi(),Qi();return}if(e.key===`Escape`&&i!==`projects`){e.preventDefault(),nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),or.current=`active-force`;return}if(e.key===`Escape`&&(tn||rn||on||cn)){e.preventDefault();let t=tn?.agentId,n=rn?.projectId,r=on?.provider,i=on?.sessionId,a=cn?.returnFocusTarget??null;nn(null),an(null),sn(null),ln(null),t?uo(t):n?po(n):r&&i?fo(r,i):a&&window.requestAnimationFrame(()=>a.focus({preventScroll:!0}));return}if(x){if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),_r();return}e.key===`/`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),Pa())}}}return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[i,tn,ni,vi,Ts,Qo,Jo,on,vn,a,uo,fo,Qi,po,xo,Os,gn,x,ri,jo,cn,ti,Ei,Di,rn,mn,Fo,Ya,V,Pa,_r]),(0,W.useEffect)(()=>{if(!mn)return;let e=mn.title,t=!1;return IE(()=>{let n=zn.current;if(!n)return;let r=document.activeElement;if(r!==n&&!Bn.current?.contains(r)&&n.focus(),!t&&document.activeElement===n&&n.value===e){if(t=!0,mn.kind===`project`){let e=n.value.length;n.setSelectionRange(e,e);return}n.select()}},{delays:[0,80,180,360]})},[En]),(0,W.useEffect)(()=>gn?IE(()=>{Vn.current?.contains(document.activeElement)||Hn.current?.focus()},{runNow:!1,delays:[180]}):void 0,[gn]),(0,W.useEffect)(()=>vn?IE(()=>{Un.current?.contains(document.activeElement)||Wn.current?.focus()},{runNow:!1,delays:[180]}):void 0,[vn]),(0,W.useEffect)(()=>{if(!bn)return;let e=window.setTimeout(()=>xn(null),1700);return()=>window.clearTimeout(e)},[bn]),(0,W.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-context-menu`)||(nn(null),an(null),sn(null),ln(null))}if(!(!tn&&!rn&&!on&&!cn))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[tn,on,cn,rn]),(0,W.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-composer-menu-anchor`)||vi()}if(!(!ti&&!ni&&!ri))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[ni,vi,ri,ti]),(0,W.useLayoutEffect)(()=>!tn&&!rn&&!on&&!cn?void 0:(qn.current=!1,Jn.current=0,IE(()=>{if(qn.current)return;let e=Kn.current;if(!e)return;let t=document.activeElement;if(t instanceof HTMLButtonElement&&e.contains(t))return;let n=e.querySelector(`button:not(:disabled)`);n&&(Jn.current=0,n.focus())},{delays:[0,80,180,360]})),[tn,on,cn,rn]),(0,W.useEffect)(()=>{if(!ri)return;let e=window.setTimeout(()=>{let e=ii===`model`?`.code-model-submenu .code-model-option.selected`:ii===`speed`?`.code-speed-submenu .code-model-option.selected`:`.code-model-picker-menu > .code-model-option.selected`,t=Ln.current?.querySelector(e),n=Ln.current?.querySelector(`button:not(:disabled)`);(t??n)?.focus()},0);return()=>window.clearTimeout(e)},[ri,ii,Mi,Ni,Pi]),(0,W.useEffect)(()=>{if(!ti)return;let e=window.setTimeout(()=>{Fn.current?.querySelector(`button:not(:disabled)`)?.focus()},0);return()=>window.clearTimeout(e)},[ti]),(0,W.useEffect)(()=>{if(!ni)return;let e=window.setTimeout(()=>{let e=In.current?.querySelector(`.code-approval-option.selected`),t=In.current?.querySelector(`button:not(:disabled)`);(e??t)?.focus()},0);return()=>window.clearTimeout(e)},[ni,Ri]),(0,W.useEffect)(()=>{if(!pe)return;let e=window.setInterval(()=>On(Date.now()),6e4);return()=>window.clearInterval(e)},[pe]),(0,W.useEffect)(()=>{let e=window.matchMedia(`(max-width: 980px)`),t=()=>{Rt(!!(window.SpeechRecognition||window.webkitSpeechRecognition)&&!GD())};return t(),e.addEventListener(`change`,t),()=>{e.removeEventListener(`change`,t),Yn.current?.stop(),Yn.current=null}},[]),(0,W.useEffect)(()=>ea(),[ea]),(0,W.useEffect)(()=>{let e=()=>{ea(),oa()};return window.addEventListener(`farming-agent-homes-saved`,e),()=>window.removeEventListener(`farming-agent-homes-saved`,e)},[oa,ea]),(0,W.useEffect)(()=>na(),[na]),(0,W.useEffect)(()=>la(si||``,Z?.cwd),[Z?.cwd,si,la]),(0,W.useEffect)(()=>{if(ri)return ta()},[ta,ri]),(0,W.useEffect)(()=>{if(!(!ri||si!==`claude`))return na()},[si,na,ri]),(0,W.useEffect)(()=>oa(),[oa]),(0,W.useEffect)(()=>{Zi()},[Zi,Yr,ei,Qr]),(0,W.useEffect)(()=>{Xr.composer.permissionMode||Xr.composer.modelPicker||_i(e=>{let t=HC(e);return Xr.composer.plusMenu||t.mode===`default`?t:{...t,mode:`default`}})},[Xr,_i]),(0,W.useEffect)(()=>{i!==`search`&&Le&&Ya(),i!==`projects`&&(nn(null),an(null),sn(null),ln(null),vi())},[i,Ya,vi,Le]),(0,W.useEffect)(()=>{a&&(nn(null),an(null),sn(null),ln(null),vi())},[vi,a]),(0,W.useEffect)(()=>{if(i===`projects`)return ea()},[i,ea]),(0,W.useEffect)(()=>{if(i!==`history`)return;let e=!1,t=lr.current;return fetch(n(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};Ke(tt(r.lastMainWorkspace,r.workspaceHistory??[])),Ye(kD(r.projectNames)),t===lr.current&&$e(new Set(kS(r.mainPageSessionKeys??[]))),$i(r),oa(!0)}).catch(()=>{e||Ke([])}),()=>{e=!0}},[i,$i,oa]),(0,W.useEffect)(()=>{function e(e){dr.current&&(e.preventDefault(),co(e.clientX))}function t(){dr.current&&(dr.current=!1,document.body.classList.remove(`code-resizing-sidebar`))}return window.addEventListener(`pointermove`,e),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t),document.body.classList.remove(`code-resizing-sidebar`)}},[co]),(0,W.useEffect)(()=>{let e=kn.current;if(!e||typeof ResizeObserver>`u`)return;let t=e=>{if(XD()){pr.current||hr(),pr.current=!0;return}if(pr.current=!1,ZD(e)){hr();return}fr.current&&gr()};t(e.getBoundingClientRect().width);let n=new ResizeObserver(n=>{t(n[0]?.contentRect.width??e.getBoundingClientRect().width)});return n.observe(e),()=>n.disconnect()},[hr,gr]),(0,W.useEffect)(()=>{let e=or.current;if(!e||i!==`projects`||Le)return;or.current=null;let t,n=0,r=e===`active-force`?4:12,a=()=>{n>=r||(t=window.setTimeout(o,90))},o=()=>{if(n+=1,qa()){a();return}let t=!1;e===`list`?(Gn.current?.focus({preventScroll:!0}),t=document.activeElement===Gn.current):t=Ga(),(!t||e===`active-force`)&&a()},s=window.setTimeout(()=>{o()},e===`list`?0:50);return()=>{window.clearTimeout(s),t!==void 0&&window.clearTimeout(t)}},[l,i,Ga,Le,qa]),(0,W.useEffect)(()=>{if(!sr.current||i!==`projects`||Le)return;sr.current=null;let e,t=0,n=()=>{t>=12||(e=window.setTimeout(r,90))},r=()=>{if(t+=1,qa()){n();return}Ja({skipIfFocusMoved:!0}),n()},a=window.setTimeout(()=>{r(),e=window.setTimeout(r,180)},50);return()=>{window.clearTimeout(a),e!==void 0&&window.clearTimeout(e)}},[Y.length,l,i,Ja,Le,qa]),(0,W.useEffect)(()=>{let e=cr.current;if(!e||i!==`projects`||Le||!Y.some(t=>t.id===e))return;cr.current=null;let t,n=0,r=()=>{n+=1,qa()||lo(e),!(n>=60)&&(t=window.setTimeout(()=>{window.requestAnimationFrame(r)},80))},a=window.setTimeout(()=>{window.requestAnimationFrame(r)},50);return()=>{window.clearTimeout(a),t!==void 0&&window.clearTimeout(t)}},[Y,i,lo,Le,qa]),(0,W.useEffect)(()=>{Ti&&en(Ti)},[Ti]),(0,W.useEffect)(()=>{Ge(0)},[Ir,Le]),(0,W.useEffect)(()=>{Ge(e=>Hr.length===0?0:Math.min(e,Hr.length-1))},[Hr.length]);let Ms={"--code-sidebar-width":`${qt?ID:Gt}px`};return(0,K.jsxs)(`div`,{className:`code-workspace ${qt?`sidebar-collapsed`:``}`,"data-testid":`code-workspace`,ref:kn,style:Ms,children:[(0,K.jsx)(CT,{sidebarCollapsed:qt,activeView:i,searchOpen:Le,displayedProjects:Pr,collapsedProjectIds:Vt,normalizedSearch:``,hasProjectListItems:zr,hasDisplayedProjectListItems:zr,activeTerminalId:l,selectedSearchAgentId:Ci,selectedSearchSessionHandle:wi,claimedAgentSessionKeyByAgentId:Sr.claimedAgentSessionKeyByAgentId,agentShortcutKeys:Ur,keyboardShortcutsEnabled:x,now:Dn,mainAgent:yr,systemStats:o,usageSummary:s,shareTarget:Ai,agentLaunchOptions:Xe,agentCreationWorkspace:Oi,openWorkspaceFile:G,openWorkspaceFiles:Ie,fileRevealRequest:Sn,fileSearchFocusRequest:wn,projectListRef:Gn,canLoadMoreAgentSessions:Ot,onLoadMoreAgentSessions:ca,onNewAgent:La,onStartAgent:Ra,onToggleSidebar:_r,onOpenSearch:Qa,onOpenWorkspaceView:$a,onOpenMainAgent:()=>{yr&&(be(`terminal`),V(`projects`),E(yr.id))},onRestartMainAgent:ie,onProjectListKeyDown:io,onToggleProject:eo,onToggleProjectSessions:to,onOpenProjectContextMenu:Ho,onOpenProjectKeyboardMenu:Uo,onOpenAgent:vo,onUpdateAgentFlags:ns,onReorderAgent:rs,onOpenAgentContextMenu:Bo,onOpenAgentKeyboardMenu:Vo,onResumeAgentSession:os,onOpenAgentSessionContextMenu:Wo,onOpenAgentSessionKeyboardMenu:Go,onOpenProjectFile:bo,onSelectOpenWorkspaceFile:To,onCloseOpenWorkspaceFile:Po,onMoveWorkspaceEntries:Ro,onDeleteWorkspaceEntries:zo,onOpenOptionsMenu:ps,copy:J}),(0,K.jsx)(DE,{open:un,activeAgentId:i===`projects`?Z?.id??null:null,language:T.language,uiPreferences:T,agentLaunchOptions:Xe,onClose:()=>dn(!1),onUpdateUiPreferences:fe}),fn&&(0,K.jsx)(Dw,{copy:J,title:Ki,url:fn,onClose:()=>pn(``)}),(0,K.jsx)(`div`,{className:`code-sidebar-resizer`,"data-testid":`code-sidebar-resizer`,onPointerDown:go}),!qt&&(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-sidebar-backdrop`,"data-testid":`code-mobile-sidebar-backdrop`,"aria-label":J.closeNavigation,onPointerDown:hr}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar`,"data-testid":`code-mobile-topbar`,children:[Xi?(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button back`,"data-testid":`code-mobile-back`,"aria-label":J.backToAgent,onClick:()=>{Yi&&Mo(Yi)},children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}):(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button menu`,"data-testid":`code-mobile-menu`,"aria-label":J.openNavigation,onClick:Ia,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar-title`,children:[(0,K.jsx)(`strong`,{children:Ki}),Ji&&(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),Ji]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button more`,"data-testid":`code-mobile-more`,"aria-label":J.openOptions,onClick:cs,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})})]}),cn&&(0,K.jsx)(`div`,{className:`code-context-menu code-options-menu`,"data-testid":`code-options-menu`,style:{left:cn.x,top:cn.y},role:`menu`,ref:Kn,onKeyDownCapture:ks,onKeyDown:ks,children:(0,K.jsx)(oO,{entries:ms})}),(0,K.jsx)(MC,{activeView:i,showFileEditor:ki,openWorkspaceFile:G,openWorkspaceFiles:Ie,openAgentsCount:Wr.length,visibleOpenAgents:Kr,activeTerminalId:l,permissionSwitchingAgentId:p,agentSwitchingKind:g,terminalFocusRequest:y,agentCreationWorkspace:Oi,displayedProjects:Br,searchQuery:Ve,searchHasQuery:Lr,searchLoading:jt,visibleSearchTargetCount:Hr.length,selectedSearchAgentId:Ci,selectedSearchSessionHandle:wi,searchInputRef:Rn,archivedRuns:Or,archivedAgents:Dr,historyAgentSessions:kr,canLoadMoreHistoryAgentSessions:Ot,now:Dn,acpComposerProps:{active:!!Z&&!qr,agentId:Z?.id||``,runtimeState:Z?.acpState||``,sessionUpdatedAt:Z?.acpSessionUpdatedAt||``,runtimeError:Z?.acpError||``,draft:Qr,attachments:$r,composerMode:ei,contextWindow:Jr,pendingFollowUp:fi??null,submitAction:gi,textareaRef:An,attachmentInputRef:Pn,permissions:Z?.acpPendingPermissions?.length?Z.acpPendingPermissions:Z?.acpPendingPermission?[Z.acpPendingPermission]:[],elicitations:Z?.acpPendingElicitations?.length?Z.acpPendingElicitations:Z?.acpPendingElicitation?[Z.acpPendingElicitation]:[],activeElicitations:Z?.acpActiveElicitations||[],speechSupported:Lt,speechListening:zt,onDraftChange:ya,onNavigateHistory:ba,onRemoveAttachment:pa,onSubmit:Ea,onInterrupt:Da,onDiscardPendingFollowUp:Na,onToggleSpeechInput:Cs,onPasteAttachment:ha,onAttachmentFiles:ma,onChooseAttachmentFile:ua,onActivateComposerMode:ga,onClearComposerMode:()=>{_i(e=>({...e,mode:`default`}))},onRespondToPermission:Aa,onRespondToElicitation:ja},composerProps:{active:!!Z&&!qr,agentKind:si,capabilities:Xr.composer,slashCommands:di,draft:Qr,attachments:$r,composerMode:ei,plusMenuOpen:ti,approvalMenuOpen:ni,modelMenuOpen:ri,modelPickerPane:ii,agentModelPreset:Fi,agentModel:Mi,agentReasoningEffort:Ni,agentServiceTier:Pi,agentModelOptions:ji,currentPermissionMode:Ri,permissionModeDisabled:!!p,currentPermissionLabel:zi,currentPermissionColor:Bi,permissionModeHint:Z?.codexRuntimeMode===`app-server`?J.permissionAppServerHint:J.permissionRestartHint,currentModelLabel:Vi,currentReasoningLabel:Hi,currentSpeedLabel:Ui,currentReasoningOptions:Ii,currentServiceTierOptions:Li,permissionModeOptions:Wi,contextWindow:Jr,pendingFollowUp:fi?{messages:fi.messages,createdAt:fi.createdAt}:null,appServerRequest:Z?.codexAppServerPendingRequest||null,appServerNotice:Z?.codexAppServerNotice||null,submitAction:hi,speechSupported:Lt,speechListening:zt,textareaRef:An,attachmentInputRef:Pn,plusMenuRef:Fn,approvalMenuRef:In,modelMenuRef:Ln,onDraftChange:ya,onNavigateHistory:ba,onRemoveAttachment:pa,onSubmit:Ta,onInterrupt:Da,onSteerPendingFollowUp:Ma,onDiscardPendingFollowUp:Na,onRespondToAppServerRequest:Oa,onRejectAppServerRequest:ka,onPasteAttachment:ha,onAttachmentFiles:ma,onChooseAttachmentFile:ua,onActivateComposerMode:ga,onClearComposerMode:()=>{_i(e=>({...e,mode:`default`})),Qi()},onTogglePlusMenu:()=>{_i(e=>({...e,ui:{plusMenuOpen:!e.ui.plusMenuOpen,approvalMenuOpen:!1,modelMenuOpen:!1,modelPickerPane:null}}))},onToggleApprovalMenu:()=>{_i(e=>({...e,ui:{plusMenuOpen:!1,approvalMenuOpen:!e.ui.approvalMenuOpen,modelMenuOpen:!1,modelPickerPane:null}}))},onToggleModelMenu:()=>{_i(e=>({...e,ui:{plusMenuOpen:!1,approvalMenuOpen:!1,modelMenuOpen:!e.ui.modelMenuOpen,modelPickerPane:null}}))},onCloseMenus:vi,onSetModelPickerPane:e=>{_i(t=>({...t,ui:{...t.ui,modelPickerPane:e}}))},onComposerMenuKeyDown:As,onComposerMenuBlur:js,onUpdatePermissionMode:gs,onUpdateModel:vs,onUpdateReasoningEffort:bs,onUpdateServiceTier:xs,onUpdateModelProfile:ys,onUpdateServiceTierInline:Ss,onToggleSpeechInput:Cs},onNewAgent:j,onOpenTerminal:E,onOpenTerminalPath:wo,onResolveTerminalPath:Co,onTerminalFollowOutputChange:va,onAgentReadLatest:_a,onRuntimeModeChange:_s,sendInput:se,resizeAgent:ue,onSessionOutput:de,onOpenSearchAgent:_o,onOpenSearchSession:e=>{os(e.provider,e.id,e.providerHomeId),Ya(),V(`projects`)},onSearchQueryChange:Ue,onSearchKeyDown:so,onCloseSearch:Xa,onLoadMoreHistoryAgentSessions:ca,onSearchHistoryAgentSessions:ia,onResumeHistorySession:os,onContinueArchivedRun:ss,onOpenArchivedAgent:as,onRestoreArchivedAgent:is,onChangeWorkspaceFileDraft:Lo,onUpdateOpenWorkspaceFile:Io,onSelectOpenWorkspaceFile:To,onOpenWorkspaceFilePath:Eo,canNavigateWorkspaceBack:Te,canNavigateWorkspaceForward:Ee,onNavigateWorkspaceHistory:jo,onCloseOpenWorkspaceFile:Po,onCloseOpenWorkspaceFiles:No,onRevealWorkspaceFileInExplorer:So,onFocusWorkspaceFilesSearch:xo,onRecordWorkspaceNavigationCursor:je,onBackToAgentFromFile:Mo,copy:J}),(0,K.jsx)(kw,{contextMenuAgent:yi,contextMenuAgentSession:xi,contextMenuProject:bi,agentMenu:tn,projectMenu:rn,agentSessionMenu:on,renameDialog:mn,killDialog:gn,deleteWorktreeDialog:vn,copyNotice:bn,contextMenuRef:Kn,renameDialogRef:Bn,renameInputRef:zn,killDialogRef:Vn,killCancelButtonRef:Hn,deleteWorktreeDialogRef:Un,deleteWorktreeCancelButtonRef:Wn,onContextMenuKeyDown:ks,onUpdateAgentFlags:ts,onRenameAgent:Ko,onRenameProject:qo,onCopyAgentWorkingDirectory:()=>{yi&&Xo(Ab(yi),{kind:`agent`,id:yi.id})},onForkAgent:es,onKillAgent:Zo,onOpenSession:(e,t)=>{sn(null),ln(null),os(e,t,xi?.providerHomeId),xi&&fo(e,Rb(xi))},onToggleSessionPinned:mo,onArchiveSession:ho,onCopySessionWorkingDirectory:()=>{xi&&Xo(Vb(xi),{kind:`agent-session`,provider:xi.provider,id:xi.id,providerHomeId:xi.providerHomeId})},onArchiveProject:ws,onCloseRenameDialog:Jo,onRenameDialogTitleChange:e=>hn(t=>t&&{...t,title:e}),onSubmitRenameDialog:Yo,onCloseKillDialog:Qo,onSubmitKillDialog:$o,onCloseDeleteWorktreeDialog:Ts,onSubmitDeleteWorktreeDialog:Es,copy:J})]})}function oO({entries:e}){return(0,K.jsx)(K.Fragment,{children:e.map(e=>e.type===`separator`?(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`},e.id):(0,K.jsxs)(`button`,{type:`button`,role:typeof e.checked==`boolean`?`menuitemradio`:`menuitem`,"aria-checked":typeof e.checked==`boolean`?e.checked:void 0,"aria-label":e.ariaLabel,className:[e.danger?`danger`:``,typeof e.checked==`boolean`?`selectable`:``,e.checked?`checked`:``].filter(Boolean).join(` `)||void 0,disabled:e.disabled,onClick:e.onSelect,children:[typeof e.checked==`boolean`&&(0,K.jsx)(`span`,{className:`code-options-menu-check`,"aria-hidden":`true`,children:e.checked?(0,K.jsx)(me,{}):null}),e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(sO,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}function sO({kind:e}){return e===`archive`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})}):(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M11.3536 1.64645C10.963 1.25592 10.3299 1.25592 9.93934 1.64645L3.14645 8.43934C3.05268 8.53311 2.99999 8.66029 2.99999 8.79289V11.5C2.99999 11.7761 3.22385 12 3.49999 12H6.2071C6.33971 12 6.46689 11.9473 6.56066 11.8536L13.3536 5.06066C13.7441 4.67014 13.7441 4.037 13.3536 3.64645L11.3536 1.64645ZM3.99999 9L8.99999 4L11 6L6 11H3.99999V9ZM9.7071 3.29289L10.6464 2.35355L12.6464 4.35355L11.7071 5.29289L9.7071 3.29289ZM2.5 14C2.22386 14 2 14.2239 2 14.5C2 14.7761 2.22386 15 2.5 15H13.5C13.7761 15 14 14.7761 14 14.5C14 14.2239 13.7761 14 13.5 14H2.5Z`})})}var cO={appearance:`light`,language:`en`};function lO(e){return e===`light`||e===`dark`?e:cO.appearance}function uO(e){return e===`zh`||e===`en`?e:cO.language}function dO(e){return e}function fO(e=`terminal`,t={}){if(typeof document>`u`)return;let n=document.body,r=t.crtEffects!==!1,i=lO(t.appearance),a=dO(i);n.dataset.theme=e,n.dataset.crtEffects=r?`on`:`off`,n.dataset.appearancePreference=i,n.dataset.appearance=a,r?n.classList.remove(`no-crt`):n.classList.add(`no-crt`)}var pO=!1,mO=3e3,hO=6e3,gO=240,_O=3e4,vO=1e4,yO=6e4,bO=45e3,xO=6e4;function SO(e){if(e)return e.projectWorkspace?e.projectWorkspace:e.cwd}function CO(e){return!e.archived&&e.status!==`dead`&&e.status!==`stopped`}function wO(e,t){return e.restartedFromAgentId===t||e.restartedFromAgentIds?.includes(t)===!0}function TO(e,t,n){return e.filter(e=>CO(e)&&wO(e,t)&&(!n?.providerSessionProvider||!n.providerSessionId||e.providerSessionProvider===n.providerSessionProvider&&(n.providerSessionTemporary===!0||e.providerSessionId===n.providerSessionId)&&(e.providerHomeId||``)===(n.providerHomeId||``))).sort((e,t)=>{let n=(t.restartedFromAgentIds?.length??0)-(e.restartedFromAgentIds?.length??0);return n===0?(t.startedAt??0)-(e.startedAt??0):n})[0]??null}function EO(e){return e?.providerSessionProvider===`codex`&&!!e.providerSessionId&&e.providerSessionTemporary!==!0}function DO(e){if(!e||!e.isConnected||e.getAttribute(`aria-disabled`)===`true`||`disabled`in e&&e.disabled)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&e.getClientRects().length>0}function OO(e){return DO(e)?(e.focus({preventScroll:!0}),document.activeElement===e||e.contains(document.activeElement)):!1}function kO(){let e=Ie(),t=Pe(),{keyMap:r}=Le(e.agents,e.mainAgentId),[i]=(0,W.useState)(()=>ee()),[a,o]=(0,W.useState)(`none`),[s,c]=(0,W.useState)(void 0),[l,u]=(0,W.useState)(void 0),[d,f]=(0,W.useState)(void 0),[p,m]=(0,W.useState)(()=>i.openTerminalIds??[]),[h,g]=(0,W.useState)(()=>i.activeTerminalId??null),[_,v]=(0,W.useState)(null),[y,b]=(0,W.useState)(null),[x,S]=(0,W.useState)(()=>i.activeView??`projects`),[C,w]=(0,W.useState)(null),[T,E]=(0,W.useState)(null),[O,k]=(0,W.useState)(null),[te,A]=(0,W.useState)(null),[j,M]=(0,W.useState)({}),[N,P]=(0,W.useState)(cO),[ne,I]=(0,W.useState)(()=>Date.now()),R=(0,W.useRef)(null),z=(0,W.useRef)(null),re=(0,W.useRef)(null),B=(0,W.useRef)(null),ie=(0,W.useRef)([]),V=(0,W.useRef)(!1),ae=(0,W.useRef)(!1),oe=(0,W.useRef)(!1),se=(0,W.useRef)(void 0),ce=(0,W.useRef)(null),le=(0,W.useRef)(0);(0,W.useLayoutEffect)(()=>{ie.current=p},[p]),(0,W.useEffect)(()=>{D({activeTerminalId:h,activeView:x,openTerminalIds:p})},[h,x,p]);let ue=(0,W.useCallback)(e=>{B.current=e,E(e)},[]),de=a,fe=(0,W.useMemo)(()=>PE(N.language),[N.language]),pe=(0,W.useMemo)(()=>{if(!T)return e.agents;let t=e.agents.filter(e=>e.id===T.agent.id||!wO(e,T.originalAgentId));return t.some(e=>e.id===T.agent.id)?t:[...t,T.agent]},[T,e.agents]),me=(0,W.useMemo)(()=>{let e=new Map,t=new Set(p);return h&&t.add(h),t.forEach(t=>{if(pe.some(e=>e.id===t&&CO(e)))return;let n=TO(pe,t);n&&e.set(t,n.id)}),e},[h,pe,p]),H=(0,W.useMemo)(()=>{if(h){let e=me.get(h);if(e)return{originalAgentId:h,replacementAgentId:e}}let e=me.entries().next().value;return e?{originalAgentId:e[0],replacementAgentId:e[1]}:null},[h,me]),he=(0,W.useMemo)(()=>Array.from(new Set(p.map(e=>me.get(e)??e))),[me,p]),ge=h?me.get(h)??h:null;(0,W.useLayoutEffect)(()=>{H&&(m(he),g(ge),k(H))},[ge,he,H]),(0,W.useEffect)(()=>{!O||H||k(null)},[O,H]),(0,W.useEffect)(()=>{let t=B.current;if(!t)return;let n=TO(e.agents,t.originalAgentId,t.agent);if(!n||n.id===t.agent.id)return;let r=t.agent.id,i={...t,agent:n,replacementAgentId:n.id,transitionFromAgentId:r};m(e=>Array.from(new Set(e.map(e=>wO(n,e)?n.id:e)))),g(e=>e&&wO(n,e)?n.id:e),ue(i)},[ue,T?.agent.id,T?.originalAgentId,e.agents]),(0,W.useEffect)(()=>{let t=T;!t?.requestSettled||!t.replacementAgentId||e.agents.some(e=>e.id===t.agent.id)&&B.current?.agent.id===t.agent.id&&(re.current=null,ue(null))},[ue,T?.agent.id,T?.replacementAgentId,T?.requestSettled,e.agents]),(0,W.useEffect)(()=>{let t=T;if(!t?.requestSettled||!t.requestError||t.replacementAgentId)return;let n=t.requestErrorAt??Date.now();if(!t.requestFreshStateAt&&e.connected&&e.lastMessageAt>n){let n=B.current;n?.originalAgentId===t.originalAgentId&&!n.replacementAgentId&&!n.requestFreshStateAt&&ue({...n,requestFreshStateAt:e.lastMessageAt});return}let r=n+yO,i=t.requestFreshStateAt?t.requestFreshStateAt+vO:1/0,a=Math.max(0,Math.min(r,i)-Date.now()),o=window.setTimeout(()=>{let e=B.current;!e?.requestSettled||!e.requestError||e.replacementAgentId||e.originalAgentId!==t.originalAgentId||(re.current=null,ue(null),w({id:Date.now(),kind:`error`,message:e.requestError}))},a);return()=>window.clearTimeout(o)},[ue,T,e.connected,e.lastMessageAt]),(0,W.useEffect)(()=>{let e=T;if(!e)return;let t=Math.max(0,e.startedAt+xO-Date.now()),n=window.setTimeout(()=>{let t=B.current;!t||t.startedAt!==e.startedAt||(re.current=null,ue(null),w({id:Date.now(),kind:`error`,message:fe.agentRestartTimedOut}))},t);return()=>window.clearTimeout(n)},[ue,fe.agentRestartTimedOut,T]);let _e=(0,W.useMemo)(()=>{let t=Math.max(0,ne-e.lastMessageAt);return!e.connected&&e.everConnected?`lost`:!e.connected&&t>=mO?`connecting`:e.connected&&t>=hO?`stale`:null},[ne,e.connected,e.everConnected,e.lastMessageAt]),ve=_e===`lost`?fe.backendConnectionLost:_e===`stale`?fe.backendHeartbeatLost:_e===`connecting`?fe.backendConnecting:``;(0,W.useEffect)(()=>{if(!t)return;let e=window.setInterval(()=>I(Date.now()),1e3);return()=>window.clearInterval(e)},[t]);let ye=(0,W.useCallback)(e=>{let t={appearance:lO(e.appearance??N.appearance),language:uO(e.language??N.language)};P(t),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}).then(e=>e.json()).then(e=>{let n=e.settings??{};P({appearance:lO(n.appearance??t.appearance),language:uO(n.language??t.language)})}).catch(()=>{w({id:Date.now(),kind:`error`,message:`Failed to save preferences`})})},[N.appearance,N.language]),be=(0,W.useCallback)(e=>{let t=Array.from(new Set(e.filter(Boolean)));t.length!==0&&fetch(n(`/api/codex/context-windows`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentIds:t})}).then(e=>e.json()).then(e=>{let t=Array.isArray(e.contextWindows)?e.contextWindows:[];M(e=>{let n={...e};return t.forEach(e=>{let t=String(e?.agentId||``);t&&(e&&e.available===!0?n[t]=e:delete n[t])}),n})}).catch(()=>{})},[]);(0,W.useEffect)(()=>{if(e.connected){if(e.mainAgentId||e.agents.some(e=>e.isMain)){V.current=!1;return}V.current||(V.current=!0,e.startAgent(`bash`,void 0,!0))}},[e.agents,e.connected,e.mainAgentId,e.startAgent]),(0,W.useEffect)(()=>{let e=()=>{let e=window.visualViewport,t=e?.width??window.innerWidth,n=e?.height??window.innerHeight,r=e?.offsetTop??0,i=e?.offsetLeft??0,a=L(),o=window.innerHeight||n||gO,s=a?Math.min(Math.max(n,gO),Math.max(o,gO)):n,c=Math.max(0,o-n-r),l=a&&F(),u=a&&c>80,d=navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches;document.body.classList.toggle(`code-mobile-touch`,a),document.body.classList.toggle(`code-mobile-ios`,l),document.body.classList.toggle(`code-mobile-standalone`,a&&d),document.body.classList.toggle(`code-mobile-keyboard-active`,u),document.documentElement.style.setProperty(`--app-visual-width`,`${t}px`),document.documentElement.style.setProperty(`--app-visual-height`,`${s}px`),document.documentElement.style.setProperty(`--app-visual-offset-top`,`${r}px`),document.documentElement.style.setProperty(`--app-visual-offset-left`,`${i}px`),document.documentElement.style.setProperty(`--mobile-keyboard-offset`,`${c}px`)};return e(),window.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`scroll`,e),()=>{window.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`scroll`,e),document.documentElement.style.removeProperty(`--app-visual-width`),document.documentElement.style.removeProperty(`--app-visual-height`),document.documentElement.style.removeProperty(`--app-visual-offset-top`),document.documentElement.style.removeProperty(`--app-visual-offset-left`),document.documentElement.style.removeProperty(`--mobile-keyboard-offset`),document.body.classList.remove(`code-mobile-touch`),document.body.classList.remove(`code-mobile-ios`),document.body.classList.remove(`code-mobile-standalone`),document.body.classList.remove(`code-mobile-keyboard-active`)}},[]);let xe=(0,W.useCallback)((t,n)=>{h!==t&&e.focusAgent(t),m(e=>e.includes(t)?e:[...e,t]),g(t),S(`projects`),n?.focusTerminal!==!1&&v(e=>({agentId:t,nonce:(e?.nonce??0)+1})),o(`none`)},[h,e]),Se=(0,W.useCallback)((e,t)=>{b({agentId:e,options:t})},[]),Ce=(0,W.useCallback)((e,t)=>{if(e===h&&p.includes(e)){xe(e,t);return}Se(e,t)},[xe,h,p,Se]);(0,W.useEffect)(()=>{y&&pe.some(e=>e.id===y.agentId&&CO(e))&&(b(null),xe(y.agentId,y.options))},[xe,pe,y]);let we=(0,W.useCallback)(e=>{let t=new Set(e);if(t.size===0)return;let n=ie.current,r=n.indexOf(h??``),i=n.filter(e=>!t.has(e)),a=r===-1?i[i.length-1]??null:i[Math.min(r,i.length-1)]??null;ie.current=i,m(i),g(e=>!e||!t.has(e)?e:a),h&&t.has(h)&&a&&v(e=>({agentId:a,nonce:(e?.nonce??0)+1}))},[h]),Te=(0,W.useCallback)(e=>{we([e])},[we]),Ee=(0,W.useCallback)(e=>{if(p.length===0)return;let t=p[(Math.max(0,p.findIndex(e=>e===h))+e+p.length)%p.length];t&&Ce(t)},[h,Ce,p]),De=(0,W.useCallback)((e,t,n,r)=>{let i=le.current+1;le.current=i,ce.current=n??(document.activeElement instanceof HTMLElement?document.activeElement:null),c(e),u(t),f(r),S(`projects`),o(`input`);let a=()=>{le.current===i&&o(e=>e===`input`?e:`input`)};window.requestAnimationFrame(a),window.setTimeout(a,80),window.setTimeout(a,180)},[]),Oe=(0,W.useCallback)(()=>{let e=ce.current,t=e?.getAttribute(`data-testid`)===`code-new-agent`;ce.current=null;let n=()=>{OO(e)||t&&OO(document.querySelector(`[data-testid="code-new-agent"]`))||OO((h?Array.from(document.querySelectorAll(`[data-testid="code-agent-row"]`)).find(e=>e.dataset.agentId===h):null)??null)||OO(document.querySelector(`[data-testid="code-new-agent"]`))||OO(document.querySelector(`[data-testid="code-project-list"]`))};window.requestAnimationFrame(n),window.setTimeout(n,80),window.setTimeout(n,180)},[h]),ke=(0,W.useCallback)(()=>{le.current+=1,o(`none`),Oe()},[Oe]),Ae=(0,W.useCallback)(e=>{w({id:Date.now(),kind:`error`,message:e})},[]),U=(0,W.useCallback)(t=>{Lg(t).catch(e=>{console.error(`Failed to destroy killed terminal session:`,e)}),e.killAgent(t),Te(t)},[e,Te]),je=(0,W.useCallback)(t=>{z.current||(V.current=!0,z.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.restartMainAgent(t)||(z.current=null,V.current=!1))},[e]),Me=(0,W.useCallback)((t,n,r)=>{R.current||(le.current+=1,R.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.startAgent(t,n,!1,r)||(R.current=null))},[e]);(0,W.useEffect)(()=>{let t=e.lastStartedAgentId,n=R.current;!t||!n||n.beforeIds.has(t)||(R.current=null,o(`none`),Se(t))},[Se,e.lastStartedAgentId]);let Ne=(0,W.useCallback)(async(e,t)=>{try{let r=await fetch(n(`/api/agents/${e}/fork`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:t})}),i=await r.json().catch(()=>null);if(!r.ok||!i?.agentId){Ae(i?.error||`Failed to fork agent (${r.status})`);return}Se(i.agentId)}catch(e){Ae(e instanceof Error?e.message:`Failed to fork agent`)}},[Ae,Se]),Fe=(0,W.useCallback)(async(e,t)=>{try{let r=await fetch(n(`/api/projects/delete-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:e,force:t?.force===!0})}),i=await r.json().catch(()=>null);if(!r.ok&&i?.requiresForce!==!0&&Ae(i?.error||`Failed to delete worktree (${r.status})`),i?.deleted&&we(i.archivedAgentIds??[]),i)return i;let a=`Failed to delete worktree (${r.status})`;return Ae(a),{error:a}}catch(e){let t=e instanceof Error?e.message:`Failed to delete worktree`;return Ae(t),{error:t}}},[we,Ae]),G=(0,W.useCallback)(async(e,t)=>{try{let r=await fetch(n(`/api/agents/${e}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({customTitle:t})}),i=await r.json().catch(()=>null);r.ok||Ae(i?.error||`Failed to rename agent (${r.status})`)}catch(e){Ae(e instanceof Error?e.message:`Failed to rename agent`)}},[Ae]),Re=(0,W.useCallback)(async(t,r)=>{let i=typeof r.launchPermissionMode==`string`?r.launchPermissionMode:``,a=typeof r.agentRuntimeMode==`string`,o=i||a?e.agents.find(e=>e.id===t)??null:null,s=o?.providerSessionProvider===`codex`&&o.codexRuntimeMode===`app-server`&&!a?null:o;if(s){if(re.current)return!1;re.current=t,ue({originalAgentId:t,agent:s,kind:a?`runtime`:`permission`,startedAt:Date.now()})}let c=()=>{s&&B.current?.originalAgentId===t&&(re.current=null,ue(null))};try{let e=new AbortController,a=window.setTimeout(()=>e.abort(),bO),o=await fetch(n(`/api/agents/${t}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r),signal:e.signal});window.clearTimeout(a);let l=await o.json().catch(()=>null);if(!o.ok){let e=B.current;return s&&e?.originalAgentId===t&&e.replacementAgentId?(ue({...e,requestSettled:!0}),l??!0):(c(),Ae(l?.error||`Failed to update agent (${o.status})`),!1)}if(l?.warning&&Ae(l.warning),r.archived===!0&&Te(t),l?.restartedAgentId){let e=l.restartedAgentId,n=B.current;s&&n?.originalAgentId===t&&(n.agent.id===t?(m(n=>n.map(n=>n===t?e:n)),g(n=>n===t?e:n),ue({...n,replacementAgentId:e,transitionFromAgentId:t,requestSettled:!0,agent:{...n.agent,id:e,launchPermissionMode:l.launchPermissionMode??i,agentRuntimeMode:l.agentRuntimeMode??n.agent.agentRuntimeMode,restartedFromAgentId:t,restartedFromAgentIds:Array.from(new Set([...n.agent.restartedFromAgentIds??[],t]))}})):ue({...n,requestSettled:!0,requestError:void 0}))}else c();return l??!0}catch(e){let n=e instanceof DOMException&&e.name===`AbortError`?fe.agentRestartTimedOut:e instanceof Error?e.message:`Failed to update agent`,r=B.current;return s&&r?.originalAgentId===t?(ue({...r,requestSettled:!0,requestError:n,requestErrorAt:Date.now()}),!!r.replacementAgentId):(Ae(n),!1)}},[Te,ue,fe.agentRestartTimedOut,Ae,e.agents]),ze=(0,W.useCallback)(async e=>{await Re(e,{archived:!1})&&Se(e)},[Re,Se]),Be=(0,W.useMemo)(()=>pe.find(e=>e.id===ge)??null,[pe,ge]);return(0,W.useEffect)(()=>{if(!t||!EO(Be))return;let e=Be.id,n,r;return n=window.setTimeout(()=>be([e]),2500),r=window.setInterval(()=>be([e]),_O),()=>{n!==void 0&&window.clearTimeout(n),r!==void 0&&window.clearInterval(r)}},[Be?.id,Be?.providerSessionId,Be?.providerSessionProvider,Be?.providerSessionTemporary,t,be]),(0,W.useEffect)(()=>{let e=SO(Be);e&&(se.current=e)},[Be]),We((0,W.useMemo)(()=>[],[Be,Ee,r,De,Ce]),pO),(0,W.useEffect)(()=>{e.error&&(R.current=null,b(null),z.current=null,V.current=!1,Ae(e.error))},[Ae,e.error,e.errorId]),(0,W.useEffect)(()=>{if(!C)return;let e=window.setTimeout(()=>w(null),2800);return()=>window.clearTimeout(e)},[C]),(0,W.useEffect)(()=>{if(!t)return;let e=!1,r,i,a=()=>{fetch(n(`/api/usage`)).then(e=>e.json()).then(t=>{e||A(t.usage??null)}).catch(()=>{e||A(null)})};return i=window.setTimeout(a,1500),r=window.setInterval(a,6e4),()=>{e=!0,i!==void 0&&window.clearTimeout(i),r!==void 0&&window.clearInterval(r)}},[t]),(0,W.useEffect)(()=>{Rg(pe.filter(CO).map(e=>e.id)).catch(e=>{console.error(`Failed to prune terminal sessions:`,e)})},[pe]),(0,W.useEffect)(()=>{let e=new Set(pe.filter(CO).map(e=>e.id));m(t=>Array.from(new Set(t.map(t=>e.has(t)?t:TO(pe,t)?.id??t))).filter(t=>e.has(t)||B.current?.agent.id===t))},[pe]),(0,W.useEffect)(()=>{let e=new Set(pe.filter(CO).map(e=>e.id));g(t=>t&&(e.has(t)||B.current?.agent.id===t)?t:p[0]??null)},[pe,p]),(0,W.useEffect)(()=>{pe.some(e=>!e.isMain&&CO(e))||(ae.current=!1)},[pe]),(0,W.useEffect)(()=>{if(p.length>0||ae.current)return;let e=pe.find(e=>!e.isMain&&CO(e))?.id;e&&(ae.current=!0,m([e]),g(e))},[pe,p.length,e.mainAgentId]),(0,W.useEffect)(()=>{let t=z.current;if(!t)return;let n=e.agents.find(e=>e.isMain&&!e.archived&&!t.beforeIds.has(e.id));n&&(z.current=null,V.current=!1,Ce(n.id))},[Ce,e.agents]),(0,W.useEffect)(()=>{if(oe.current||e.agents.length===0)return;let t=new URLSearchParams(window.location.search).get(`agent`);if(!t){oe.current=!0;return}e.agents.some(e=>e.id===t&&!e.archived)&&(oe.current=!0,Ce(t))},[Ce,e.agents]),(0,W.useEffect)(()=>(document.body.classList.add(`code-mode`),()=>{document.body.classList.remove(`code-mode`)}),[]),(0,W.useEffect)(()=>{fO(`terminal`,{crtEffects:!1,appearance:N.appearance})},[N.appearance]),(0,W.useEffect)(()=>{let e=!1;return fetch(n(`/api/settings`)).then(e=>e.json()).then(t=>{if(e)return;let n=t.settings??{};P({appearance:lO(n.appearance),language:uO(n.language)})}).catch(()=>{}),()=>{e=!0}},[]),(0,K.jsxs)(`div`,{className:`app-container code-app-shell`,"data-testid":`app-shell`,children:[(0,K.jsx)(aO,{agents:pe,taskHistory:e.taskHistory,mainPageSessionKeys:e.mainPageSessionKeys,activeView:x,dialogOpen:de!==`none`,systemStats:e.systemStats??te?.systemStats??null,usageSummary:te,contextWindowByAgentId:j,activeTerminalId:ge,permissionSwitchingAgentId:T?.agent.id??null,agentSwitchingKind:T?.kind??null,permissionSwitchReplacement:T?.replacementAgentId?{originalAgentId:T.transitionFromAgentId??T.originalAgentId,replacementAgentId:T.replacementAgentId}:H??O,openTerminalIds:he,terminalFocusRequest:_,keyMap:r,keyboardShortcutsEnabled:pO,uiPreferences:N,onOpenTerminal:Ce,onOpenTerminalWhenReady:Se,onNewAgent:De,onStartAgent:Me,onRenameAgent:G,onUpdateAgentFlags:Re,onOpenArchivedAgent:ze,onForkAgent:Ne,onDeleteForkWorktreeProject:Fe,onRestartMainAgent:je,onWorkspaceViewChange:S,onKill:U,onInterruptAgent:e.interruptAgent,sendInput:e.sendInput,sendComposerInput:e.sendComposerInput,respondToAppServerRequest:e.respondToAppServerRequest,resizeAgent:e.resizeAgent,onSessionOutput:e.onSessionOutput,onUpdateUiPreferences:ye}),(0,K.jsx)(pt,{open:de===`input`,mustStartMain:!1,initialWorkspace:s,initialCommand:l,initialCustomTitle:d,showWorkflowTaskFields:!1,copy:fe,onStart:Me,onClose:ke}),_e&&(0,K.jsxs)(`div`,{className:`connection-status ${_e}`,"data-testid":`connection-status`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`connection-status-dot`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:ve})]}),C&&(0,K.jsx)(`div`,{className:`app-toast ${C.kind}`,"data-testid":`app-toast`,role:`status`,children:C.message})]})}export{kO as App};
124
+ `))})),Qi()},[Yr,da,Qi,H]),pa=(0,W.useCallback)(e=>{_i(t=>{let n=t.attachments.find(t=>t.id===e);return n&&aw(n),{...t,attachments:t.attachments.filter(t=>t.id!==e)}}),Qi()},[Qi,_i]),ma=(0,W.useCallback)(e=>{let t=Array.from(e.target.files??[]);e.target.value=``,fa(t)},[fa]),ha=(0,W.useCallback)(e=>{let t=mw(e.clipboardData);t.length!==0&&(e.preventDefault(),fa(t))},[fa]);(0,W.useEffect)(()=>{let e=Pn.current;if(e)return e.addEventListener(`cancel`,Qi),()=>e.removeEventListener(`cancel`,Qi)},[Qi]),(0,W.useEffect)(()=>{jn.current=Object.values(me).flatMap(e=>e.attachments)},[me]),(0,W.useEffect)(()=>()=>{jn.current.forEach(aw)},[]);let ga=(0,W.useCallback)(e=>{_i(t=>({...t,mode:e,ui:{...t.ui,plusMenuOpen:!1}})),Qi()},[Qi,_i]),_a=(0,W.useCallback)(e=>{let t=Y.find(t=>t.id===e);if(!t)return;let n=Number.isFinite(t.attentionSeq)?Math.max(0,Number(t.attentionSeq)):0;n>(Number.isFinite(t.readAttentionSeq)?Math.max(0,Number(t.readAttentionSeq)):0)?F(e,{readAttentionSeq:n}):t.unread&&F(e,{unread:!1})},[Y,F]),va=(0,W.useCallback)((e,t)=>{ve(n=>{let r=n[e];return r?.following===t.following&&r?.hasUnreadOutput===t.hasUnreadOutput?n:{...n,[e]:t}}),e===l&&i===`projects`&&ye===`terminal`&&t.following&&!t.hasUnreadOutput&&_a(e)},[l,i,ye,_a]);(0,W.useEffect)(()=>{if(!l||i!==`projects`||ye!==`terminal`)return;let e=_e[l];e&&e.following&&!e.hasUnreadOutput&&_a(l)},[l,i,ye,_a,_e]);let ya=(0,W.useCallback)(e=>{_i(t=>({...t,draft:e,history:{...t.history,cursor:null}}))},[_i]),ba=(0,W.useCallback)((e,t)=>{if(!Z||!Yr||!FC(t))return null;let n=IC(Zr.history,e,t.value);return n.changed?(H(Yr,e=>({...e,draft:n.value,history:n.history})),n.value):null},[Z,Yr,Zr.history,H]),xa=(0,W.useCallback)((e,t,n,r)=>{if(!Z||si!==`codex`||[`acp`,`json`].includes(Z.agentRuntimeMode||``)||Z.codexRuntimeMode===`app-server`)return;let i=dt.findIndex(t=>t.value===e),a=dt[i],o=a?.reasoningLevels||[],s=o.findIndex(e=>e.value===t);if(i<0||s<0)return;let c=Mn.current[Z.id],l=!!a?.serviceTiers?.some(e=>e.value===`priority`);Mn.current[Z.id]={model:e,effort:t,modelIndex:i,reasoningIndex:s,reasoningCount:o.length,fast:n===`priority`,fastAvailable:l,applyModel:!!(r.applyModel||c?.applyModel),applyFast:!!(r.applyFast||c?.applyFast)}},[Z,dt,si]),Sa=(0,W.useCallback)((e,t,n)=>{let r=jE(t,n),i=t=>{let n=r[t];if(!n||!se(n.input,e.id))return!1;let a=r[t+1];if(a){let e=window.setTimeout(()=>{Nn.current=Nn.current.filter(t=>t!==e),i(t+1)},a.delayMs-n.delayMs);Nn.current.push(e)}return!0};return i(0)?(delete Mn.current[e.id],!0):!1},[se]),Ca=(0,W.useCallback)((e,t,n=[])=>{if([`acp`,`json`].includes(e.agentRuntimeMode||``)||e.providerSessionProvider===`codex`&&e.codexRuntimeMode===`app-server`)return ce(t,e.id,e.agentRuntimeMode===`acp`?n:[]);if(rb(e.command)===`codex`){let n=Mn.current[e.id];if(n)return Sa(e,n,t)}return rb(e.command)===`shell`||lC(e).kind===`shell`||KD(e.command)?se(`${t}\r`,e.id):se(kE(t),e.id)},[Sa,ce,se]),wa=(0,W.useCallback)(async(e,t)=>(await fetch(n(`/api/agents/${encodeURIComponent(e.id)}/codex-goal`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({objective:t,status:`active`,tokenBudget:null})})).ok,[]),Ta=(0,W.useCallback)(e=>{let t=e??An.current?.value??Qr,n=sw(t,$r);if(!n||!Z||!Yr||$r.some(e=>e.status===`uploading`))return;if(ei===`goal`&&Z.providerSessionProvider===`codex`&&Z.codexRuntimeMode===`app-server`){(async()=>{await wa(Z,n)&&Ca(Z,n)&&(H(Yr,e=>(e.attachments.forEach(aw),{...e,draft:``,attachments:[],mode:`default`,history:PC(e.history,t)})),Qi())})();return}let r=hw(ei,n),i=!0;xb(Z)&&Z.codexRuntimeMode!==`app-server`&&![`acp`,`json`].includes(Z.agentRuntimeMode||``)?H(Yr,e=>{let t=e.pendingFollowUp;return{...e,pendingFollowUp:{messages:[...t?.messages||[],BC(r)],createdAt:t?.createdAt||Date.now()}}}):i=Ca(Z,r),i&&(H(Yr,e=>(e.attachments.forEach(aw),{...e,draft:``,attachments:[],mode:`default`,history:PC(e.history,t)})),Qi())},[Z,Yr,$r,ei,Qr,Qi,Ca,wa,H]),Ea=(0,W.useCallback)(e=>{gw({agent:Z,composerKey:Yr,draft:e??An.current?.value??Qr,attachments:$r,composerMode:ei,turnActive:ai,sendMessage:Ca,updateComposerState:H})&&Qi()},[Z,ai,Yr,$r,ei,Qr,Qi,Ca,H]),Da=(0,W.useCallback)(()=>{!Z||!ui||(oe(Z.id),Qi())},[Z,ui,Qi,oe]),Oa=(0,W.useCallback)((e,t)=>{Z&&le(Z.id,e,t)},[Z,le]),ka=(0,W.useCallback)(e=>{Z&&le(Z.id,e,void 0,{reject:!0,reason:`Declined in Farming`})},[Z,le]),Aa=(0,W.useCallback)((e,t,n)=>{Z&&_w(Z.id,e,t,n===!0)},[Z]),ja=(0,W.useCallback)((e,t,n)=>{Z&&vw(Z.id,e,t,n)},[Z]),Ma=(0,W.useCallback)(e=>{if(!Z||!Yr)return;let t=me[Yr]?.pendingFollowUp;if(!t||t.messages.length===0)return;let n=t.messages.find(t=>t.id===e);n&&Ca(Z,n.text,n.attachments)&&(ge.current[Yr]=n.id,H(Yr,t=>t.pendingFollowUp?{...t,pendingFollowUp:VC(t.pendingFollowUp,e)}:t),Qi())},[Z,Yr,me,Qi,Ca,H]),Na=(0,W.useCallback)(e=>{!Z||!Yr||(H(Yr,t=>t.pendingFollowUp?{...t,pendingFollowUp:VC(t.pendingFollowUp,e)}:t),Qi())},[Z,Yr,Qi,H]);(0,W.useEffect)(()=>{let e=[];Y.forEach(t=>{let n=t.agentRuntimeMode===`acp`?bw(t):KC(t);if(!n)return;let r=me[n]?.pendingFollowUp;if(!r||r.messages.length===0){delete ge.current[n];return}if(t.archived||t.status===`dead`||t.status===`stopped`)return;if(t.agentRuntimeMode===`acp`?Sb(t):xb(t)){delete ge.current[n];return}if(ge.current[n])return;let i=r.messages[0];i&&e.push({agent:t,composerKey:n,message:i})}),e.length!==0&&e.forEach(({agent:e,composerKey:t,message:n})=>{Ca(e,n.text,n.attachments)&&(ge.current[t]=n.id,he(t,e=>e.pendingFollowUp?{...e,pendingFollowUp:VC(e.pendingFollowUp,n.id)}:e))})},[Y,me,Ca,he]);let Pa=(0,W.useCallback)(()=>{nn(null),an(null),sn(null),ln(null),vi(),gr(),V(`search`),Be(!0),requestAnimationFrame(()=>Rn.current?.focus())},[vi,gr,V]),Fa=(0,W.useCallback)(()=>{XD()&&hr()},[hr]),Ia=(0,W.useCallback)(()=>{gr()},[gr]),La=(0,W.useCallback)((e,t,n)=>{M(e,t,n),Fa()},[Fa,M]),Ra=(0,W.useCallback)((e,t,n)=>{if(Ue(``),Be(!1),Ge(0),be(`terminal`),V(`projects`),rb(e)!==`codex`){te(e,t,n);return}let r=n?.codexApprovalMode||et;te(e,t,{...n,codexApprovalMode:r,...r===`full`?{dangerouslySkipPermissions:!0}:{}})},[et,te,V]);(0,W.useEffect)(()=>{let e=!1;return fetch(n(`/api/executables`)).then(e=>{if(!e.ok)throw Error(`Failed to load executables: ${e.status}`);return e.json()}).then(t=>{e||Ze(Je(Array.isArray(t)?t:t.agents??[]))}).catch(()=>{e||Ze([])}),()=>{e=!0}},[]);let za=(0,W.useCallback)(e=>{fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mainPageSessionKeys:kS(e)})}).catch(()=>{})},[]),Ba=(0,W.useCallback)(e=>{$e(t=>{let n=kS(e(t));return jD(t,n)?t:(lr.current+=1,za(n),new Set(n))})},[za]);(0,W.useEffect)(()=>{let e=kS(r);$e(t=>jD(t,e)?t:new Set(e))},[r]);let Va=(0,W.useCallback)((e,t,n=``)=>{let r=Rb({provider:e,id:t,providerHomeId:n});Ba(e=>[...e,r])},[Ba]),Ha=(0,W.useCallback)(e=>{Ba(t=>Array.from(t).filter(t=>t!==e))},[Ba]),Ua=(0,W.useCallback)(e=>{let t=new Set(e);Ba(e=>Array.from(e).filter(e=>!t.has(e)))},[Ba]),Wa=(0,W.useCallback)(e=>{Promise.resolve(e).then(e=>{if(!e||typeof e!=`object`)return;let t=Array.isArray(e.removedMainPageSessionKeys)?e.removedMainPageSessionKeys:[];t.length>0&&Ua(t)}).catch(()=>{})},[Ua]);(0,W.useEffect)(()=>{Y.forEach(e=>{if(e.providerSessionTemporary===!0)return;let t=e.providerSessionKey||NS(e.source);if(!t)return;let n=`${e.id}:${t}`;ur.current.has(n)||(ur.current.add(n),Ba(e=>[...e,t]),sa())})},[Y,sa,Ba]),(0,W.useEffect)(()=>{if(!pe||!Y.some(e=>e.providerSessionTemporary===!0))return;sa();let e=window.setInterval(sa,5e3);return()=>window.clearInterval(e)},[Y,pe,sa]);let Ga=(0,W.useCallback)(()=>{let e=$n.current,t=Array.from(kn.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`)??[]),n=(e?t.find(t=>t.dataset.agentId===e):null)??t[0]??Gn.current;return n?(n.focus({preventScroll:!0}),document.activeElement===n):!1},[]),Ka=(0,W.useCallback)(e=>{let t=Array.from(kn.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`)??[]).find(t=>e.kind===`agent`?t.dataset.agentId===e.id:t.dataset.provider===e.provider&&t.dataset.sessionId===YD(e));return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),qa=(0,W.useCallback)(()=>{if(a||document.querySelector(`.code-context-menu`)||document.querySelector(`.code-composer.menu-open, .code-composer-menu`))return!0;let e=document.activeElement;return e instanceof HTMLElement?e.closest(`.code-context-menu`)?!0:e===document.body||e===document.documentElement||Gn.current?.contains(e)||e.closest(`.code-sidebar`)?!1:!!e.closest(`.code-composer`):!1},[a]),Ja=(0,W.useCallback)(e=>{window.requestAnimationFrame(()=>{e?.skipIfFocusMoved&&qa()||Ga()})},[Ga,qa]),Ya=(0,W.useCallback)(()=>{Ue(``),Be(!1),Ge(0)},[]),Xa=(0,W.useCallback)(()=>{Ya(),V(`projects`),or.current=`active-force`},[Ya,V]);(0,W.useEffect)(()=>{if(!Le||i!==`search`)return;let e=e=>{let t=e.target;t instanceof Element&&(t.closest(`.code-search-panel, [data-testid="code-nav-search"], [data-testid="code-mobile-menu"]`)||Xa())};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[i,Xa,Le]);let Za=(0,W.useCallback)(e=>{nn(null),an(null),sn(null),ln(null),e===`projects`?(gr(),Ya()):e!==`search`&&Ya(),V(e)},[Ya,gr,V]),Qa=(0,W.useCallback)(()=>{Pa(),Fa()},[Fa,Pa]),$a=(0,W.useCallback)(e=>{Za(e),Fa()},[Fa,Za]),eo=(0,W.useCallback)(e=>{Ht(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),to=(0,W.useCallback)(e=>{Wt(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),no=(0,W.useCallback)((e,t)=>{be(`terminal`),V(`projects`),e.kind===`agent`?E(e.id,{focusTerminal:t?.focusTerminal}):Qn.current(e.provider,e.id,e.providerHomeId)},[E,V]),Q=(0,W.useCallback)(()=>{let e=document.activeElement;if(e instanceof HTMLElement){let t=e.closest(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"], [data-testid="code-active-session-row"]`);if(t?.dataset.agentId)return Ob({kind:`agent`,id:t.dataset.agentId});if(t?.dataset.sessionId&&t.dataset.provider)return t.dataset.sessionId}let t=$n.current;return t?Ob({kind:`agent`,id:t}):``},[]),ro=(0,W.useCallback)(e=>{if(Vr.length===0)return;let t=Q(),n=Vr.findIndex(e=>YD(e)===t),r=Vr[((n===-1?e>0?-1:0:n)+e+Vr.length)%Vr.length];r&&(no(r,{focusTerminal:!1}),r.kind===`agent`&&(qa()||Ka(r),window.requestAnimationFrame(()=>{qa()||Ka(r)})),or.current=`active`)},[Q,Ka,no,qa,Vr]),io=(0,W.useCallback)(e=>{if(!(e.ctrlKey||e.metaKey||e.altKey)){if(e.key===`/`&&!e.shiftKey){e.preventDefault(),Pa();return}if(e.key===`ArrowDown`){e.preventDefault(),ro(1);return}e.key===`ArrowUp`&&(e.preventDefault(),ro(-1))}},[ro,Pa]),ao=(0,W.useCallback)(e=>{Hr.length!==0&&Ge(t=>(t+e+Hr.length)%Hr.length)},[Hr.length]),oo=(0,W.useCallback)(()=>{Si&&(no(Si),Ya())},[Ya,no,Si]),so=(0,W.useCallback)(e=>{if(e.key===`Escape`){e.preventDefault(),Xa();return}if(e.key===`ArrowDown`){e.preventDefault(),ao(1);return}if(e.key===`ArrowUp`){e.preventDefault(),ao(-1);return}e.key===`Enter`&&(e.preventDefault(),oo())},[Xa,ao,oo]),co=(0,W.useCallback)(e=>{let t=e-(kn.current?.getBoundingClientRect().left??0);if(t<=LD){mr();return}let n=Math.max(PD,Math.min(FD,t));gr(),Kt(n)},[mr,gr]),lo=(0,W.useCallback)(e=>{let t=Array.from(kn.current?.querySelectorAll(`[data-testid="code-agent-row"], [data-testid="code-project-agent-compact"], [data-testid="code-pinned-agent-compact"], [data-testid="code-agent-rail-item"]`)??[]).find(t=>t.dataset.agentId===e);return t?(t.focus({preventScroll:!0}),document.activeElement===t):!1},[]),uo=(0,W.useCallback)(e=>{IE(()=>{lo(e)},{delays:[80,180]})},[lo]),fo=(0,W.useCallback)((e,t)=>{window.requestAnimationFrame(()=>{Array.from(kn.current?.querySelectorAll(`[data-testid="code-active-session-row"]`)??[]).find(n=>n.dataset.provider===e&&n.dataset.sessionId===t)?.focus({preventScroll:!0})})},[]),po=(0,W.useCallback)(e=>{window.requestAnimationFrame(()=>{Array.from(kn.current?.querySelectorAll(`[data-testid="code-project-title"]`)??[]).find(t=>t.dataset.projectId===e)?.focus()})},[]),mo=(0,W.useCallback)(async()=>{if(!xi)return;let e=Rb(xi),t=xi.pinned!==!0;It(n=>({...n,[e]:t})),sn(null),ln(null),Qe.has(e)?fo(xi.provider,e):window.requestAnimationFrame(()=>Gn.current?.focus({preventScroll:!0}));try{if(!(await fetch(n(`/api/agent-sessions/${encodeURIComponent(xi.provider)}/${encodeURIComponent(xi.id)}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t,providerHomeId:xi.providerHomeId||`default`})})).ok)throw Error(J.updateFailed);let r=await aa({limit:Pt.current});Tt(r.sessions),Dt(r.nextCursor),kt(r.hasMore),It(t=>{let n={...t};return delete n[e],n})}catch(n){It(n=>({...n,[e]:!t})),xn({id:Date.now(),kind:`error`,message:n instanceof Error?n.message:J.updateFailed})}},[xi,J.updateFailed,aa,fo,Qe]),ho=(0,W.useCallback)(()=>{if(!xi)return;let e=Rb(xi);It(t=>({...t,[e]:!1})),Ha(e),sn(null),ln(null),window.requestAnimationFrame(()=>Gn.current?.focus({preventScroll:!0}))},[xi,Ha]),go=(0,W.useCallback)(e=>{e.preventDefault(),gr(),dr.current=!0,document.body.classList.add(`code-resizing-sidebar`),co(e.clientX)},[gr,co]),_o=(0,W.useCallback)((e,t)=>{nn(null),an(null),sn(null),ln(null),Ya(),be(`terminal`),V(`projects`),E(e,t)},[Ya,E,V]),vo=(0,W.useCallback)(e=>{_o(e),Fa()},[Fa,_o]),yo=(0,W.useCallback)(e=>d(e,{cursorRequestId:e?.lineNumber?er.current+=1:er.current,diffRequestId:e?.view===`diff`?tr.current+=1:tr.current}),[]),bo=(0,W.useCallback)((e,t,n)=>{let r=Oe(e),i=n?.sourceAgentId??(r?$n.current??void 0:e),a=Y.find(t=>t.id===(r?i:e)),o=r?`/`:a&&!a.isMain?Ab(a):void 0;if(!r&&a){let e=a.isMain?Tb:Ab(a);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`editor`);let s={...yo(n),workspaceRoot:o,sourceAgentId:i};we.openFromRead(e,t,s),u(n)&&Cn({agentId:e,path:t.path,kind:`file`,requestId:nr.current+=1}),a&&i&&E(i,{focusTerminal:!1}),Fa()},[Y,Ya,Fa,yo,E,V,we]);(0,W.useEffect)(()=>{if(Ce.current||Se.current||Y.length===0)return;Se.current=!0;let e=xe;if(!e){Ce.current=!0;return}if(e.kind===`agent`){let t=Y.find(t=>t.id===e.agentId)??Y.find(t=>!!e.providerSessionKey&&t.providerSessionKey===e.providerSessionKey)??Y.find(t=>!!e.workspace&&Ab(t)===e.workspace);t?_o(t.id,{focusTerminal:!1}):D({surface:void 0}),Ce.current=!0;return}let t=e.workspace===`/`?ke:Y.find(t=>Ab(t)===e.workspace)?.id;if(!t){D({surface:void 0}),Ce.current=!0;return}R(t,e.filePath).then(n=>{bo(t,n,{view:e.view??`editor`,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn,revealInTree:!0,sourceAgentId:e.sourceAgentId})}).catch(()=>{D({surface:void 0})}).finally(()=>{Ce.current=!0})},[Y,xe,bo,_o]),(0,W.useEffect)(()=>{if(!Ce.current||i!==`projects`)return;if(ye===`terminal`){let e=Y.find(e=>e.id===l);if(!e)return;D({surface:{kind:`agent`,agentId:e.id,providerSessionKey:e.providerSessionKey||void 0,workspace:Ab(e)}});return}if(!G)return;let e=G.workspaceRoot??Y.find(e=>e.id===G.agentId)?.projectWorkspace??Y.find(e=>e.id===G.agentId)?.cwd??``;e&&D({surface:{kind:`file`,workspace:e,filePath:G.file.path,view:G.diffRequestId?`diff`:`editor`,lineNumber:G.cursor?.lineNumber,column:G.cursor?.column,endColumn:G.cursor?.endColumn,sourceAgentId:G.sourceAgentId}})},[Y,l,i,ye,G]);let xo=(0,W.useCallback)((e,t)=>{let n=Y.find(t=>t.id===e);if(!Oe(e)&&n){let e=n.isMain?Tb:Ab(n);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}nn(null),an(null),sn(null),ln(null),Ya(),gr(),V(`projects`),Tn({agentId:e,...t?{query:t}:{},requestId:rr.current+=1})},[Y,Ya,gr,V]),So=(0,W.useCallback)((e,t,n)=>{let r=Y.find(t=>t.id===e);if(!Oe(e)&&r){let e=r.isMain?Tb:Ab(r);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}nn(null),an(null),sn(null),ln(null),Ya(),gr(),V(`projects`),Cn({agentId:e,path:t,kind:n,requestId:nr.current+=1})},[Y,Ya,gr,V]),Co=(0,W.useCallback)(async(e,t)=>{let n=Y.find(t=>t.id===e),r=gv(t.path,n?Ab(n):``);if(!r)return null;try{let n=nO((await I(e,r,{limit:zD})).matches),i=n.find(e=>e.path===r)?.path??(n.length===1?n[0]?.path:``);return i?{...t,path:i}:null}catch{return null}},[Y]),wo=(0,W.useCallback)((e,t)=>{let n=Y.find(t=>t.id===e),r=gv(t.path,n?Ab(n):``);if(!r)return;let i=ir.current+1;ir.current=i;let a=tO(t),o=async(t,n=a)=>{let r=await R(e,t);ir.current===i&&bo(e,r,n)},s=t=>{ir.current===i&&So(e,t,`directory`)},c=async e=>{if(e.entryType===`directory`){s(e.path);return}await o(e.path)},l=()=>{ir.current===i&&xo(e,r)};(async()=>{try{await ne(e,r),s(r);return}catch{}try{await o(r);return}catch{}try{let t=await I(e,r,{limit:zD});if(ir.current!==i)return;let n=nO(t.matches);if(n.length===1){let e=n[0];if(!e)return;await c(e);return}let s=rO(t.matches);if(n.length===0&&s.length===1){let e=s[0];if(!e)return;await o(e.path,a??(e.kind===`content`?{lineNumber:e.lineNumber,column:e.ranges[0]?e.ranges[0].start+1:void 0,endColumn:e.ranges[0]?Math.max(e.ranges[0].start+1,e.ranges[0].end+1):void 0}:void 0));return}}catch{}l()})()},[Y,xo,bo,So]),To=(0,W.useCallback)((e,t,n)=>{let r=Oe(e),i=n?.sourceAgentId??(r?$n.current??void 0:e),a=Y.find(t=>t.id===(r?i:e)),o=r?`/`:a&&!a.isMain?Ab(a):void 0;if(!r&&a){let e=a.isMain?Tb:Ab(a);Ht(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})}let s=f({agentId:e,workspaceRoot:o,filePath:t});if(!Fe.some(e=>m(e)===s))return!1;let c={...yo(n),workspaceRoot:o,sourceAgentId:i};return we.select(e,t,c)?(nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`editor`),u(n)&&Cn({agentId:e,path:t,kind:`file`,requestId:nr.current+=1}),a&&i&&E(i,{focusTerminal:!1}),Fa(),!0):!1},[Y,Ya,Fa,yo,E,V,Fe,we]),Eo=(0,W.useCallback)(async(e,t,n)=>{let r=n?.globalRoot?ke:e,i=n?.globalRoot?Ae(t):t,a=n?.globalRoot?{...n,sourceAgentId:n.sourceAgentId??e}:n;if(To(r,i,a))return;let o=async(e,t=a)=>{bo(r,await R(r,e),t)};try{await o(i,a)}catch{try{await ne(r,i),So(r,i,`directory`)}catch{try{let e=await I(r,i,{limit:zD}),t=nO(e.matches),n=rO(e.matches);if(t.length===1){let e=t[0];if(e?.entryType===`directory`){So(r,e.path,`directory`);return}if(e?.path){await o(e.path,a);return}}if(t.length===0&&n.length===1){let e=n[0];if(e?.path){await o(e.path,a??(e.kind===`content`?{lineNumber:e.lineNumber,column:e.ranges[0]?e.ranges[0].start+1:void 0,endColumn:e.ranges[0]?Math.max(e.ranges[0].start+1,e.ranges[0].end+1):void 0}:void 0));return}}}catch{}a?.suppressSearchOnMiss||xo(r,i)}}},[xo,bo,So,To]),Do=(0,W.useCallback)(async e=>{if(e.kind===`agent`)return br.has(e.agentId)?(nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`terminal`),E(e.agentId,{focusTerminal:!1}),Fa(),!0):!1;let t=O(e,Y.filter(e=>!e.isMain).map(e=>({agentId:e.id,workspace:Ab(e)})),ke);if(!t)return!1;if(e.kind===`folder`)try{let e=C((await ne(t.agentId,t.filePath)).items);if(e){let n=await R(t.agentId,e);return bo(t.agentId,n),!0}return So(t.agentId,t.filePath,`directory`),!0}catch{return!1}let n=N(e);if(To(t.agentId,t.filePath,n))return!0;try{let e=await R(t.agentId,t.filePath);return bo(t.agentId,e,n),!0}catch{return!1}},[Y,Ya,Fa,E,V,bo,So,To,br]),Oo=(0,W.useRef)(Do);Oo.current=Do;let ko=(0,W.useCallback)(()=>{if(typeof window>`u`)return;let e=S(window.location.search);window.history.replaceState(window.history.state,``,`${window.location.pathname}${e}${window.location.hash}`)},[]);(0,W.useEffect)(()=>{if(!Yt)return;let e=!1,t=null,n=Yt.kind===`agent`?Yt.agentId:Yt.absolutePath||(Yt.kind===`folder`?Yt.folderPath:Yt.filePath);return Oo.current(Yt).then(r=>{if(!e){if(r){Xt(null),ko();return}if(ar.current+=1,ar.current>=20){xn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),Xt(null),ko();return}t=window.setTimeout(()=>{Qt(e=>e+1)},250)}}).catch(()=>{e||(xn({id:Date.now(),kind:`error`,message:J.sharedLocationUnavailable(n)}),Xt(null),ko())}),()=>{e=!0,t!==null&&window.clearTimeout(t)}},[ko,J.sharedLocationUnavailable,Yt,Zt]);let Ao=(0,W.useCallback)(async e=>{if(!br.has(e.agentId))return!1;if(nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),e.kind===`agent`)return be(`terminal`),E(e.agentId),Fa(),!0;let t={view:e.view,lineNumber:e.lineNumber,column:e.column,endColumn:e.endColumn};if(To(e.agentId,e.filePath,t))return!0;try{let n=await R(e.agentId,e.filePath);return bo(e.agentId,n,t),!0}catch{return!1}},[Ya,Fa,E,V,bo,To,br]),jo=(0,W.useCallback)(e=>{let t=Me(e);return t?((async()=>{let n=t;for(;n;){if(await Ao(n))return;n=Me(e)}})().finally(()=>{Ne()}),!0):!1},[Me,Ne,Ao]),Mo=(0,W.useCallback)(e=>{be(`terminal`),V(`projects`),E(e,{focusTerminal:!L()}),Fa()},[Fa,E,V]),No=(0,W.useCallback)(e=>{let t=we.close(e);t.closedFiles.length!==0&&t.activeFileClosed&&be(t.activeFile?`editor`:`terminal`)},[we]),Po=(0,W.useCallback)((e,t,n)=>{No([{agentId:e,filePath:t,workspaceRoot:n}])},[No]),Fo=(0,W.useCallback)(()=>{let e=we.reopenLastClosed(e=>Y.some(t=>t.id===e.agentId&&!t.isMain)||Oe(e.agentId))?.activeFile;if(!e)return!1;nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),be(`editor`);let t=Oe(e.agentId)?e.sourceAgentId:e.agentId;return t&&Y.some(e=>e.id===t)&&E(t,{focusTerminal:!1}),Fa(),!0},[Y,Ya,Fa,E,V,we]),Io=(0,W.useCallback)(e=>{we.update(e)},[we]),Lo=(0,W.useCallback)(e=>{we.updateDraft(e)},[we]),Ro=(0,W.useCallback)((e,t)=>{t.length!==0&&we.move(e,t)},[we]),zo=(0,W.useCallback)((e,t)=>{if(t.length===0)return;let n=we.deleteEntries(e,t);n.activeFileDeleted&&(n.activeFile||be(`terminal`))},[we]),Bo=(0,W.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=Y.find(e=>e.id===t),r=Hw(e.clientX,e.clientY,Gw(n));an(null),sn(null),ln(null),nn({agentId:t,x:r.x,y:r.y})},[Y]),Vo=(0,W.useCallback)((e,t)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=Y.find(e=>e.id===t),i=Hw(n.left+24,n.top+n.height,Gw(r));an(null),sn(null),ln(null),nn({agentId:t,x:i.x,y:i.y})},[Y]),Ho=(0,W.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=L()?VD:Vw(2),i=L()?Ww(n,r,void 0,BD):Uw(n,r);nn(null),sn(null),ln(null),an({projectId:t,x:i.x,y:i.y})},[]),Uo=(0,W.useCallback)((e,t)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let n=e.currentTarget.getBoundingClientRect(),r=L()?VD:Vw(2),i=L()?Ww(n,r,void 0,BD):Uw(n,r);nn(null),sn(null),ln(null),an({projectId:t,x:i.x,y:i.y})},[]),Wo=(0,W.useCallback)((e,t,n)=>{e.preventDefault(),e.stopPropagation();let r=Hw(e.clientX,e.clientY,Vw(3));nn(null),an(null),ln(null),sn({provider:t,sessionId:n,x:r.x,y:r.y})},[]),Go=(0,W.useCallback)((e,t,n)=>{if(e.key!==`ContextMenu`&&!(e.shiftKey&&e.key===`F10`))return;e.preventDefault(),e.stopPropagation();let r=e.currentTarget.getBoundingClientRect(),i=Hw(r.left+24,r.top+r.height,Vw(3));nn(null),an(null),ln(null),sn({provider:t,sessionId:n,x:i.x,y:i.y})},[]),Ko=(0,W.useCallback)(()=>{if(!yi)return;let e=h(yi);nn(null),ln(null),hn({kind:`agent`,agentId:yi.id,title:e})},[yi]),qo=(0,W.useCallback)(()=>{bi&&(an(null),ln(null),hn({kind:`project`,projectId:bi.id,workspace:bi.workspace,title:bi.name}))},[bi]),Jo=(0,W.useCallback)(()=>{let e=mn;hn(null),e&&(e.kind===`agent`&&uo(e.agentId),e.kind===`project`&&po(e.projectId))},[uo,po,mn]),Yo=(0,W.useCallback)(()=>{if(!mn)return;let e=mn.title.trim();if(mn.kind===`agent`){if(!e)return;P(mn.agentId,e),hn(null),uo(mn.agentId);return}if(!e)return;let t={...qe,[mn.workspace]:e};Ye(t),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({projectNames:t})}).then(e=>e.json()).then(e=>{Ye(kD((e.settings??{}).projectNames))}).catch(()=>{xn({id:Date.now(),kind:`error`,message:J.copyFailed})}),hn(null),po(mn.projectId)},[J.copyFailed,uo,po,P,qe,mn]),Xo=(0,W.useCallback)(async(e,t)=>{nn(null),an(null),sn(null),ln(null);let n=await iO(e);xn({id:Date.now(),kind:n?`success`:`error`,message:n?J.copiedWorkingDirectory:J.copyFailed}),t?.kind===`agent`&&uo(t.id),t?.kind===`agent-session`&&fo(t.provider,Rb(t))},[J.copiedWorkingDirectory,J.copyFailed,uo,fo]),Zo=(0,W.useCallback)(()=>{yi&&(nn(null),ln(null),_n({agentId:yi.id,title:h(yi)}))},[yi]),Qo=(0,W.useCallback)(()=>{let e=gn?.agentId;_n(null),e&&uo(e)},[uo,gn?.agentId]),$o=(0,W.useCallback)(()=>{gn&&(ae(gn.agentId),_n(null))},[gn,ae]),es=(0,W.useCallback)(e=>{yi&&(nn(null),ln(null),z(yi.id,e))},[yi,z]),ts=(0,W.useCallback)(e=>{if(!yi)return;let t=yi.id;if(nn(null),ln(null),e.archived===!0){let e=yi.providerSessionKey||NS(yi.source);e&&Ha(e),sr.current=t,window.setTimeout(()=>Ga(),120),window.setTimeout(()=>Ga(),360),window.setTimeout(()=>Ga(),720)}let n=F(t,e);e.archived===!0&&Wa(n),e.archived!==!0&&uo(t)},[yi,Ga,uo,F,Ha,Wa]),ns=(0,W.useCallback)((e,t)=>{let n=e.id;if(nn(null),ln(null),t.archived===!0){let t=e.providerSessionKey||NS(e.source);t&&Ha(t),sr.current=n,window.setTimeout(()=>Ga(),120),window.setTimeout(()=>Ga(),360),window.setTimeout(()=>Ga(),720)}let r=F(n,t);t.archived===!0&&Wa(r),t.archived!==!0&&uo(n)},[Ga,uo,F,Ha,Wa]),rs=(0,W.useCallback)(async(e,t,r)=>{try{let i=await fetch(n(`/api/agents/${encodeURIComponent(e)}/reorder`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({beforeAgentId:t,afterAgentId:r})});if(!i.ok){let e=await i.json().catch(()=>null);throw Error(e?.error||J.reorderAgentFailed)}}catch(e){xn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.reorderAgentFailed})}},[J.reorderAgentFailed]),is=(0,W.useCallback)(e=>{sr.current=null,cr.current=e,F(e,{archived:!1}),Ya(),V(`projects`),[120,360,720,1200,1800].forEach(t=>{window.setTimeout(()=>{qa()||lo(e)},t)})},[Ya,lo,F,V,qa]),as=(0,W.useCallback)(e=>{re(e)},[re]),os=(0,W.useCallback)(async(e,t,r=``,i=``)=>{let a=Rb({provider:e,id:t,providerHomeId:r}),o=()=>{Tt(n=>n.map(n=>n.provider===e&&n.id===t&&(n.providerHomeId||`default`)===(r||`default`)?{...n,archived:!1}:n))},s=Y.find(n=>(n.providerSessionKey===a||n.source===jS(e,t,r))&&n.archived!==!0&&n.status!==`dead`&&n.status!==`stopped`);if(s){o(),Va(e,t,r),E(s.id),Fa();return}try{let a=await fetch(n(`/api/agent-sessions/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resume`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({unarchiveArchived:!0,providerHomeId:r,...[`codex`,`claude`,`opencode`,`qoder`].includes(e)?{agentRuntimeMode:`acp`,acpHistoryMode:`load`}:{},...i?{customTitle:i}:{}})}),s=await a.json().catch(()=>null);if(!a.ok||!s?.agentId){xn({id:Date.now(),kind:`error`,message:s?.error||`Failed to resume agent session (${a.status})`});return}o(),Va(e,t,r),ee(s.agentId),Fa()}catch(e){xn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:`Failed to resume agent session`})}},[Y,Va,Fa,E,ee]);Qn.current=os;let ss=(0,W.useCallback)(e=>{let t=JD(e.source);if(t){os(t.provider,t.sessionId,t.providerHomeId,e.customTitle||``),V(`projects`);return}M(dT(e),e.command||void 0,null,e.customTitle||void 0)},[M,V,os]),cs=(0,W.useCallback)(e=>{if(e.preventDefault(),e.stopPropagation(),nn(null),an(null),sn(null),!L()){ln(null),dn(!0);return}let t=e.currentTarget.getBoundingClientRect();ln({x:Math.max(8,t.right-164),y:Math.min(window.innerHeight-12,t.bottom+6),returnFocusTarget:e.currentTarget})},[]),ls=(0,W.useCallback)(async()=>{ln(null);try{let e=await fetch(n(`/api/share/qr-ticket`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ai?{target:Ai}:{})}),t=await e.json().catch(()=>null);if(!e.ok||!t?.longUrl&&!t?.shortUrl)throw Error(t?.error||J.shareLinkFailed);pn(t.longUrl||t.shortUrl||``)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;xn({id:Date.now(),kind:`error`,message:e instanceof Error?e.message:J.shareLinkFailed})}},[J.shareLinkFailed,Ai]),us=(0,W.useCallback)(e=>{ln(null),fe({language:e})},[fe]),ds=(0,W.useCallback)(e=>{ln(null),fe({appearance:e})},[fe]),fs=(0,W.useCallback)(()=>{ln(null),dn(!0)},[]),ps=(0,W.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),ln(null),dn(!0)},[]),ms=(0,W.useMemo)(()=>L()?Ow([{type:`separator`,id:`options-mobile-share-separator`},{type:`item`,id:`options-mobile-share`,label:J.sharePage,ariaLabel:J.sharePage,onSelect:ls}]):Ow([{type:`item`,id:`options-appearance-light`,label:AD(J.appearanceLight),ariaLabel:J.appearanceLight,checked:T.appearance===`light`,onSelect:()=>ds(`light`)},{type:`item`,id:`options-appearance-dark`,label:AD(J.appearanceDark),ariaLabel:J.appearanceDark,checked:T.appearance===`dark`,onSelect:()=>ds(`dark`)},{type:`separator`,id:`options-appearance-language-separator`},{type:`item`,id:`options-language-en`,label:OD(J.languageEnglish),ariaLabel:J.languageEnglish,checked:T.language===`en`,onSelect:()=>us(`en`)},{type:`item`,id:`options-language-zh`,label:OD(J.languageChinese),ariaLabel:J.languageChinese,checked:T.language===`zh`,onSelect:()=>us(`zh`)},{type:`separator`,id:`options-settings-separator`},{type:`item`,id:`options-open-settings`,label:J.openSettings,ariaLabel:J.openSettings,onSelect:fs}]),[J.appearanceDark,J.appearanceLight,J.languageChinese,J.languageEnglish,J.openSettings,J.sharePage,fs,ls,T.appearance,T.language,ds,us]),hs=(0,W.useCallback)((e,t)=>{fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentLaunchProfiles:{[e]:t}})}).catch(()=>{})},[]),gs=(0,W.useCallback)(e=>{if(p)return;if(si===`claude`){let t=YE(e)?e:`default`;mt(t),hs(`claude`,{permissionMode:t}),Z&&(xn({id:Date.now(),kind:`success`,message:J.permissionProfileRestarting}),F(Z.id,{launchPermissionMode:t})),vi(),Qi();return}let t=JE(e)?e:`approve`;nt(t),hs(`codex`,{approvalMode:t}),Z&&si===`codex`&&(xn({id:Date.now(),kind:`success`,message:Z.codexRuntimeMode===`app-server`?J.permissionProfileApplying:J.permissionProfileRestarting}),F(Z.id,{launchPermissionMode:t})),vi(),Qi()},[Z,vi,si,J.permissionProfileApplying,J.permissionProfileRestarting,Qi,F,p,hs]),_s=(0,W.useCallback)((e,t)=>{p||(xn({id:Date.now(),kind:`success`,message:J.runtimeModeRestarting}),F(e,{agentRuntimeMode:t}))},[J.runtimeModeRestarting,F,p]),vs=(0,W.useCallback)(e=>{if(si===`claude`){let t=$E(e);gt(t),vi(),Qi(),hs(`claude`,{model:t,effort:_t});return}let t=dt.find(t=>t.value===e),n=t?.reasoningLevels??[],r=t?.serviceTiers??[],i=n.some(e=>e.value===st)?st:t?.defaultEffort||n[0]?.value||st,a=r.some(e=>e.value===lt)?lt:`default`;ot(e),ct(i),ut(a),it(`${e}:${i}`),vi(),Qi(),hs(`codex`,{model:e,reasoningEffort:i,serviceTier:a}),xa(e,i,a,{applyModel:!0})},[_t,vi,dt,st,lt,si,Qi,hs,xa]),ys=(0,W.useCallback)((e,t)=>{if(si!==`codex`)return;let n=dt.find(t=>t.value===e);if(!n)return;let r=n.reasoningLevels?.some(e=>e.value===t)?t:n.defaultEffort||n.reasoningLevels?.[0]?.value||t,i=n.serviceTiers?.some(e=>e.value===lt)?lt:`default`;ot(e),ct(r),ut(i),it(`${e}:${r}`),hs(`codex`,{model:e,reasoningEffort:r,serviceTier:i}),xa(e,r,i,{applyModel:!0})},[dt,lt,si,hs,xa]),bs=(0,W.useCallback)(e=>{if(si===`claude`){let t=tD(e);vt(t),vi(),Qi(),hs(`claude`,{model:ht,effort:t});return}ct(e),it(`${at}:${e}`),vi(),Qi(),hs(`codex`,{model:at,reasoningEffort:e,serviceTier:lt}),xa(at,e,lt,{applyModel:!0})},[ht,vi,at,lt,si,Qi,hs,xa]),xs=(0,W.useCallback)(e=>{si!==`claude`&&(ut(e),vi(),Qi(),hs(`codex`,{model:at,reasoningEffort:st,serviceTier:e}),xa(at,st,e,{applyFast:!0}))},[vi,at,st,si,Qi,hs,xa]),Ss=(0,W.useCallback)(e=>{si===`codex`&&(ut(e),hs(`codex`,{model:at,reasoningEffort:st,serviceTier:e}),xa(at,st,e,{applyFast:!0}))},[at,st,si,hs,xa]),Cs=(0,W.useCallback)(()=>{if(zt){Yn.current?.stop(),Yn.current=null,Bt(!1);return}let e=Yr;if(!e)return;let t=L(),n=GD(),r=Lt&&!n?window.SpeechRecognition||window.webkitSpeechRecognition:null;if(!r){(GD()||t)&&Qi(),Bt(!1);return}let i=new r,a=null,o=()=>{a!==null&&(window.clearTimeout(a),a=null)},s=()=>{if(Yn.current===i)try{i.stop()}catch{Bt(!1),Yn.current=null}};i.continuous=!1,i.interimResults=!1,i.lang=T.language===`zh`?`zh-CN`:navigator.language||`en-US`,i.onresult=t=>{let n=``;for(let e=t.resultIndex;e<t.results.length;e+=1)n+=t.results[e]?.[0]?.transcript??``;n.trim()&&(H(e,e=>{let t=e.draft&&!/\s$/.test(e.draft)?` `:``;return{...e,draft:`${e.draft}${t}${n.trim()}`}}),Qi())},i.onerror=()=>{o(),Bt(!1)},i.onspeechend=s,i.onaudioend=s,i.onend=()=>{o(),Bt(!1),Yn.current=null},Yn.current=i,Bt(!0);try{i.start(),a=window.setTimeout(s,6e4)}catch{o(),Yn.current=null,Bt(!1),t&&Qi()}},[Yr,Qi,zt,Lt,T.language,H]),ws=(0,W.useCallback)(()=>{if(!bi)return;let e=bi.workspace,t=bi.agents.filter(e=>!e.isMain),n=Cr.filter(t=>Bb(t)===e);if(t.length===0&&n.length===0){an(null),ln(null),or.current=`list`;return}t.forEach(e=>{F(e.id,{archived:!0})}),Ua(n.map(Rb)),an(null),ln(null),or.current=`list`},[Cr,bi,F,Ua]),Ts=(0,W.useCallback)(()=>{let e=vn?.projectId;yn(null),e&&po(e)},[vn?.projectId,po]),Es=(0,W.useCallback)(async()=>{if(!vn)return;let e=vn,t=await B(e.workspace,{force:!0});t.deleted&&(Ua([...e.sessionHandles,...t.removedMainPageSessionKeys??[]]),or.current=`list`,yn(null))},[vn,B,Ua]),Ds=(0,W.useCallback)(()=>{let e=tn?.agentId,t=rn?.projectId,n=on?.provider,r=on?.sessionId,i=cn?.returnFocusTarget??null;nn(null),an(null),sn(null),ln(null),e?uo(e):t?po(t):n&&r?fo(n,r):i&&window.requestAnimationFrame(()=>i.focus({preventScroll:!0}))},[tn?.agentId,on?.provider,on?.sessionId,uo,fo,po,cn?.returnFocusTarget,rn?.projectId]),Os=(0,W.useCallback)((e,t)=>{if(!t)return!1;if(e.key===`Escape`)return e.preventDefault(),e.stopPropagation(),Ds(),!0;let n=Array.from(t.querySelectorAll(`button:not(:disabled)`));if(n.length===0)return;let r=n.findIndex(e=>e===document.activeElement),i=Math.min(Jn.current,n.length-1),a=r===-1?i:r,o=e=>{Jn.current=e,n[e]?.focus()};if(e.key===`Tab`){qn.current=!0,e.preventDefault(),e.stopPropagation();let t=a+(e.shiftKey?-1:1);if(t<0||t>=n.length){Ds();return}return o(t),!0}if(e.key===`ArrowDown`||e.key===`ArrowUp`){qn.current=!0,e.preventDefault(),e.stopPropagation();let t=e.key===`ArrowDown`?1:-1;return o(a===-1?t>0?0:n.length-1:(a+t+n.length)%n.length),!0}return e.key===`Home`?(qn.current=!0,e.preventDefault(),e.stopPropagation(),o(0),!0):e.key===`End`?(qn.current=!0,e.preventDefault(),e.stopPropagation(),o(n.length-1),!0):!1},[Ds]),ks=(0,W.useCallback)(e=>{e.defaultPrevented||Os(e.nativeEvent,e.currentTarget)},[Os]);(0,W.useLayoutEffect)(()=>{if(!tn&&!rn&&!on&&!cn)return;let e=e=>{Os(e,document.querySelector(`.code-context-menu`))&&e.stopImmediatePropagation()};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[tn,on,Os,cn,rn]);let As=(0,W.useCallback)(e=>{let t=Array.from(e.currentTarget.querySelectorAll(`button:not(:disabled)`)),n=e.target instanceof Element?e.target.closest(`button`):null,r=t.findIndex(e=>e===n||e===document.activeElement);if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),vi(),Qi();return}if(e.key===`Tab`){e.preventDefault(),e.stopPropagation();let t=ni?`[data-testid="code-composer-model-picker"]`:ri?XD()?`[data-testid="code-composer-send"]`:`[data-testid="code-composer-mic"]`:`[data-testid="code-composer-approval"]`;vi(),window.requestAnimationFrame(()=>{document.querySelector(t)?.focus({preventScroll:!0})});return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation();let n=e.key===`ArrowDown`?1:-1;t[r===-1?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus();return}if(e.key===`Home`){e.preventDefault(),e.stopPropagation(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),e.stopPropagation(),t[t.length-1]?.focus())},[ni,vi,Qi,ri]),js=(0,W.useCallback)(e=>{let t=e.relatedTarget;t&&(t instanceof Node&&e.currentTarget.contains(t)||t instanceof Element&&t.closest(`.code-composer`)||vi())},[vi]);(0,W.useEffect)(()=>{function e(e){if(a)return;let t=e.target;if(tn||rn||on||cn){if(Os(e,Kn.current))return;if(e.key.length===1||e.key===`Tab`||e.key===`ArrowDown`||e.key===`ArrowUp`||e.key===`Home`||e.key===`End`){e.preventDefault(),e.stopPropagation();return}}if(e.key===`Escape`&&mn){e.preventDefault(),Jo();return}if(e.key===`Escape`&&gn){e.preventDefault(),Qo();return}if(e.key===`Escape`&&vn){e.preventDefault(),Ts();return}if(mn||gn||vn){He(t)||(e.preventDefault(),e.stopPropagation());return}let n=x?bt(e):null;if(n){$D(e),jo(n);return}if(MD(e)&&!He(t)){e.preventDefault(),e.stopPropagation(),Fo();return}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&!e.altKey&&!e.shiftKey&&!mn&&!gn&&!vn&&!He(t)&&!qD(t)&&!Re(t)){let n=Di(t)??Ei;if(!n)return;e.preventDefault(),xo(n.id);return}if(!(ze(t)||Re(t))&&!(He(t)&&e.key!==`Escape`)){if(e.key===`Escape`&&(ti||ni||ri)){e.preventDefault(),vi(),Qi();return}if(e.key===`Escape`&&i!==`projects`){e.preventDefault(),nn(null),an(null),sn(null),ln(null),Ya(),V(`projects`),or.current=`active-force`;return}if(e.key===`Escape`&&(tn||rn||on||cn)){e.preventDefault();let t=tn?.agentId,n=rn?.projectId,r=on?.provider,i=on?.sessionId,a=cn?.returnFocusTarget??null;nn(null),an(null),sn(null),ln(null),t?uo(t):n?po(n):r&&i?fo(r,i):a&&window.requestAnimationFrame(()=>a.focus({preventScroll:!0}));return}if(x){if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`b`){e.preventDefault(),_r();return}e.key===`/`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.shiftKey&&(e.preventDefault(),Pa())}}}return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[i,tn,ni,vi,Ts,Qo,Jo,on,vn,a,uo,fo,Qi,po,xo,Os,gn,x,ri,jo,cn,ti,Ei,Di,rn,mn,Fo,Ya,V,Pa,_r]),(0,W.useEffect)(()=>{if(!mn)return;let e=mn.title,t=!1;return IE(()=>{let n=zn.current;if(!n)return;let r=document.activeElement;if(r!==n&&!Bn.current?.contains(r)&&n.focus(),!t&&document.activeElement===n&&n.value===e){if(t=!0,mn.kind===`project`){let e=n.value.length;n.setSelectionRange(e,e);return}n.select()}},{delays:[0,80,180,360]})},[En]),(0,W.useEffect)(()=>gn?IE(()=>{Vn.current?.contains(document.activeElement)||Hn.current?.focus()},{runNow:!1,delays:[180]}):void 0,[gn]),(0,W.useEffect)(()=>vn?IE(()=>{Un.current?.contains(document.activeElement)||Wn.current?.focus()},{runNow:!1,delays:[180]}):void 0,[vn]),(0,W.useEffect)(()=>{if(!bn)return;let e=window.setTimeout(()=>xn(null),1700);return()=>window.clearTimeout(e)},[bn]),(0,W.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-context-menu`)||(nn(null),an(null),sn(null),ln(null))}if(!(!tn&&!rn&&!on&&!cn))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[tn,on,cn,rn]),(0,W.useEffect)(()=>{function e(e){let t=e.target;t instanceof Element&&t.closest(`.code-composer-menu-anchor`)||vi()}if(!(!ti&&!ni&&!ri))return window.addEventListener(`pointerdown`,e),()=>window.removeEventListener(`pointerdown`,e)},[ni,vi,ri,ti]),(0,W.useLayoutEffect)(()=>!tn&&!rn&&!on&&!cn?void 0:(qn.current=!1,Jn.current=0,IE(()=>{if(qn.current)return;let e=Kn.current;if(!e)return;let t=document.activeElement;if(t instanceof HTMLButtonElement&&e.contains(t))return;let n=e.querySelector(`button:not(:disabled)`);n&&(Jn.current=0,n.focus())},{delays:[0,80,180,360]})),[tn,on,cn,rn]),(0,W.useEffect)(()=>{if(!ri)return;let e=window.setTimeout(()=>{let e=ii===`model`?`.code-model-submenu .code-model-option.selected`:ii===`speed`?`.code-speed-submenu .code-model-option.selected`:`.code-model-picker-menu > .code-model-option.selected`,t=Ln.current?.querySelector(e),n=Ln.current?.querySelector(`button:not(:disabled)`);(t??n)?.focus()},0);return()=>window.clearTimeout(e)},[ri,ii,Mi,Ni,Pi]),(0,W.useEffect)(()=>{if(!ti)return;let e=window.setTimeout(()=>{Fn.current?.querySelector(`button:not(:disabled)`)?.focus()},0);return()=>window.clearTimeout(e)},[ti]),(0,W.useEffect)(()=>{if(!ni)return;let e=window.setTimeout(()=>{let e=In.current?.querySelector(`.code-approval-option.selected`),t=In.current?.querySelector(`button:not(:disabled)`);(e??t)?.focus()},0);return()=>window.clearTimeout(e)},[ni,Ri]),(0,W.useEffect)(()=>{if(!pe)return;let e=window.setInterval(()=>On(Date.now()),6e4);return()=>window.clearInterval(e)},[pe]),(0,W.useEffect)(()=>{let e=window.matchMedia(`(max-width: 980px)`),t=()=>{Rt(!!(window.SpeechRecognition||window.webkitSpeechRecognition)&&!GD())};return t(),e.addEventListener(`change`,t),()=>{e.removeEventListener(`change`,t),Yn.current?.stop(),Yn.current=null}},[]),(0,W.useEffect)(()=>ea(),[ea]),(0,W.useEffect)(()=>{let e=()=>{ea(),oa()};return window.addEventListener(`farming-agent-homes-saved`,e),()=>window.removeEventListener(`farming-agent-homes-saved`,e)},[oa,ea]),(0,W.useEffect)(()=>na(),[na]),(0,W.useEffect)(()=>la(si||``,Z?.cwd),[Z?.cwd,si,la]),(0,W.useEffect)(()=>{if(ri)return ta()},[ta,ri]),(0,W.useEffect)(()=>{if(!(!ri||si!==`claude`))return na()},[si,na,ri]),(0,W.useEffect)(()=>oa(),[oa]),(0,W.useEffect)(()=>{Zi()},[Zi,Yr,ei,Qr]),(0,W.useEffect)(()=>{Xr.composer.permissionMode||Xr.composer.modelPicker||_i(e=>{let t=HC(e);return Xr.composer.plusMenu||t.mode===`default`?t:{...t,mode:`default`}})},[Xr,_i]),(0,W.useEffect)(()=>{i!==`search`&&Le&&Ya(),i!==`projects`&&(nn(null),an(null),sn(null),ln(null),vi())},[i,Ya,vi,Le]),(0,W.useEffect)(()=>{a&&(nn(null),an(null),sn(null),ln(null),vi())},[vi,a]),(0,W.useEffect)(()=>{if(i===`projects`)return ea()},[i,ea]),(0,W.useEffect)(()=>{if(i!==`history`)return;let e=!1,t=lr.current;return fetch(n(`/api/settings`)).then(e=>e.json()).then(n=>{if(e)return;let r=n.settings??{};Ke(tt(r.lastMainWorkspace,r.workspaceHistory??[])),Ye(kD(r.projectNames)),t===lr.current&&$e(new Set(kS(r.mainPageSessionKeys??[]))),$i(r),oa(!0)}).catch(()=>{e||Ke([])}),()=>{e=!0}},[i,$i,oa]),(0,W.useEffect)(()=>{function e(e){dr.current&&(e.preventDefault(),co(e.clientX))}function t(){dr.current&&(dr.current=!1,document.body.classList.remove(`code-resizing-sidebar`))}return window.addEventListener(`pointermove`,e),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t),document.body.classList.remove(`code-resizing-sidebar`)}},[co]),(0,W.useEffect)(()=>{let e=kn.current;if(!e||typeof ResizeObserver>`u`)return;let t=e=>{if(XD()){pr.current||hr(),pr.current=!0;return}if(pr.current=!1,ZD(e)){hr();return}fr.current&&gr()};t(e.getBoundingClientRect().width);let n=new ResizeObserver(n=>{t(n[0]?.contentRect.width??e.getBoundingClientRect().width)});return n.observe(e),()=>n.disconnect()},[hr,gr]),(0,W.useEffect)(()=>{let e=or.current;if(!e||i!==`projects`||Le)return;or.current=null;let t,n=0,r=e===`active-force`?4:12,a=()=>{n>=r||(t=window.setTimeout(o,90))},o=()=>{if(n+=1,qa()){a();return}let t=!1;e===`list`?(Gn.current?.focus({preventScroll:!0}),t=document.activeElement===Gn.current):t=Ga(),(!t||e===`active-force`)&&a()},s=window.setTimeout(()=>{o()},e===`list`?0:50);return()=>{window.clearTimeout(s),t!==void 0&&window.clearTimeout(t)}},[l,i,Ga,Le,qa]),(0,W.useEffect)(()=>{if(!sr.current||i!==`projects`||Le)return;sr.current=null;let e,t=0,n=()=>{t>=12||(e=window.setTimeout(r,90))},r=()=>{if(t+=1,qa()){n();return}Ja({skipIfFocusMoved:!0}),n()},a=window.setTimeout(()=>{r(),e=window.setTimeout(r,180)},50);return()=>{window.clearTimeout(a),e!==void 0&&window.clearTimeout(e)}},[Y.length,l,i,Ja,Le,qa]),(0,W.useEffect)(()=>{let e=cr.current;if(!e||i!==`projects`||Le||!Y.some(t=>t.id===e))return;cr.current=null;let t,n=0,r=()=>{n+=1,qa()||lo(e),!(n>=60)&&(t=window.setTimeout(()=>{window.requestAnimationFrame(r)},80))},a=window.setTimeout(()=>{window.requestAnimationFrame(r)},50);return()=>{window.clearTimeout(a),t!==void 0&&window.clearTimeout(t)}},[Y,i,lo,Le,qa]),(0,W.useEffect)(()=>{Ti&&en(Ti)},[Ti]),(0,W.useEffect)(()=>{Ge(0)},[Ir,Le]),(0,W.useEffect)(()=>{Ge(e=>Hr.length===0?0:Math.min(e,Hr.length-1))},[Hr.length]);let Ms={"--code-sidebar-width":`${qt?ID:Gt}px`};return(0,K.jsxs)(`div`,{className:`code-workspace ${qt?`sidebar-collapsed`:``}`,"data-testid":`code-workspace`,ref:kn,style:Ms,children:[(0,K.jsx)(CT,{sidebarCollapsed:qt,activeView:i,searchOpen:Le,displayedProjects:Pr,collapsedProjectIds:Vt,normalizedSearch:``,hasProjectListItems:zr,hasDisplayedProjectListItems:zr,activeTerminalId:l,selectedSearchAgentId:Ci,selectedSearchSessionHandle:wi,claimedAgentSessionKeyByAgentId:Sr.claimedAgentSessionKeyByAgentId,agentShortcutKeys:Ur,keyboardShortcutsEnabled:x,now:Dn,mainAgent:yr,systemStats:o,usageSummary:s,shareTarget:Ai,agentLaunchOptions:Xe,agentCreationWorkspace:Oi,openWorkspaceFile:G,openWorkspaceFiles:Fe,fileRevealRequest:Sn,fileSearchFocusRequest:wn,projectListRef:Gn,canLoadMoreAgentSessions:Ot,onLoadMoreAgentSessions:ca,onNewAgent:La,onStartAgent:Ra,onToggleSidebar:_r,onOpenSearch:Qa,onOpenWorkspaceView:$a,onOpenMainAgent:()=>{yr&&(be(`terminal`),V(`projects`),E(yr.id))},onRestartMainAgent:ie,onProjectListKeyDown:io,onToggleProject:eo,onToggleProjectSessions:to,onOpenProjectContextMenu:Ho,onOpenProjectKeyboardMenu:Uo,onOpenAgent:vo,onUpdateAgentFlags:ns,onReorderAgent:rs,onOpenAgentContextMenu:Bo,onOpenAgentKeyboardMenu:Vo,onResumeAgentSession:os,onOpenAgentSessionContextMenu:Wo,onOpenAgentSessionKeyboardMenu:Go,onOpenProjectFile:bo,onSelectOpenWorkspaceFile:To,onCloseOpenWorkspaceFile:Po,onMoveWorkspaceEntries:Ro,onDeleteWorkspaceEntries:zo,onOpenOptionsMenu:ps,copy:J}),(0,K.jsx)(DE,{open:un,activeAgentId:i===`projects`?Z?.id??null:null,language:T.language,uiPreferences:T,agentLaunchOptions:Xe,onClose:()=>dn(!1),onUpdateUiPreferences:fe}),fn&&(0,K.jsx)(Dw,{copy:J,title:Ki,url:fn,onClose:()=>pn(``)}),(0,K.jsx)(`div`,{className:`code-sidebar-resizer`,"data-testid":`code-sidebar-resizer`,onPointerDown:go}),!qt&&(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-sidebar-backdrop`,"data-testid":`code-mobile-sidebar-backdrop`,"aria-label":J.closeNavigation,onPointerDown:hr}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar`,"data-testid":`code-mobile-topbar`,children:[Xi?(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button back`,"data-testid":`code-mobile-back`,"aria-label":J.backToAgent,onClick:()=>{Yi&&Mo(Yi)},children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}):(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button menu`,"data-testid":`code-mobile-menu`,"aria-label":J.openNavigation,onClick:Ia,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})}),(0,K.jsxs)(`div`,{className:`code-mobile-topbar-title`,children:[(0,K.jsx)(`strong`,{children:Ki}),Ji&&(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),Ji]})]}),(0,K.jsx)(`button`,{type:`button`,className:`code-mobile-topbar-button more`,"data-testid":`code-mobile-more`,"aria-label":J.openOptions,onClick:cs,children:(0,K.jsx)(`span`,{"aria-hidden":`true`})})]}),cn&&(0,K.jsx)(`div`,{className:`code-context-menu code-options-menu`,"data-testid":`code-options-menu`,style:{left:cn.x,top:cn.y},role:`menu`,ref:Kn,onKeyDownCapture:ks,onKeyDown:ks,children:(0,K.jsx)(oO,{entries:ms})}),(0,K.jsx)(MC,{activeView:i,showFileEditor:ki,openWorkspaceFile:G,openWorkspaceFiles:Fe,openAgentsCount:Wr.length,visibleOpenAgents:Kr,activeTerminalId:l,permissionSwitchingAgentId:p,agentSwitchingKind:g,terminalFocusRequest:y,agentCreationWorkspace:Oi,displayedProjects:Br,searchQuery:Ve,searchHasQuery:Lr,searchLoading:jt,visibleSearchTargetCount:Hr.length,selectedSearchAgentId:Ci,selectedSearchSessionHandle:wi,searchInputRef:Rn,archivedRuns:Or,archivedAgents:Dr,historyAgentSessions:kr,canLoadMoreHistoryAgentSessions:Ot,now:Dn,acpComposerProps:{active:!!Z&&!qr,agentId:Z?.id||``,runtimeState:Z?.acpState||``,sessionUpdatedAt:Z?.acpSessionUpdatedAt||``,runtimeError:Z?.acpError||``,draft:Qr,attachments:$r,composerMode:ei,contextWindow:Jr,pendingFollowUp:fi??null,submitAction:gi,textareaRef:An,attachmentInputRef:Pn,permissions:Z?.acpPendingPermissions?.length?Z.acpPendingPermissions:Z?.acpPendingPermission?[Z.acpPendingPermission]:[],elicitations:Z?.acpPendingElicitations?.length?Z.acpPendingElicitations:Z?.acpPendingElicitation?[Z.acpPendingElicitation]:[],activeElicitations:Z?.acpActiveElicitations||[],speechSupported:Lt,speechListening:zt,onDraftChange:ya,onNavigateHistory:ba,onRemoveAttachment:pa,onSubmit:Ea,onInterrupt:Da,onDiscardPendingFollowUp:Na,onToggleSpeechInput:Cs,onPasteAttachment:ha,onAttachmentFiles:ma,onChooseAttachmentFile:ua,onActivateComposerMode:ga,onClearComposerMode:()=>{_i(e=>({...e,mode:`default`}))},onRespondToPermission:Aa,onRespondToElicitation:ja},composerProps:{active:!!Z&&!qr,agentKind:si,capabilities:Xr.composer,slashCommands:di,draft:Qr,attachments:$r,composerMode:ei,plusMenuOpen:ti,approvalMenuOpen:ni,modelMenuOpen:ri,modelPickerPane:ii,agentModelPreset:Fi,agentModel:Mi,agentReasoningEffort:Ni,agentServiceTier:Pi,agentModelOptions:ji,currentPermissionMode:Ri,permissionModeDisabled:!!p,currentPermissionLabel:zi,currentPermissionColor:Bi,permissionModeHint:Z?.codexRuntimeMode===`app-server`?J.permissionAppServerHint:J.permissionRestartHint,currentModelLabel:Vi,currentReasoningLabel:Hi,currentSpeedLabel:Ui,currentReasoningOptions:Ii,currentServiceTierOptions:Li,permissionModeOptions:Wi,contextWindow:Jr,pendingFollowUp:fi?{messages:fi.messages,createdAt:fi.createdAt}:null,appServerRequest:Z?.codexAppServerPendingRequest||null,appServerNotice:Z?.codexAppServerNotice||null,submitAction:hi,speechSupported:Lt,speechListening:zt,textareaRef:An,attachmentInputRef:Pn,plusMenuRef:Fn,approvalMenuRef:In,modelMenuRef:Ln,onDraftChange:ya,onNavigateHistory:ba,onRemoveAttachment:pa,onSubmit:Ta,onInterrupt:Da,onSteerPendingFollowUp:Ma,onDiscardPendingFollowUp:Na,onRespondToAppServerRequest:Oa,onRejectAppServerRequest:ka,onPasteAttachment:ha,onAttachmentFiles:ma,onChooseAttachmentFile:ua,onActivateComposerMode:ga,onClearComposerMode:()=>{_i(e=>({...e,mode:`default`})),Qi()},onTogglePlusMenu:()=>{_i(e=>({...e,ui:{plusMenuOpen:!e.ui.plusMenuOpen,approvalMenuOpen:!1,modelMenuOpen:!1,modelPickerPane:null}}))},onToggleApprovalMenu:()=>{_i(e=>({...e,ui:{plusMenuOpen:!1,approvalMenuOpen:!e.ui.approvalMenuOpen,modelMenuOpen:!1,modelPickerPane:null}}))},onToggleModelMenu:()=>{_i(e=>({...e,ui:{plusMenuOpen:!1,approvalMenuOpen:!1,modelMenuOpen:!e.ui.modelMenuOpen,modelPickerPane:null}}))},onCloseMenus:vi,onSetModelPickerPane:e=>{_i(t=>({...t,ui:{...t.ui,modelPickerPane:e}}))},onComposerMenuKeyDown:As,onComposerMenuBlur:js,onUpdatePermissionMode:gs,onUpdateModel:vs,onUpdateReasoningEffort:bs,onUpdateServiceTier:xs,onUpdateModelProfile:ys,onUpdateServiceTierInline:Ss,onToggleSpeechInput:Cs},onNewAgent:M,onOpenTerminal:E,onOpenTerminalPath:wo,onResolveTerminalPath:Co,onTerminalFollowOutputChange:va,onAgentReadLatest:_a,onRuntimeModeChange:_s,sendInput:se,resizeAgent:ue,onSessionOutput:de,onOpenSearchAgent:_o,onOpenSearchSession:e=>{os(e.provider,e.id,e.providerHomeId),Ya(),V(`projects`)},onSearchQueryChange:Ue,onSearchKeyDown:so,onCloseSearch:Xa,onLoadMoreHistoryAgentSessions:ca,onSearchHistoryAgentSessions:ia,onResumeHistorySession:os,onContinueArchivedRun:ss,onOpenArchivedAgent:as,onRestoreArchivedAgent:is,onChangeWorkspaceFileDraft:Lo,onUpdateOpenWorkspaceFile:Io,onSelectOpenWorkspaceFile:To,onOpenWorkspaceFilePath:Eo,canNavigateWorkspaceBack:Te,canNavigateWorkspaceForward:Ee,onNavigateWorkspaceHistory:jo,onCloseOpenWorkspaceFile:Po,onCloseOpenWorkspaceFiles:No,onRevealWorkspaceFileInExplorer:So,onFocusWorkspaceFilesSearch:xo,onRecordWorkspaceNavigationCursor:je,onBackToAgentFromFile:Mo,copy:J}),(0,K.jsx)(kw,{contextMenuAgent:yi,contextMenuAgentSession:xi,contextMenuProject:bi,agentMenu:tn,projectMenu:rn,agentSessionMenu:on,renameDialog:mn,killDialog:gn,deleteWorktreeDialog:vn,copyNotice:bn,contextMenuRef:Kn,renameDialogRef:Bn,renameInputRef:zn,killDialogRef:Vn,killCancelButtonRef:Hn,deleteWorktreeDialogRef:Un,deleteWorktreeCancelButtonRef:Wn,onContextMenuKeyDown:ks,onUpdateAgentFlags:ts,onRenameAgent:Ko,onRenameProject:qo,onCopyAgentWorkingDirectory:()=>{yi&&Xo(Ab(yi),{kind:`agent`,id:yi.id})},onForkAgent:es,onKillAgent:Zo,onOpenSession:(e,t)=>{sn(null),ln(null),os(e,t,xi?.providerHomeId),xi&&fo(e,Rb(xi))},onToggleSessionPinned:mo,onArchiveSession:ho,onCopySessionWorkingDirectory:()=>{xi&&Xo(Vb(xi),{kind:`agent-session`,provider:xi.provider,id:xi.id,providerHomeId:xi.providerHomeId})},onArchiveProject:ws,onCloseRenameDialog:Jo,onRenameDialogTitleChange:e=>hn(t=>t&&{...t,title:e}),onSubmitRenameDialog:Yo,onCloseKillDialog:Qo,onSubmitKillDialog:$o,onCloseDeleteWorktreeDialog:Ts,onSubmitDeleteWorktreeDialog:Es,copy:J})]})}function oO({entries:e}){return(0,K.jsx)(K.Fragment,{children:e.map(e=>e.type===`separator`?(0,K.jsx)(`div`,{className:`code-context-menu-separator`,role:`separator`},e.id):(0,K.jsxs)(`button`,{type:`button`,role:typeof e.checked==`boolean`?`menuitemradio`:`menuitem`,"aria-checked":typeof e.checked==`boolean`?e.checked:void 0,"aria-label":e.ariaLabel,className:[e.danger?`danger`:``,typeof e.checked==`boolean`?`selectable`:``,e.checked?`checked`:``].filter(Boolean).join(` `)||void 0,disabled:e.disabled,onClick:e.onSelect,children:[typeof e.checked==`boolean`&&(0,K.jsx)(`span`,{className:`code-options-menu-check`,"aria-hidden":`true`,children:e.checked?(0,K.jsx)(me,{}):null}),e.icon&&(0,K.jsx)(`span`,{className:`code-context-menu-icon`,"aria-hidden":`true`,children:(0,K.jsx)(sO,{kind:e.icon})}),(0,K.jsx)(`span`,{children:e.label})]},e.id))})}function sO({kind:e}){return e===`archive`?(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M6.5 8C6.22386 8 6 8.22386 6 8.5C6 8.77614 6.22386 9 6.5 9H9.5C9.77614 9 10 8.77614 10 8.5C10 8.22386 9.77614 8 9.5 8H6.5ZM1 3.5C1 2.67157 1.67157 2 2.5 2H13.5C14.3284 2 15 2.67157 15 3.5V4.5C15 5.15311 14.5826 5.70873 14 5.91465V11.5C14 12.8807 12.8807 14 11.5 14H4.5C3.11929 14 2 12.8807 2 11.5V5.91465C1.4174 5.70873 1 5.15311 1 4.5V3.5ZM2.5 3C2.22386 3 2 3.22386 2 3.5V4.5C2 4.77614 2.22386 5 2.5 5H13.5C13.7761 5 14 4.77614 14 4.5V3.5C14 3.22386 13.7761 3 13.5 3H2.5ZM3 6V11.5C3 12.3284 3.67157 13 4.5 13H11.5C12.3284 13 13 12.3284 13 11.5V6H3Z`})}):(0,K.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 16 16`,"aria-hidden":`true`,focusable:`false`,children:(0,K.jsx)(`path`,{fill:`currentColor`,d:`M11.3536 1.64645C10.963 1.25592 10.3299 1.25592 9.93934 1.64645L3.14645 8.43934C3.05268 8.53311 2.99999 8.66029 2.99999 8.79289V11.5C2.99999 11.7761 3.22385 12 3.49999 12H6.2071C6.33971 12 6.46689 11.9473 6.56066 11.8536L13.3536 5.06066C13.7441 4.67014 13.7441 4.037 13.3536 3.64645L11.3536 1.64645ZM3.99999 9L8.99999 4L11 6L6 11H3.99999V9ZM9.7071 3.29289L10.6464 2.35355L12.6464 4.35355L11.7071 5.29289L9.7071 3.29289ZM2.5 14C2.22386 14 2 14.2239 2 14.5C2 14.7761 2.22386 15 2.5 15H13.5C13.7761 15 14 14.7761 14 14.5C14 14.2239 13.7761 14 13.5 14H2.5Z`})})}var cO={appearance:`light`,language:`en`};function lO(e){return e===`light`||e===`dark`?e:cO.appearance}function uO(e){return e===`zh`||e===`en`?e:cO.language}function dO(e){return e}function fO(e=`terminal`,t={}){if(typeof document>`u`)return;let n=document.body,r=t.crtEffects!==!1,i=lO(t.appearance),a=dO(i);n.dataset.theme=e,n.dataset.crtEffects=r?`on`:`off`,n.dataset.appearancePreference=i,n.dataset.appearance=a,r?n.classList.remove(`no-crt`):n.classList.add(`no-crt`)}var pO=!1,mO=3e3,hO=6e3,gO=240,_O=3e4,vO=1e4,yO=6e4,bO=45e3,xO=6e4;function SO(e){if(e)return e.projectWorkspace?e.projectWorkspace:e.cwd}function CO(e){return!e.archived&&e.status!==`dead`&&e.status!==`stopped`}function wO(e,t){return e.restartedFromAgentId===t||e.restartedFromAgentIds?.includes(t)===!0}function TO(e,t,n){return e.filter(e=>CO(e)&&wO(e,t)&&(!n?.providerSessionProvider||!n.providerSessionId||e.providerSessionProvider===n.providerSessionProvider&&(n.providerSessionTemporary===!0||e.providerSessionId===n.providerSessionId)&&(e.providerHomeId||``)===(n.providerHomeId||``))).sort((e,t)=>{let n=(t.restartedFromAgentIds?.length??0)-(e.restartedFromAgentIds?.length??0);return n===0?(t.startedAt??0)-(e.startedAt??0):n})[0]??null}function EO(e){return e?.providerSessionProvider===`codex`&&!!e.providerSessionId&&e.providerSessionTemporary!==!0}function DO(e){if(!e||!e.isConnected||e.getAttribute(`aria-disabled`)===`true`||`disabled`in e&&e.disabled)return!1;let t=window.getComputedStyle(e);return t.display!==`none`&&t.visibility!==`hidden`&&e.getClientRects().length>0}function OO(e){return DO(e)?(e.focus({preventScroll:!0}),document.activeElement===e||e.contains(document.activeElement)):!1}function kO(){let e=G(),t=Ie(),{keyMap:r}=Le(e.agents,e.mainAgentId),[i]=(0,W.useState)(()=>A()),[a,o]=(0,W.useState)(`none`),[s,c]=(0,W.useState)(void 0),[l,u]=(0,W.useState)(void 0),[d,f]=(0,W.useState)(void 0),[p,m]=(0,W.useState)(()=>i.openTerminalIds??[]),[h,g]=(0,W.useState)(()=>i.activeTerminalId??null),[_,v]=(0,W.useState)(null),[y,b]=(0,W.useState)(null),[x,S]=(0,W.useState)(()=>i.activeView??`projects`),[C,w]=(0,W.useState)(null),[T,E]=(0,W.useState)(null),[O,k]=(0,W.useState)(null),[ee,j]=(0,W.useState)(null),[M,N]=(0,W.useState)({}),[te,P]=(0,W.useState)(cO),[ne,I]=(0,W.useState)(()=>Date.now()),re=(0,W.useRef)(null),R=(0,W.useRef)(null),z=(0,W.useRef)(null),B=(0,W.useRef)(null),ie=(0,W.useRef)([]),V=(0,W.useRef)(!1),ae=(0,W.useRef)(!1),oe=(0,W.useRef)(!1),se=(0,W.useRef)(void 0),ce=(0,W.useRef)(null),le=(0,W.useRef)(0);(0,W.useLayoutEffect)(()=>{ie.current=p},[p]),(0,W.useEffect)(()=>{D({activeTerminalId:h,activeView:x,openTerminalIds:p})},[h,x,p]);let ue=(0,W.useCallback)(e=>{B.current=e,E(e)},[]),de=a,fe=(0,W.useMemo)(()=>PE(te.language),[te.language]),pe=(0,W.useMemo)(()=>{if(!T)return e.agents;let t=e.agents.filter(e=>e.id===T.agent.id||!wO(e,T.originalAgentId));return t.some(e=>e.id===T.agent.id)?t:[...t,T.agent]},[T,e.agents]),me=(0,W.useMemo)(()=>{let e=new Map,t=new Set(p);return h&&t.add(h),t.forEach(t=>{if(pe.some(e=>e.id===t&&CO(e)))return;let n=TO(pe,t);n&&e.set(t,n.id)}),e},[h,pe,p]),H=(0,W.useMemo)(()=>{if(h){let e=me.get(h);if(e)return{originalAgentId:h,replacementAgentId:e}}let e=me.entries().next().value;return e?{originalAgentId:e[0],replacementAgentId:e[1]}:null},[h,me]),he=(0,W.useMemo)(()=>Array.from(new Set(p.map(e=>me.get(e)??e))),[me,p]),ge=h?me.get(h)??h:null;(0,W.useLayoutEffect)(()=>{H&&(m(he),g(ge),k(H))},[ge,he,H]),(0,W.useEffect)(()=>{!O||H||k(null)},[O,H]),(0,W.useEffect)(()=>{let t=B.current;if(!t)return;let n=TO(e.agents,t.originalAgentId,t.agent);if(!n||n.id===t.agent.id)return;let r=t.agent.id,i={...t,agent:n,replacementAgentId:n.id,transitionFromAgentId:r};m(e=>Array.from(new Set(e.map(e=>wO(n,e)?n.id:e)))),g(e=>e&&wO(n,e)?n.id:e),ue(i)},[ue,T?.agent.id,T?.originalAgentId,e.agents]),(0,W.useEffect)(()=>{let t=T;!t?.requestSettled||!t.replacementAgentId||e.agents.some(e=>e.id===t.agent.id)&&B.current?.agent.id===t.agent.id&&(z.current=null,ue(null))},[ue,T?.agent.id,T?.replacementAgentId,T?.requestSettled,e.agents]),(0,W.useEffect)(()=>{let t=T;if(!t?.requestSettled||!t.requestError||t.replacementAgentId)return;let n=t.requestErrorAt??Date.now();if(!t.requestFreshStateAt&&e.connected&&e.lastMessageAt>n){let n=B.current;n?.originalAgentId===t.originalAgentId&&!n.replacementAgentId&&!n.requestFreshStateAt&&ue({...n,requestFreshStateAt:e.lastMessageAt});return}let r=n+yO,i=t.requestFreshStateAt?t.requestFreshStateAt+vO:1/0,a=Math.max(0,Math.min(r,i)-Date.now()),o=window.setTimeout(()=>{let e=B.current;!e?.requestSettled||!e.requestError||e.replacementAgentId||e.originalAgentId!==t.originalAgentId||(z.current=null,ue(null),w({id:Date.now(),kind:`error`,message:e.requestError}))},a);return()=>window.clearTimeout(o)},[ue,T,e.connected,e.lastMessageAt]),(0,W.useEffect)(()=>{let e=T;if(!e)return;let t=Math.max(0,e.startedAt+xO-Date.now()),n=window.setTimeout(()=>{let t=B.current;!t||t.startedAt!==e.startedAt||(z.current=null,ue(null),w({id:Date.now(),kind:`error`,message:fe.agentRestartTimedOut}))},t);return()=>window.clearTimeout(n)},[ue,fe.agentRestartTimedOut,T]);let _e=(0,W.useMemo)(()=>{let t=Math.max(0,ne-e.lastMessageAt);return!e.connected&&e.everConnected?`lost`:!e.connected&&t>=mO?`connecting`:e.connected&&t>=hO?`stale`:null},[ne,e.connected,e.everConnected,e.lastMessageAt]),ve=_e===`lost`?fe.backendConnectionLost:_e===`stale`?fe.backendHeartbeatLost:_e===`connecting`?fe.backendConnecting:``;(0,W.useEffect)(()=>{if(!t)return;let e=window.setInterval(()=>I(Date.now()),1e3);return()=>window.clearInterval(e)},[t]);let ye=(0,W.useCallback)(e=>{let t={appearance:lO(e.appearance??te.appearance),language:uO(e.language??te.language)};P(t),fetch(n(`/api/settings`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)}).then(e=>e.json()).then(e=>{let n=e.settings??{};P({appearance:lO(n.appearance??t.appearance),language:uO(n.language??t.language)})}).catch(()=>{w({id:Date.now(),kind:`error`,message:`Failed to save preferences`})})},[te.appearance,te.language]),be=(0,W.useCallback)(e=>{let t=Array.from(new Set(e.filter(Boolean)));t.length!==0&&fetch(n(`/api/codex/context-windows`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentIds:t})}).then(e=>e.json()).then(e=>{let t=Array.isArray(e.contextWindows)?e.contextWindows:[];N(e=>{let n={...e};return t.forEach(e=>{let t=String(e?.agentId||``);t&&(e&&e.available===!0?n[t]=e:delete n[t])}),n})}).catch(()=>{})},[]);(0,W.useEffect)(()=>{if(e.connected){if(e.mainAgentId||e.agents.some(e=>e.isMain)){V.current=!1;return}V.current||(V.current=!0,e.startAgent(`bash`,void 0,!0))}},[e.agents,e.connected,e.mainAgentId,e.startAgent]),(0,W.useEffect)(()=>{let e=()=>{let e=window.visualViewport,t=e?.width??window.innerWidth,n=e?.height??window.innerHeight,r=e?.offsetTop??0,i=e?.offsetLeft??0,a=L(),o=window.innerHeight||n||gO,s=a?Math.min(Math.max(n,gO),Math.max(o,gO)):n,c=Math.max(0,o-n-r),l=a&&F(),u=a&&c>80,d=navigator.standalone===!0||window.matchMedia(`(display-mode: standalone)`).matches;document.body.classList.toggle(`code-mobile-touch`,a),document.body.classList.toggle(`code-mobile-ios`,l),document.body.classList.toggle(`code-mobile-standalone`,a&&d),document.body.classList.toggle(`code-mobile-keyboard-active`,u),document.documentElement.style.setProperty(`--app-visual-width`,`${t}px`),document.documentElement.style.setProperty(`--app-visual-height`,`${s}px`),document.documentElement.style.setProperty(`--app-visual-offset-top`,`${r}px`),document.documentElement.style.setProperty(`--app-visual-offset-left`,`${i}px`),document.documentElement.style.setProperty(`--mobile-keyboard-offset`,`${c}px`)};return e(),window.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`scroll`,e),()=>{window.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`scroll`,e),document.documentElement.style.removeProperty(`--app-visual-width`),document.documentElement.style.removeProperty(`--app-visual-height`),document.documentElement.style.removeProperty(`--app-visual-offset-top`),document.documentElement.style.removeProperty(`--app-visual-offset-left`),document.documentElement.style.removeProperty(`--mobile-keyboard-offset`),document.body.classList.remove(`code-mobile-touch`),document.body.classList.remove(`code-mobile-ios`),document.body.classList.remove(`code-mobile-standalone`),document.body.classList.remove(`code-mobile-keyboard-active`)}},[]);let xe=(0,W.useCallback)((t,n)=>{h!==t&&e.focusAgent(t),m(e=>e.includes(t)?e:[...e,t]),g(t),S(`projects`),n?.focusTerminal!==!1&&v(e=>({agentId:t,nonce:(e?.nonce??0)+1})),o(`none`)},[h,e]),Se=(0,W.useCallback)((e,t)=>{b({agentId:e,options:t})},[]),Ce=(0,W.useCallback)((e,t)=>{if(e===h&&p.includes(e)){xe(e,t);return}Se(e,t)},[xe,h,p,Se]);(0,W.useEffect)(()=>{y&&pe.some(e=>e.id===y.agentId&&CO(e))&&(b(null),xe(y.agentId,y.options))},[xe,pe,y]);let we=(0,W.useCallback)(e=>{let t=new Set(e);if(t.size===0)return;let n=ie.current,r=n.indexOf(h??``),i=n.filter(e=>!t.has(e)),a=r===-1?i[i.length-1]??null:i[Math.min(r,i.length-1)]??null;ie.current=i,m(i),g(e=>!e||!t.has(e)?e:a),h&&t.has(h)&&a&&v(e=>({agentId:a,nonce:(e?.nonce??0)+1}))},[h]),Te=(0,W.useCallback)(e=>{we([e])},[we]),Ee=(0,W.useCallback)(e=>{if(p.length===0)return;let t=p[(Math.max(0,p.findIndex(e=>e===h))+e+p.length)%p.length];t&&Ce(t)},[h,Ce,p]),De=(0,W.useCallback)((e,t,n,r)=>{let i=le.current+1;le.current=i,ce.current=n??(document.activeElement instanceof HTMLElement?document.activeElement:null),c(e),u(t),f(r),S(`projects`),o(`input`);let a=()=>{le.current===i&&o(e=>e===`input`?e:`input`)};window.requestAnimationFrame(a),window.setTimeout(a,80),window.setTimeout(a,180)},[]),Oe=(0,W.useCallback)(()=>{let e=ce.current,t=e?.getAttribute(`data-testid`)===`code-new-agent`;ce.current=null;let n=()=>{OO(e)||t&&OO(document.querySelector(`[data-testid="code-new-agent"]`))||OO((h?Array.from(document.querySelectorAll(`[data-testid="code-agent-row"]`)).find(e=>e.dataset.agentId===h):null)??null)||OO(document.querySelector(`[data-testid="code-new-agent"]`))||OO(document.querySelector(`[data-testid="code-project-list"]`))};window.requestAnimationFrame(n),window.setTimeout(n,80),window.setTimeout(n,180)},[h]),ke=(0,W.useCallback)(()=>{le.current+=1,o(`none`),Oe()},[Oe]),Ae=(0,W.useCallback)(e=>{w({id:Date.now(),kind:`error`,message:e})},[]),U=(0,W.useCallback)(t=>{Lg(t).catch(e=>{console.error(`Failed to destroy killed terminal session:`,e)}),e.killAgent(t),Te(t)},[e,Te]),je=(0,W.useCallback)(t=>{R.current||(V.current=!0,R.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.restartMainAgent(t)||(R.current=null,V.current=!1))},[e]),Me=(0,W.useCallback)((t,n,r)=>{re.current||(le.current+=1,re.current={beforeIds:new Set(e.agents.map(e=>e.id))},e.startAgent(t,n,!1,r)||(re.current=null))},[e]);(0,W.useEffect)(()=>{let t=e.lastStartedAgentId,n=re.current;!t||!n||n.beforeIds.has(t)||(re.current=null,o(`none`),Se(t))},[Se,e.lastStartedAgentId]);let Ne=(0,W.useCallback)(async(e,t)=>{try{let r=await fetch(n(`/api/agents/${e}/fork`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({mode:t})}),i=await r.json().catch(()=>null);if(!r.ok||!i?.agentId){Ae(i?.error||`Failed to fork agent (${r.status})`);return}Se(i.agentId)}catch(e){Ae(e instanceof Error?e.message:`Failed to fork agent`)}},[Ae,Se]),Pe=(0,W.useCallback)(async(e,t)=>{try{let r=await fetch(n(`/api/projects/delete-worktree`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({workspace:e,force:t?.force===!0})}),i=await r.json().catch(()=>null);if(!r.ok&&i?.requiresForce!==!0&&Ae(i?.error||`Failed to delete worktree (${r.status})`),i?.deleted&&we(i.archivedAgentIds??[]),i)return i;let a=`Failed to delete worktree (${r.status})`;return Ae(a),{error:a}}catch(e){let t=e instanceof Error?e.message:`Failed to delete worktree`;return Ae(t),{error:t}}},[we,Ae]),Fe=(0,W.useCallback)(async(e,t)=>{try{let r=await fetch(n(`/api/agents/${e}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({customTitle:t})}),i=await r.json().catch(()=>null);r.ok||Ae(i?.error||`Failed to rename agent (${r.status})`)}catch(e){Ae(e instanceof Error?e.message:`Failed to rename agent`)}},[Ae]),Re=(0,W.useCallback)(async(t,r)=>{let i=typeof r.launchPermissionMode==`string`?r.launchPermissionMode:``,a=typeof r.agentRuntimeMode==`string`,o=i||a?e.agents.find(e=>e.id===t)??null:null,s=o?.providerSessionProvider===`codex`&&o.codexRuntimeMode===`app-server`&&!a?null:o;if(s){if(z.current)return!1;z.current=t,ue({originalAgentId:t,agent:s,kind:a?`runtime`:`permission`,startedAt:Date.now()})}let c=()=>{s&&B.current?.originalAgentId===t&&(z.current=null,ue(null))};try{let e=new AbortController,a=window.setTimeout(()=>e.abort(),bO),o=await fetch(n(`/api/agents/${t}`),{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r),signal:e.signal});window.clearTimeout(a);let l=await o.json().catch(()=>null);if(!o.ok){let e=B.current;return s&&e?.originalAgentId===t&&e.replacementAgentId?(ue({...e,requestSettled:!0}),l??!0):(c(),Ae(l?.error||`Failed to update agent (${o.status})`),!1)}if(l?.warning&&Ae(l.warning),r.archived===!0&&Te(t),l?.restartedAgentId){let e=l.restartedAgentId,n=B.current;s&&n?.originalAgentId===t&&(n.agent.id===t?(m(n=>n.map(n=>n===t?e:n)),g(n=>n===t?e:n),ue({...n,replacementAgentId:e,transitionFromAgentId:t,requestSettled:!0,agent:{...n.agent,id:e,launchPermissionMode:l.launchPermissionMode??i,agentRuntimeMode:l.agentRuntimeMode??n.agent.agentRuntimeMode,restartedFromAgentId:t,restartedFromAgentIds:Array.from(new Set([...n.agent.restartedFromAgentIds??[],t]))}})):ue({...n,requestSettled:!0,requestError:void 0}))}else c();return l??!0}catch(e){let n=e instanceof DOMException&&e.name===`AbortError`?fe.agentRestartTimedOut:e instanceof Error?e.message:`Failed to update agent`,r=B.current;return s&&r?.originalAgentId===t?(ue({...r,requestSettled:!0,requestError:n,requestErrorAt:Date.now()}),!!r.replacementAgentId):(Ae(n),!1)}},[Te,ue,fe.agentRestartTimedOut,Ae,e.agents]),ze=(0,W.useCallback)(async e=>{await Re(e,{archived:!1})&&Se(e)},[Re,Se]),Be=(0,W.useMemo)(()=>pe.find(e=>e.id===ge)??null,[pe,ge]);return(0,W.useEffect)(()=>{if(!t||!EO(Be))return;let e=Be.id,n,r;return n=window.setTimeout(()=>be([e]),2500),r=window.setInterval(()=>be([e]),_O),()=>{n!==void 0&&window.clearTimeout(n),r!==void 0&&window.clearInterval(r)}},[Be?.id,Be?.providerSessionId,Be?.providerSessionProvider,Be?.providerSessionTemporary,t,be]),(0,W.useEffect)(()=>{let e=SO(Be);e&&(se.current=e)},[Be]),We((0,W.useMemo)(()=>[],[Be,Ee,r,De,Ce]),pO),(0,W.useEffect)(()=>{e.error&&(re.current=null,b(null),R.current=null,V.current=!1,Ae(e.error))},[Ae,e.error,e.errorId]),(0,W.useEffect)(()=>{if(!C)return;let e=window.setTimeout(()=>w(null),2800);return()=>window.clearTimeout(e)},[C]),(0,W.useEffect)(()=>{if(!t)return;let e=!1,r,i,a=()=>{fetch(n(`/api/usage`)).then(e=>e.json()).then(t=>{e||j(t.usage??null)}).catch(()=>{e||j(null)})};return i=window.setTimeout(a,1500),r=window.setInterval(a,6e4),()=>{e=!0,i!==void 0&&window.clearTimeout(i),r!==void 0&&window.clearInterval(r)}},[t]),(0,W.useEffect)(()=>{Rg(pe.filter(CO).map(e=>e.id)).catch(e=>{console.error(`Failed to prune terminal sessions:`,e)})},[pe]),(0,W.useEffect)(()=>{let e=new Set(pe.filter(CO).map(e=>e.id));m(t=>Array.from(new Set(t.map(t=>e.has(t)?t:TO(pe,t)?.id??t))).filter(t=>e.has(t)||B.current?.agent.id===t))},[pe]),(0,W.useEffect)(()=>{let e=new Set(pe.filter(CO).map(e=>e.id));g(t=>t&&(e.has(t)||B.current?.agent.id===t)?t:p[0]??null)},[pe,p]),(0,W.useEffect)(()=>{pe.some(e=>!e.isMain&&CO(e))||(ae.current=!1)},[pe]),(0,W.useEffect)(()=>{if(p.length>0||ae.current)return;let e=pe.find(e=>!e.isMain&&CO(e))?.id;e&&(ae.current=!0,m([e]),g(e))},[pe,p.length,e.mainAgentId]),(0,W.useEffect)(()=>{let t=R.current;if(!t)return;let n=e.agents.find(e=>e.isMain&&!e.archived&&!t.beforeIds.has(e.id));n&&(R.current=null,V.current=!1,Ce(n.id))},[Ce,e.agents]),(0,W.useEffect)(()=>{if(oe.current||e.agents.length===0)return;let t=new URLSearchParams(window.location.search).get(`agent`);if(!t){oe.current=!0;return}e.agents.some(e=>e.id===t&&!e.archived)&&(oe.current=!0,Ce(t))},[Ce,e.agents]),(0,W.useEffect)(()=>(document.body.classList.add(`code-mode`),()=>{document.body.classList.remove(`code-mode`)}),[]),(0,W.useEffect)(()=>{fO(`terminal`,{crtEffects:!1,appearance:te.appearance})},[te.appearance]),(0,W.useEffect)(()=>{let e=!1;return fetch(n(`/api/settings`)).then(e=>e.json()).then(t=>{if(e)return;let n=t.settings??{};P({appearance:lO(n.appearance),language:uO(n.language)})}).catch(()=>{}),()=>{e=!0}},[]),(0,K.jsxs)(`div`,{className:`app-container code-app-shell`,"data-testid":`app-shell`,children:[(0,K.jsx)(aO,{agents:pe,taskHistory:e.taskHistory,mainPageSessionKeys:e.mainPageSessionKeys,activeView:x,dialogOpen:de!==`none`,systemStats:e.systemStats??ee?.systemStats??null,usageSummary:ee,contextWindowByAgentId:M,activeTerminalId:ge,permissionSwitchingAgentId:T?.agent.id??null,agentSwitchingKind:T?.kind??null,permissionSwitchReplacement:T?.replacementAgentId?{originalAgentId:T.transitionFromAgentId??T.originalAgentId,replacementAgentId:T.replacementAgentId}:H??O,openTerminalIds:he,terminalFocusRequest:_,keyMap:r,keyboardShortcutsEnabled:pO,uiPreferences:te,onOpenTerminal:Ce,onOpenTerminalWhenReady:Se,onNewAgent:De,onStartAgent:Me,onRenameAgent:Fe,onUpdateAgentFlags:Re,onOpenArchivedAgent:ze,onForkAgent:Ne,onDeleteForkWorktreeProject:Pe,onRestartMainAgent:je,onWorkspaceViewChange:S,onKill:U,onInterruptAgent:e.interruptAgent,sendInput:e.sendInput,sendComposerInput:e.sendComposerInput,respondToAppServerRequest:e.respondToAppServerRequest,resizeAgent:e.resizeAgent,onSessionOutput:e.onSessionOutput,onUpdateUiPreferences:ye}),(0,K.jsx)(pt,{open:de===`input`,mustStartMain:!1,initialWorkspace:s,initialCommand:l,initialCustomTitle:d,showWorkflowTaskFields:!1,copy:fe,onStart:Me,onClose:ke}),_e&&(0,K.jsxs)(`div`,{className:`connection-status ${_e}`,"data-testid":`connection-status`,role:`status`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`connection-status-dot`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{children:ve})]}),C&&(0,K.jsx)(`div`,{className:`app-toast ${C.kind}`,"data-testid":`app-toast`,role:`status`,children:C.message})]})}export{kO as App};